text
stringlengths 5
1.04M
|
|---|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <proxygen/httpserver/samples/hq/FizzContext.h>
#include <fizz/protocol/ZlibCertificateDecompressor.h>
#include <fizz/protocol/ZstdCertificateDecompressor.h>
#include <fizz/server/AeadTicketCipher.h>
#include <fizz/server/CertManager.h>
#include <fizz/server/TicketCodec.h>
#include <string>
namespace {
const std::string kDefaultCertData = R"(
-----BEGIN CERTIFICATE-----
MIIGGzCCBAOgAwIBAgIJAPowD79hiDyZMA0GCSqGSIb3DQEBCwUAMIGjMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTETMBEGA1UEBwwKTWVubG8gUGFy
azERMA8GA1UECgwIUHJveHlnZW4xETAPBgNVBAsMCFByb3h5Z2VuMREwDwYDVQQD
DAhQcm94eWdlbjExMC8GCSqGSIb3DQEJARYiZmFjZWJvb2stcHJveHlnZW5AZ29v
Z2xlZ3JvdXBzLmNvbTAeFw0xOTA1MDgwNjU5MDBaFw0yOTA1MDUwNjU5MDBaMIGj
MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTETMBEGA1UEBwwKTWVu
bG8gUGFyazERMA8GA1UECgwIUHJveHlnZW4xETAPBgNVBAsMCFByb3h5Z2VuMREw
DwYDVQQDDAhQcm94eWdlbjExMC8GCSqGSIb3DQEJARYiZmFjZWJvb2stcHJveHln
ZW5AZ29vZ2xlZ3JvdXBzLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC
ggIBALXZs4+YnCE8aMAL5gWNjLRm2EZiFHWoKpt42on8y+SZdb1xdSZ0rx6/jl4w
8V5aiLLNmboa1ULNWLS40mEUoqRPEUiBiN3T/3HomzMCLZ52xaaKS1sW9+ZPsSlT
omwV4HupJWKQaxpu+inY98mxGaZjzHie3AoydovD+rWWLj4mSX9DchWbC8DYq7xu
4qKedgHMJlsP3luYgnRSsZ+vlTEe/K41Czt+GGhViRNL8Nm3wZrxAGYqTx/zrqsT
R8qA3gwfPPqJJH5UprtvHXDS99yiy6MYyWBr/BbZ37A5X9pWCL09aLEIrQGQWtVu
CnBNCrQgYDgD7Y4+Q4Lfouap7I3YpuJM5cP1NO1x0Voyv2km1tmZpjUavnKyYT/v
XUCkGrWxeuMkqm68eOnadA7A8BM9b++f6NIgaexb9+Rq8QK74MpMm7/+XMWiAS9z
62hgKBd4mtUulJH1YxoQBIkfRa8pkB45nGiTrL2zzpIOoOirNe3/7FVI9LqPphPN
64ojfqZsTiGrC50R/86/p2jBs0fwrXy8opWM7Kmp1h2oNPqtgOC0Zj7IcmvEp2xa
wI6jN4XxbhDQpo3Iz/KRDxXFT4kAjdLDibWH41PccwSbHvg8zjmAGCxW6sC6bmp6
lywMzonS1VWkp1iNQ2u4bdMeDGnsaN0hOBemBLr/p3L1ee/RAgMBAAGjUDBOMB0G
A1UdDgQWBBSHFEM/GlCxZgg9qpi9REqm/RDkZDAfBgNVHSMEGDAWgBSHFEM/GlCx
Zgg9qpi9REqm/RDkZDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQBG
AtowRS0Wsr9cVRKVxEM/7ZxCDcrTg7gUBD/S8RYnS2bJp5ut/3SgO0FZsQKG4k8O
CXE/dQgwIaBqxSioE3L/l+m/+gedZgqaXg7l6EJLr20sUB5PVrJoQznMIwr/FuYZ
LG4nKK/K7eKf2m1Gn54kpeWz+BtgIRU4YPkZHGtQW3ER+wnmlPQfGDiN0JymqR80
TTXlgg03L6jCFQpYGKCLbKpql+cBixmI6TeUtArosCsqZokUXNM7j5u7m1IhY1EL
pNpSaUMU7LmHOmfnxIHzmNzages+mxKOHJLKBbuQx0u87uGy3HInwbNK7hDHXWLF
mXPXDhrWjBbm1RPnq8cX9nFuPS6Cd+hROEr+VB7m+Sij5QyV5pRBS0x/54tiiEv3
8eIFl6aYqTBcCMrtlxVn8sHcA/iGrysIuidWVxQfs4wmM/apR5YgSjTvN/OAB5Mo
/5RWdxBg3jNPGk/GzPDk6FcN5kp7yRLLyAOAnPDUQRC8CkSkyOwriOMe310CnTL4
KCWp7UpoF/qZJEGhYffH85SORpxj09284tZUnLSthnRmIdYB2kWg9AARu3Vhugx8
E9HGSZzTGAsPEBikDbpUimN0zWLw8VJKL+KJURl4dX4tDRe+R2u5cWm8x3HOcDUI
j9aXkPagbL/an2g05K0hIhyANbER7HAZlJ21pJdCIQ==
-----END CERTIFICATE-----
)";
// The private key below is only used for test purposes
// @lint-ignore-every PRIVATEKEY
const std::string kDefaultKeyData = R"(
-----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEAtdmzj5icITxowAvmBY2MtGbYRmIUdagqm3jaifzL5Jl1vXF1
JnSvHr+OXjDxXlqIss2ZuhrVQs1YtLjSYRSipE8RSIGI3dP/ceibMwItnnbFpopL
Wxb35k+xKVOibBXge6klYpBrGm76Kdj3ybEZpmPMeJ7cCjJ2i8P6tZYuPiZJf0Ny
FZsLwNirvG7iop52AcwmWw/eW5iCdFKxn6+VMR78rjULO34YaFWJE0vw2bfBmvEA
ZipPH/OuqxNHyoDeDB88+okkflSmu28dcNL33KLLoxjJYGv8FtnfsDlf2lYIvT1o
sQitAZBa1W4KcE0KtCBgOAPtjj5Dgt+i5qnsjdim4kzlw/U07XHRWjK/aSbW2Zmm
NRq+crJhP+9dQKQatbF64ySqbrx46dp0DsDwEz1v75/o0iBp7Fv35GrxArvgykyb
v/5cxaIBL3PraGAoF3ia1S6UkfVjGhAEiR9FrymQHjmcaJOsvbPOkg6g6Ks17f/s
VUj0uo+mE83riiN+pmxOIasLnRH/zr+naMGzR/CtfLyilYzsqanWHag0+q2A4LRm
Pshya8SnbFrAjqM3hfFuENCmjcjP8pEPFcVPiQCN0sOJtYfjU9xzBJse+DzOOYAY
LFbqwLpuanqXLAzOidLVVaSnWI1Da7ht0x4Maexo3SE4F6YEuv+ncvV579ECAwEA
AQKCAgBg5/5UC1NIMtTvYmfVlbThfdzKxQF6IX9zElgDKH/O9ihUJ93x/ERF8nZ/
oz08tqoZ/o5pKltzGdKnm8YgjcqOHMRtCvpQm+SIYxgxenus8kYplZDKndbFGLqj
9zmat53EyEJv393zXChbnI+PH503mf8gWCeSF4osuOclVT6XR/fqpZpqARGmVtBN
vhlv51mjY5Mc+7vWu9LpAhg9rGeooYatnv65WVzQXKSLb/CNVOsLElrQFsPLlyQB
bmjXdQzfENaB/AtCdwHS6EecFBCZtvclltPZWjIgS0J0ul5mD2rgzZS4opLvPmnp
SpateaC2lHox34X8Qxne6CX7HZo8phw1g3Lt5378cAcSOxQGyjCw3k7CS28Uwze6
4t7VSn9VxWviYiIV+sgj0EbEyJ/K2YcRKDTG1+jY3AuuTR7lcTO35MCroaQIpk14
4ywTKT1HSTkPV5bNYB3tD4fHAB24Q9rs7GvZgeGWWv3RQTWVTZXnx3zuy5Uh8quy
0Nu8OAEZcKNo+Qq2iTTMf4m9F7OMkWq3aGzdeTBsiKnkaYKyYrNiSNQHgepO5jBT
jRGgJaA7LUakenb0yCexpz5u06zWWeCHu2f7STaVELFWAzvu5WfFcIZbPIY5zGDR
gwcrOQJGAc6CKZI6QCd/h0ruwux8z0E9UAnrxHYK/oaov2Oj8QKCAQEA6FphCswr
7ZwB+EXLIZ0eIfDEg3ms1+bEjhMxq4if7FUVS8OOJBqhn0Q1Tj+goCuGtZdwmNqA
nTjh2A0MDYkBmqpyY+BiJRA/87qVYESPNObMs39Sk6CwKk0esHiquyiMavj1pqYw
Sje5cEdcB551MncyxL+IjC2GGojAJnolgV1doLh08Y6pHa6OkrwjmQxJc7jDBQEv
6h/m3J9Fp1cjdkiM8A3MWW/LomZUEqQerjnW7d0YxbgKk4peGq+kymgZIESuaeaI
36fPy9Md53XAs+eHES/YLbdM54pAQR93fta0GoxkGCc0lEr/z917ybyj5AljYwRq
BiPDEVpyqPHeEwKCAQEAyFuMm5z4crMiE843w1vOiTo17uqG1m7x4qbpY7+TA+nd
d491CPkt7M+eDjlCplHhDYjXWOBKrPnaijemA+GMubOJBJyitNsIq0T+wnwU20PA
THqm7dOuQVeBW9EEmMxLoq7YEFx6CnQMHhWP0JlCRwXTB4ksQsZX6GRUtJ5dAwaQ
ALUuydJ0nVtTFb07WudK654xlkpq5gxB1zljBInHV8hQgsRnXY0SijtGzbenHWvs
jBmXTiOeOBVGehENNxolrLB07JhsXM4/9UAtn+nxESosM0zBGJC79pW3yVb+/7FL
0tEFi4e040ock0BlxVlOBkayAA/hAaaBvAhlUs2nCwKCAQEAosSdcojwxPUi1B9g
W13LfA9EOq4EDQLV8okzpGyDS3WXA4ositI1InMPvI8KIOoc5hz+fbWjn3/3hfgt
11WA0C5TD/BiEIC/rCeq+NNOVsrP33Z0DILmpdt8gjclsxKGu3FH9MQ60+MRfrwe
lh/FDeM+p2FdcIV7ih7+LHYoy+Tx7+MH2SgNBIQB0H0HmvFmizCFPX5FaIeMnETe
8Ik0iGnugUPJQWX1iwCQKLbb30UZcWwPLILutciaf6tHj5s47sfuPrWGcNcH1EtC
iaCNq/mnPrz7fZsIvrK0rGo0taAGbwqmG91rEe8wIReQ3hPN47NH8ldnRoHK5t8r
r3owDQKCAQBWw/avSRn6qgKe6xYQ/wgBO3kxvtSntiIAEmJN9R+YeUWUSkbXnPk7
bWm4JSns1taMQu9nKLKOGCGA67p0Qc/sd4hlu+NmSNiHOvjMhmmNzthPBmqV4a67
00ZM2caQ2SAEEo21ACdFsZ2xxYqjPkuKcEZEJC5LuJNHK3PXSCFldwkTlWLuuboQ
jwT7DBjRNAqo4Lf+qrmCaFp29v4fb/8oz7G1/5H33Gjj/emamua/AgbNYSO6Dgit
puD/abT8YNFh6ISqFRQQWK0v6xwW/XuNAGNlz95rYfpUPd/6TDdfyYrZf/VTyHAY
Yfbf+epYvWThqOnaxwWc7luOb2BZrH+jAoIBAEODPVTsGYwqh5D5wqV1QikczGz4
/37CgGNIWkHvH/dadLDiAQ6DGuMDiJ6pvRQaZCoALdovjzFHH4JDJR6fCkZzKkQs
eaF+jB9pzq3GEXylU9JPIPs58jozC0S9HVsBN3v80jGRTfm5tRvQ6fNJhmYmuxNk
TA+w548kYHiRLAQVGgAqDsIZ1Enx55TaKj60Dquo7d6Bt6xCb+aE4UFtEZNOfEa5
IN+p06Nnnm2ZVTRebTx/WnnG+lTXSOuBuGAGpuOSa3yi84kFfYxBFgGcgUQt4i1M
CzoemuHOSmcvQpU604U+J20FO2gaiYJFxz1h1v+Z/9edY9R9NCwmyFa3LfI=
-----END RSA PRIVATE KEY-----
)";
const std::string kPrime256v1CertData = R"(
-----BEGIN CERTIFICATE-----
MIICkDCCAjWgAwIBAgIJAOILJQbZxXtaMAoGCCqGSM49BAMCMIGjMQswCQYDVQQG
EwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTETMBEGA1UEBwwKTWVubG8gUGFyazER
MA8GA1UECgwIUHJveHlnZW4xETAPBgNVBAsMCFByb3h5Z2VuMREwDwYDVQQDDAhQ
cm94eWdlbjExMC8GCSqGSIb3DQEJARYiZmFjZWJvb2stcHJveHlnZW5AZ29vZ2xl
Z3JvdXBzLmNvbTAeFw0yMDA0MDcyMDMyMDRaFw0zMDA0MDUyMDMyMDRaMIGjMQsw
CQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTETMBEGA1UEBwwKTWVubG8g
UGFyazERMA8GA1UECgwIUHJveHlnZW4xETAPBgNVBAsMCFByb3h5Z2VuMREwDwYD
VQQDDAhQcm94eWdlbjExMC8GCSqGSIb3DQEJARYiZmFjZWJvb2stcHJveHlnZW5A
Z29vZ2xlZ3JvdXBzLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABB5MtBjA
TaKYREMWTIbzK6utt7Jjb3xWcWowKeN14WFz8sDqvHcAufaN8OP2NBHRAZGi4UDs
1thkXHtSPcc7DT+jUDBOMB0GA1UdDgQWBBSWhUXpZWkCj6YywA8iZIvl52GvzDAf
BgNVHSMEGDAWgBSWhUXpZWkCj6YywA8iZIvl52GvzDAMBgNVHRMEBTADAQH/MAoG
CCqGSM49BAMCA0kAMEYCIQCduzLSWUJ2RgxYvNiApmmH9Yml/s7T2bB2r6+1wlPw
OgIhAPfLxzClQvbpPvchgQkWEJTsMgmI/CgNWX02SIzeg934
-----END CERTIFICATE-----
)";
const std::string kPrime256v1KeyData = R"(
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg/NeWSkmQEmaO2f0T
5ogGmfvwGId3k5i8o8hJOoV9pOuhRANCAAQeTLQYwE2imERDFkyG8yurrbeyY298
VnFqMCnjdeFhc/LA6rx3ALn2jfDj9jQR0QGRouFA7NbYZFx7Uj3HOw0/
-----END PRIVATE KEY-----
)";
}; // namespace
namespace quic { namespace samples {
FizzServerContextPtr createFizzServerContext(const HQParams& params) {
std::string certData = kDefaultCertData;
if (!params.certificateFilePath.empty()) {
folly::readFile(params.certificateFilePath.c_str(), certData);
}
std::string keyData = kDefaultKeyData;
if (!params.keyFilePath.empty()) {
folly::readFile(params.keyFilePath.c_str(), keyData);
}
auto cert = fizz::CertUtils::makeSelfCert(certData, keyData);
auto certManager = std::make_shared<fizz::server::CertManager>();
certManager->addCert(std::move(cert), true);
auto cert2 =
fizz::CertUtils::makeSelfCert(kPrime256v1CertData, kPrime256v1KeyData);
certManager->addCert(std::move(cert2), false);
auto serverCtx = std::make_shared<fizz::server::FizzServerContext>();
serverCtx->setCertManager(certManager);
auto ticketCipher = std::make_shared<fizz::server::Aead128GCMTicketCipher<
fizz::server::TicketCodec<fizz::server::CertificateStorage::X509>>>(
serverCtx->getFactoryPtr(), std::move(certManager));
std::array<uint8_t, 32> ticketSeed;
folly::Random::secureRandom(ticketSeed.data(), ticketSeed.size());
ticketCipher->setTicketSecrets({{folly::range(ticketSeed)}});
serverCtx->setTicketCipher(ticketCipher);
serverCtx->setClientAuthMode(params.clientAuth);
serverCtx->setSupportedAlpns(params.supportedAlpns);
serverCtx->setAlpnMode(fizz::server::AlpnMode::Required);
serverCtx->setSendNewSessionTicket(false);
serverCtx->setEarlyDataFbOnly(false);
serverCtx->setVersionFallbackEnabled(false);
fizz::server::ClockSkewTolerance tolerance;
tolerance.before = std::chrono::minutes(-5);
tolerance.after = std::chrono::minutes(5);
std::shared_ptr<fizz::server::ReplayCache> replayCache =
std::make_shared<fizz::server::AllowAllReplayReplayCache>();
serverCtx->setEarlyDataSettings(true, tolerance, std::move(replayCache));
return serverCtx;
}
FizzClientContextPtr createFizzClientContext(const HQParams& params) {
auto ctx = std::make_shared<fizz::client::FizzClientContext>();
std::string certData = kDefaultCertData;
if (!params.certificateFilePath.empty()) {
folly::readFile(params.certificateFilePath.c_str(), certData);
}
std::string keyData = kDefaultKeyData;
if (!params.keyFilePath.empty()) {
folly::readFile(params.keyFilePath.c_str(), keyData);
}
auto cert = fizz::CertUtils::makeSelfCert(certData, keyData);
ctx->setClientCertificate(std::move(cert));
ctx->setSupportedAlpns(params.supportedAlpns);
ctx->setDefaultShares(
{fizz::NamedGroup::x25519, fizz::NamedGroup::secp256r1});
ctx->setSendEarlyData(params.earlyData);
auto mgr = std::make_shared<fizz::CertDecompressionManager>();
mgr->setDecompressors(
{std::make_shared<fizz::ZstdCertificateDecompressor>(),
std::make_shared<fizz::ZlibCertificateDecompressor>()});
ctx->setCertDecompressionManager(std::move(mgr));
return ctx;
}
wangle::SSLContextConfig createSSLContext(const HQParams& params) {
wangle::SSLContextConfig sslCfg;
sslCfg.isDefault = true;
sslCfg.clientVerification =
folly::SSLContext::VerifyClientCertificate::DO_NOT_REQUEST;
if (!params.certificateFilePath.empty() && !params.keyFilePath.empty()) {
sslCfg.setCertificate(params.certificateFilePath, params.keyFilePath, "");
} else {
sslCfg.setCertificateBuf(kDefaultCertData, kDefaultKeyData);
}
sslCfg.setNextProtocols({"h2"});
return sslCfg;
}
}} // namespace quic::samples
|
// Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
/******************************************************************************\
Copyright (c) 2005-2020, Intel Corporation
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 of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <algorithm>
#include <utility>
#include <vector>
#include "peak.hpp"
namespace human_pose_estimation {
Peak::Peak(const int id, const cv::Point2f& pos, const float score)
: id(id),
pos(pos),
score(score) {}
HumanPoseByPeaksIndices::HumanPoseByPeaksIndices(const int keypointsNumber)
: peaksIndices(std::vector<int>(keypointsNumber, -1)),
nJoints(0),
score(0.0f) {}
TwoJointsConnection::TwoJointsConnection(const int firstJointIdx,
const int secondJointIdx,
const float score)
: firstJointIdx(firstJointIdx),
secondJointIdx(secondJointIdx),
score(score) {}
void findPeaks(const std::vector<cv::Mat>& heatMaps,
const float minPeaksDistance,
std::vector<std::vector<Peak> >& allPeaks,
int heatMapId) {
const float threshold = 0.1f;
std::vector<cv::Point> peaks;
const cv::Mat& heatMap = heatMaps[heatMapId];
const float* heatMapData = heatMap.ptr<float>();
size_t heatMapStep = heatMap.step1();
for (int y = -1; y < heatMap.rows + 1; y++) {
for (int x = -1; x < heatMap.cols + 1; x++) {
float val = 0;
if (x >= 0
&& y >= 0
&& x < heatMap.cols
&& y < heatMap.rows) {
val = heatMapData[y * heatMapStep + x];
val = val >= threshold ? val : 0;
}
float left_val = 0;
if (y >= 0
&& x < (heatMap.cols - 1)
&& y < heatMap.rows) {
left_val = heatMapData[y * heatMapStep + x + 1];
left_val = left_val >= threshold ? left_val : 0;
}
float right_val = 0;
if (x > 0
&& y >= 0
&& y < heatMap.rows) {
right_val = heatMapData[y * heatMapStep + x - 1];
right_val = right_val >= threshold ? right_val : 0;
}
float top_val = 0;
if (x >= 0
&& x < heatMap.cols
&& y < (heatMap.rows - 1)) {
top_val = heatMapData[(y + 1) * heatMapStep + x];
top_val = top_val >= threshold ? top_val : 0;
}
float bottom_val = 0;
if (x >= 0
&& y > 0
&& x < heatMap.cols) {
bottom_val = heatMapData[(y - 1) * heatMapStep + x];
bottom_val = bottom_val >= threshold ? bottom_val : 0;
}
if ((val > left_val)
&& (val > right_val)
&& (val > top_val)
&& (val > bottom_val)) {
peaks.push_back(cv::Point(x, y));
}
}
}
std::sort(peaks.begin(), peaks.end(), [](const cv::Point& a, const cv::Point& b) {
return a.x < b.x;
});
std::vector<bool> isActualPeak(peaks.size(), true);
int peakCounter = 0;
std::vector<Peak>& peaksWithScoreAndID = allPeaks[heatMapId];
for (size_t i = 0; i < peaks.size(); i++) {
if (isActualPeak[i]) {
for (size_t j = i + 1; j < peaks.size(); j++) {
if (sqrt((peaks[i].x - peaks[j].x) * (peaks[i].x - peaks[j].x) +
(peaks[i].y - peaks[j].y) * (peaks[i].y - peaks[j].y)) < minPeaksDistance) {
isActualPeak[j] = false;
}
}
peaksWithScoreAndID.push_back(Peak(peakCounter++, peaks[i], heatMap.at<float>(peaks[i])));
}
}
}
std::vector<HumanPose> groupPeaksToPoses(const std::vector<std::vector<Peak> >& allPeaks,
const std::vector<cv::Mat>& pafs,
const size_t keypointsNumber,
const float midPointsScoreThreshold,
const float foundMidPointsRatioThreshold,
const int minJointsNumber,
const float minSubsetScore) {
static const std::vector<std::pair<int, int> > limbIdsHeatmap = {
{2, 3}, {2, 6}, {3, 4}, {4, 5}, {6, 7}, {7, 8}, {2, 9}, {9, 10}, {10, 11}, {2, 12}, {12, 13}, {13, 14},
{2, 1}, {1, 15}, {15, 17}, {1, 16}, {16, 18}, {3, 17}, {6, 18}
};
static const std::vector<std::pair<int, int> > limbIdsPaf = {
{31, 32}, {39, 40}, {33, 34}, {35, 36}, {41, 42}, {43, 44}, {19, 20}, {21, 22}, {23, 24}, {25, 26},
{27, 28}, {29, 30}, {47, 48}, {49, 50}, {53, 54}, {51, 52}, {55, 56}, {37, 38}, {45, 46}
};
std::vector<Peak> candidates;
for (const auto& peaks : allPeaks) {
candidates.insert(candidates.end(), peaks.begin(), peaks.end());
}
std::vector<HumanPoseByPeaksIndices> subset(0, HumanPoseByPeaksIndices(keypointsNumber));
for (size_t k = 0; k < limbIdsPaf.size(); k++) {
std::vector<TwoJointsConnection> connections;
const int mapIdxOffset = keypointsNumber + 1;
std::pair<cv::Mat, cv::Mat> scoreMid = { pafs[limbIdsPaf[k].first - mapIdxOffset],
pafs[limbIdsPaf[k].second - mapIdxOffset] };
const int idxJointA = limbIdsHeatmap[k].first - 1;
const int idxJointB = limbIdsHeatmap[k].second - 1;
const std::vector<Peak>& candA = allPeaks[idxJointA];
const std::vector<Peak>& candB = allPeaks[idxJointB];
const size_t nJointsA = candA.size();
const size_t nJointsB = candB.size();
if (nJointsA == 0
&& nJointsB == 0) {
continue;
} else if (nJointsA == 0) {
for (size_t i = 0; i < nJointsB; i++) {
int num = 0;
for (size_t j = 0; j < subset.size(); j++) {
if (subset[j].peaksIndices[idxJointB] == candB[i].id) {
num++;
continue;
}
}
if (num == 0) {
HumanPoseByPeaksIndices personKeypoints(keypointsNumber);
personKeypoints.peaksIndices[idxJointB] = candB[i].id;
personKeypoints.nJoints = 1;
personKeypoints.score = candB[i].score;
subset.push_back(personKeypoints);
}
}
continue;
} else if (nJointsB == 0) {
for (size_t i = 0; i < nJointsA; i++) {
int num = 0;
for (size_t j = 0; j < subset.size(); j++) {
if (subset[j].peaksIndices[idxJointA] == candA[i].id) {
num++;
continue;
}
}
if (num == 0) {
HumanPoseByPeaksIndices personKeypoints(keypointsNumber);
personKeypoints.peaksIndices[idxJointA] = candA[i].id;
personKeypoints.nJoints = 1;
personKeypoints.score = candA[i].score;
subset.push_back(personKeypoints);
}
}
continue;
}
std::vector<TwoJointsConnection> tempJointConnections;
for (size_t i = 0; i < nJointsA; i++) {
for (size_t j = 0; j < nJointsB; j++) {
cv::Point2f pt = candA[i].pos * 0.5 + candB[j].pos * 0.5;
cv::Point mid = cv::Point(cvRound(pt.x), cvRound(pt.y));
cv::Point2f vec = candB[j].pos - candA[i].pos;
double norm_vec = cv::norm(vec);
if (norm_vec == 0) {
continue;
}
vec /= norm_vec;
float score = vec.x * scoreMid.first.at<float>(mid) + vec.y * scoreMid.second.at<float>(mid);
int height_n = pafs[0].rows / 2;
float suc_ratio = 0.0f;
float mid_score = 0.0f;
const int mid_num = 10;
const float scoreThreshold = -100.0f;
if (score > scoreThreshold) {
float p_sum = 0;
int p_count = 0;
cv::Size2f step((candB[j].pos.x - candA[i].pos.x)/(mid_num - 1),
(candB[j].pos.y - candA[i].pos.y)/(mid_num - 1));
for (int n = 0; n < mid_num; n++) {
cv::Point midPoint(cvRound(candA[i].pos.x + n * step.width),
cvRound(candA[i].pos.y + n * step.height));
cv::Point2f pred(scoreMid.first.at<float>(midPoint),
scoreMid.second.at<float>(midPoint));
score = vec.x * pred.x + vec.y * pred.y;
if (score > midPointsScoreThreshold) {
p_sum += score;
p_count++;
}
}
suc_ratio = static_cast<float>(p_count / mid_num);
float ratio = p_count > 0 ? p_sum / p_count : 0.0f;
mid_score = ratio + static_cast<float>(std::min(height_n / norm_vec - 1, 0.0));
}
if (mid_score > 0
&& suc_ratio > foundMidPointsRatioThreshold) {
tempJointConnections.push_back(TwoJointsConnection(i, j, mid_score));
}
}
}
if (!tempJointConnections.empty()) {
std::sort(tempJointConnections.begin(), tempJointConnections.end(),
[](const TwoJointsConnection& a,
const TwoJointsConnection& b) {
return (a.score > b.score);
});
}
size_t num_limbs = std::min(nJointsA, nJointsB);
size_t cnt = 0;
std::vector<int> occurA(nJointsA, 0);
std::vector<int> occurB(nJointsB, 0);
for (size_t row = 0; row < tempJointConnections.size(); row++) {
if (cnt == num_limbs) {
break;
}
const int& indexA = tempJointConnections[row].firstJointIdx;
const int& indexB = tempJointConnections[row].secondJointIdx;
const float& score = tempJointConnections[row].score;
if (occurA[indexA] == 0
&& occurB[indexB] == 0) {
connections.push_back(TwoJointsConnection(candA[indexA].id, candB[indexB].id, score));
cnt++;
occurA[indexA] = 1;
occurB[indexB] = 1;
}
}
if (connections.empty()) {
continue;
}
bool extraJointConnections = (k == 17 || k == 18);
if (k == 0) {
subset = std::vector<HumanPoseByPeaksIndices>(
connections.size(), HumanPoseByPeaksIndices(keypointsNumber));
for (size_t i = 0; i < connections.size(); i++) {
const int& indexA = connections[i].firstJointIdx;
const int& indexB = connections[i].secondJointIdx;
subset[i].peaksIndices[idxJointA] = indexA;
subset[i].peaksIndices[idxJointB] = indexB;
subset[i].nJoints = 2;
subset[i].score = candidates[indexA].score + candidates[indexB].score + connections[i].score;
}
} else if (extraJointConnections) {
for (size_t i = 0; i < connections.size(); i++) {
const int& indexA = connections[i].firstJointIdx;
const int& indexB = connections[i].secondJointIdx;
for (size_t j = 0; j < subset.size(); j++) {
if (subset[j].peaksIndices[idxJointA] == indexA
&& subset[j].peaksIndices[idxJointB] == -1) {
subset[j].peaksIndices[idxJointB] = indexB;
} else if (subset[j].peaksIndices[idxJointB] == indexB
&& subset[j].peaksIndices[idxJointA] == -1) {
subset[j].peaksIndices[idxJointA] = indexA;
}
}
}
continue;
} else {
for (size_t i = 0; i < connections.size(); i++) {
const int& indexA = connections[i].firstJointIdx;
const int& indexB = connections[i].secondJointIdx;
bool num = false;
for (size_t j = 0; j < subset.size(); j++) {
if (subset[j].peaksIndices[idxJointA] == indexA) {
subset[j].peaksIndices[idxJointB] = indexB;
subset[j].nJoints++;
subset[j].score += candidates[indexB].score + connections[i].score;
num = true;
}
}
if (!num) {
HumanPoseByPeaksIndices hpWithScore(keypointsNumber);
hpWithScore.peaksIndices[idxJointA] = indexA;
hpWithScore.peaksIndices[idxJointB] = indexB;
hpWithScore.nJoints = 2;
hpWithScore.score = candidates[indexA].score + candidates[indexB].score + connections[i].score;
subset.push_back(hpWithScore);
}
}
}
}
std::vector<HumanPose> poses;
for (const auto& subsetI : subset) {
if (subsetI.nJoints < minJointsNumber
|| subsetI.score / subsetI.nJoints < minSubsetScore) {
continue;
}
int position = -1;
HumanPose pose(std::vector<cv::Point2f>(keypointsNumber, cv::Point2f(-1.0f, -1.0f)),
subsetI.score * std::max(0, subsetI.nJoints - 1));
for (const auto& peakIdx : subsetI.peaksIndices) {
position++;
if (peakIdx >= 0) {
pose.keypoints[position] = candidates[peakIdx].pos;
pose.keypoints[position].x += 0.5;
pose.keypoints[position].y += 0.5;
}
}
poses.push_back(pose);
}
return poses;
}
} // namespace human_pose_estimation
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* VariableTypeInfo.cc (C) 2000-2020 */
/* */
/* Infos caractérisant le type d'une variable. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/VariableTypeInfo.h"
#include "arcane/utils/StringBuilder.h"
#include "arcane/utils/String.h"
#include "arcane/datatype/DataStorageTypeInfo.h"
#include "arcane/VariableInfo.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Arcane
{
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
String VariableTypeInfo::
_buildFullTypeName() const
{
StringBuilder full_type_b;
full_type_b = dataTypeName(dataType());
full_type_b += ".";
full_type_b += itemKindName(itemKind());
full_type_b += ".";
full_type_b += dimension();
full_type_b += ".";
full_type_b += multiTag();
if (isPartial())
full_type_b += ".Partial";
return full_type_b.toString();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
String VariableTypeInfo::
fullName() const
{
return _buildFullTypeName();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
DataStorageTypeInfo VariableTypeInfo::
_internalDefaultDataStorage() const
{
return VariableInfo::_internalGetStorageTypeInfo(m_data_type,m_dimension,m_multi_tag);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // End namespace Arcane
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
|
// OTUS C++ Basic course homework skeleton.
// Lexer interface
#pragma once
#include <istream>
#include <string>
class Lexer {
public:
enum class Token {
Number,
Operator,
End,
Lbrace,
Rbrace,
Name,
};
explicit Lexer(std::istream &in);
Lexer(const Lexer &other) = delete;
Lexer &operator=(const Lexer &other) = delete;
Token next_token();
int get_number() const { return number_; }
std::string get_operator() const { return operator_; }
std::string get_name() const { return name_; }
protected:
bool isbrace(char ch) const;
bool isoperator(char ch) const;
private:
enum class State {
Empty,
ReadNumber,
ReadName,
End,
};
char next_char();
bool end() const;
State state_;
std::string name_;
int number_;
std::string operator_;
char ch_;
std::istream &in_;
};
inline Lexer::Lexer(std::istream &in)
: state_(State::Empty)
, number_(0)
, in_(in) {
next_char();
}
inline char Lexer::next_char() {
in_.get(ch_);
return ch_;
}
inline bool Lexer::end() const { return in_.eof() || ch_ == '\n'; }
inline bool Lexer::isbrace(char ch) const { return ch == '(' || ch == ')'; }
inline bool Lexer::isoperator(char ch) const {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
|
/** ExaTN::Numerics: Tensor network builder factory
REVISION: 2019/11/01
Copyright (C) 2018-2019 Dmitry I. Lyakh (Liakh)
Copyright (C) 2018-2019 Oak Ridge National Laboratory (UT-Battelle) **/
/** Rationale:
(a) Creates tensor network builders of desired kind.
**/
#ifndef EXATN_NUMERICS_NETWORK_BUILD_FACTORY_HPP_
#define EXATN_NUMERICS_NETWORK_BUILD_FACTORY_HPP_
#include "tensor_basic.hpp"
#include "network_builder.hpp"
#include "network_builder_mps.hpp"
#include "network_builder_tree.hpp"
#include <string>
#include <memory>
#include <map>
#include "errors.hpp"
namespace exatn{
namespace numerics{
class NetworkBuildFactory{
public:
NetworkBuildFactory(const NetworkBuildFactory &) = delete;
NetworkBuildFactory & operator=(const NetworkBuildFactory &) = delete;
NetworkBuildFactory(NetworkBuildFactory &&) noexcept = default;
NetworkBuildFactory & operator=(NetworkBuildFactory &&) noexcept = default;
~NetworkBuildFactory() = default;
/** Registers a new tensor network builder subtype to produce instances of. **/
void registerNetworkBuilder(const std::string & name, createNetworkBuilderFn creator);
/** Creates a new instance of a desired subtype. **/
std::unique_ptr<NetworkBuilder> createNetworkBuilder(const std::string & name);
/** Creates a new instance of a desired subtype. **/
std::shared_ptr<NetworkBuilder> createNetworkBuilderShared(const std::string & name);
/** Returns a pointer to the NetworkBuildFactory singleton. **/
static NetworkBuildFactory * get();
private:
NetworkBuildFactory(); //private ctor
std::map<std::string,createNetworkBuilderFn> factory_map_;
};
} //namespace numerics
} //namespace exatn
#endif //EXATN_NUMERICS_NETWORK_BUILD_FACTORY_HPP_
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__wchar_t_console_ofstream_54d.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-54d.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: console Read input from the console
* GoodSource: Full path and file name
* Sink: ofstream
* BadSink : Open the file named in data using ofstream::open()
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#include <fstream>
using namespace std;
namespace CWE36_Absolute_Path_Traversal__wchar_t_console_ofstream_54
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void badSink_e(wchar_t * data);
void badSink_d(wchar_t * data)
{
badSink_e(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_e(wchar_t * data);
void goodG2BSink_d(wchar_t * data)
{
goodG2BSink_e(data);
}
#endif /* OMITGOOD */
} /* close namespace */
|
//===- SoftplusLower.cpp --------------------------------------------------===//
//
// The ONNC Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <onnc/Transforms/TensorSel/Lower.h>
#include <onnc/Transforms/TensorSel/Standards/SoftplusLower.h>
#include <onnc/IR/Compute/Softplus.h>
#include "DefaultAttributes.h"
#include <onnc/IR/IRBuilder.h>
using namespace onnc;
//===----------------------------------------------------------------------===//
// SoftplusLower
//===----------------------------------------------------------------------===//
SoftplusLower::SoftplusLower()
{
}
SoftplusLower::~SoftplusLower()
{
}
int SoftplusLower::isMe(const xNode& pNode) const
{
if (pNode.kind() == xSymbol("Softplus"))
return kStdLower;
return kNotMe;
}
ComputeOperator*
SoftplusLower::activate(ComputeGraph& pGraph, xNode& pNode) const
{
// check input/output number
if (pNode.inputs().size() != 1)
return nullptr;
if (pNode.outputs().size() != 1)
return nullptr;
// check input/output name
for (xValue* xv : pNode.inputs()) {
if (!xv->has_unique_name())
return nullptr;
}
for (xValue* xv : pNode.outputs()) {
if (!xv->has_unique_name())
return nullptr;
}
// check default attributes
// create operators
onnc::Softplus* op = pGraph.addOperator<onnc::Softplus>();
// set default attributes
SetDefaultAttributes(pNode, *op);
// set optional attributes
// set input/output
for (xValue* xv : pNode.inputs()) {
onnc::Tensor* tensor = pGraph.getValue<onnc::Tensor>(xv->uniqueName());
if (nullptr == tensor)
tensor = IRBuilder::CreateComputeTensor(pGraph, *xv);
op->addInput(*tensor);
}
for (xValue* xv : pNode.outputs()) {
onnc::Tensor* tensor = pGraph.getValue<onnc::Tensor>(xv->uniqueName());
if (nullptr == tensor)
tensor = IRBuilder::CreateComputeTensor(pGraph, *xv);
op->addOutput(*tensor);
}
return op;
}
|
// Copyright 2002 The Trustees of Indiana University.
// 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)
// Boost.MultiArray Library
// Authors: Ronald Garcia
// Jeremy Siek
// Andrew Lumsdaine
// See http://www.boost.org/libs/multi_array for documentation.
//
// fail_cparen.cpp -
// Testing const operator() constness.
//
#include "boost/multi_array.hpp"
#include "boost/test/minimal.hpp"
#include "boost/array.hpp"
int
test_main(int,char*[])
{
const int ndims=3;
typedef boost::multi_array<int,ndims> array;
boost::array<array::size_type,ndims> sma_dims = {{2,3,4}};
int data[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,
14,15,16,17,18,19,20,21,22,23};
const int data_size = 24;
array sma(sma_dims);
sma.assign(data,data+data_size);
const array& csma = sma;
boost::array<array::index,ndims> indices = {{0,0,0}};
// FAIL! Cannot assign to csma
csma(indices) = 5;
return boost::exit_success;
}
|
// TestITree.cpp : Defines the entry point for the console application.
//
// VIT 2014 test project for ITREE.H
// http://blog.coolsoftware.ru/
#include "stdafx.h"
#include "itree.h"
#include <time.h>
#include <limits.h>
#include <iostream>
class observation {
public:
typedef double range_type;
typedef unsigned int id_type;
observation(range_type rHigh, range_type rLow, unsigned short sID)
: m_rHigh(rHigh > rLow ? rHigh : rLow), m_rLow(rLow <= rHigh ? rLow : rHigh), m_sID(sID) {}
range_type low() const { return m_rLow; }
range_type high() const { return m_rHigh; }
id_type id() const { return m_sID; }
private:
range_type m_rHigh, m_rLow;
id_type m_sID;
};
#define MAX_OBS 100000
//#define QUERY_VALUE 1.0
int _tmain(int argc, _TCHAR* argv[])
{
itree<observation> Tree; // The interval tree
srand((unsigned)time(NULL)); // Initialize radnom generator
std::cout << "Constructing intervals vector..." << std::endl;
// Add some intervals to the tree
for (observation::id_type s = 0; s < MAX_OBS; ++s)
{
observation::range_type rHigh, rLow;
rLow = (double)rand() / RAND_MAX * 70.0;
rHigh = rLow + (double)rand() / RAND_MAX * 40.0;
observation obs(rHigh, rLow, s);
Tree.push_back(obs); // use a vector insertion function
}
std::cout << "Constructing query vector..." << std::endl;
std::vector<observation::range_type> query_vec;
for (unsigned int i = 0; i < 100; i++)
{
observation::range_type queryValue = (double)rand() / RAND_MAX * 100.0; //QUERY_VALUE;
query_vec.push_back(queryValue);
}
std::cout << "Constructing itree (" << MAX_OBS <<" items) ..." << std::endl;
clock_t cbegin = clock();
// Put the tree in query mode
itree<observation> const * ConstTree = Tree.construct();
clock_t cend = clock();
std::cout << double(cend - cbegin) / CLOCKS_PER_SEC << " sec." << std::endl;
bool bCheckResults = false;
std::set<observation::id_type> bfresults;
int bfn = 0;
// Use the const iterator to access all intervals sequentially
std::cout << "Brute-force search..." << std::endl;
clock_t bfbegin = clock();
for (unsigned int i = 0; i < query_vec.size(); i++)
{
observation::range_type queryValue = query_vec[i];
//std::cout << "Query value: " << queryValue << std::endl;
for (itree<observation>::const_iterator citer = ConstTree->begin(); citer != ConstTree->end(); ++citer)
{
if ((citer->low() <= queryValue) &&
(citer->high() >= queryValue))
{
if (bCheckResults) bfresults.insert(citer->id());
bfn++;
// std::cout << "ID: " << citer->id()
// << ", Low: " << citer->low()
// << ", High: " << citer->high() << std::endl;
}
}
}
clock_t bfend = clock();
std::cout << bfn << " brute-force search results, " << double(bfend - bfbegin) / CLOCKS_PER_SEC << " sec." << std::endl;
std::set<observation::id_type> qresults;
int qn = 0;
// Use the query iterator to access intervals
std::cout << "Itree search..." << std::endl;
clock_t qbegin = clock();
for (unsigned int i = 0; i < query_vec.size(); i++)
{
observation::range_type queryValue = query_vec[i];
//std::cout << "Query value: " << queryValue << std::endl;
//itree<observation>::query_iterator iter;
for (itree<observation>::query_iterator iter = ConstTree->qbegin(queryValue); iter != ConstTree->qend(queryValue); ++iter)
{
if (bCheckResults) qresults.insert(iter->id());
qn++;
// std::cout << "ID: " << iter->id()
// << ", Low: " << iter->low()
// << ", High: " << iter->high() << std::endl;
}
}
clock_t qend = clock();
std::cout << qn << " itree search results, " << double(qend - qbegin) / CLOCKS_PER_SEC << " sec." << std::endl;
if (bCheckResults)
{
std::cout << "Checking results..." << std::endl;
assert(bfn == qn);
for (std::set<observation::id_type>::const_iterator it = qresults.begin(); it != qresults.end(); ++it)
{
assert(bfresults.find(*it) != bfresults.end());
}
std::cout << "Ok." << std::endl;
}
return 0;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkFEMSolver.h"
#include "itkFEMSpatialObjectReader.h"
#include "itkFEMSpatialObjectWriter.h"
int
itkFEMLoadBCMFCTest(int argc, char * argv[])
{
if (argc < 1)
{
std::cerr << "Missing Spatial Object Filename" << std::endl;
return EXIT_FAILURE;
}
// Need to register default FEM object types,
// and setup SpatialReader to recognize FEM types
// which is all currently done as a HACK in
// the initializaiton of the itk::FEMFactoryBase::GetFactory()
itk::FEMFactoryBase::GetFactory()->RegisterDefaultTypes();
using Solver2DType = itk::fem::Solver<2>;
Solver2DType::Pointer solver = Solver2DType::New();
using FEMSpatialObjectReaderType = itk::FEMSpatialObjectReader<2>;
using FEMSpatialObjectReaderPointer = FEMSpatialObjectReaderType::Pointer;
FEMSpatialObjectReaderPointer SpatialReader = FEMSpatialObjectReaderType::New();
SpatialReader->SetFileName(argv[1]);
// SpatialReader->SetFileName("C:/Research/ITKGit/ITK/Testing/Data/Input/FEM/LoadBCMFCTest.meta");
SpatialReader->Update();
FEMSpatialObjectReaderType::GroupPointer myGroup = SpatialReader->GetGroup();
if (!myGroup)
{
std::cout << "No Group : [FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << " [PASSED]" << std::endl;
// Testing the fe mesh validity
using FEMObjectSpatialObjectType = itk::FEMObjectSpatialObject<2>;
FEMObjectSpatialObjectType::ChildrenListType * children = SpatialReader->GetGroup()->GetChildren();
if (children->front()->GetTypeName() != "FEMObjectSpatialObject")
{
std::cout << " [FAILED]" << std::endl;
return EXIT_FAILURE;
}
FEMObjectSpatialObjectType::Pointer femSO =
dynamic_cast<FEMObjectSpatialObjectType *>((*(children->begin())).GetPointer());
if (!femSO)
{
std::cout << " dynamic_cast [FAILED]" << std::endl;
return EXIT_FAILURE;
}
delete children;
femSO->GetFEMObject()->FinalizeMesh();
// femSO->GetFEMObject()->Solve();
solver->SetInput(femSO->GetFEMObject());
solver->Update();
int numDOF = femSO->GetFEMObject()->GetNumberOfDegreesOfFreedom();
vnl_vector<float> soln(numDOF);
float expectedResult[10] = { 0.283525f, 0.0f, 0.283525f, 1.70115f, 0.283525f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
bool foundError = false;
for (int i = 0; i < numDOF; i++)
{
soln[i] = solver->GetSolution(i);
// std::cout << "Solution[" << i << "]:" << soln[i] << std::endl;
if (std::abs(expectedResult[i] - soln[i]) > 0.0001)
{
std::cout << "ERROR: Index " << i << ". Expected " << expectedResult[i] << " Solution " << soln[i] << std::endl;
foundError = true;
}
}
if (foundError)
{
std::cout << "Test FAILED!" << std::endl;
return EXIT_FAILURE;
}
// to write the deformed mesh
FEMObjectSpatialObjectType::Pointer femSODef = FEMObjectSpatialObjectType::New();
femSODef->SetFEMObject(solver->GetOutput());
using FEMSpatialObjectWriterType = itk::FEMSpatialObjectWriter<2>;
using FEMSpatialObjectWriterPointer = FEMSpatialObjectWriterType::Pointer;
FEMSpatialObjectWriterPointer SpatialWriter = FEMSpatialObjectWriterType::New();
SpatialWriter->SetInput(femSODef);
SpatialWriter->SetFileName(argv[2]);
SpatialWriter->Update();
std::cout << "Test PASSED!" << std::endl;
return EXIT_SUCCESS;
}
|
/* Copyright 2015 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 "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER5(UnaryOp, CPU, "Rsqrt", functor::rsqrt, float, Eigen::half, double,
complex64, complex128);
#if GOOGLE_CUDA
REGISTER3(UnaryOp, GPU, "Rsqrt", functor::rsqrt, float, Eigen::half, double);
#endif
} // namespace tensorflow
|
#ifdef PIXELBOOST_PLATFORM_ANDROID
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif
|
/* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_MINITL_TYPEMANIPULATION_HH_
#define BE_MINITL_TYPEMANIPULATION_HH_
/**************************************************************************************************/
#include <bugengine/minitl/stdafx.h>
namespace minitl {
template < typename T >
struct is_const
{
enum
{
Value = 0
};
};
template < typename T >
struct is_const< const T >
{
enum
{
Value = 1
};
};
template < typename T >
struct remove_const
{
typedef T type;
};
template < typename T >
struct remove_const< const T >
{
typedef T type;
};
template < typename T >
struct is_reference
{
enum
{
Value = 0
};
};
template < typename T >
struct is_reference< T& >
{
enum
{
Value = 1
};
};
template < typename T >
struct remove_reference
{
typedef T type;
};
template < typename T >
struct remove_reference< T& >
{
typedef T type;
};
template < typename T1, typename T2 >
struct type_equals
{
enum
{
Value = 0
};
};
template < typename T >
struct type_equals< T, T >
{
enum
{
Value = 1
};
};
} // namespace minitl
/**************************************************************************************************/
#endif
|
/*
* SimpleMoveSequence.cpp
*
* Created on: Dec 1, 2018
* Author: Developer
*/
#include <Commands/SimpleMoveSequence.h>
#include "Commands/TimedMove.h"
#include "Commands/LeftTurn.h"
SimpleMoveSequence::SimpleMoveSequence() {
// I Made a Square!!!
AddSequential(new TimedMove(1.00, .2, .3));
AddSequential(new LeftTurn(.5, .27));
AddSequential(new TimedMove(1.00, .2, .3));
AddSequential(new LeftTurn(.5, .27));
AddSequential(new TimedMove(1.00, .2, .3));
AddSequential(new LeftTurn(.5, .27));
AddSequential(new TimedMove(1.00, .2, .3));
}
|
// Copyright (c) 2018-2019 The StakeWork Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "consensus/dao.h"
#include "base58.h"
#include "main.h"
#include "rpc/server.h"
#include "utilmoneystr.h"
void GetVersionMask(uint64_t &nProposalMask, uint64_t &nPaymentRequestMask, uint64_t &nConsultationMask, uint64_t &nConsultationAnswerMask, CBlockIndex* pindex)
{
bool fReducedQuorum = IsReducedCFundQuorumEnabled(pindex, Params().GetConsensus());
bool fAbstainVote = IsDAOEnabled(pindex, Params().GetConsensus());
nProposalMask = Params().GetConsensus().nProposalMaxVersion;
nPaymentRequestMask = Params().GetConsensus().nPaymentRequestMaxVersion;
nConsultationMask = Params().GetConsensus().nConsultationMaxVersion;
nConsultationAnswerMask = Params().GetConsensus().nConsultationAnswerMaxVersion;
if (!fReducedQuorum)
{
nProposalMask &= ~CProposal::REDUCED_QUORUM_VERSION;
nPaymentRequestMask &= ~CPaymentRequest::REDUCED_QUORUM_VERSION;
}
if (!fAbstainVote)
{
nProposalMask &= ~CProposal::ABSTAIN_VOTE_VERSION;
nPaymentRequestMask &= ~CPaymentRequest::ABSTAIN_VOTE_VERSION;
}
}
void SetScriptForCommunityFundContribution(CScript &script)
{
script.resize(2);
script[0] = OP_RETURN;
script[1] = OP_CFUND;
}
void SetScriptForProposalVote(CScript &script, uint256 proposalhash, int64_t vote)
{
script.resize(37);
script[0] = OP_RETURN;
script[1] = OP_CFUND;
script[2] = OP_PROP;
script[3] = vote == VoteFlags::VOTE_REMOVE ? OP_REMOVE : (vote == VoteFlags::VOTE_ABSTAIN ? OP_ABSTAIN : (vote == VoteFlags::VOTE_YES ? OP_YES : OP_NO));
script[4] = 0x20;
memcpy(&script[5], proposalhash.begin(), 32);
}
void SetScriptForPaymentRequestVote(CScript &script, uint256 prequesthash, int64_t vote)
{
script.resize(37);
script[0] = OP_RETURN;
script[1] = OP_CFUND;
script[2] = OP_PREQ;
script[3] = vote == VoteFlags::VOTE_REMOVE ? OP_REMOVE : (vote == VoteFlags::VOTE_ABSTAIN ? OP_ABSTAIN : (vote == VoteFlags::VOTE_YES ? OP_YES : OP_NO));
script[4] = 0x20;
memcpy(&script[5], prequesthash.begin(), 32);
}
void SetScriptForConsultationSupport(CScript &script, uint256 hash)
{
script.resize(36);
script[0] = OP_RETURN;
script[1] = OP_DAO;
script[2] = OP_YES;
script[3] = 0x20;
memcpy(&script[4], hash.begin(), 32);
}
void SetScriptForConsultationSupportRemove(CScript &script, uint256 hash)
{
script.resize(36);
script[0] = OP_RETURN;
script[1] = OP_DAO;
script[2] = OP_REMOVE;
script[3] = 0x20;
memcpy(&script[4], hash.begin(), 32);
}
void SetScriptForConsultationVote(CScript &script, uint256 hash, int64_t vote)
{
script.resize(36);
script[0] = OP_RETURN;
script[1] = OP_CONSULTATION;
script[2] = vote == VoteFlags::VOTE_ABSTAIN ? OP_ABSTAIN : OP_ANSWER;
script[3] = 0x20;
memcpy(&script[4], hash.begin(), 32);
if (vote > -1)
script << CScriptNum(vote);
}
void SetScriptForConsultationVoteRemove(CScript &script, uint256 hash)
{
script.resize(36);
script[0] = OP_RETURN;
script[1] = OP_CONSULTATION;
script[2] = OP_REMOVE;
script[3] = 0x20;
memcpy(&script[4], hash.begin(), 32);
}
bool Support(uint256 hash, bool &duplicate)
{
AssertLockHeld(cs_main);
std::string str = hash.ToString();
if (mapSupported.count(hash) > 0)
duplicate = true;
RemoveConfigFile("support", str);
RemoveConfigFile("support", str);
std::string strCmd = "support";
WriteConfigFile(strCmd, str);
mapSupported[hash] = true;
LogPrint("dao", "%s: Supporting %s\n", __func__, str);
return true;
}
bool Vote(uint256 hash, int64_t vote, bool &duplicate)
{
AssertLockHeld(cs_main);
std::string str = hash.ToString();
if (mapAddedVotes.count(hash) > 0 && mapAddedVotes[hash] == vote)
duplicate = true;
RemoveConfigFile("voteyes", str);
RemoveConfigFile("voteabs", str);
RemoveConfigFile("voteno", str);
RemoveConfigFile("addproposalvoteyes", str);
RemoveConfigFile("addproposalvoteabs", str);
RemoveConfigFile("addproposalvoteno", str);
CConsultationAnswer answer;
CStateViewCache view(pcoinsTip);
if (view.GetConsultationAnswer(hash, answer))
{
std::string strParent = answer.parent.ToString();
mapAddedVotes.erase(answer.parent);
RemoveConfigFile("voteyes", strParent);
RemoveConfigFile("voteabs", strParent);
RemoveConfigFile("voteno", strParent);
RemoveConfigFile("addproposalvoteyes", strParent);
RemoveConfigFile("addproposalvoteabs", strParent);
RemoveConfigFile("addproposalvoteno", strParent);
}
std::string strCmd = "voteno";
if (vote == -1)
strCmd = "voteabs";
if (vote == 1)
strCmd = "voteyes";
WriteConfigFile(strCmd, str);
mapAddedVotes[hash] = vote;
LogPrint("dao", "%s: Voting %d for %s\n", __func__, vote, hash.ToString());
return true;
}
bool VoteValue(uint256 hash, int64_t vote, bool &duplicate)
{
AssertLockHeld(cs_main);
std::string str = hash.ToString();
if (mapAddedVotes.count(hash) > 0 && mapAddedVotes[hash] == vote)
duplicate = true;
RemoveConfigFile("vote", str);
WriteConfigFile("vote", str + "~" + to_string(vote));
mapAddedVotes[hash] = vote;
LogPrint("dao", "%s: Voting %d for %s\n", __func__, vote, hash.ToString());
return true;
}
bool RemoveSupport(string str)
{
RemoveConfigFile("support", str);
if (mapSupported.count(uint256S(str)) > 0)
{
mapSupported.erase(uint256S(str));
LogPrint("dao", "%s: Removing support for %s\n", __func__, str);
}
else
return false;
return true;
}
bool RemoveVote(string str)
{
RemoveConfigFile("voteyes", str);
RemoveConfigFile("voteabs", str);
RemoveConfigFile("voteno", str);
RemoveConfigFile("addproposalvoteyes", str);
RemoveConfigFile("addproposalvoteabs", str);
RemoveConfigFile("addproposalvoteno", str);
RemoveConfigFile("addpaymentrequestvoteyes", str);
RemoveConfigFile("addpaymentrequestvoteabs", str);
RemoveConfigFile("addpaymentrequestvoteno", str);
if (mapAddedVotes.count(uint256S(str)) > 0)
{
mapAddedVotes.erase(uint256S(str));
LogPrint("dao", "%s: Removing vote for %s\n", __func__, str);
}
else
return false;
return true;
}
bool RemoveVoteValue(string str)
{
RemoveConfigFilePair("vote", str);
if (mapAddedVotes.count(uint256S(str)) > 0)
{
mapAddedVotes.erase(uint256S(str));
LogPrint("dao", "%s: Removing support for %s\n", __func__, str);
}
else
return false;
return true;
}
bool RemoveVote(uint256 hash)
{
return RemoveVote(hash.ToString());
}
bool IsBeginningCycle(const CBlockIndex* pindex, const CStateViewCache& view)
{
return pindex->nHeight % GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) == 0;
}
bool IsEndCycle(const CBlockIndex* pindex, const CStateViewCache& view)
{
return (pindex->nHeight+1) % GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) == 0;
}
std::string FormatConsensusParameter(Consensus::ConsensusParamsPos pos, std::string string)
{
std::string ret = string;
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_XSW)
ret = FormatMoney(stoll(string)) + " XSW";
else if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_PERCENT)
{
std::ostringstream out;
out.precision(2);
out << std::fixed << (float)stoll(string) / 100.0;
ret = out.str() + "%";
}
else if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_NUMBER)
{
if (pos == Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES || pos == Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES)
{
ret = to_string(stoll(string) + 1);
}
}
return ret;
}
std::string RemoveFormatConsensusParameter(Consensus::ConsensusParamsPos pos, std::string string)
{
string.erase(std::remove_if(string.begin(), string.end(),
[](const char& c ) -> bool { return !std::isdigit(c) && c != '.' && c != ',' && c != '-'; } ), string.end());
std::string ret = string;
try
{
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_XSW)
ret = std::to_string((uint64_t)(stof(string) * COIN));
else if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_PERCENT)
{
ret = std::to_string((uint64_t)(stof(string) * 100));
}
else if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_NUMBER)
{
if (pos == Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES || pos == Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES)
{
ret = to_string(stoll(string) - 1);
}
}
}
catch(...)
{
return "";
}
return ret;
}
std::map<uint256, std::pair<std::pair<int, int>, int>> mapCacheProposalsToUpdate;
std::map<uint256, std::pair<std::pair<int, int>, int>> mapCachePaymentRequestToUpdate;
std::map<uint256, int> mapCacheSupportToUpdate;
std::map<std::pair<uint256, int64_t>, int> mapCacheConsultationToUpdate;
uint256 lastConsensusStateHash;
bool VoteStep(const CValidationState& state, CBlockIndex *pindexNew, const bool fUndo, CStateViewCache& view)
{
AssertLockHeld(cs_main);
const CBlockIndex* pindexDelete;
if (fUndo)
{
pindexDelete = pindexNew;
pindexNew = pindexNew->pprev;
assert(pindexNew);
}
int64_t nTimeStart = GetTimeMicros();
auto nCycleLength = GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view);
int nBlocks = (pindexNew->nHeight % nCycleLength) + 1;
const CBlockIndex* pindexblock = pindexNew;
bool fCFund = IsCommunityFundEnabled(pindexNew->pprev, Params().GetConsensus());
bool fDAOConsultations = IsDAOEnabled(pindexNew->pprev, Params().GetConsensus());
bool fScanningWholeCycle = false;
std::map<uint256, bool> mapSeen;
std::map<uint256, bool> mapSeenSupport;
uint256 consensusStateHash = GetConsensusStateHash(view);
if (fUndo || lastConsensusStateHash != consensusStateHash || nBlocks == 1 ||
(mapCacheProposalsToUpdate.empty() && mapCachePaymentRequestToUpdate.empty() && mapCacheSupportToUpdate.empty() && mapCacheConsultationToUpdate.empty())) {
mapCacheProposalsToUpdate.clear();
mapCachePaymentRequestToUpdate.clear();
mapCacheSupportToUpdate.clear();
mapCacheConsultationToUpdate.clear();
fScanningWholeCycle = true;
} else {
nBlocks = 1;
}
int64_t nTimeStart2 = GetTimeMicros();
LogPrint("dao", "%s: Scanning %d block(s) starting at %d (fUndo=%d fScanningWholeCycle=%d consensusChanged=%d). We are in block %d inside of the cycle.\n",
__func__, nBlocks, pindexblock->nHeight, fUndo, fScanningWholeCycle, lastConsensusStateHash != consensusStateHash,
(pindexNew->nHeight % nCycleLength) + 1);
lastConsensusStateHash = consensusStateHash;
while(nBlocks > 0 && pindexblock != NULL)
{
CProposal proposal;
CPaymentRequest prequest;
CConsultation consultation;
CConsultationAnswer answer;
mapSeen.clear();
mapSeenSupport.clear();
if (fCFund)
{
auto pVotes = GetProposalVotes(pindexblock->GetBlockHash());
if (pVotes != nullptr)
{
for(unsigned int i = 0; i < pVotes->size(); i++)
{
if(mapSeen.count((*pVotes)[i].first) == 0)
{
LogPrint("daoextra", "%s: Found vote %d for proposal %s at block height %d\n", __func__,
(*pVotes)[i].second, (*pVotes)[i].first.ToString(),
pindexblock->nHeight);
if(mapCacheProposalsToUpdate.count((*pVotes)[i].first) == 0)
mapCacheProposalsToUpdate[(*pVotes)[i].first] = make_pair(make_pair(0, 0), 0);
if((*pVotes)[i].second == VoteFlags::VOTE_YES)
mapCacheProposalsToUpdate[(*pVotes)[i].first].first.first += 1;
else if((*pVotes)[i].second == VoteFlags::VOTE_ABSTAIN)
mapCacheProposalsToUpdate[(*pVotes)[i].first].second += 1;
else if((*pVotes)[i].second == VoteFlags::VOTE_NO)
mapCacheProposalsToUpdate[(*pVotes)[i].first].first.second += 1;
mapSeen[(*pVotes)[i].first]=true;
}
}
}
auto prVotes = GetPaymentRequestVotes(pindexblock->GetBlockHash());
if (prVotes != nullptr)
{
for(unsigned int i = 0; i < prVotes->size(); i++)
{
if(mapSeen.count((*prVotes)[i].first) == 0)
{
LogPrint("daoextra", "%s: Found vote %d for payment request %s at block height %d\n", __func__,
(*prVotes)[i].second, (*prVotes)[i].first.ToString(),
pindexblock->nHeight);
if(mapCachePaymentRequestToUpdate.count((*prVotes)[i].first) == 0)
mapCachePaymentRequestToUpdate[(*prVotes)[i].first] = make_pair(make_pair(0, 0), 0);
if((*prVotes)[i].second == VoteFlags::VOTE_YES)
mapCachePaymentRequestToUpdate[(*prVotes)[i].first].first.first += 1;
else if((*prVotes)[i].second == VoteFlags::VOTE_ABSTAIN)
mapCachePaymentRequestToUpdate[(*prVotes)[i].first].second += 1;
else if((*prVotes)[i].second == VoteFlags::VOTE_NO)
mapCachePaymentRequestToUpdate[(*prVotes)[i].first].first.second += 1;
mapSeen[(*prVotes)[i].first]=true;
}
}
}
}
if (fDAOConsultations)
{
auto supp = GetSupport(pindexblock->GetBlockHash());
if (supp != nullptr)
{
for (auto& it: *supp)
{
if (!it.second)
continue;
if (!mapSeenSupport.count(it.first))
{
LogPrint("daoextra", "%s: Found support vote for %s at block height %d\n", __func__,
it.first.ToString(),
pindexblock->nHeight);
if(mapCacheSupportToUpdate.count(it.first) == 0)
mapCacheSupportToUpdate[it.first] = 0;
mapCacheSupportToUpdate[it.first] += 1;
mapSeenSupport[it.first]=true;
}
}
}
auto cVotes = GetConsultationVotes(pindexblock->GetBlockHash());
if (cVotes != nullptr)
{
for (auto&it: *cVotes)
{
if (mapSeen.count(it.first))
continue;
if (view.HaveConsultation(it.first) || view.HaveConsultationAnswer(it.first))
{
if (it.second == VoteFlags::VOTE_ABSTAIN && view.GetConsultationAnswer(it.first, answer))
{
if(mapCacheConsultationToUpdate.count(std::make_pair(answer.parent,it.second)) == 0)
mapCacheConsultationToUpdate[std::make_pair(answer.parent,it.second)] = 0;
mapCacheConsultationToUpdate[std::make_pair(answer.parent,it.second)] += 1;
mapSeen[it.first]=true;
LogPrint("daoextra", "%s: Found consultation answer vote %d for %s at block height %d (total %d)\n", __func__,
it.second, answer.parent.ToString(), pindexblock->nHeight, mapCacheConsultationToUpdate[std::make_pair(answer.parent,it.second)]);
}
else
{
if(mapCacheConsultationToUpdate.count(std::make_pair(it.first,it.second)) == 0)
mapCacheConsultationToUpdate[std::make_pair(it.first,it.second)] = 0;
mapCacheConsultationToUpdate[std::make_pair(it.first,it.second)] += 1;
mapSeen[it.first]=true;
LogPrint("daoextra", "%s: Found consultation vote %d for %s at block height %d (total %d)\n", __func__,
it.second, it.first.ToString(), pindexblock->nHeight, mapCacheConsultationToUpdate[std::make_pair(it.first,it.second)]);
}
}
}
}
}
pindexblock = pindexblock->pprev;
nBlocks--;
}
mapSeen.clear();
mapSeenSupport.clear();
int64_t nTimeEnd2 = GetTimeMicros();
LogPrint("bench", " - CFund count votes from headers: %.2fms\n", (nTimeEnd2 - nTimeStart2) * 0.001);
int64_t nTimeStart3 = GetTimeMicros();
bool fLog = LogAcceptCategory("dao");
if (fCFund)
{
for(auto& it: mapCacheProposalsToUpdate)
{
if (view.HaveProposal(it.first))
{
CProposalModifier proposal = view.ModifyProposal(it.first, pindexNew->nHeight);
if (proposal->txblockhash == uint256())
continue;
if (mapBlockIndex.count(proposal->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of proposal %s\n",
__func__, proposal->txblockhash.ToString(), proposal->hash.ToString());
continue;
}
CBlockIndex* pblockindex = mapBlockIndex[proposal->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view) + 1);
if(fUndo)
{
proposal->ClearState(pindexDelete);
if(proposal->GetLastState() == DAOFlags::NIL)
proposal->nVotingCycle = nVotingCycles;
proposal->fDirty = true;
}
if (!proposal->CanVote(view))
continue;
proposal->nVotesYes = it.second.first.first;
proposal->nVotesAbs = it.second.second;
proposal->nVotesNo = it.second.first.second;
proposal->fDirty = true;
mapSeen[proposal->hash]=true;
}
}
for(auto& it: mapCachePaymentRequestToUpdate)
{
if(view.HavePaymentRequest(it.first))
{
CPaymentRequestModifier prequest = view.ModifyPaymentRequest(it.first, pindexNew->nHeight);
if (prequest->txblockhash == uint256())
continue;
CBlockIndex* pblockindex = mapBlockIndex[prequest->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view) + 1);
if(fUndo)
{
prequest->ClearState(pindexDelete);
if(prequest->GetLastState() == DAOFlags::NIL)
prequest->nVotingCycle = nVotingCycles;
prequest->fDirty = true;
}
if (!prequest->CanVote(view))
continue;
prequest->nVotesYes = it.second.first.first;
prequest->nVotesAbs = it.second.second;
prequest->nVotesNo = it.second.first.second;
prequest->fDirty = true;
mapSeen[prequest->hash]=true;
}
}
}
if (fDAOConsultations)
{
for(auto& it: mapCacheSupportToUpdate)
{
if (view.HaveConsultation(it.first))
{
CConsultationModifier consultation = view.ModifyConsultation(it.first, pindexNew->nHeight);
if (consultation->txblockhash == uint256())
continue;
if (mapBlockIndex.count(consultation->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of consultation %s\n",
__func__, consultation->txblockhash.ToString(), consultation->hash.ToString());
continue;
}
CBlockIndex* pblockindex = mapBlockIndex[consultation->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min((uint64_t)nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view));
if(fUndo)
{
consultation->ClearState(pindexDelete);
auto newState = consultation->GetLastState();
if (newState != DAOFlags::EXPIRED && newState != DAOFlags::PASSED)
consultation->nVotingCycle = nVotingCycles;
consultation->fDirty = true;
}
if (!consultation->CanBeSupported())
continue;
consultation->nSupport = it.second;
consultation->fDirty = true;
mapSeenSupport[consultation->hash]=true;
}
else if (view.HaveConsultationAnswer(it.first))
{
CConsultationAnswerModifier answer = view.ModifyConsultationAnswer(it.first, pindexNew->nHeight);
if (answer->txblockhash == uint256())
continue;
if (mapBlockIndex.count(answer->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of answer %s\n",
__func__, answer->txblockhash.ToString(), answer->hash.ToString());
continue;
}
if(fUndo)
{
answer->ClearState(pindexDelete);
answer->fDirty = true;
}
if (!answer->CanBeSupported(view))
continue;
answer->nSupport = it.second;
answer->fDirty = true;
mapSeenSupport[answer->hash]=true;
}
}
std::map<uint256, bool> mapAlreadyCleared;
for(auto& it: mapCacheConsultationToUpdate)
{
if (view.HaveConsultation(it.first.first))
{
CConsultationModifier consultation = view.ModifyConsultation(it.first.first, pindexNew->nHeight);
if (consultation->txblockhash == uint256())
continue;
if (mapBlockIndex.count(consultation->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of consultation %s\n",
__func__, consultation->txblockhash.ToString(), consultation->hash.ToString());
continue;
}
CBlockIndex* pblockindex = mapBlockIndex[consultation->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view) + 1);
if(fUndo)
{
consultation->ClearState(pindexDelete);
auto newState = consultation->GetLastState();
if (newState != DAOFlags::EXPIRED && newState != DAOFlags::PASSED)
consultation->nVotingCycle = nVotingCycles;
consultation->fDirty = true;
}
if (!(consultation->CanBeVoted(it.first.second) && consultation->IsValidVote(it.first.second)))
continue;
if (fScanningWholeCycle && mapAlreadyCleared.count(it.first.first) == 0)
{
mapAlreadyCleared[it.first.first] = true;
consultation->mapVotes.clear();
}
consultation->mapVotes[it.first.second] = it.second;
consultation->fDirty = true;
mapSeen[it.first.first]=true;
}
else if (view.HaveConsultationAnswer(it.first.first))
{
CConsultationAnswerModifier answer = view.ModifyConsultationAnswer(it.first.first, pindexNew->nHeight);
if (answer->txblockhash == uint256())
continue;
if (mapBlockIndex.count(answer->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of answer %s\n",
__func__, answer->txblockhash.ToString(), answer->hash.ToString());
continue;
}
if(fUndo)
{
answer->ClearState(pindexDelete);
answer->fDirty = true;
}
if (!answer->CanBeVoted(view))
continue;
answer->nVotes = it.second;
answer->fDirty = true;
mapSeen[it.first.first]=true;
}
}
}
int64_t nTimeEnd3 = GetTimeMicros();
LogPrint("bench", " - CFund update votes: %.2fms\n", (nTimeEnd3 - nTimeStart3) * 0.001);
int64_t nTimeStart4 = GetTimeMicros();
CPaymentRequestMap mapPaymentRequests;
CProposalMap mapProposals;
CConsultationAnswerMap mapConsultationAnswers;
CConsultationMap mapConsultations;
if (fCFund)
{
if (!view.GetAllProposals(mapProposals) || !view.GetAllPaymentRequests(mapPaymentRequests))
return false;
}
if (fDAOConsultations)
{
if(!view.GetAllConsultationAnswers(mapConsultationAnswers) || !view.GetAllConsultations(mapConsultations))
return false;
}
std::vector<uint256> vClearAnswers;
if(lastConsensusStateHash != lastConsensusStateHash)
{
if (fCFund)
{
for (CPaymentRequestMap::iterator it = mapPaymentRequests.begin(); it != mapPaymentRequests.end(); it++)
{
if (!view.HavePaymentRequest(it->first))
continue;
CPaymentRequestModifier prequest = view.ModifyPaymentRequest(it->first, pindexNew->nHeight);
if (!mapSeen.count(prequest->hash) && prequest->CanVote(view))
{
prequest->nVotesYes = 0;
prequest->nVotesNo = 0;
prequest->fDirty = true;
}
}
for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end(); it++)
{
if (!view.HaveProposal(it->first))
continue;
CProposalModifier proposal = view.ModifyProposal(it->first, pindexNew->nHeight);
if (!mapSeen.count(proposal->hash) && proposal->CanVote(view))
{
proposal->nVotesYes = 0;
proposal->nVotesNo = 0;
proposal->fDirty = true;
}
}
}
if (fDAOConsultations)
{
for (CConsultationMap::iterator it = mapConsultations.begin(); it != mapConsultations.end(); it++)
{
if (!view.HaveConsultation(it->first))
continue;
CConsultationModifier consultation = view.ModifyConsultation(it->first, pindexNew->nHeight);
if (consultation->CanBeSupported() && !mapSeenSupport.count(consultation->hash))
{
consultation->nSupport = 0;
consultation->fDirty = true;
}
if (consultation->GetLastState() == DAOFlags::ACCEPTED)
{
if (!consultation->IsRange())
vClearAnswers.push_back(consultation->hash);
if ((consultation->mapVotes.count(VoteFlags::VOTE_ABSTAIN) || consultation->IsRange()) && !mapSeen.count(consultation->hash))
consultation->mapVotes.clear();
}
}
for (CConsultationAnswerMap::iterator it = mapConsultationAnswers.begin(); it != mapConsultationAnswers.end(); it++)
{
if (!view.HaveConsultationAnswer(it->first) || mapSeen.count(it->first))
continue;
CConsultationAnswerModifier answer = view.ModifyConsultationAnswer(it->first, pindexNew->nHeight);
if (answer->CanBeSupported(view) && !mapSeenSupport.count(answer->hash))
{
answer->nSupport = 0;
answer->fDirty = true;
}
if (std::find(vClearAnswers.begin(), vClearAnswers.end(), it->second.parent) == vClearAnswers.end())
continue;
answer->nVotes = 0;
answer->fDirty = true;
}
}
}
if (fCFund)
{
for (CPaymentRequestMap::iterator it = mapPaymentRequests.begin(); it != mapPaymentRequests.end(); it++)
{
if (!view.HavePaymentRequest(it->first))
continue;
CPaymentRequestModifier prequest = view.ModifyPaymentRequest(it->first, pindexNew->nHeight);
if (prequest->txblockhash == uint256())
continue;
CBlockIndex* pblockindex = mapBlockIndex[prequest->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, nCycleLength + 1);
auto oldCycle = prequest->nVotingCycle;
CProposal proposal;
if (!view.GetProposal(prequest->proposalhash, proposal))
continue;
if(fUndo)
{
prequest->ClearState(pindexDelete);
if(prequest->GetLastState() == DAOFlags::NIL)
prequest->nVotingCycle = nVotingCycles;
prequest->fDirty = true;
}
else
{
auto oldState = prequest->GetLastState();
if(oldState == DAOFlags::NIL)
{
prequest->nVotingCycle = nVotingCycles;
prequest->fDirty = true;
}
if((pindexNew->nHeight + 1) % nCycleLength == 0)
{
if(prequest->IsExpired(view))
{
if (oldState != DAOFlags::EXPIRED)
{
prequest->SetState(pindexNew, DAOFlags::EXPIRED);
prequest->fDirty = true;
}
}
else if(prequest->IsRejected(view))
{
if (oldState != DAOFlags::REJECTED)
{
prequest->SetState(pindexNew, DAOFlags::REJECTED);
prequest->fDirty = true;
}
}
else if(oldState == DAOFlags::NIL)
{
flags proposalOldState = proposal.GetLastState();
if((proposalOldState == DAOFlags::ACCEPTED || proposalOldState == DAOFlags::PENDING_VOTING_PREQ) && prequest->IsAccepted(view))
{
if(prequest->nAmount <= pindexNew->nCFLocked && prequest->nAmount <= proposal.GetAvailable(view))
{
pindexNew->nCFLocked -= prequest->nAmount;
prequest->SetState(pindexNew, DAOFlags::ACCEPTED);
prequest->fDirty = true;
LogPrint("daoextra", "%s: Updated nCFSupply %s nCFLocked %s\n", __func__, FormatMoney(pindexNew->nCFSupply), FormatMoney(pindexNew->nCFLocked));
}
}
}
}
}
}
int64_t nTimeEnd4 = GetTimeMicros();
LogPrint("bench", " - CFund update payment request status: %.2fms (%d entries)\n", (nTimeEnd4 - nTimeStart4) * 0.001, mapPaymentRequests.size());
int64_t nTimeStart5 = GetTimeMicros();
for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end(); it++)
{
if (!view.HaveProposal(it->first))
continue;
CProposalModifier proposal = view.ModifyProposal(it->first, pindexNew->nHeight);
if (proposal->txblockhash == uint256())
continue;
if (mapBlockIndex.count(proposal->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of proposal %s\n",
__func__, proposal->txblockhash.ToString(), proposal->hash.ToString());
continue;
}
CBlockIndex* pblockindex = mapBlockIndex[proposal->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view) + 1);
auto oldCycle = proposal->nVotingCycle;
if(fUndo)
{
proposal->ClearState(pindexDelete);
if(proposal->GetLastState() == DAOFlags::NIL)
proposal->nVotingCycle = nVotingCycles;
proposal->fDirty = true;
}
else
{
auto oldState = proposal->GetLastState();
if(oldState == DAOFlags::NIL)
{
proposal->nVotingCycle = nVotingCycles;
proposal->fDirty = true;
}
if((pindexNew->nHeight + 1) % nCycleLength == 0)
{
if(proposal->IsExpired(pindexNew->GetBlockTime(), view))
{
if (oldState != DAOFlags::EXPIRED)
{
if (proposal->HasPendingPaymentRequests(view))
{
proposal->SetState(pindexNew, DAOFlags::PENDING_VOTING_PREQ);
proposal->fDirty = true;
}
else
{
if(oldState == DAOFlags::ACCEPTED || oldState == DAOFlags::PENDING_VOTING_PREQ)
{
pindexNew->nCFSupply += proposal->GetAvailable(view);
pindexNew->nCFLocked -= proposal->GetAvailable(view);
LogPrint("daoextra", "%s: Updated nCFSupply %s nCFLocked %s\n", __func__, FormatMoney(pindexNew->nCFSupply), FormatMoney(pindexNew->nCFLocked));
}
proposal->SetState(pindexNew, DAOFlags::EXPIRED);
proposal->fDirty = true;
}
}
}
else if(proposal->IsRejected(view))
{
if(oldState != DAOFlags::REJECTED)
{
proposal->SetState(pindexNew, DAOFlags::REJECTED);
}
} else if(proposal->IsAccepted(view))
{
if((oldState == DAOFlags::NIL || oldState == DAOFlags::PENDING_FUNDS))
{
if(pindexNew->nCFSupply >= proposal->GetAvailable(view))
{
pindexNew->nCFSupply -= proposal->GetAvailable(view);
pindexNew->nCFLocked += proposal->GetAvailable(view);
LogPrint("daoextra", "%s: Updated nCFSupply %s nCFLocked %s\n", __func__, FormatMoney(pindexNew->nCFSupply), FormatMoney(pindexNew->nCFLocked));
proposal->SetState(pindexNew, DAOFlags::ACCEPTED);
proposal->fDirty = true;
}
else if(oldState != DAOFlags::PENDING_FUNDS)
{
proposal->SetState(pindexNew, DAOFlags::PENDING_FUNDS);
proposal->fDirty = true;
}
}
}
}
}
}
int64_t nTimeEnd5 = GetTimeMicros();
LogPrint("bench", " - CFund update proposal status: %.2fms (%d entries)\n", (nTimeEnd5 - nTimeStart5) * 0.001, mapProposals.size());
}
int64_t nTimeStart6 = GetTimeMicros();
std::map<uint64_t, uint64_t> mapConsensusToChange;
if (fDAOConsultations)
{
for (CConsultationAnswerMap::iterator it = mapConsultationAnswers.begin(); it != mapConsultationAnswers.end(); it++)
{
if (!view.HaveConsultationAnswer(it->first))
continue;
bool fParentExpired = false;
bool fParentPassed = false;
CConsultationAnswerModifier answer = view.ModifyConsultationAnswer(it->first, pindexNew->nHeight);
if (answer->txblockhash == uint256())
continue;
if (mapBlockIndex.count(answer->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of answer %s\n",
__func__, answer->txblockhash.ToString(), answer->hash.ToString());
continue;
}
if(fUndo)
{
answer->ClearState(pindexDelete);
answer->fDirty = true;
}
else if((pindexNew->nHeight + 1) % nCycleLength == 0)
{
flags oldState = answer->GetLastState();
if(answer->IsSupported(view))
{
if(oldState == DAOFlags::NIL)
{
answer->SetState(pindexNew, DAOFlags::ACCEPTED);
answer->fDirty = true;
}
}
if (answer->IsConsensusAccepted(view) && oldState != DAOFlags::PASSED)
{
CConsultation parent;
if (view.GetConsultation(answer->parent, parent) && parent.IsAboutConsensusParameter())
{
mapConsensusToChange.insert(std::make_pair(parent.nMin, stoll(answer->sAnswer)));
answer->SetState(pindexNew, DAOFlags::PASSED);
answer->fDirty = true;
}
}
}
}
int64_t nTimeEnd6 = GetTimeMicros();
LogPrint("bench", " - CFund update consultation answer status: %.2fms (%d entries)\n", (nTimeEnd6 - nTimeStart6) * 0.001, mapConsultationAnswers.size());
int64_t nTimeStart7 = GetTimeMicros();
for (CConsultationMap::iterator it = mapConsultations.begin(); it != mapConsultations.end(); it++)
{
if (!view.HaveConsultation(it->first))
continue;
CConsultationModifier consultation = view.ModifyConsultation(it->first, pindexNew->nHeight);
if (consultation->txblockhash == uint256())
continue;
if (mapBlockIndex.count(consultation->txblockhash) == 0)
{
LogPrintf("%s: Can't find block %s of consultation %s\n",
__func__, consultation->txblockhash.ToString(), consultation->hash.ToString());
continue;
}
CBlockIndex* pblockindex = mapBlockIndex[consultation->txblockhash];
uint64_t nCreatedOnCycle = (pblockindex->nHeight / nCycleLength);
uint64_t nCurrentCycle = (pindexNew->nHeight / nCycleLength);
uint64_t nElapsedCycles = std::max(nCurrentCycle - nCreatedOnCycle, (uint64_t)0);
uint64_t nVotingCycles = std::min(nElapsedCycles, GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view) + 1);
if(fUndo)
{
consultation->ClearState(pindexDelete);
auto newState = consultation->GetLastState();
if (newState != DAOFlags::EXPIRED && newState != DAOFlags::PASSED)
consultation->nVotingCycle = nVotingCycles;
consultation->fDirty = true;
}
else
{
auto oldState = consultation->GetLastState();
if (oldState != DAOFlags::EXPIRED && oldState != DAOFlags::PASSED)
{
consultation->nVotingCycle = nVotingCycles;
consultation->fDirty = true;
}
if((pindexNew->nHeight + 1) % nCycleLength == 0)
{
if(consultation->IsExpired(pindexNew, view))
{
if (oldState != DAOFlags::EXPIRED)
{
consultation->SetState(pindexNew, DAOFlags::EXPIRED);
consultation->fDirty = true;
}
}
else if(consultation->IsSupported(view))
{
if(oldState == DAOFlags::NIL)
{
consultation->SetState(pindexNew, DAOFlags::SUPPORTED);
consultation->fDirty = true;
}
else if(oldState == DAOFlags::SUPPORTED && consultation->CanMoveInReflection(view))
{
consultation->SetState(pindexNew, DAOFlags::REFLECTION);
consultation->fDirty = true;
}
else if(oldState == DAOFlags::REFLECTION && consultation->IsReflectionOver(pindexNew, view))
{
consultation->SetState(pindexNew, DAOFlags::ACCEPTED);
consultation->fDirty = true;
}
}
CConsensusParameter cparameter;
if (consultation->IsAboutConsensusParameter() && mapConsensusToChange.count(consultation->nMin) && oldState == DAOFlags::ACCEPTED && consultation->GetLastState() != DAOFlags::EXPIRED)
{
consultation->SetState(pindexNew, DAOFlags::PASSED);
consultation->fDirty = true;
}
}
}
}
int64_t nTimeEnd7 = GetTimeMicros();
LogPrint("bench", " - CFund update consultation status: %.2fms (%d entries)\n", (nTimeEnd7 - nTimeStart7) * 0.001, mapConsultations.size());
}
int64_t nTimeStart71 = GetTimeMicros();
if(fScanningWholeCycle)
{
if (fCFund)
{
for (CPaymentRequestMap::iterator it = mapPaymentRequests.begin(); it != mapPaymentRequests.end(); it++)
{
if (!view.HavePaymentRequest(it->first))
continue;
CPaymentRequestModifier prequest = view.ModifyPaymentRequest(it->first, pindexNew->nHeight);
if (!mapSeen.count(prequest->hash) && prequest->CanVote(view))
{
prequest->nVotesYes = 0;
prequest->nVotesNo = 0;
prequest->fDirty = true;
}
}
for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end(); it++)
{
if (!view.HaveProposal(it->first))
continue;
CProposalModifier proposal = view.ModifyProposal(it->first, pindexNew->nHeight);
if (!mapSeen.count(proposal->hash) && proposal->CanVote(view))
{
proposal->nVotesYes = 0;
proposal->nVotesNo = 0;
proposal->fDirty = true;
}
}
}
if (fDAOConsultations)
{
for (CConsultationMap::iterator it = mapConsultations.begin(); it != mapConsultations.end(); it++)
{
if (!view.HaveConsultation(it->first))
continue;
CConsultationModifier consultation = view.ModifyConsultation(it->first, pindexNew->nHeight);
if (consultation->CanBeSupported() && !mapSeenSupport.count(consultation->hash))
{
consultation->nSupport = 0;
consultation->fDirty = true;
}
if (consultation->GetLastState() == DAOFlags::ACCEPTED)
{
if (!consultation->IsRange())
vClearAnswers.push_back(consultation->hash);
if ((consultation->mapVotes.count(VoteFlags::VOTE_ABSTAIN) || consultation->IsRange()) && !mapSeen.count(consultation->hash))
consultation->mapVotes.clear();
}
}
for (CConsultationAnswerMap::iterator it = mapConsultationAnswers.begin(); it != mapConsultationAnswers.end(); it++)
{
if (!view.HaveConsultationAnswer(it->first) || mapSeen.count(it->first))
continue;
CConsultationAnswerModifier answer = view.ModifyConsultationAnswer(it->first, pindexNew->nHeight);
if (answer->CanBeSupported(view) && !mapSeenSupport.count(answer->hash))
{
answer->nSupport = 0;
answer->fDirty = true;
}
if (std::find(vClearAnswers.begin(), vClearAnswers.end(), it->second.parent) == vClearAnswers.end())
continue;
answer->nVotes = 0;
answer->fDirty = true;
}
}
int64_t nTimeEnd71 = GetTimeMicros();
LogPrint("bench", " - CFund restart vote counters: %.2fms\n", (nTimeEnd71 - nTimeStart71) * 0.001);
}
int64_t nTimeStart8 = GetTimeMicros();
for (auto &it: mapConsensusToChange)
{
CConsensusParameterModifier mcparameter = view.ModifyConsensusParameter(it.first, pindexNew->nHeight);
mcparameter->Set(pindexNew->nHeight, it.second);
}
int64_t nTimeEnd8 = GetTimeMicros();
LogPrint("bench", " - CFund update consensus parameter status: %.2fms\n", (nTimeEnd8 - nTimeStart8) * 0.001);
int64_t nTimeEnd = GetTimeMicros();
LogPrint("bench", " - CFund total VoteStep() function: %.2fms\n", (nTimeEnd - nTimeStart) * 0.001);
return true;
}
bool IsValidDaoTxVote(const CTransaction& tx, const CStateViewCache& view)
{
CAmount nAmountContributed = 0;
bool fHasVote = false;
for (const CTxOut& out: tx.vout)
{
if (out.IsCommunityFundContribution())
nAmountContributed += out.nValue;
if (out.IsVote() || out.IsSupportVote() || out.IsConsultationVote())
fHasVote = true;
}
return tx.nVersion == CTransaction::VOTE_VERSION && fHasVote && nAmountContributed >= GetConsensusParameter(Consensus::CONSENSUS_PARAMS_DAO_VOTE_LIGHT_MIN_FEE, view);
}
// CONSENSUS PARAMETERS
bool CConsensusParameter::Get(uint64_t& val)
{
bool ret = false;
int nHeight = 0;
for (auto& it: list)
{
if (it.first < nHeight)
continue;
ret = true;
val = it.second;
nHeight = it.first;
}
return ret;
}
int CConsensusParameter::GetHeight() const
{
int nHeight = 0;
for (auto& it: list)
{
if (it.first < nHeight)
continue;
nHeight = it.first;
}
return nHeight;
}
bool CConsensusParameter::Set(const int& height, const uint64_t& val)
{
if (list.count(height) == 0)
list.insert(std::make_pair(height, val));
else
list[height] = val;
return true;
}
bool CConsensusParameter::Clear(const int& height)
{
auto it = list.find(height);
if (it != list.end())
list.erase(it);
return true;
}
std::map<int, uint64_t>* CConsensusParameter::GetFullList()
{
return &list;
}
std::string CConsensusParameter::ToString() const
{
std::string sList;
for (auto& it:list)
{
sList += strprintf("{height %d => %d},", it.first, it.second);
}
return strprintf("CConsensusParameter([%s])", sList);
}
// VOTES
bool CVoteList::Get(const uint256& hash, int64_t& val)
{
bool ret = false;
int nHeight = 0;
for (auto& it: list)
{
if (it.first < nHeight)
continue;
for (auto& it2: it.second)
{
if (it.first > nHeight && it2.first == hash)
{
ret = true;
val = it2.second;
nHeight = it.first;
}
}
}
return ret;
}
bool CVoteList::Set(const int& height, const uint256& hash, int64_t vote)
{
int64_t prevVote;
if (Get(hash, prevVote) && prevVote == vote)
return false;
if (list.count(height) == 0)
{
std::map<uint256, int64_t> mapVote;
mapVote.insert(std::make_pair(hash, vote));
list.insert(std::make_pair(height, mapVote));
}
else if (list[height].count(hash) == 0)
list[height].insert(std::make_pair(hash, vote));
else
list[height][hash] = vote;
return true;
}
bool CVoteList::Clear(const int& height, const uint256& hash)
{
if (list.count(height))
{
auto it = list[height].find(hash);
if (it != list[height].end())
list[height].erase(it);
}
return true;
}
bool CVoteList::Clear(const int& height)
{
auto it = list.find(height);
if (it != list.end())
list.erase(it);
return true;
}
std::map<uint256, int64_t> CVoteList::GetList()
{
std::map<uint256, int64_t> ret;
std::map<uint256, int> mapCacheHeight;
for (auto &it: list)
{
for (auto &it2: it.second)
{
if (mapCacheHeight.count(it2.first) == 0)
mapCacheHeight[it2.first] = 0;
if (it.first > mapCacheHeight[it2.first])
{
ret[it2.first] = it2.second;
mapCacheHeight[it2.first] = it.first;
}
}
}
return ret;
}
std::map<int, std::map<uint256, int64_t>>* CVoteList::GetFullList()
{
return &list;
}
std::string CVoteList::ToString() const
{
std::string sList;
for (auto& it:list)
{
sList += strprintf("{height %d => {", it.first);
for (auto&it2: it.second)
{
sList += strprintf("\n\t%s => %d,", it2.first.ToString(), it2.second);
}
sList += strprintf("}},");
}
return strprintf("CVoteList([%s])", sList);
}
// CONSULTATIONS
bool IsValidConsultationAnswer(CTransaction tx, CStateViewCache& coins, uint64_t nMaskVersion, CBlockIndex* pindex)
{
if(tx.strDZeel.length() > 255)
return error("%s: Too long strdzeel for answer %s", __func__, tx.GetHash().ToString());
UniValue metadata(UniValue::VOBJ);
try {
UniValue valRequest;
if (!valRequest.read(tx.strDZeel))
return error("%s: Wrong strdzeel for answer %s", __func__, tx.GetHash().ToString());
if (valRequest.isObject())
metadata = valRequest.get_obj();
else
return error("%s: Wrong strdzeel for answer %s", __func__, tx.GetHash().ToString());
} catch (const UniValue& objError) {
return error("%s: Wrong strdzeel for answer %s", __func__, tx.GetHash().ToString());
} catch (const std::exception& e) {
return error("%s: Wrong strdzeel for answer %s: %s", __func__, tx.GetHash().ToString(), e.what());
}
try
{
if(!find_value(metadata, "a").isStr() || !find_value(metadata, "h").isStr())
{
return error("%s: Wrong strdzeel for answer %s ()", __func__, tx.GetHash().ToString(), tx.strDZeel);
}
std::string sAnswer = find_value(metadata, "a").get_str();
if (sAnswer == "")
return error("%s: Empty text for answer %s", __func__, tx.GetHash().ToString());
std::string Hash = find_value(metadata, "h").get_str();
int nVersion = find_value(metadata, "v").isNum() ? find_value(metadata, "v").get_int64() : CConsultationAnswer::BASE_VERSION;
CConsultation consultation;
if(!coins.GetConsultation(uint256S(Hash), consultation))
return error("%s: Could not find consultation %s for answer %s", __func__, Hash.c_str(), tx.GetHash().ToString());
CHashWriter hashAnswer(0,0);
hashAnswer << uint256S(Hash);
hashAnswer << sAnswer;
if(coins.HaveConsultationAnswer(hashAnswer.GetHash()))
return error("%s: Duplicated answers are forbidden, we already have %s.", __func__, hashAnswer.GetHash().ToString());
if(consultation.nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION)
return error("%s: The consultation %s does not admit new answers", __func__, Hash.c_str());
if(consultation.nVersion & CConsultation::CONSENSUS_PARAMETER_VERSION && !IsValidConsensusParameterProposal((Consensus::ConsensusParamsPos)consultation.nMin, sAnswer, pindex, coins))
return error("%s: Invalid consultation %s. The proposed parameter %s is not valid", __func__, Hash, sAnswer);
CAmount nContribution = 0;
for(unsigned int i=0;i<tx.vout.size();i++)
if(tx.vout[i].IsCommunityFundContribution())
nContribution +=tx.vout[i].nValue;
bool ret = (nContribution >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, coins));
if (!ret)
return error("%s: Not enough fee for answer %s (%d < %d)", __func__, hashAnswer.GetHash().ToString(), nContribution, GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, coins));
}
catch(...)
{
return false;
}
return true;
}
bool IsValidConsultation(CTransaction tx, CStateViewCache& coins, uint64_t nMaskVersion, CBlockIndex* pindex)
{
if(tx.strDZeel.length() > 1024)
return error("%s: Too long strdzeel for consultation %s", __func__, tx.GetHash().ToString());
UniValue metadata(UniValue::VOBJ);
try {
UniValue valRequest;
if (!valRequest.read(tx.strDZeel))
return error("%s: Wrong strdzeel for consultation %s", __func__, tx.GetHash().ToString());
if (valRequest.isObject())
metadata = valRequest.get_obj();
else
return error("%s: Wrong strdzeel for consultation %s", __func__, tx.GetHash().ToString());
} catch (const UniValue& objError) {
return error("%s: Wrong strdzeel for consultation %s", __func__, tx.GetHash().ToString());
} catch (const std::exception& e) {
return error("%s: Wrong strdzeel for consultation %s: %s", __func__, tx.GetHash().ToString(), e.what());
}
try
{
if(!(find_value(metadata, "n").isNum() &&
find_value(metadata, "q").isStr()))
{
return error("%s: Wrong strdzeel for consultation %s (%s)", __func__, tx.GetHash().ToString(), tx.strDZeel);
}
CAmount nMin = find_value(metadata, "m").isNum() ? find_value(metadata, "m").get_int64() : 0;
CAmount nMax = find_value(metadata, "n").get_int64();
std::string sQuestion = find_value(metadata, "q").get_str();
CAmount nContribution = 0;
int nVersion = find_value(metadata, "v").isNum() ? find_value(metadata, "v").get_int64() : CConsultation::BASE_VERSION;
for(unsigned int i=0;i<tx.vout.size();i++)
if(tx.vout[i].IsCommunityFundContribution())
nContribution +=tx.vout[i].nValue;
bool fRange = nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION;
bool fAcceptMoreAnswers = nVersion & CConsultation::MORE_ANSWERS_VERSION;
bool fIsAboutConsensusParameter = nVersion & CConsultation::CONSENSUS_PARAMETER_VERSION;
if (fIsAboutConsensusParameter)
{
if (fRange || !fAcceptMoreAnswers)
return error("%s: Invalid consultation %s. A consultation about consensus parameters must allow proposals for answers and can't be a range", __func__, tx.GetHash().ToString());
if (nMax != 1)
return error("%s: Invalid consultation %s. n must be 1", __func__, tx.GetHash().ToString());
if (nMin < Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH || nMin >= Consensus::MAX_CONSENSUS_PARAMS)
return error("%s: Invalid consultation %s. Invalid m", __func__, tx.GetHash().ToString());
CConsultationMap consultationMap;
if (coins.GetAllConsultations(consultationMap))
{
for (auto& it: consultationMap)
{
CConsultation consultation = it.second;
if (consultation.txblockhash != uint256()) // only check if not mempool
{
if (mapBlockIndex.count(consultation.txblockhash) == 0)
continue;
if (!chainActive.Contains(mapBlockIndex[consultation.txblockhash]))
continue;
}
if (consultation.IsAboutConsensusParameter() && !consultation.IsFinished() && consultation.nMin == nMin)
return error("%s: Invalid consultation %s. There already exists an active consultation %s about that consensus parameter.", __func__, tx.GetHash().ToString(), consultation.ToString(pindex, coins));
}
}
}
UniValue answers(UniValue::VARR);
if (find_value(metadata, "a").isArray())
answers = find_value(metadata, "a").get_array();
std::map<std::string, bool> mapSeen;
UniValue answersArray = answers.get_array();
if (fRange && fAcceptMoreAnswers)
{
return error("%s: Invalid consultation %s. Range consultations can't accept answers.", __func__, tx.GetHash().ToString());
}
if (!fAcceptMoreAnswers && !fRange)
{
if (nMax > answersArray.size())
{
return error("%s: Invalid consultation %s. Wrong number of max answers %d.", __func__, tx.GetHash().ToString(), nMax);
}
}
for (unsigned int i = 0; i < answersArray.size(); i++)
{
if (!answersArray[i].isStr())
continue;
std::string it = answersArray[i].get_str();
if (mapSeen.count(it) == 0)
mapSeen[it] = true;
if(fIsAboutConsensusParameter && !IsValidConsensusParameterProposal((Consensus::ConsensusParamsPos)nMin, it, pindex, coins))
return error("%s: Invalid consultation %s. The proposed value %s is not valid", __func__, tx.GetHash().ToString(), it);
}
CAmount nMinFee = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_FEE, coins) + GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, coins) * answersArray.size();
bool ret = (sQuestion != "" && nContribution >= nMinFee &&
((fRange && nMin >= 0 && nMax < (uint64_t)VoteFlags::VOTE_ABSTAIN && nMax > nMin) ||
(!fRange && nMax > 0 && nMax < 16)) &&
((!fAcceptMoreAnswers && mapSeen.size() > 1) || fAcceptMoreAnswers || fRange) &&
(nVersion & ~nMaskVersion) == 0);
if (!ret)
return error("%s: Wrong strdzeel %s for proposal %s", __func__, tx.strDZeel.c_str(), tx.GetHash().ToString());
}
catch(...)
{
return false;
}
return true;
}
bool IsValidConsensusParameterProposal(Consensus::ConsensusParamsPos pos, std::string proposal, CBlockIndex *pindex, CStateViewCache& coins)
{
if (proposal.empty() || proposal.find_first_not_of("0123456789") != string::npos)
return error("%s: Proposed parameter is empty or not integer", __func__);
uint64_t val = stoll(proposal);
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_PERCENT)
{
if (val < 0 || val > 10000)
return error("%s: Proposed parameter out of range for percentages", __func__);
}
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_XSW)
{
if (val < 0 || val > MAX_MONEY)
return error("%s: Proposed parameter out of range for coin amounts", __func__);
}
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_NUMBER)
{
if (val <= 0 || val > pow(2,24))
return error("%s: Proposed parameter out of range for type number", __func__);
}
if (pos == Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES && val > GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, coins))
return error("%s: Proposed cycles number out of range", __func__);
if (pos == Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES && val < GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES, coins))
return error("%s: Proposed cycles number out of range", __func__);
if (pos == Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES || pos == Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES)
{
auto lookFor = (pos == Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES) ? Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES : Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES;
CConsultationMap consultationMap;
if (coins.GetAllConsultations(consultationMap))
{
for (auto& it: consultationMap)
{
CConsultation consultation = it.second;
if (consultation.txblockhash != uint256()) // only check if not mempool
{
if (mapBlockIndex.count(consultation.txblockhash) == 0)
continue;
if (!chainActive.Contains(mapBlockIndex[consultation.txblockhash]))
continue;
}
if (consultation.IsAboutConsensusParameter() && !consultation.IsFinished() && consultation.nMin == lookFor)
return error("%s: There already exists an active consultation %s about the consensus parameter %d. Both can not happen at the same time", __func__, consultation.ToString(pindex, coins), lookFor);
}
}
}
if (val == GetConsensusParameter(pos, coins))
return error("%s: The proposed value is the current one", __func__);
if (Consensus::vConsensusParamsType[pos] == Consensus::TYPE_BOOL && val != 0 && val != 1)
return error("%s: Boolean values can only be 0 or 1", __func__);
return true;
}
bool CConsultation::IsAboutConsensusParameter() const
{
return (nVersion & CConsultation::CONSENSUS_PARAMETER_VERSION);
}
bool CConsultation::HaveEnoughAnswers(const CStateViewCache& view) const {
AssertLockHeld(cs_main);
int nSupportedAnswersCount = 0;
if (nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION)
{
return true;
}
else
{
CConsultationAnswer answer;
for (auto& it: vAnswers)
{
if (!view.GetConsultationAnswer(it, answer))
continue;
if (answer.parent != hash)
continue;
if (!answer.IsSupported(view))
continue;
nSupportedAnswersCount++;
}
}
return nSupportedAnswersCount >= (IsAboutConsensusParameter() ? 1 : 2);
}
flags CConsultation::GetLastState() const {
flags ret = NIL;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = it.second;
}
}
return ret;
}
CBlockIndex* CConsultation::GetLastStateBlockIndex() const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
CBlockIndex* CConsultation::GetLastStateBlockIndexForState(flags state) const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (it.second != state)
continue;
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
bool CConsultation::SetState(const CBlockIndex* pindex, flags state) {
mapState[pindex->GetBlockHash()] = state;
return true;
}
bool CConsultation::ClearState(const CBlockIndex* pindex) {
mapState.erase(pindex->GetBlockHash());
return true;
}
bool CConsultation::IsFinished() const {
flags fState = GetLastState();
return fState == DAOFlags::EXPIRED || fState == DAOFlags::PASSED;
}
std::string CConsultation::GetState(const CBlockIndex* pindex, const CStateViewCache& view) const {
std::string sFlags = "waiting for support";
flags fState = GetLastState();
if (!HaveEnoughAnswers(view))
sFlags += ", waiting for having enough supported answers";
if(IsSupported(view))
{
sFlags = "found support";
if (!HaveEnoughAnswers(view))
sFlags += ", waiting for having enough supported answers";
if(fState != DAOFlags::SUPPORTED)
sFlags += ", waiting for end of voting period";
if(fState == DAOFlags::REFLECTION)
sFlags = "reflection phase";
else if(fState == DAOFlags::ACCEPTED)
sFlags = "voting started";
}
if(IsExpired(pindex, view))
{
sFlags = IsSupported(view) ? "finished" : "expired";
if (fState != DAOFlags::EXPIRED)
sFlags = IsSupported(view) ? "last cycle, waiting for end of voting period" : "expiring, waiting for end of voting period";
}
if (fState == DAOFlags::PASSED)
sFlags = "passed";
return sFlags;
}
bool CConsultation::IsSupported(const CStateViewCache& view) const
{
if (IsRange())
{
float nMinimumSupport = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_SUPPORT, view) / 10000.0;
return nSupport > GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumSupport;
}
else
return HaveEnoughAnswers(view);
}
bool CConsultation::CanMoveInReflection(const CStateViewCache& view) const
{
return nVotingCycle >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MIN_CYCLES, view);
}
std::string CConsultation::ToString(const CBlockIndex* pindex, const CStateViewCache& view) const {
AssertLockHeld(cs_main);
flags fState = GetLastState();
uint256 blockhash;
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex) blockhash = pblockindex->GetBlockHash();
std::string sRet = strprintf("CConsultation(hash=%s, nVersion=%d, strDZeel=\"%s\", fState=%s, status=%s, answers=[",
hash.ToString(), nVersion, strDZeel, fState, GetState(pindex, view));
UniValue answers(UniValue::VARR);
if (nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION)
{
UniValue a(UniValue::VOBJ);
for (auto &it: mapVotes)
{
sRet += ((it.first == VoteFlags::VOTE_ABSTAIN ? "abstain" : to_string(it.first)) + "=" + to_string(it.second) + ", ");
}
}
else
{
if (mapVotes.count(VoteFlags::VOTE_ABSTAIN) != 0)
{
sRet += "abstain=" + to_string(mapVotes.at(VoteFlags::VOTE_ABSTAIN)) + ", ";
}
CConsultationAnswerMap mapConsultationAnswers;
CConsultationAnswer answer;
for (auto& it: vAnswers)
{
if (!view.GetConsultationAnswer(it, answer))
continue;
if (answer.parent != hash)
continue;
sRet += answer.ToString();
}
}
sRet += strprintf("]");
if (IsRange())
sRet += strprintf(", fRange=true, nMin=%u, nMax=%u", nMin, nMax);
sRet += strprintf(", nVotingCycle=%u, nSupport=%u, blockhash=%s)",
nVotingCycle, nSupport, blockhash.ToString().substr(0,10));
return sRet;
}
void CConsultation::ToJson(UniValue& ret, const CStateViewCache& view) const
{
flags fState = GetLastState();
uint256 blockhash;
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex) blockhash = pblockindex->GetBlockHash();
ret.pushKV("version",(uint64_t)nVersion);
ret.pushKV("hash", hash.ToString());
ret.pushKV("blockhash", txblockhash.ToString());
ret.pushKV("question", strDZeel);
ret.pushKV("support", nSupport);
UniValue answers(UniValue::VARR);
if (nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION)
{
UniValue a(UniValue::VOBJ);
bool fAbstainAdded = false;
for (auto &it: mapVotes)
{
if (it.first == VoteFlags::VOTE_ABSTAIN)
{
fAbstainAdded = true;
ret.pushKV("abstain", it.second);
}
else
a.pushKV(to_string(it.first), it.second);
}
if (!fAbstainAdded)
ret.pushKV("abstain", 0);
answers.push_back(a);
}
else
{
if (mapVotes.count(VoteFlags::VOTE_ABSTAIN) != 0)
{
ret.pushKV("abstain", mapVotes.at(VoteFlags::VOTE_ABSTAIN));
}
else
{
ret.pushKV("abstain", 0);
}
CConsultationAnswerMap mapConsultationAnswers;
CConsultationAnswer answer;
for (auto& it: vAnswers)
{
if (!view.GetConsultationAnswer(it, answer))
continue;
if (answer.parent != hash)
continue;
UniValue a(UniValue::VOBJ);
answer.ToJson(a, view);
answers.push_back(a);
}
}
UniValue mapState(UniValue::VOBJ);
for (auto&it: this->mapState)
{
mapState.pushKV(std::to_string(it.second), it.first.ToString());
}
ret.pushKV("mapState", mapState);
ret.pushKV("answers", answers);
ret.pushKV("min", nMin);
ret.pushKV("max", nMax);
ret.pushKV("votingCyclesFromCreation", std::min((uint64_t)nVotingCycle, GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view)));
auto nMaxCycles = 0;
auto nCurrentCycle = 0;
auto nVotingLength = GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view);
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view)+GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view);
if (pblockindex)
{
auto nCreated = (unsigned int)(pblockindex->nHeight / nVotingLength);
auto nCurrent = (unsigned int)(chainActive.Tip()->nHeight / nVotingLength);
nCurrentCycle = std::min(nCurrent - nCreated, nVotingCycle);
}
else
{
nCurrentCycle = nVotingCycle;
}
if (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED)
{
nCurrentCycle = nVotingCycle;
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view);
}
else if (fState == DAOFlags::REFLECTION)
{
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view);
}
else if (fState == DAOFlags::ACCEPTED)
{
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view);
}
UniValue votingCycleForState(UniValue::VOBJ);
votingCycleForState.pushKV("current", (uint64_t)nCurrentCycle);
votingCycleForState.pushKV("max", (uint64_t)nMaxCycles);
ret.pushKV("votingCycleForState", votingCycleForState);
ret.pushKV("status", GetState(chainActive.Tip(), view));
ret.pushKV("state", (uint64_t)fState);
ret.pushKV("stateChangedOnBlock", blockhash.ToString());
}
bool CConsultation::IsExpired(const CBlockIndex* pindex, const CStateViewCache& view) const
{
flags fState = GetLastState();
CBlockIndex* pblockindex = GetLastStateBlockIndexForState(ACCEPTED);
if (fState == DAOFlags::ACCEPTED && pblockindex) {
uint64_t nAcceptedOnCycle = ((uint64_t)pblockindex->nHeight / GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view));
uint64_t nCurrentCycle = ((uint64_t)pindex->nHeight / GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view));
uint64_t nElapsedCycles = std::max(nCurrentCycle - nAcceptedOnCycle, (uint64_t)0);
return (nElapsedCycles >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view));
}
return (fState == DAOFlags::EXPIRED) || (ExceededMaxVotingCycles(view) && fState == DAOFlags::NIL);
};
bool CConsultation::IsReflectionOver(const CBlockIndex* pindex, const CStateViewCache& view) const
{
auto nVotingLength = GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view);
CBlockIndex* pblockindex = GetLastStateBlockIndexForState(REFLECTION);
if (pblockindex) {
auto nCreated = (unsigned int)(pblockindex->nHeight / nVotingLength);
auto nCurrent = (unsigned int)(pindex->nHeight / nVotingLength);
auto nElapsedCycles = nCurrent - nCreated;
auto nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view);
return nElapsedCycles >= nMaxCycles;
}
return false;
}
bool CConsultation::CanBeSupported() const
{
flags fState = GetLastState();
return fState == DAOFlags::NIL && IsRange();
}
bool CConsultation::CanBeVoted(int64_t vote) const
{
flags fState = GetLastState();
return fState == DAOFlags::ACCEPTED && (IsRange() || vote == VoteFlags::VOTE_ABSTAIN);
}
bool CConsultation::IsRange() const
{
return (nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION);
}
bool CConsultation::CanHaveNewAnswers() const
{
flags fState = GetLastState();
return CanHaveAnswers() && (nVersion & MORE_ANSWERS_VERSION);
}
bool CConsultation::CanHaveAnswers() const
{
flags fState = GetLastState();
return (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED) && !IsRange();
}
bool CConsultation::IsValidVote(int64_t vote) const
{
return vote == VoteFlags::VOTE_ABSTAIN || (IsRange() && vote >= nMin && vote <= nMax);
}
bool CConsultation::ExceededMaxVotingCycles(const CStateViewCache& view) const
{
return nVotingCycle >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view);
};
void CConsultationAnswer::Vote() {
nVotes++;
}
void CConsultationAnswer::DecVote() {
nVotes = std::max(0,nVotes-1);
}
void CConsultationAnswer::ClearVotes() {
nVotes=0;
}
int CConsultationAnswer::GetVotes() const {
return nVotes;
}
flags CConsultationAnswer::GetLastState() const {
flags ret = NIL;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = it.second;
}
}
return ret;
}
CBlockIndex* CConsultationAnswer::GetLastStateBlockIndex() const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
CBlockIndex* CConsultationAnswer::GetLastStateBlockIndexForState(flags state) const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (it.second != state)
continue;
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
bool CConsultationAnswer::SetState(const CBlockIndex* pindex, flags state) {
mapState[pindex->GetBlockHash()] = state;
return true;
}
bool CConsultationAnswer::ClearState(const CBlockIndex* pindex) {
mapState.erase(pindex->GetBlockHash());
return true;
}
std::string CConsultationAnswer::GetState(const CStateViewCache& view) const {
flags fState = GetLastState();
std::string sFlags = "waiting for support";
if(IsSupported(view)) {
sFlags = "found support";
if(fState != DAOFlags::ACCEPTED)
sFlags += ", waiting for end of voting period";
}
if (fState == DAOFlags::PASSED)
sFlags = "passed";
return sFlags;
}
std::string CConsultationAnswer::GetText() const {
return sAnswer;
}
bool CConsultationAnswer::CanBeSupported(const CStateViewCache& view) const {
CConsultation consultation;
flags fState = GetLastState();
if (!view.GetConsultation(parent, consultation))
return error("%s: Can't find parent consultation %s of answer %s", __func__, parent.ToString(), hash.ToString());
flags fConsultationState = consultation.GetLastState();
if (fConsultationState != DAOFlags::NIL && fConsultationState != DAOFlags::SUPPORTED)
return false;
return fState == DAOFlags::NIL;
}
bool CConsultationAnswer::CanBeVoted(const CStateViewCache& view) const {
CConsultation consultation;
flags fState = GetLastState();
if (!view.GetConsultation(parent, consultation))
return false;
if (consultation.IsRange())
return false;
flags fConsultationState = consultation.GetLastState();
return fState == DAOFlags::ACCEPTED && fConsultationState == DAOFlags::ACCEPTED &&
!(consultation.nVersion & CConsultation::ANSWER_IS_A_RANGE_VERSION);
}
bool CConsultationAnswer::IsSupported(const CStateViewCache& view) const
{
float nMinimumSupport = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_SUPPORT, view) / 10000.0;
return nSupport >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumSupport;
}
bool CConsultationAnswer::IsConsensusAccepted(const CStateViewCache& view) const
{
float nMinimumQuorum = Params().GetConsensus().nConsensusChangeMinAccept/10000.0;
return nVotes >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumQuorum;
}
std::string CConsultationAnswer::ToString() const {
flags fState = GetLastState();
return strprintf("CConsultationAnswer(hash=%s, fState=%u, sAnswer=\"%s\", nVotes=%u, nSupport=%u)", hash.ToString(), fState, sAnswer, nVotes, nSupport);
}
void CConsultationAnswer::ToJson(UniValue& ret, const CStateViewCache& view) const {
flags fState = GetLastState();
uint256 blockhash;
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex) blockhash = pblockindex->GetBlockHash();
CConsultation consultation;
ret.pushKV("version",(uint64_t)nVersion);
if(view.GetConsultation(parent, consultation) && consultation.IsAboutConsensusParameter() && (consultation.nMin == Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES || consultation.nMin == Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES))
ret.pushKV("answer", std::to_string(stoll(sAnswer)+1));
else
ret.pushKV("answer", sAnswer);
ret.pushKV("support", nSupport);
ret.pushKV("votes", nVotes);
UniValue mapState(UniValue::VOBJ);
for (auto&it: this->mapState)
{
mapState.pushKV(std::to_string(it.second), it.first.ToString());
}
ret.pushKV("mapState", mapState);
ret.pushKV("status", GetState(view));
ret.pushKV("state", (uint64_t)fState);
ret.pushKV("stateChangedOnBlock", blockhash.ToString());
ret.pushKV("txblockhash", txblockhash.ToString());
ret.pushKV("parent", parent.ToString());
if (hash != uint256())
ret.pushKV("hash", hash.ToString());
}
// CFUND
bool IsValidPaymentRequest(CTransaction tx, CStateViewCache& coins, uint64_t nMaskVersion)
{
if(tx.strDZeel.length() > 1024)
return error("%s: Too long strdzeel for payment request %s", __func__, tx.GetHash().ToString());
UniValue metadata(UniValue::VOBJ);
try {
UniValue valRequest;
if (!valRequest.read(tx.strDZeel))
return error("%s: Wrong strdzeel for payment request %s", __func__, tx.GetHash().ToString());
if (valRequest.isObject())
metadata = valRequest.get_obj();
else
return error("%s: Wrong strdzeel for payment request %s", __func__, tx.GetHash().ToString());
} catch (const UniValue& objError) {
return error("%s: Wrong strdzeel for payment request %s", __func__, tx.GetHash().ToString());
} catch (const std::exception& e) {
return error("%s: Wrong strdzeel for payment request %s: %s", __func__, tx.GetHash().ToString(), e.what());
}
if(!(find_value(metadata, "n").isNum() && find_value(metadata, "s").isStr() && find_value(metadata, "h").isStr() && find_value(metadata, "i").isStr()))
return error("%s: Wrong strdzeel for payment request %s", __func__, tx.GetHash().ToString());
CAmount nAmount = find_value(metadata, "n").get_int64();
std::string Signature = find_value(metadata, "s").get_str();
std::string Hash = find_value(metadata, "h").get_str();
std::string strDZeel = find_value(metadata, "i").get_str();
int nVersion = find_value(metadata, "v").isNum() ? find_value(metadata, "v").get_int64() : 1;
if (nAmount < 0) {
return error("%s: Payment Request cannot have amount less than 0: %s", __func__, tx.GetHash().ToString());
}
CProposal proposal;
if(!coins.GetProposal(uint256S(Hash), proposal) || proposal.GetLastState() != DAOFlags::ACCEPTED)
return error("%s: Could not find parent proposal %s for payment request %s", __func__, Hash.c_str(),tx.GetHash().ToString());
std::string sRandom = "";
if (nVersion >= CPaymentRequest::BASE_VERSION && find_value(metadata, "r").isStr())
sRandom = find_value(metadata, "r").get_str();
std::string Secret = sRandom + "I kindly ask to withdraw " +
std::to_string(nAmount) + "XSW from the proposal " +
proposal.hash.ToString() + ". Payment request id: " + strDZeel;
CStakeWorkAddress addr(proposal.GetOwnerAddress());
if (!addr.IsValid())
return error("%s: Address %s is not valid for payment request %s", __func__, proposal.GetOwnerAddress(), Hash.c_str(), tx.GetHash().ToString());
CKeyID keyID;
addr.GetKeyID(keyID);
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(Signature.c_str(), &fInvalid);
if (fInvalid)
return error("%s: Invalid signature for payment request %s", __func__, tx.GetHash().ToString());
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << Secret;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig) || pubkey.GetID() != keyID)
return error("%s: Invalid signature for payment request %s", __func__, tx.GetHash().ToString());
if(nAmount > proposal.GetAvailable(coins, true))
return error("%s: Invalid requested amount for payment request %s (%d vs %d available)",
__func__, tx.GetHash().ToString(), nAmount, proposal.GetAvailable(coins, true));
CAmount nContribution = 0;
for(unsigned int i=0;i<tx.vout.size();i++)
if(tx.vout[i].IsCommunityFundContribution())
nContribution +=tx.vout[i].nValue;
bool ret = (nContribution >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MIN_FEE, coins) &&
nVersion & ~nMaskVersion) == 0;
if(!ret)
return error("%s: Invalid version for payment request %s", __func__, tx.GetHash().ToString());
return true;
}
flags CPaymentRequest::GetLastState() const {
flags ret = NIL;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = it.second;
}
}
return ret;
}
CBlockIndex* CPaymentRequest::GetLastStateBlockIndex() const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
CBlockIndex* CPaymentRequest::GetLastStateBlockIndexForState(flags state) const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (it.second != state)
continue;
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
bool CPaymentRequest::SetState(const CBlockIndex* pindex, flags state) {
mapState[pindex->GetBlockHash()] = state;
return true;
}
bool CPaymentRequest::ClearState(const CBlockIndex* pindex) {
mapState.erase(pindex->GetBlockHash());
return true;
}
bool CPaymentRequest::CanVote(CStateViewCache& coins) const
{
AssertLockHeld(cs_main);
CProposal proposal;
if(!coins.GetProposal(proposalhash, proposal))
return false;
flags fLastState = GetLastState();
flags fProposalLastState = proposal.GetLastState();
auto nProposalAvailable = proposal.GetAvailable(coins);
return nAmount <= nProposalAvailable && fLastState == NIL &&
(fProposalLastState == DAOFlags::ACCEPTED || fProposalLastState == DAOFlags::PENDING_VOTING_PREQ);
}
bool CPaymentRequest::IsExpired(const CStateViewCache& view) const {
if(nVersion >= BASE_VERSION)
{
flags fLastState = GetLastState();
return (ExceededMaxVotingCycles(view) && fLastState != ACCEPTED && fLastState != REJECTED && fLastState != PAID);
}
return false;
}
bool IsValidProposal(CTransaction tx, const CStateViewCache& view, uint64_t nMaskVersion)
{
if(tx.strDZeel.length() > 1024)
return error("%s: Too long strdzeel for proposal %s", __func__, tx.GetHash().ToString());
UniValue metadata(UniValue::VOBJ);
try {
UniValue valRequest;
if (!valRequest.read(tx.strDZeel))
return error("%s: Wrong strdzeel for proposal %s", __func__, tx.GetHash().ToString());
if (valRequest.isObject())
metadata = valRequest.get_obj();
else
return error("%s: Wrong strdzeel for proposal %s", __func__, tx.GetHash().ToString());
} catch (const UniValue& objError) {
return error("%s: Wrong strdzeel for proposal %s", __func__, tx.GetHash().ToString());
} catch (const std::exception& e) {
return error("%s: Wrong strdzeel for proposal %s: %s", __func__, tx.GetHash().ToString(), e.what());
}
if(!(find_value(metadata, "n").isNum() &&
find_value(metadata, "a").isStr() &&
find_value(metadata, "d").isNum() &&
find_value(metadata, "s").isStr()))
{
return error("%s: Wrong strdzeel for proposal %s", __func__, tx.GetHash().ToString());
}
CAmount nAmount = find_value(metadata, "n").get_int64();
std::string ownerAddress = find_value(metadata, "a").get_str();
std::string paymentAddress = find_value(metadata, "p").isStr() ? find_value(metadata, "p").get_str() : ownerAddress;
int64_t nDeadline = find_value(metadata, "d").get_int64();
CAmount nContribution = 0;
int nVersion = find_value(metadata, "v").isNum() ? find_value(metadata, "v").get_int64() : 1;
CStakeWorkAddress oaddress(ownerAddress);
if (!oaddress.IsValid())
return error("%s: Wrong address %s for proposal %s", __func__, ownerAddress.c_str(), tx.GetHash().ToString());
CStakeWorkAddress paddress(paymentAddress);
if (!paddress.IsValid())
return error("%s: Wrong address %s for proposal %s", __func__, paymentAddress.c_str(), tx.GetHash().ToString());
for(unsigned int i=0;i<tx.vout.size();i++)
if(tx.vout[i].IsCommunityFundContribution())
nContribution +=tx.vout[i].nValue;
bool ret = (nContribution >= GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_FEE, view) &&
ownerAddress != "" &&
paymentAddress != "" &&
nAmount < MAX_MONEY &&
nAmount > 0 &&
nDeadline > 0 &&
(nVersion & ~nMaskVersion) == 0);
if (!ret)
return error("%s: Wrong strdzeel %s for proposal %s", __func__, tx.strDZeel.c_str(), tx.GetHash().ToString());
return true;
}
bool CPaymentRequest::IsAccepted(const CStateViewCache& view) const
{
int nTotalVotes = nVotesYes + nVotesNo;
float nMinimumQuorum = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MIN_QUORUM, view)/10000.0;
if (nVersion & REDUCED_QUORUM_VERSION)
nMinimumQuorum = nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view) / 2 ? Params().GetConsensus().nMinimumQuorumSecondHalf : Params().GetConsensus().nMinimumQuorumFirstHalf;
if (nVersion & ABSTAIN_VOTE_VERSION)
nTotalVotes += nVotesAbs;
return nTotalVotes > GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumQuorum
&& ((float)nVotesYes > ((float)(nTotalVotes) * GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MIN_ACCEPT, view) / 10000.0));
}
bool CPaymentRequest::IsRejected(const CStateViewCache& view) const {
int nTotalVotes = nVotesYes + nVotesNo;
float nMinimumQuorum = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MIN_QUORUM, view)/10000.0;
if (nVersion & REDUCED_QUORUM_VERSION)
nMinimumQuorum = nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view) / 2 ? Params().GetConsensus().nMinimumQuorumSecondHalf : Params().GetConsensus().nMinimumQuorumFirstHalf;
if (nVersion & ABSTAIN_VOTE_VERSION)
nTotalVotes += nVotesAbs;
return nTotalVotes > GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumQuorum
&& ((float)nVotesNo > ((float)(nTotalVotes) * GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MIN_REJECT, view) / 10000.0));
}
bool CPaymentRequest::ExceededMaxVotingCycles(const CStateViewCache& view) const {
return nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view);
}
bool CProposal::IsAccepted(const CStateViewCache& view) const
{
int nTotalVotes = nVotesYes + nVotesNo;
float nMinimumQuorum = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_QUORUM, view)/10000.0;
if (nVersion & REDUCED_QUORUM_VERSION)
nMinimumQuorum = nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view) / 2 ? Params().GetConsensus().nMinimumQuorumSecondHalf : Params().GetConsensus().nMinimumQuorumFirstHalf;
if (nVersion & ABSTAIN_VOTE_VERSION)
nTotalVotes += nVotesAbs;
return nTotalVotes > GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumQuorum
&& ((float)nVotesYes > ((float)(nTotalVotes) * GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_ACCEPT, view) / 10000.0));
}
bool CProposal::IsRejected(const CStateViewCache& view) const
{
int nTotalVotes = nVotesYes + nVotesNo;
float nMinimumQuorum = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_QUORUM, view)/10000.0;
if (nVersion & REDUCED_QUORUM_VERSION)
nMinimumQuorum = nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view) / 2 ? Params().GetConsensus().nMinimumQuorumSecondHalf : Params().GetConsensus().nMinimumQuorumFirstHalf;
if (nVersion & ABSTAIN_VOTE_VERSION)
nTotalVotes += nVotesAbs;
return nTotalVotes > GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view) * nMinimumQuorum
&& ((float)nVotesNo > ((float)(nTotalVotes) * GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_REJECT, view)/ 10000.0));
}
std::string CProposal::GetOwnerAddress() const {
return ownerAddress;
}
std::string CProposal::GetPaymentAddress() const {
return (nVersion & PAYMENT_ADDRESS_VERSION) ? paymentAddress : ownerAddress;
}
bool CProposal::CanVote(const CStateViewCache& view) const {
AssertLockHeld(cs_main);
auto fLastState = GetLastState();
return (fLastState == NIL);
}
uint64_t CProposal::getTimeTillExpired(uint32_t currentTime) const
{
if(nVersion & BASE_VERSION) {
CBlockIndex* pblockindex = GetLastStateBlockIndexForState(ACCEPTED);
if (pblockindex) {
return currentTime - (pblockindex->GetBlockTime() + nDeadline);
}
}
return 0;
}
bool CProposal::IsExpired(uint32_t currentTime, const CStateViewCache& view) const {
if(nVersion & BASE_VERSION) {
CBlockIndex* pblockindex = GetLastStateBlockIndexForState(ACCEPTED);
flags fLastState = GetLastState();
if (fLastState == ACCEPTED && pblockindex) {
return (pblockindex->GetBlockTime() + nDeadline < currentTime);
}
return (fLastState == EXPIRED) || (fLastState == PENDING_VOTING_PREQ) || (ExceededMaxVotingCycles(view) && fLastState == NIL);
} else {
return (nDeadline < currentTime);
}
}
bool CProposal::ExceededMaxVotingCycles(const CStateViewCache& view) const {
return nVotingCycle > GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view);
}
CAmount CProposal::GetAvailable(CStateViewCache& coins, bool fIncludeRequests) const
{
AssertLockHeld(cs_main);
CAmount initial = nAmount;
CPaymentRequestMap mapPaymentRequests;
if(coins.GetAllPaymentRequests(mapPaymentRequests))
{
for (CPaymentRequestMap::iterator it_ = mapPaymentRequests.begin(); it_ != mapPaymentRequests.end(); it_++)
{
CPaymentRequest prequest;
if (!coins.GetPaymentRequest(it_->first, prequest))
continue;
if (prequest.proposalhash != hash)
continue;
flags fLastState = prequest.GetLastState();
if((fIncludeRequests && fLastState != DAOFlags::REJECTED && fLastState != DAOFlags::EXPIRED) || (!fIncludeRequests && (fLastState == DAOFlags::ACCEPTED || fLastState == DAOFlags::PAID)))
initial -= prequest.nAmount;
}
}
return initial;
}
std::string CProposal::ToString(CStateViewCache& coins, uint32_t currentTime) const {
AssertLockHeld(cs_main);
uint256 blockhash;
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex) blockhash = pblockindex->GetBlockHash();
std::string str;
str += strprintf("CProposal(hash=%s, nVersion=%i, nAmount=%f, available=%f, nFee=%f, ownerAddress=%s, paymentAddress=%s, nDeadline=%u, nVotesYes=%u, "
"nVotesAbs=%u, nVotesNo=%u, nVotingCycle=%u, fState=%s, strDZeel=%s, blockhash=%s)",
hash.ToString(), nVersion, (float)nAmount/COIN, (float)GetAvailable(coins)/COIN, (float)nFee/COIN, ownerAddress, paymentAddress, nDeadline,
nVotesYes, nVotesAbs, nVotesNo, nVotingCycle, GetState(currentTime, coins), strDZeel, blockhash.ToString().substr(0,10));
CPaymentRequestMap mapPaymentRequests;
if(coins.GetAllPaymentRequests(mapPaymentRequests))
{
for (CPaymentRequestMap::iterator it_ = mapPaymentRequests.begin(); it_ != mapPaymentRequests.end(); it_++)
{
CPaymentRequest prequest;
if (!coins.GetPaymentRequest(it_->first, prequest))
continue;
if (prequest.proposalhash != hash)
continue;
str += "\n " + prequest.ToString(coins);
}
}
return str + "\n";
}
bool CProposal::HasPendingPaymentRequests(CStateViewCache& coins) const {
AssertLockHeld(cs_main);
CPaymentRequestMap mapPaymentRequests;
if(coins.GetAllPaymentRequests(mapPaymentRequests))
{
for (CPaymentRequestMap::iterator it_ = mapPaymentRequests.begin(); it_ != mapPaymentRequests.end(); it_++)
{
CPaymentRequest prequest;
if (!coins.GetPaymentRequest(it_->first, prequest))
continue;
if (prequest.proposalhash != hash)
continue;
if(prequest.CanVote(coins))
return true;
}
}
return false;
}
std::string CProposal::GetState(uint32_t currentTime, const CStateViewCache& view) const {
std::string sFlags = "pending";
flags fState = GetLastState();
if(IsAccepted(view)) {
sFlags = "accepted";
if(fState == DAOFlags::PENDING_FUNDS)
sFlags += ", waiting for enough coins in fund";
else if(fState != DAOFlags::ACCEPTED)
sFlags += ", waiting for end of voting period";
}
if(IsRejected(view)) {
sFlags = "rejected";
if(fState != DAOFlags::REJECTED)
sFlags += ", waiting for end of voting period";
}
if(currentTime > 0 && IsExpired(currentTime, view)) {
sFlags = "expired";
if(fState != DAOFlags::EXPIRED)
sFlags += ", waiting for end of voting period";
}
if(fState == DAOFlags::PENDING_VOTING_PREQ) {
sFlags = "expired, pending voting of payment requests";
}
return sFlags;
}
flags CProposal::GetLastState() const {
flags ret = NIL;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = it.second;
}
}
return ret;
}
CBlockIndex* CProposal::GetLastStateBlockIndex() const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
CBlockIndex* CProposal::GetLastStateBlockIndexForState(flags state) const {
CBlockIndex* ret = nullptr;
int nHeight = 0;
for (auto& it: mapState)
{
if (it.second != state)
continue;
if (mapBlockIndex.count(it.first) == 0)
continue;
if (mapBlockIndex[it.first]->nHeight > nHeight)
{
nHeight = mapBlockIndex[it.first]->nHeight;
ret = mapBlockIndex[it.first];
}
}
return ret;
}
bool CProposal::SetState(const CBlockIndex* pindex, flags state) {
mapState[pindex->GetBlockHash()] = state;
return true;
}
bool CProposal::ClearState(const CBlockIndex* pindex) {
mapState.erase(pindex->GetBlockHash());
return true;
}
void CProposal::ToJson(UniValue& ret, CStateViewCache& coins) const {
AssertLockHeld(cs_main);
flags fState = GetLastState();
uint256 blockhash;
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex) blockhash = pblockindex->GetBlockHash();
ret.pushKV("version", (uint64_t)nVersion);
ret.pushKV("hash", hash.ToString());
ret.pushKV("blockHash", txblockhash.ToString());
ret.pushKV("description", strDZeel);
ret.pushKV("requestedAmount", FormatMoney(nAmount));
ret.pushKV("notPaidYet", FormatMoney(GetAvailable(coins)));
ret.pushKV("notRequestedYet", FormatMoney(GetAvailable(coins, true)));
ret.pushKV("userPaidFee", FormatMoney(nFee));
ret.pushKV("ownerAddress", GetOwnerAddress());
ret.pushKV("paymentAddress", GetPaymentAddress());
if(nVersion & BASE_VERSION) {
ret.pushKV("proposalDuration", (uint64_t)nDeadline);
if ((fState == DAOFlags::ACCEPTED || fState == DAOFlags::PAID) && mapBlockIndex.count(blockhash) > 0) {
ret.pushKV("expiresOn", pblockindex->GetBlockTime() + (uint64_t)nDeadline);
}
} else {
ret.pushKV("expiresOn", (uint64_t)nDeadline);
}
ret.pushKV("votesYes", nVotesYes);
ret.pushKV("votesAbs", nVotesAbs);
ret.pushKV("votesNo", nVotesNo);
ret.pushKV("votingCycle", std::min((uint64_t)nVotingCycle, GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, coins)+1));
// votingCycle does not return higher than nCyclesProposalVoting to avoid reader confusion, since votes are not counted anyway when votingCycle > nCyclesProposalVoting
UniValue mapState(UniValue::VOBJ);
for (auto&it: this->mapState)
{
mapState.pushKV(std::to_string(it.second), it.first.ToString());
}
ret.pushKV("mapState", mapState);
ret.pushKV("status", GetState(chainActive.Tip()->GetBlockTime(), coins));
ret.pushKV("state", (uint64_t)fState);
if(blockhash != uint256())
ret.pushKV("stateChangedOnBlock", blockhash.ToString());
CPaymentRequestMap mapPaymentRequests;
if(coins.GetAllPaymentRequests(mapPaymentRequests))
{
UniValue preq(UniValue::VOBJ);
UniValue arr(UniValue::VARR);
CPaymentRequest prequest;
for (CPaymentRequestMap::iterator it_ = mapPaymentRequests.begin(); it_ != mapPaymentRequests.end(); it_++)
{
CPaymentRequest prequest;
if (!coins.GetPaymentRequest(it_->first, prequest))
continue;
if (prequest.proposalhash != hash)
continue;
prequest.ToJson(preq, coins);
arr.push_back(preq);
}
ret.pushKV("paymentRequests", arr);
}
}
std::string CPaymentRequest::ToString(const CStateViewCache& view) const {
uint256 blockhash = uint256();
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex)
blockhash = pblockindex->GetBlockHash();
return strprintf("CPaymentRequest(hash=%s, nVersion=%d, nAmount=%f, fState=%s, nVotesYes=%u, nVotesNo=%u, nVotesAbs=%u, nVotingCycle=%u, "
" proposalhash=%s, blockhash=%s, strDZeel=%s)",
hash.ToString(), nVersion, (float)nAmount/COIN, GetState(view), nVotesYes, nVotesNo, nVotesAbs,
nVotingCycle, proposalhash.ToString(), blockhash.ToString().substr(0,10), strDZeel);
}
void CPaymentRequest::ToJson(UniValue& ret, const CStateViewCache& view) const {
ret.pushKV("version",(uint64_t)nVersion);
ret.pushKV("hash", hash.ToString());
ret.pushKV("blockHash", txblockhash.ToString());
ret.pushKV("proposalHash", proposalhash.ToString());
ret.pushKV("description", strDZeel);
ret.pushKV("requestedAmount", FormatMoney(nAmount));
ret.pushKV("votesYes", nVotesYes);
ret.pushKV("votesAbs", nVotesAbs);
ret.pushKV("votesNo", nVotesNo);
ret.pushKV("votingCycle", std::min((uint64_t)nVotingCycle, GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view)+1));
// votingCycle does not return higher than nCyclesPaymentRequestVoting to avoid reader confusion, since votes are not counted anyway when votingCycle > nCyclesPaymentRequestVoting
UniValue mapState(UniValue::VOBJ);
for (auto&it: this->mapState)
{
mapState.pushKV(std::to_string(it.second), it.first.ToString());
}
ret.pushKV("mapState", mapState);
ret.pushKV("status", GetState(view));
ret.pushKV("state", (uint64_t)GetLastState());
CBlockIndex* pblockindex = GetLastStateBlockIndex();
if (pblockindex)
ret.pushKV("stateChangedOnBlock", pblockindex->GetBlockHash().ToString());
}
uint256 GetConsensusStateHash(CStateViewCache& view)
{
CHashWriter writer(0,0);
for (unsigned int i = 0; i < Consensus::MAX_CONSENSUS_PARAMS; i++)
{
Consensus::ConsensusParamsPos id = (Consensus::ConsensusParamsPos)i;
writer << GetConsensusParameter(id, view);
}
uint256 ret = writer.GetHash();
return ret;
}
uint256 GetDAOStateHash(CStateViewCache& view, const CAmount& nCFLocked, const CAmount& nCFSupply)
{
CPaymentRequestMap mapPaymentRequests;
CProposalMap mapProposals;
CConsultationMap mapConsultations;
CConsultationAnswerMap mapAnswers;
CVoteMap mapVotes;
int64_t nTimeStart = GetTimeMicros();
CHashWriter writer(0,0);
writer << nCFSupply;
writer << nCFLocked;
if (view.GetAllProposals(mapProposals) && view.GetAllPaymentRequests(mapPaymentRequests) &&
view.GetAllConsultations(mapConsultations) && view.GetAllVotes(mapVotes) &&
view.GetAllConsultationAnswers(mapAnswers))
{
for (auto &it: mapProposals)
{
if (!it.second.IsNull())
{
writer << it.second;
}
}
for (auto &it: mapPaymentRequests)
{
if (!it.second.IsNull())
{
writer << it.second;
}
}
for (auto &it: mapConsultations)
{
if (!it.second.IsNull())
{
writer << it.second;
}
}
for (auto &it: mapVotes)
{
if (!it.second.IsNull())
{
writer << it.first;
writer << it.second.GetList();
}
}
for (auto &it: mapAnswers)
{
if (!it.second.IsNull())
{
writer << it.second;
}
}
for (unsigned int i = 0; i < Consensus::MAX_CONSENSUS_PARAMS; i++)
{
Consensus::ConsensusParamsPos id = (Consensus::ConsensusParamsPos)i;
writer << GetConsensusParameter(id, view);
}
}
uint256 ret = writer.GetHash();
int64_t nTimeEnd = GetTimeMicros();
LogPrint("bench", " Benchmark: Calculate CFundDB state hash: %.2fms\n", (nTimeEnd - nTimeStart) * 0.001);
return ret;
}
|
#include <iostream>
#include <string>
int main () {
std::string str;
while (getline (std::cin, str)) {
char max = '\0';
for (int i = 0; i < str.size (); ++i) {
if (str[i] > max) {
max = str [i];
}
}
for (int i = 0; i < str.size (); ++i) {
printf ("%c", str[i]);
if (str[i] == max) {
printf ("(max)");
}
}
printf ("\n");
}
return 0;
}
|
#include "irqhandler.h"
// Local logging tag
static const char TAG[] = __FILE__;
// irq handler task, handles all our application level interrupts
void irqHandler(void *pvParameters) {
configASSERT(((uint32_t)pvParameters) == 1); // FreeRTOS check
uint32_t InterruptStatus;
// task remains in blocked state until it is notified by an irq
for (;;) {
xTaskNotifyWait(0x00, // Don't clear any bits on entry
ULONG_MAX, // Clear all bits on exit
&InterruptStatus, // Receives the notification value
portMAX_DELAY); // wait forever
if (InterruptStatus & UNMASK_IRQ) // interrupt handler to be enabled?
InterruptStatus &= ~MASK_IRQ; // then clear irq mask flag
// else suppress processing if interrupt handler is disabled
// or time critical lmic jobs are pending in next 100ms
else if ((InterruptStatus & MASK_IRQ)
#if (HAS_LORA)
|| os_queryTimeCriticalJobs(ms2osticks(100))
#endif
)
continue;
// button pressed?
#ifdef HAS_BUTTON
if (InterruptStatus & BUTTON_IRQ) {
readButton();
InterruptStatus &= ~BUTTON_IRQ;
}
#endif
// display needs refresh?
#ifdef HAS_DISPLAY
if (InterruptStatus & DISPLAY_IRQ) {
dp_refresh();
InterruptStatus &= ~DISPLAY_IRQ;
}
#endif
// LED Matrix display needs refresh?
#ifdef HAS_MATRIX_DISPLAY
if (InterruptStatus & MATRIX_DISPLAY_IRQ) {
refreshTheMatrixDisplay();
InterruptStatus &= ~MATRIX_DISPLAY_IRQ;
}
#endif
#if (TIME_SYNC_INTERVAL)
// is time to be synced?
if (InterruptStatus & TIMESYNC_IRQ) {
now(); // ensure sysTime is recent
calibrateTime();
InterruptStatus &= ~TIMESYNC_IRQ;
}
#endif
// BME sensor data to be read?
#if (HAS_BME)
if (InterruptStatus & BME_IRQ) {
bme_storedata(&bme_status);
InterruptStatus &= ~BME_IRQ;
}
#endif
// Solar data to be read?
#if (HAS_SOLAR)
if (InterruptStatus & SOLAR_IRQ)
{
solar_storedata(&solarStatus);
InterruptStatus &= ~SOLAR_IRQ;
}
if (InterruptStatus & PMU_IRQ)
{
Coloumb_PowerEvent_IRQ();
InterruptStatus &= ~PMU_IRQ;
}
#endif
// are cyclic tasks due?
if (InterruptStatus & CYCLIC_IRQ) {
doHousekeeping();
InterruptStatus &= ~CYCLIC_IRQ;
}
// do we have a power event?
#if (HAS_PMU)
if (InterruptStatus & PMU_IRQ) {
AXP192_powerevent_IRQ();
InterruptStatus &= ~PMU_IRQ;
}
#endif
// is time to send the payload?
if (InterruptStatus & SENDCYCLE_IRQ) {
sendData();
InterruptStatus &= ~SENDCYCLE_IRQ;
}
} // for
} // irqHandler()
// esp32 hardware timer triggered interrupt service routines
// they notify the irq handler task
#ifdef HAS_DISPLAY
void IRAM_ATTR DisplayIRQ() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTaskNotifyFromISR(irqHandlerTask, DISPLAY_IRQ, eSetBits,
&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken)
portYIELD_FROM_ISR();
}
#endif
#ifdef HAS_MATRIX_DISPLAY
void IRAM_ATTR MatrixDisplayIRQ() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTaskNotifyFromISR(irqHandlerTask, MATRIX_DISPLAY_IRQ, eSetBits,
&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken)
portYIELD_FROM_ISR();
}
#endif
#ifdef HAS_BUTTON
void IRAM_ATTR ButtonIRQ() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTaskNotifyFromISR(irqHandlerTask, BUTTON_IRQ, eSetBits,
&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken)
portYIELD_FROM_ISR();
}
#endif
#ifdef HAS_PMU
void IRAM_ATTR PMUIRQ() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTaskNotifyFromISR(irqHandlerTask, PMU_IRQ, eSetBits,
&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken)
portYIELD_FROM_ISR();
}
#endif
void mask_user_IRQ() { xTaskNotify(irqHandlerTask, MASK_IRQ, eSetBits); }
void unmask_user_IRQ() { xTaskNotify(irqHandlerTask, UNMASK_IRQ, eSetBits); }
|
//
// bluetooth/detail/impl/endpoint.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2019 Huang Qinjin (huangqinjin at gmail 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_BLUETOOTH_DETAIL_IMPL_ENDPOINT_IPP
#define BOOST_ASIO_BLUETOOTH_DETAIL_IMPL_ENDPOINT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_BLUETOOTH_SOCKETS)
#include <cstring>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/bluetooth/detail/endpoint.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace bluetooth {
namespace detail {
endpoint::endpoint() BOOST_ASIO_NOEXCEPT
: data_()
{
data_.bt.addressFamily = BOOST_ASIO_OS_DEF(AF_BLUETOOTH);
}
endpoint::endpoint(const boost::asio::bluetooth::address& addr,
unsigned short channel_num) BOOST_ASIO_NOEXCEPT
: data_()
{
data_.bt.addressFamily = BOOST_ASIO_OS_DEF(AF_BLUETOOTH);
address(addr);
channel(channel_num);
}
void endpoint::resize(std::size_t new_size)
{
if (new_size > sizeof(data_))
{
boost::system::error_code ec(boost::asio::error::invalid_argument);
boost::asio::detail::throw_error(ec);
}
}
unsigned short endpoint::channel() const BOOST_ASIO_NOEXCEPT
{
return data_.bt.port;
}
void endpoint::channel(unsigned short channel_num) BOOST_ASIO_NOEXCEPT
{
data_.bt.port = channel_num;
}
boost::asio::bluetooth::address endpoint::address() const BOOST_ASIO_NOEXCEPT
{
boost::asio::bluetooth::address addr;
memcpy(&addr.data, &data_.bt.btAddr, sizeof(addr.data));
return addr;
}
void endpoint::address(const boost::asio::bluetooth::address& addr) BOOST_ASIO_NOEXCEPT
{
memcpy(&data_.bt.btAddr, &addr.data, sizeof(addr.data));
}
bool operator==(const endpoint& e1, const endpoint& e2) BOOST_ASIO_NOEXCEPT
{
return e1.address() == e2.address() && e1.channel() == e2.channel();
}
bool operator<(const endpoint& e1, const endpoint& e2) BOOST_ASIO_NOEXCEPT
{
if (e1.address() < e2.address())
return true;
if (e1.address() != e2.address())
return false;
return (e1.channel() < e2.channel());
}
#if !defined(BOOST_ASIO_NO_IOSTREAM)
std::string endpoint::to_string() const
{
std::ostringstream tmp_os;
tmp_os.imbue(std::locale::classic());
tmp_os << '[' << address() << ']' << ':' << channel();
return tmp_os.str();
}
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
} // namespace detail
} // namespace bluetooth
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_BLUETOOTH_SOCKETS)
#endif // BOOST_ASIO_BLUETOOTH_DETAIL_IMPL_ENDPOINT_IPP
|
#include "timer.h"
#include <stdio.h>
#include <sys/time.h>
namespace utils {
double TimingUnit::get_current_time() {
struct timeval tp;
gettimeofday(&tp, NULL);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1.0E-6);
}
void Timer::add(std::string name, std::string parent) {
if (name == "") {
return;
}
if (_timer.find(name) == _timer.end()) {
int level = 0;
int id = 0;
if (parent != "" && _timer.find(parent) != _timer.end()) {
level = _timer[parent]._level + 1;
id = _timer[parent]._number_of_children;
_timer[parent]._number_of_children += 1;
}
if (level >= _number_of_levels) {
_number_of_levels = level + 1;
}
_timer[name] = TimerUnit(level, id, parent);
}
}
std::string Timer::trans_to_string() {
//return trans_to_string(0, "");
return trans_to_string_in_order(0, "");
}
void Timer::print() {
print_in_order(0, "");
clear();
}
std::string Timer::trans_to_string(int level, std::string parent) {
std::stringstream result;
for (std::map<std::string, TimerUnit>::iterator iter = _timer.begin();
iter != _timer.end(); ++iter) {
if (iter->second._level == level &&
iter->second._parent.compare(parent) == 0) {
for (int i = 0; i < level; ++i) {
result << "....";
}
result << iter->first << ": "
<< iter->second._seconds * 1000 << " ms, "
<< iter->second._seconds * 100 / _seconds << "%\n";
result << trans_to_string(level + 1, iter->first);
}
}
return result.str();
}
std::string Timer::trans_to_string_in_order(int level, std::string parent) {
std::stringstream result;
int number_of_children = 0;
if (level == 0) {
number_of_children = 1;
} else if (_timer.find(parent) != _timer.end()) {
number_of_children = _timer[parent]._number_of_children;
} else {
number_of_children = 0;
}
for (int id = 0; id < number_of_children; ++id) {
for (std::map<std::string, TimerUnit>::iterator iter = _timer.begin();
iter != _timer.end(); ++iter) {
if (iter->second._level == level && iter->second._id == id
&& iter->second._parent.compare(parent) == 0) {
for (int i = 0; i < level; ++i) {
result << "....";
}
result << "[" << iter->second._id << "] "
<< iter->first << ": " << iter->second._seconds * 1000 << " ms"
//<< ", " << iter->second._seconds * 100 / _seconds << "%"
<< "\n";
result << trans_to_string_in_order(level + 1, iter->first);
}
}
}
return result.str();
}
void Timer::print_in_order(int level, std::string parent) {
int number_of_children = 0;
if (level == 0) {
number_of_children = 1;
} else if (_timer.find(parent) != _timer.end()) {
number_of_children = _timer[parent]._number_of_children;
} else {
number_of_children = 0;
}
for (int id = 0; id < number_of_children; ++id) {
for (std::map<std::string, TimerUnit>::iterator iter = _timer.begin();
iter != _timer.end(); ++iter) {
if (iter->second._level == level && iter->second._id == id &&
iter->second._parent.compare(parent) == 0) {
std::stringstream result;
for (int i = 0; i < level; ++i) {
result << "....";
}
result << "[" << iter->second._id << "] "
<< iter->first << ": " << iter->second._seconds * 1000 << " ms"
//<< ", " << iter->second._seconds * 100 / _seconds << "%"
<< "\n";
fprintf(stdout, "%s", result.str().c_str());
print_in_order(level + 1, iter->first);
}
}
}
}
Timer g_utils_timer;
} // namespace utils
|
/******************************************************************************
*
* Project: GDAL Utilities
* Purpose: Rasterize OGR shapes into a GDAL raster.
* Authors: Even Rouault, <even dot rouault at spatialys dot com>
*
******************************************************************************
* Copyright (c) 2015, Even Rouault <even dot rouault at spatialys dot com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_string.h"
#include "commonutils.h"
#include "gdal_utils_priv.h"
#include "gdal_priv.h"
CPL_CVSID("$Id$");
/************************************************************************/
/* Usage() */
/************************************************************************/
static void Usage(const char* pszErrorMsg = NULL)
{
printf(
"Usage: gdal_rasterize [-b band]* [-i] [-at]\n"
" {[-burn value]* | [-a attribute_name] | [-3d]} [-add]\n"
" [-l layername]* [-where expression] [-sql select_statement]\n"
" [-dialect dialect] [-of format] [-a_srs srs_def]\n"
" [-co \"NAME=VALUE\"]* [-a_nodata value] [-init value]*\n"
" [-te xmin ymin xmax ymax] [-tr xres yres] [-tap] [-ts width height]\n"
" [-ot {Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/\n"
" CInt16/CInt32/CFloat32/CFloat64}] [-q]\n"
" <src_datasource> <dst_filename>\n" );
if( pszErrorMsg != NULL )
fprintf(stderr, "\nFAILURE: %s\n", pszErrorMsg);
exit( 1 );
}
/************************************************************************/
/* GDALRasterizeOptionsForBinaryNew() */
/************************************************************************/
static GDALRasterizeOptionsForBinary *GDALRasterizeOptionsForBinaryNew(void)
{
return (GDALRasterizeOptionsForBinary*) CPLCalloc( 1, sizeof(GDALRasterizeOptionsForBinary) );
}
/************************************************************************/
/* GDALRasterizeOptionsForBinaryFree() */
/************************************************************************/
static void GDALRasterizeOptionsForBinaryFree( GDALRasterizeOptionsForBinary* psOptionsForBinary )
{
if( psOptionsForBinary )
{
CPLFree(psOptionsForBinary->pszSource);
CPLFree(psOptionsForBinary->pszDest);
CPLFree(psOptionsForBinary->pszFormat);
CPLFree(psOptionsForBinary);
}
}
/************************************************************************/
/* main() */
/************************************************************************/
int main(int argc, char** argv)
{
/* Check strict compilation and runtime library version as we use C++ API */
if (! GDAL_CHECK_VERSION(argv[0]))
exit(1);
EarlySetConfigOptions(argc, argv);
/* -------------------------------------------------------------------- */
/* Generic arg processing. */
/* -------------------------------------------------------------------- */
GDALAllRegister();
argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
if( argc < 1 )
exit( -argc );
for( int i = 0; i < argc; i++ )
{
if( EQUAL(argv[i], "--utility_version") )
{
printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
CSLDestroy( argv );
return 0;
}
else if( EQUAL(argv[i],"--help") )
{
Usage();
}
}
GDALRasterizeOptionsForBinary* psOptionsForBinary = GDALRasterizeOptionsForBinaryNew();
/* coverity[tainted_data] */
GDALRasterizeOptions *psOptions = GDALRasterizeOptionsNew(argv + 1, psOptionsForBinary);
CSLDestroy( argv );
if( psOptions == NULL )
{
Usage();
}
if( !(psOptionsForBinary->bQuiet) )
{
GDALRasterizeOptionsSetProgress(psOptions, GDALTermProgress, NULL);
}
if( psOptionsForBinary->pszSource == NULL )
Usage("No input file specified.");
if( psOptionsForBinary->pszDest == NULL )
Usage("No output file specified.");
/* -------------------------------------------------------------------- */
/* Open input file. */
/* -------------------------------------------------------------------- */
GDALDatasetH hInDS = GDALOpenEx( psOptionsForBinary->pszSource, GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR,
NULL, NULL, NULL );
if( hInDS == NULL )
exit( 1 );
/* -------------------------------------------------------------------- */
/* Open output file if it exists. */
/* -------------------------------------------------------------------- */
GDALDatasetH hDstDS = NULL;
if( !(psOptionsForBinary->bCreateOutput) )
{
CPLPushErrorHandler( CPLQuietErrorHandler );
hDstDS = GDALOpenEx( psOptionsForBinary->pszDest, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR | GDAL_OF_UPDATE,
NULL, NULL, NULL );
CPLPopErrorHandler();
}
if( psOptionsForBinary->bCreateOutput || hDstDS == NULL )
{
GDALDriverManager *poDM = GetGDALDriverManager();
GDALDriver* poDriver = poDM->GetDriverByName(psOptionsForBinary->pszFormat);
char** papszDriverMD = (poDriver) ? poDriver->GetMetadata(): NULL;
if( poDriver == NULL
|| !CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE") )
|| !CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE") ) )
{
fprintf( stderr, "Output driver `%s' not recognised or does not support "
"direct output file creation.\n", psOptionsForBinary->pszFormat);
fprintf(stderr, "The following format drivers are configured and support direct output:\n" );
for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ )
{
GDALDriver* poIter = poDM->GetDriver(iDriver);
papszDriverMD = poIter->GetMetadata();
if( CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE") ) &&
CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE") ) )
{
fprintf( stderr, " -> `%s'\n", poIter->GetDescription() );
}
}
exit( 1 );
}
}
if (hDstDS == NULL && !psOptionsForBinary->bQuiet && !psOptionsForBinary->bFormatExplicitlySet)
CheckExtensionConsistency(psOptionsForBinary->pszDest, psOptionsForBinary->pszFormat);
int bUsageError = FALSE;
GDALDatasetH hRetDS = GDALRasterize(psOptionsForBinary->pszDest,
hDstDS,
hInDS,
psOptions, &bUsageError);
if(bUsageError == TRUE)
Usage();
int nRetCode = (hRetDS) ? 0 : 1;
GDALClose(hInDS);
GDALClose(hRetDS);
GDALRasterizeOptionsFree(psOptions);
GDALRasterizeOptionsForBinaryFree(psOptionsForBinary);
GDALDestroyDriverManager();
return nRetCode;
}
|
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "spork.h"
#include "base58.h"
#include "key.h"
#include "main.h"
#include "masternode-budget.h"
#include "net.h"
#include "protocol.h"
#include "sync.h"
#include "sporkdb.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
// Delion: on startup load spork values from previous session if they exist in the sporkDB
void LoadSporksFromDB()
{
for (int i = SPORK_START; i <= SPORK_END; ++i) {
// Since not all spork IDs are in use, we have to exclude undefined IDs
std::string strSpork = sporkManager.GetSporkNameByID(i);
if (strSpork == "Unknown") continue;
// attempt to read spork from sporkDB
CSporkMessage spork;
if (!pSporkDB->ReadSpork(i, spork)) {
LogPrintf("%s : no previous value for %s found in database\n", __func__, strSpork);
continue;
}
// add spork to memory
mapSporks[spork.GetHash()] = spork;
mapSporksActive[spork.nSporkID] = spork;
std::time_t result = spork.nValue;
// If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format
if (spork.nValue > 1000000) {
LogPrintf("%s : loaded spork %s with value %d : %s", __func__,
sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue,
std::ctime(&result));
} else {
LogPrintf("%s : loaded spork %s with value %d\n", __func__,
sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue);
}
}
}
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (fLiteMode) return; //disable all obfuscation/masternode related functionality
if (strCommand == "spork") {
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if (chainActive.Tip() == NULL) return;
// Ignore spork messages about unknown/deleted sporks
std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID);
if (strSpork == "Unknown") return;
uint256 hash = spork.GetHash();
if (mapSporksActive.count(spork.nSporkID)) {
if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {
if (fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if (fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if (!sporkManager.CheckSignature(spork)) {
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
// Delion: add to spork database.
pSporkDB->WriteSpork(spork.nSporkID, spork);
}
if (strCommand == "getsporks") {
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while (it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the value of the spork on the network, or the default
int64_t GetSporkValue(int nSporkID)
{
int64_t r = -1;
if (mapSporksActive.count(nSporkID)) {
r = mapSporksActive[nSporkID].nValue;
} else {
if (nSporkID == SPORK_2_SWIFTTX) r = SPORK_2_SWIFTTX_DEFAULT;
if (nSporkID == SPORK_3_SWIFTTX_BLOCK_FILTERING) r = SPORK_3_SWIFTTX_BLOCK_FILTERING_DEFAULT;
if (nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if (nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if (nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if (nSporkID == SPORK_11_LOCK_INVALID_UTXO) r = SPORK_11_LOCK_INVALID_UTXO_DEFAULT;
if (nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if (nSporkID == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) r = SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT;
if (nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) r = SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT;
if (nSporkID == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) r = SPORK_16_ZEROCOIN_MAINTENANCE_MODE_DEFAULT;
if (r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
// grab the spork value, and see if it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = GetSporkValue(nSporkID);
if (r == -1) return false;
return r < GetTime();
}
void ReprocessBlocks(int nBlocks)
{
std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();
while (it != mapRejectedBlocks.end()) {
//use a window twice as large as is usual for the nBlocks we want to reset
if ((*it).second > GetTime() - (nBlocks * 60 * 5)) {
BlockMap::iterator mi = mapBlockIndex.find((*it).first);
if (mi != mapBlockIndex.end() && (*mi).second) {
LOCK(cs_main);
CBlockIndex* pindex = (*mi).second;
LogPrintf("ReprocessBlocks - %s\n", (*it).first.ToString());
CValidationState state;
ReconsiderBlock(state, pindex);
}
}
++it;
}
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nBlocks);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkeynew(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if (obfuScationSigner.VerifyMessage(pubkeynew, spork.vchSig, strMessage, errorMessage)) {
return true;
}
return false;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if (!obfuScationSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) {
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if (!obfuScationSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if (!obfuScationSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if (Sign(msg)) {
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if (CheckSignature(msg)) {
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if (strName == "SPORK_2_SWIFTTX") return SPORK_2_SWIFTTX;
if (strName == "SPORK_3_SWIFTTX_BLOCK_FILTERING") return SPORK_3_SWIFTTX_BLOCK_FILTERING;
if (strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if (strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if (strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if (strName == "SPORK_11_LOCK_INVALID_UTXO") return SPORK_11_LOCK_INVALID_UTXO;
if (strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
if (strName == "SPORK_14_NEW_PROTOCOL_ENFORCEMENT") return SPORK_14_NEW_PROTOCOL_ENFORCEMENT;
if (strName == "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2") return SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2;
if (strName == "SPORK_16_ZEROCOIN_MAINTENANCE_MODE") return SPORK_16_ZEROCOIN_MAINTENANCE_MODE;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if (id == SPORK_2_SWIFTTX) return "SPORK_2_SWIFTTX";
if (id == SPORK_3_SWIFTTX_BLOCK_FILTERING) return "SPORK_3_SWIFTTX_BLOCK_FILTERING";
if (id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if (id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if (id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if (id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if (id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if (id == SPORK_11_LOCK_INVALID_UTXO) return "SPORK_11_LOCK_INVALID_UTXO";
if (id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
if (id == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) return "SPORK_14_NEW_PROTOCOL_ENFORCEMENT";
if (id == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) return "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2";
if (id == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) return "SPORK_16_ZEROCOIN_MAINTENANCE_MODE";
return "Unknown";
}
|
#include <chrono>
#include <fstream>
#include <list>
#include <map>
#include <memory>
#include <string>
#include "envoy/api/v2/rds.pb.validate.h"
#include "envoy/api/v2/route/route.pb.validate.h"
#include "envoy/server/filter_config.h"
#include "common/config/metadata.h"
#include "common/config/well_known_names.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/network/address_impl.h"
#include "common/router/config_impl.h"
#include "extensions/filters/http/common/empty_http_filter_config.h"
#include "test/common/router/route_fuzz.pb.h"
#include "test/fuzz/utility.h"
#include "test/mocks/server/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/printers.h"
#include "test/test_common/registry.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::ContainerEq;
using testing::ElementsAreArray;
using testing::Eq;
using testing::Matcher;
using testing::MockFunction;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::StrNe;
namespace Envoy {
namespace Router {
namespace {
// Wrap ConfigImpl, the target of tests to allow us to regenerate the route_fuzz_test
// corpus when run with:
// bazel run //test/common/router:config_impl_test
// --test_env="ROUTE_CORPUS_PATH=$PWD/test/common/router/route_corpus"
class TestConfigImpl : public ConfigImpl {
public:
TestConfigImpl(const envoy::api::v2::RouteConfiguration& config,
Server::Configuration::FactoryContext& factory_context,
bool validate_clusters_default)
: ConfigImpl(config, factory_context, validate_clusters_default), config_(config) {}
RouteConstSharedPtr route(const Http::HeaderMap& headers, uint64_t random_value) const override {
absl::optional<std::string> corpus_path =
TestEnvironment::getOptionalEnvVar("GENRULE_OUTPUT_DIR");
if (corpus_path) {
static uint32_t n;
test::common::router::RouteTestCase route_test_case;
route_test_case.mutable_config()->MergeFrom(config_);
route_test_case.mutable_headers()->MergeFrom(Fuzz::toHeaders(headers));
route_test_case.set_random_value(random_value);
const std::string path = fmt::format("{}/generated_corpus_{}", corpus_path.value(), n++);
const std::string corpus = route_test_case.DebugString();
{
std::ofstream corpus_file(path);
ENVOY_LOG_MISC(debug, "Writing {} to {}", corpus, path);
corpus_file << corpus;
}
}
return ConfigImpl::route(headers, random_value);
}
const envoy::api::v2::RouteConfiguration config_;
};
Http::TestHeaderMapImpl genHeaders(const std::string& host, const std::string& path,
const std::string& method) {
return Http::TestHeaderMapImpl{{":authority", host}, {":path", path},
{":method", method}, {"x-safe", "safe"},
{"x-global-nope", "global"}, {"x-vhost-nope", "vhost"},
{"x-route-nope", "route"}, {"x-forwarded-proto", "http"}};
}
envoy::api::v2::RouteConfiguration parseRouteConfigurationFromV2Yaml(const std::string& yaml) {
envoy::api::v2::RouteConfiguration route_config;
TestUtility::loadFromYaml(yaml, route_config);
TestUtility::validate(route_config);
return route_config;
}
class ConfigImplTestBase {
protected:
ConfigImplTestBase() : api_(Api::createApiForTest()) {
ON_CALL(factory_context_, api()).WillByDefault(ReturnRef(*api_));
}
std::string virtualHostName(const RouteEntry* route) {
Stats::StatName name = route->virtualHost().statName();
return factory_context_.scope().symbolTable().toString(name);
}
std::string virtualClusterName(const RouteEntry* route, Http::TestHeaderMapImpl& headers) {
Stats::StatName name = route->virtualCluster(headers)->statName();
return factory_context_.scope().symbolTable().toString(name);
}
Stats::TestSymbolTable symbol_table_;
Api::ApiPtr api_;
NiceMock<Server::Configuration::MockFactoryContext> factory_context_;
};
class RouteMatcherTest : public testing::Test, public ConfigImplTestBase {};
// TODO(alyssawilk) go through all these tests and update or duplicate.
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(TestRoutes)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- lyft.com
- www.lyft.com
- w.lyft.com
- ww.lyft.com
- wwww.lyft.com
routes:
- match:
prefix: "/new_endpoint"
route:
prefix_rewrite: "/api/new_endpoint"
cluster: www2
- match:
path: "/"
route:
cluster: root_www2
- match:
prefix: "/"
route:
cluster: www2
- name: www2_staging
domains:
- www-staging.lyft.net
- www-staging-orca.lyft.com
routes:
- match:
prefix: "/"
route:
cluster: www2_staging
- name: wildcard
domains:
- "*.foo.com"
- "*-bar.baz.com"
routes:
- match:
prefix: "/"
route:
cluster: wildcard
- name: wildcard2
domains:
- "*.baz.com"
routes:
- match:
prefix: "/"
route:
cluster: wildcard2
- name: regex
domains:
- bat.com
routes:
- match:
regex: "/t[io]c"
route:
cluster: clock
- match:
safe_regex:
google_re2: {}
regex: "/baa+"
route:
cluster: sheep
- match:
regex: ".*/\\d{3}$"
route:
cluster: three_numbers
prefix_rewrite: "/rewrote"
- match:
regex: ".*"
route:
cluster: regex_default
- name: regex2
domains:
- bat2.com
routes:
- match:
regex: ''
route:
cluster: nothingness
- match:
regex: ".*"
route:
cluster: regex_default
- name: default
domains:
- "*"
routes:
- match:
prefix: "/api/application_data"
route:
cluster: ats
- match:
path: "/api/locations"
case_sensitive: false
route:
cluster: locations
prefix_rewrite: "/rewrote"
- match:
prefix: "/api/leads/me"
route:
cluster: ats
- match:
prefix: "/host/rewrite/me"
route:
cluster: ats
host_rewrite: new_host
- match:
prefix: "/oldhost/rewrite/me"
route:
cluster: ats
host_rewrite: new_oldhost
- match:
path: "/foo"
case_sensitive: true
route:
prefix_rewrite: "/bar"
cluster: instant-server
- match:
path: "/tar"
case_sensitive: false
route:
prefix_rewrite: "/car"
cluster: instant-server
- match:
prefix: "/newhost/rewrite/me"
case_sensitive: false
route:
cluster: ats
host_rewrite: new_host
- match:
path: "/FOOD"
case_sensitive: false
route:
prefix_rewrite: "/cAndy"
cluster: ats
- match:
path: "/ApplEs"
case_sensitive: true
route:
prefix_rewrite: "/oranGES"
cluster: instant-server
- match:
path: "/rewrite-host-with-header-value"
request_headers_to_add:
- header:
key: x-rewrite-host
value: rewrote
route:
cluster: ats
auto_host_rewrite_header: x-rewrite-host
- match:
path: "/do-not-rewrite-host-with-header-value"
route:
cluster: ats
auto_host_rewrite_header: x-rewrite-host
- match:
prefix: "/"
route:
cluster: instant-server
timeout: 30s
virtual_clusters:
- pattern: "^/rides$"
method: POST
name: ride_request
- pattern: "^/rides/\\d+$"
method: PUT
name: update_ride
- pattern: "^/users/\\d+/chargeaccounts$"
method: POST
name: cc_add
- pattern: "^/users/\\d+/chargeaccounts/(?!validate)\\w+$"
method: PUT
name: cc_add
- pattern: "^/users$"
method: POST
name: create_user_login
- pattern: "^/users/\\d+$"
method: PUT
name: update_user
- headers:
- name: ":path"
safe_regex_match:
google_re2: {}
regex: "^/users/\\d+/location$"
- name: ":method"
exact_match: POST
name: ulu
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// Base routing testing.
EXPECT_EQ("instant-server",
config.route(genHeaders("api.lyft.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("ats", config.route(genHeaders("api.lyft.com", "/api/leads/me", "GET"), 0)
->routeEntry()
->clusterName());
EXPECT_EQ("ats", config.route(genHeaders("api.lyft.com", "/api/application_data", "GET"), 0)
->routeEntry()
->clusterName());
EXPECT_EQ("locations",
config.route(genHeaders("api.lyft.com", "/api/locations?works=true", "GET"), 0)
->routeEntry()
->clusterName());
EXPECT_EQ("locations", config.route(genHeaders("api.lyft.com", "/api/locations", "GET"), 0)
->routeEntry()
->clusterName());
EXPECT_EQ("www2",
config.route(genHeaders("lyft.com", "/foo", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("root_www2",
config.route(genHeaders("wwww.lyft.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("www2",
config.route(genHeaders("LYFT.COM", "/foo", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("root_www2",
config.route(genHeaders("wWww.LyfT.coM", "/", "GET"), 0)->routeEntry()->clusterName());
// Wildcards
EXPECT_EQ("wildcard",
config.route(genHeaders("www.foo.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ(
"wildcard",
config.route(genHeaders("foo-bar.baz.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("wildcard2",
config.route(genHeaders("-bar.baz.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("wildcard2",
config.route(genHeaders("bar.baz.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("instant-server",
config.route(genHeaders(".foo.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("instant-server",
config.route(genHeaders("foo.com", "/", "GET"), 0)->routeEntry()->clusterName());
// Regular Expression matching
EXPECT_EQ("clock",
config.route(genHeaders("bat.com", "/tic", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("clock",
config.route(genHeaders("bat.com", "/toc", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat.com", "/tac", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat.com", "", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat.com", "/tick", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat.com", "/tic/toc", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("sheep",
config.route(genHeaders("bat.com", "/baa", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ(
"sheep",
config.route(genHeaders("bat.com", "/baaaaaaaaaaaa", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat.com", "/ba", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("nothingness",
config.route(genHeaders("bat2.com", "", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat2.com", "/foo", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("regex_default",
config.route(genHeaders("bat2.com", " ", "GET"), 0)->routeEntry()->clusterName());
// Regular Expression matching with query string params
EXPECT_EQ(
"clock",
config.route(genHeaders("bat.com", "/tic?tac=true", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ(
"regex_default",
config.route(genHeaders("bat.com", "/tac?tic=true", "GET"), 0)->routeEntry()->clusterName());
// Timeout testing.
EXPECT_EQ(std::chrono::milliseconds(30000),
config.route(genHeaders("api.lyft.com", "/", "GET"), 0)->routeEntry()->timeout());
EXPECT_EQ(
std::chrono::milliseconds(15000),
config.route(genHeaders("api.lyft.com", "/api/leads/me", "GET"), 0)->routeEntry()->timeout());
// Prefix rewrite testing.
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/new_endpoint/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www2", route->clusterName());
EXPECT_EQ("www2", virtualHostName(route));
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/api/new_endpoint/foo", headers.get_(Http::Headers::get().Path));
EXPECT_EQ("/new_endpoint/foo", headers.get_(Http::Headers::get().EnvoyOriginalPath));
}
// Prefix rewrite testing (x-envoy-* headers suppressed).
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/new_endpoint/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www2", route->clusterName());
EXPECT_EQ("www2", virtualHostName(route));
route->finalizeRequestHeaders(headers, stream_info, false);
EXPECT_EQ("/api/new_endpoint/foo", headers.get_(Http::Headers::get().Path));
EXPECT_FALSE(headers.has(Http::Headers::get().EnvoyOriginalPath));
}
// Prefix rewrite on path match with query string params
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/api/locations?works=true", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/rewrote?works=true", headers.get_(Http::Headers::get().Path));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/bar", headers.get_(Http::Headers::get().Path));
}
// Host rewrite testing.
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/host/rewrite/me", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("new_host", headers.get_(Http::Headers::get().Host));
}
// Rewrites host using supplied header.
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/rewrite-host-with-header-value", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("rewrote", headers.get_(Http::Headers::get().Host));
}
// Does not rewrite host because of missing header.
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/do-not-rewrite-host-with-header-value", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("api.lyft.com", headers.get_(Http::Headers::get().Host));
}
// Case sensitive rewrite matching test.
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/API/locations?works=true", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/rewrote?works=true", headers.get_(Http::Headers::get().Path));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/fooD", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/cAndy", headers.get_(Http::Headers::get().Path));
}
// Case sensitive is set to true and will not rewrite
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/FOO", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/FOO", headers.get_(Http::Headers::get().Path));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/ApPles", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/ApPles", headers.get_(Http::Headers::get().Path));
}
// Case insensitive set to false so there is no rewrite
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/oLDhost/rewrite/me", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("api.lyft.com", headers.get_(Http::Headers::get().Host));
}
// Case sensitive is set to false and will not rewrite
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/Tart", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/Tart", headers.get_(Http::Headers::get().Path));
}
// Case sensitive is set to false and will not rewrite
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/newhost/rewrite/me", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("new_host", headers.get_(Http::Headers::get().Host));
}
// Prefix rewrite for regular expression matching
{
Http::TestHeaderMapImpl headers = genHeaders("bat.com", "/647", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/rewrote", headers.get_(Http::Headers::get().Path));
}
// Prefix rewrite for regular expression matching with query string
{
Http::TestHeaderMapImpl headers = genHeaders("bat.com", "/970?foo=true", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/rewrote?foo=true", headers.get_(Http::Headers::get().Path));
}
{
Http::TestHeaderMapImpl headers = genHeaders("bat.com", "/foo/bar/238?bar=true", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("/rewrote?bar=true", headers.get_(Http::Headers::get().Path));
}
// Virtual cluster testing.
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/rides", "GET");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/rides/blah", "POST");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/rides", "POST");
EXPECT_EQ("ride_request", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/rides/123", "PUT");
EXPECT_EQ("update_ride", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/rides/123/456", "POST");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/users/123/chargeaccounts", "POST");
EXPECT_EQ("cc_add", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/users/123/chargeaccounts/hello123", "PUT");
EXPECT_EQ("cc_add", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers =
genHeaders("api.lyft.com", "/users/123/chargeaccounts/validate", "PUT");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/foo/bar", "PUT");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/users", "POST");
EXPECT_EQ("create_user_login",
virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/users/123", "PUT");
EXPECT_EQ("update_user", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/users/123/location", "POST");
EXPECT_EQ("ulu", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/something/else", "GET");
EXPECT_EQ("other", virtualClusterName(config.route(headers, 0)->routeEntry(), headers));
}
}
TEST_F(RouteMatcherTest, TestRoutesWithWildcardAndDefaultOnly) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: wildcard
domains: ["*.solo.io"]
routes:
- match: { prefix: "/" }
route: { cluster: "wildcard" }
- name: default
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: "default" }
)EOF";
const auto proto_config = parseRouteConfigurationFromV2Yaml(yaml);
TestConfigImpl config(proto_config, factory_context_, true);
EXPECT_EQ("wildcard",
config.route(genHeaders("gloo.solo.io", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("default",
config.route(genHeaders("example.com", "/", "GET"), 0)->routeEntry()->clusterName());
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(TestRoutesWithInvalidRegex)) {
std::string invalid_route = R"EOF(
virtual_hosts:
- name: regex
domains: ["*"]
routes:
- match: { regex: "/(+invalid)" }
route: { cluster: "regex" }
)EOF";
std::string invalid_virtual_cluster = R"EOF(
virtual_hosts:
- name: regex
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: "regex" }
virtual_clusters:
- pattern: "^/(+invalid)"
name: "invalid"
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_route), factory_context_, true),
EnvoyException, "Invalid regex '/\\(\\+invalid\\)':");
EXPECT_THROW_WITH_REGEX(TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_virtual_cluster),
factory_context_, true),
EnvoyException, "Invalid regex '\\^/\\(\\+invalid\\)':");
}
// Virtual cluster that contains neither pattern nor regex. This must be checked while pattern is
// deprecated.
TEST_F(RouteMatcherTest, TestRoutesWithInvalidVirtualCluster) {
const std::string invalid_virtual_cluster = R"EOF(
virtual_hosts:
- name: regex
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: "regex" }
virtual_clusters:
- name: "invalid"
)EOF";
EXPECT_THROW_WITH_REGEX(TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_virtual_cluster),
factory_context_, true),
EnvoyException,
"virtual clusters must define either 'pattern' or 'headers'");
}
// Validates behavior of request_headers_to_add at router, vhost, and route levels.
TEST_F(RouteMatcherTest, TestAddRemoveRequestHeaders) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- lyft.com
- www.lyft.com
- w.lyft.com
- ww.lyft.com
- wwww.lyft.com
request_headers_to_add:
- header:
key: x-global-header1
value: vhost-override
- header:
key: x-vhost-header1
value: vhost1-www2
routes:
- match:
prefix: "/new_endpoint"
route:
prefix_rewrite: "/api/new_endpoint"
cluster: www2
request_headers_to_add:
- header:
key: x-global-header1
value: route-override
- header:
key: x-vhost-header1
value: route-override
- header:
key: x-route-header
value: route-new_endpoint
- match:
path: "/"
route:
cluster: root_www2
request_headers_to_add:
- header:
key: x-route-header
value: route-allpath
- match:
prefix: "/"
route:
cluster: www2
- name: www2_staging
domains:
- www-staging.lyft.net
- www-staging-orca.lyft.com
request_headers_to_add:
- header:
key: x-vhost-header1
value: vhost1-www2_staging
routes:
- match:
prefix: "/"
route:
cluster: www2_staging
request_headers_to_add:
- header:
key: x-route-header
value: route-allprefix
- name: default
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: instant-server
timeout: 3s
internal_only_headers:
- x-lyft-user-id
response_headers_to_add:
- header:
key: x-envoy-upstream-canary
value: 'true'
response_headers_to_remove:
- x-envoy-upstream-canary
- x-envoy-virtual-cluster
request_headers_to_add:
- header:
key: x-global-header1
value: global1
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// Request header manipulation testing.
{
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/new_endpoint/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("route-override", headers.get_("x-global-header1"));
EXPECT_EQ("route-override", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-new_endpoint", headers.get_("x-route-header"));
}
// Multiple routes can have same route-level headers with different values.
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("vhost-override", headers.get_("x-global-header1"));
EXPECT_EQ("vhost1-www2", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-allpath", headers.get_("x-route-header"));
}
// Multiple virtual hosts can have same virtual host level headers with different values.
{
Http::TestHeaderMapImpl headers = genHeaders("www-staging.lyft.net", "/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("global1", headers.get_("x-global-header1"));
EXPECT_EQ("vhost1-www2_staging", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-allprefix", headers.get_("x-route-header"));
}
// Global headers.
{
Http::TestHeaderMapImpl headers = genHeaders("api.lyft.com", "/", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("global1", headers.get_("x-global-header1"));
}
}
}
// Validates behavior of request_headers_to_add at router, vhost, and route levels when append is
// disabled.
TEST_F(RouteMatcherTest, TestRequestHeadersToAddWithAppendFalse) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: www2
domains: ["www.lyft.com"]
request_headers_to_add:
- header:
key: x-global-header
value: vhost-www2
append: false
- header:
key: x-vhost-header
value: vhost-www2
append: false
request_headers_to_remove: ["x-vhost-nope"]
routes:
- match: { prefix: "/endpoint" }
request_headers_to_add:
- header:
key: x-global-header
value: route-endpoint
append: false
- header:
key: x-vhost-header
value: route-endpoint
append: false
- header:
key: x-route-header
value: route-endpoint
append: false
request_headers_to_remove: ["x-route-nope"]
route:
cluster: www2
- match: { prefix: "/" }
route: { cluster: www2 }
- name: default
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: default }
request_headers_to_add:
- header:
key: x-global-header
value: global
append: false
request_headers_to_remove: ["x-global-nope"]
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
envoy::api::v2::RouteConfiguration route_config = parseRouteConfigurationFromV2Yaml(yaml);
TestConfigImpl config(route_config, factory_context_, true);
// Request header manipulation testing.
{
// Global and virtual host override route, route overrides route action.
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/endpoint", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
// Added headers.
EXPECT_EQ("global", headers.get_("x-global-header"));
EXPECT_EQ("vhost-www2", headers.get_("x-vhost-header"));
EXPECT_EQ("route-endpoint", headers.get_("x-route-header"));
// Removed headers.
EXPECT_FALSE(headers.has("x-global-nope"));
EXPECT_FALSE(headers.has("x-vhost-nope"));
EXPECT_FALSE(headers.has("x-route-nope"));
}
// Global overrides virtual host.
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
// Added headers.
EXPECT_EQ("global", headers.get_("x-global-header"));
EXPECT_EQ("vhost-www2", headers.get_("x-vhost-header"));
EXPECT_FALSE(headers.has("x-route-header"));
// Removed headers.
EXPECT_FALSE(headers.has("x-global-nope"));
EXPECT_FALSE(headers.has("x-vhost-nope"));
EXPECT_TRUE(headers.has("x-route-nope"));
}
// Global only.
{
Http::TestHeaderMapImpl headers = genHeaders("www.example.com", "/", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
// Added headers.
EXPECT_EQ("global", headers.get_("x-global-header"));
EXPECT_FALSE(headers.has("x-vhost-header"));
EXPECT_FALSE(headers.has("x-route-header"));
// Removed headers.
EXPECT_FALSE(headers.has("x-global-nope"));
EXPECT_TRUE(headers.has("x-vhost-nope"));
EXPECT_TRUE(headers.has("x-route-nope"));
}
}
}
// Validates behavior of response_headers_to_add and response_headers_to_remove at router, vhost,
// and route levels.
TEST_F(RouteMatcherTest, TestAddRemoveResponseHeaders) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: www2
domains: ["www.lyft.com"]
response_headers_to_add:
- header:
key: x-global-header1
value: vhost-override
- header:
key: x-vhost-header1
value: vhost1-www2
response_headers_to_remove: ["x-vhost-remove"]
routes:
- match: { prefix: "/new_endpoint" }
route:
prefix_rewrite: "/api/new_endpoint"
cluster: www2
response_headers_to_add:
- header:
key: x-route-header
value: route-override
- header:
key: x-global-header1
value: route-override
- header:
key: x-vhost-header1
value: route-override
- match: { path: "/" }
route:
cluster: root_www2
response_headers_to_add:
- header:
key: x-route-header
value: route-allpath
response_headers_to_remove: ["x-route-remove"]
- match: { prefix: "/" }
route: { cluster: "www2" }
- name: www2_staging
domains: ["www-staging.lyft.net"]
response_headers_to_add:
- header:
key: x-vhost-header1
value: vhost1-www2_staging
routes:
- match: { prefix: "/" }
route:
cluster: www2_staging
response_headers_to_add:
- header:
key: x-route-header
value: route-allprefix
- name: default
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: "instant-server" }
internal_only_headers: ["x-lyft-user-id"]
response_headers_to_add:
- header:
key: x-global-header1
value: global1
response_headers_to_remove: ["x-global-remove"]
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// Response header manipulation testing.
{
{
Http::TestHeaderMapImpl req_headers = genHeaders("www.lyft.com", "/new_endpoint/foo", "GET");
const RouteEntry* route = config.route(req_headers, 0)->routeEntry();
Http::TestHeaderMapImpl headers;
route->finalizeResponseHeaders(headers, stream_info);
EXPECT_EQ("route-override", headers.get_("x-global-header1"));
EXPECT_EQ("route-override", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-override", headers.get_("x-route-header"));
}
// Multiple routes can have same route-level headers with different values.
{
Http::TestHeaderMapImpl req_headers = genHeaders("www.lyft.com", "/", "GET");
const RouteEntry* route = config.route(req_headers, 0)->routeEntry();
Http::TestHeaderMapImpl headers;
route->finalizeResponseHeaders(headers, stream_info);
EXPECT_EQ("vhost-override", headers.get_("x-global-header1"));
EXPECT_EQ("vhost1-www2", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-allpath", headers.get_("x-route-header"));
}
// Multiple virtual hosts can have same virtual host level headers with different values.
{
Http::TestHeaderMapImpl req_headers = genHeaders("www-staging.lyft.net", "/foo", "GET");
const RouteEntry* route = config.route(req_headers, 0)->routeEntry();
Http::TestHeaderMapImpl headers;
route->finalizeResponseHeaders(headers, stream_info);
EXPECT_EQ("global1", headers.get_("x-global-header1"));
EXPECT_EQ("vhost1-www2_staging", headers.get_("x-vhost-header1"));
EXPECT_EQ("route-allprefix", headers.get_("x-route-header"));
}
// Global headers.
{
Http::TestHeaderMapImpl req_headers = genHeaders("api.lyft.com", "/", "GET");
const RouteEntry* route = config.route(req_headers, 0)->routeEntry();
Http::TestHeaderMapImpl headers;
route->finalizeResponseHeaders(headers, stream_info);
EXPECT_EQ("global1", headers.get_("x-global-header1"));
}
}
EXPECT_THAT(std::list<Http::LowerCaseString>{Http::LowerCaseString("x-lyft-user-id")},
ContainerEq(config.internalOnlyHeaders()));
}
// Validate that we can't add :-prefixed request headers.
TEST_F(RouteMatcherTest, TestRequestHeadersToAddNoPseudoHeader) {
for (const std::string& header : {":path", ":authority", ":method", ":scheme", ":status",
":protocol", ":no-chunks", ":status"}) {
const std::string yaml = fmt::format(R"EOF(
name: foo
virtual_hosts:
- name: www2
domains: ["*"]
request_headers_to_add:
- header:
key: {}
value: vhost-www2
append: false
)EOF",
header);
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
envoy::api::v2::RouteConfiguration route_config = parseRouteConfigurationFromV2Yaml(yaml);
EXPECT_THROW_WITH_MESSAGE(TestConfigImpl config(route_config, factory_context_, true),
EnvoyException, ":-prefixed headers may not be modified");
}
}
// Validate that we can't remove :-prefixed request headers.
TEST_F(RouteMatcherTest, TestRequestHeadersToRemoveNoPseudoHeader) {
for (const std::string& header : {":path", ":authority", ":method", ":scheme", ":status",
":protocol", ":no-chunks", ":status", "host"}) {
const std::string yaml = fmt::format(R"EOF(
name: foo
virtual_hosts:
- name: www2
domains: ["*"]
request_headers_to_remove:
- {}
)EOF",
header);
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
envoy::api::v2::RouteConfiguration route_config = parseRouteConfigurationFromV2Yaml(yaml);
EXPECT_THROW_WITH_MESSAGE(TestConfigImpl config(route_config, factory_context_, true),
EnvoyException, ":-prefixed or host headers may not be removed");
}
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(Priority)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/foo"
route:
cluster: local_service_grpc
priority: high
- match:
prefix: "/bar"
route:
cluster: local_service_grpc
virtual_clusters:
- pattern: "^/bar$"
method: POST
name: foo
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(Upstream::ResourcePriority::High,
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)->routeEntry()->priority());
EXPECT_EQ(Upstream::ResourcePriority::Default,
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)->routeEntry()->priority());
}
TEST_F(RouteMatcherTest, NoHostRewriteAndAutoRewrite) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: local_service
host_rewrite: foo
auto_host_rewrite: true
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, NoHostRewriteAndAutoRewriteHeader) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: local_service
host_rewrite: foo
auto_host_rewrite_header: "dummy-header"
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, NoAutoRewriteAndAutoRewriteHeader) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: local_service
auto_host_rewrite: true
auto_host_rewrite_header: "dummy-header"
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(HeaderMatchedRouting)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
headers:
- name: test_header
exact_match: test
route:
cluster: local_service_with_headers
- match:
prefix: "/"
headers:
- name: test_header_multiple1
exact_match: test1
- name: test_header_multiple2
exact_match: test2
route:
cluster: local_service_with_multiple_headers
- match:
prefix: "/"
headers:
- name: test_header_presence
present_match: true
route:
cluster: local_service_with_empty_headers
- match:
prefix: "/"
headers:
- name: test_header_pattern
regex_match: "^user=test-\\d+$"
route:
cluster: local_service_with_header_pattern_set_regex
- match:
prefix: "/"
headers:
- name: test_header_pattern
exact_match: "^customer=test-\\d+$"
route:
cluster: local_service_with_header_pattern_unset_regex
- match:
prefix: "/"
headers:
- name: test_header_range
range_match:
start: 1
end: 10
route:
cluster: local_service_with_header_range
- match:
prefix: "/"
route:
cluster: local_service_without_headers
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
EXPECT_EQ("local_service_without_headers",
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header", "test");
EXPECT_EQ("local_service_with_headers", config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_multiple1", "test1");
headers.addCopy("test_header_multiple2", "test2");
EXPECT_EQ("local_service_with_multiple_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("non_existent_header", "foo");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_presence", "test");
EXPECT_EQ("local_service_with_empty_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_pattern", "user=test-1223");
EXPECT_EQ("local_service_with_header_pattern_set_regex",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_pattern", "customer=test-1223");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "9");
EXPECT_EQ("local_service_with_header_range",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "19");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
}
// Verify the fixes for https://github.com/envoyproxy/envoy/issues/2406
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(InvalidHeaderMatchedRoutingConfig)) {
std::string value_with_regex_chars = R"EOF(
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
headers:
- name: test_header
exact_match: "(+not a regex)"
route: { cluster: "local_service" }
)EOF";
std::string invalid_regex = R"EOF(
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
headers:
- name: test_header
regex_match: "(+invalid regex)"
route: { cluster: "local_service" }
)EOF";
EXPECT_NO_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(value_with_regex_chars),
factory_context_, true));
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_regex), factory_context_, true),
EnvoyException, "Invalid regex");
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(QueryParamMatchedRouting)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
query_parameters:
- name: id
value: "\\d+[02468]"
regex: true
- name: debug
route:
cluster: local_service_with_multiple_query_parameters
- match:
prefix: "/"
query_parameters:
- name: param
value: test
route:
cluster: local_service_with_query_parameter
- match:
prefix: "/"
query_parameters:
- name: debug
route:
cluster: local_service_with_valueless_query_parameter
- match:
prefix: "/"
query_parameters:
- name: debug2
present_match: true
route:
cluster: local_service_with_present_match_query_parameter
- match:
prefix: "/"
query_parameters:
- name: debug3
string_match:
exact: foo
route:
cluster: local_service_with_string_match_query_parameter
- match:
prefix: "/"
route:
cluster: local_service_without_query_parameters
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/", "GET");
EXPECT_EQ("local_service_without_query_parameters",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?", "GET");
EXPECT_EQ("local_service_without_query_parameters",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?param=testing", "GET");
EXPECT_EQ("local_service_without_query_parameters",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?param=test", "GET");
EXPECT_EQ("local_service_with_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?debug", "GET");
EXPECT_EQ("local_service_with_valueless_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?debug2", "GET");
EXPECT_EQ("local_service_with_present_match_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?debug3=foo", "GET");
EXPECT_EQ("local_service_with_string_match_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?debug=2", "GET");
EXPECT_EQ("local_service_with_valueless_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?param=test&debug&id=01", "GET");
EXPECT_EQ("local_service_with_query_parameter",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("example.com", "/?param=test&debug&id=02", "GET");
EXPECT_EQ("local_service_with_multiple_query_parameters",
config.route(headers, 0)->routeEntry()->clusterName());
}
}
// Verify the fixes for https://github.com/envoyproxy/envoy/issues/2406
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(InvalidQueryParamMatchedRoutingConfig)) {
std::string value_with_regex_chars = R"EOF(
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
query_parameters:
- name: test_param
value: "(+not a regex)"
route: { cluster: "local_service" }
)EOF";
std::string invalid_regex = R"EOF(
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
query_parameters:
- name: test_param
value: "(+invalid regex)"
regex: true
route: { cluster: "local_service" }
)EOF";
EXPECT_NO_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(value_with_regex_chars),
factory_context_, true));
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_regex), factory_context_, true),
EnvoyException, "Invalid regex");
}
class RouterMatcherHashPolicyTest : public testing::Test, public ConfigImplTestBase {
protected:
RouterMatcherHashPolicyTest()
: add_cookie_nop_(
[](const std::string&, const std::string&, std::chrono::seconds) { return ""; }) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/foo"
route:
cluster: foo
- match:
prefix: "/bar"
route:
cluster: bar
)EOF";
route_config_ = parseRouteConfigurationFromV2Yaml(yaml);
}
envoy::api::v2::route::RouteAction_HashPolicy* firstRouteHashPolicy() {
auto hash_policies = route_config_.mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->mutable_hash_policy();
if (!hash_policies->empty()) {
return hash_policies->Mutable(0);
} else {
return hash_policies->Add();
}
}
ConfigImpl& config() {
if (config_ == nullptr) {
config_ = std::make_unique<TestConfigImpl>(route_config_, factory_context_, true);
}
return *config_;
}
envoy::api::v2::RouteConfiguration route_config_;
HashPolicy::AddCookieCallback add_cookie_nop_;
private:
std::unique_ptr<TestConfigImpl> config_;
};
TEST_F(RouterMatcherHashPolicyTest, HashHeaders) {
firstRouteHashPolicy()->mutable_header()->set_header_name("foo_header");
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("foo_header", "bar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_EQ(nullptr, route->routeEntry()->hashPolicy());
}
}
class RouterMatcherCookieHashPolicyTest : public RouterMatcherHashPolicyTest {
public:
RouterMatcherCookieHashPolicyTest() {
firstRouteHashPolicy()->mutable_cookie()->set_name("hash");
}
};
TEST_F(RouterMatcherCookieHashPolicyTest, NoTtl) {
{
// With no cookie, no hash is generated.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
// With no matching cookie, no hash is generated.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "choco=late; su=gar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
// Matching cookie produces a valid hash.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "choco=late; hash=brown");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
// The hash policy is per-route.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_EQ(nullptr, route->routeEntry()->hashPolicy());
}
}
TEST_F(RouterMatcherCookieHashPolicyTest, DifferentCookies) {
// Different cookies produce different hashes.
uint64_t hash_1, hash_2;
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "hash=brown");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_1 =
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_).value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "hash=green");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_2 =
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_).value();
}
EXPECT_NE(hash_1, hash_2);
}
TEST_F(RouterMatcherCookieHashPolicyTest, TtlSet) {
firstRouteHashPolicy()->mutable_cookie()->mutable_ttl()->set_seconds(42);
MockFunction<std::string(const std::string&, const std::string&, long)> mock_cookie_cb;
auto add_cookie = [&mock_cookie_cb](const std::string& name, const std::string& path,
std::chrono::seconds ttl) -> std::string {
return mock_cookie_cb.Call(name, path, ttl.count());
};
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "", 42));
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "choco=late; su=gar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "", 42));
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "choco=late; hash=brown");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie));
}
{
uint64_t hash_1, hash_2;
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "", 42)).WillOnce(Return("AAAAAAA"));
hash_1 =
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie).value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "", 42)).WillOnce(Return("BBBBBBB"));
hash_2 =
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie).value();
}
EXPECT_NE(hash_1, hash_2);
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_EQ(nullptr, route->routeEntry()->hashPolicy());
}
}
TEST_F(RouterMatcherCookieHashPolicyTest, SetSessionCookie) {
firstRouteHashPolicy()->mutable_cookie()->mutable_ttl()->set_seconds(0);
MockFunction<std::string(const std::string&, const std::string&, long)> mock_cookie_cb;
auto add_cookie = [&mock_cookie_cb](const std::string& name, const std::string& path,
std::chrono::seconds ttl) -> std::string {
return mock_cookie_cb.Call(name, path, ttl.count());
};
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "", 0));
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie));
}
}
TEST_F(RouterMatcherCookieHashPolicyTest, SetCookiePath) {
firstRouteHashPolicy()->mutable_cookie()->mutable_ttl()->set_seconds(0);
firstRouteHashPolicy()->mutable_cookie()->set_path("/");
MockFunction<std::string(const std::string&, const std::string&, long)> mock_cookie_cb;
auto add_cookie = [&mock_cookie_cb](const std::string& name, const std::string& path,
std::chrono::seconds ttl) -> std::string {
return mock_cookie_cb.Call(name, path, ttl.count());
};
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_CALL(mock_cookie_cb, Call("hash", "/", 0));
EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie));
}
}
TEST_F(RouterMatcherHashPolicyTest, HashIp) {
Network::Address::Ipv4Instance valid_address("1.2.3.4");
firstRouteHashPolicy()->mutable_connection_properties()->set_source_ip(true);
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_TRUE(
route->routeEntry()->hashPolicy()->generateHash(&valid_address, headers, add_cookie_nop_));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
uint64_t old_hash = config()
.route(headers, 0)
->routeEntry()
->hashPolicy()
->generateHash(&valid_address, headers, add_cookie_nop_)
.value();
headers.addCopy("foo_header", "bar");
EXPECT_EQ(old_hash, config()
.route(headers, 0)
->routeEntry()
->hashPolicy()
->generateHash(&valid_address, headers, add_cookie_nop_)
.value());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_EQ(nullptr, route->routeEntry()->hashPolicy());
}
}
TEST_F(RouterMatcherHashPolicyTest, HashIpNonIpAddress) {
NiceMock<Network::MockIp> bad_ip;
NiceMock<Network::MockResolvedAddress> bad_ip_address("", "");
firstRouteHashPolicy()->mutable_connection_properties()->set_source_ip(true);
{
ON_CALL(bad_ip_address, ip()).WillByDefault(Return(nullptr));
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(&bad_ip_address, headers, add_cookie_nop_));
}
{
const std::string empty;
ON_CALL(bad_ip_address, ip()).WillByDefault(Return(&bad_ip));
ON_CALL(bad_ip, addressAsString()).WillByDefault(ReturnRef(empty));
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(&bad_ip_address, headers, add_cookie_nop_));
}
}
TEST_F(RouterMatcherHashPolicyTest, HashIpv4DifferentAddresses) {
firstRouteHashPolicy()->mutable_connection_properties()->set_source_ip(true);
{
// Different addresses should produce different hashes.
Network::Address::Ipv4Instance first_ip("1.2.3.4");
Network::Address::Ipv4Instance second_ip("4.3.2.1");
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
const auto hash_policy = config().route(headers, 0)->routeEntry()->hashPolicy();
const uint64_t hash_1 = hash_policy->generateHash(&first_ip, headers, add_cookie_nop_).value();
const uint64_t hash_2 = hash_policy->generateHash(&second_ip, headers, add_cookie_nop_).value();
EXPECT_NE(hash_1, hash_2);
}
{
// Same IP addresses but different ports should produce the same hash.
Network::Address::Ipv4Instance first_ip("1.2.3.4", 8081);
Network::Address::Ipv4Instance second_ip("1.2.3.4", 1331);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
const auto hash_policy = config().route(headers, 0)->routeEntry()->hashPolicy();
const uint64_t hash_1 = hash_policy->generateHash(&first_ip, headers, add_cookie_nop_).value();
const uint64_t hash_2 = hash_policy->generateHash(&second_ip, headers, add_cookie_nop_).value();
EXPECT_EQ(hash_1, hash_2);
}
}
TEST_F(RouterMatcherHashPolicyTest, HashIpv6DifferentAddresses) {
firstRouteHashPolicy()->mutable_connection_properties()->set_source_ip(true);
{
// Different addresses should produce different hashes.
Network::Address::Ipv6Instance first_ip("2001:0db8:85a3:0000:0000::");
Network::Address::Ipv6Instance second_ip("::1");
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
const auto hash_policy = config().route(headers, 0)->routeEntry()->hashPolicy();
const uint64_t hash_1 = hash_policy->generateHash(&first_ip, headers, add_cookie_nop_).value();
const uint64_t hash_2 = hash_policy->generateHash(&second_ip, headers, add_cookie_nop_).value();
EXPECT_NE(hash_1, hash_2);
}
{
// Same IP addresses but different ports should produce the same hash.
Network::Address::Ipv6Instance first_ip("1:2:3:4:5::", 8081);
Network::Address::Ipv6Instance second_ip("1:2:3:4:5::", 1331);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
const auto hash_policy = config().route(headers, 0)->routeEntry()->hashPolicy();
const uint64_t hash_1 = hash_policy->generateHash(&first_ip, headers, add_cookie_nop_).value();
const uint64_t hash_2 = hash_policy->generateHash(&second_ip, headers, add_cookie_nop_).value();
EXPECT_EQ(hash_1, hash_2);
}
}
TEST_F(RouterMatcherHashPolicyTest, HashMultiple) {
auto route = route_config_.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_route();
route->add_hash_policy()->mutable_header()->set_header_name("foo_header");
route->add_hash_policy()->mutable_connection_properties()->set_source_ip(true);
Network::Address::Ipv4Instance address("4.3.2.1");
uint64_t hash_h, hash_ip, hash_both;
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
EXPECT_FALSE(
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("foo_header", "bar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_h =
route->routeEntry()->hashPolicy()->generateHash(nullptr, headers, add_cookie_nop_).value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_ip =
route->routeEntry()->hashPolicy()->generateHash(&address, headers, add_cookie_nop_).value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
headers.addCopy("foo_header", "bar");
hash_both =
route->routeEntry()->hashPolicy()->generateHash(&address, headers, add_cookie_nop_).value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
headers.addCopy("foo_header", "bar");
// stability
EXPECT_EQ(hash_both, route->routeEntry()
->hashPolicy()
->generateHash(&address, headers, add_cookie_nop_)
.value());
}
EXPECT_NE(hash_ip, hash_h);
EXPECT_NE(hash_ip, hash_both);
EXPECT_NE(hash_h, hash_both);
}
TEST_F(RouterMatcherHashPolicyTest, HashTerminal) {
// Hash policy list: cookie, header [terminal=true], user_ip.
auto route = route_config_.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_route();
route->add_hash_policy()->mutable_cookie()->set_name("cookie_hash");
auto* header_hash = route->add_hash_policy();
header_hash->mutable_header()->set_header_name("foo_header");
header_hash->set_terminal(true);
route->add_hash_policy()->mutable_connection_properties()->set_source_ip(true);
Network::Address::Ipv4Instance address1("4.3.2.1");
Network::Address::Ipv4Instance address2("1.2.3.4");
uint64_t hash_1, hash_2;
// Test terminal works when there is hash computed, the rest of the policy
// list is ignored.
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "cookie_hash=foo;");
headers.addCopy("foo_header", "bar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_1 = route->routeEntry()
->hashPolicy()
->generateHash(&address1, headers, add_cookie_nop_)
.value();
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
headers.addCopy("Cookie", "cookie_hash=foo;");
headers.addCopy("foo_header", "bar");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_2 = route->routeEntry()
->hashPolicy()
->generateHash(&address2, headers, add_cookie_nop_)
.value();
}
EXPECT_EQ(hash_1, hash_2);
// If no hash computed after evaluating a hash policy, the rest of the policy
// list is evaluated.
{
// Input: {}, {}, address1. Hash on address1.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_1 = route->routeEntry()
->hashPolicy()
->generateHash(&address1, headers, add_cookie_nop_)
.value();
}
{
// Input: {}, {}, address2. Hash on address2.
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config().route(headers, 0);
hash_2 = route->routeEntry()
->hashPolicy()
->generateHash(&address2, headers, add_cookie_nop_)
.value();
}
EXPECT_NE(hash_1, hash_2);
}
TEST_F(RouterMatcherHashPolicyTest, InvalidHashPolicies) {
{
auto hash_policy = firstRouteHashPolicy();
EXPECT_EQ(envoy::api::v2::route::RouteAction::HashPolicy::POLICY_SPECIFIER_NOT_SET,
hash_policy->policy_specifier_case());
EXPECT_THROW(config(), EnvoyException);
}
{
auto route = route_config_.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_route();
route->add_hash_policy()->mutable_header()->set_header_name("foo_header");
route->add_hash_policy()->mutable_connection_properties()->set_source_ip(true);
auto hash_policy = route->add_hash_policy();
EXPECT_EQ(envoy::api::v2::route::RouteAction::HashPolicy::POLICY_SPECIFIER_NOT_SET,
hash_policy->policy_specifier_case());
EXPECT_THROW(config(), EnvoyException);
}
}
TEST_F(RouteMatcherTest, ClusterHeader) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/foo"
route:
cluster_header: ":authority"
- match:
prefix: "/bar"
route:
cluster_header: some_header
timeout: 0s
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(
"some_cluster",
config.route(genHeaders("some_cluster", "/foo", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ(
"", config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)->routeEntry()->clusterName());
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
headers.addCopy("some_header", "some_cluster");
Router::RouteConstSharedPtr route = config.route(headers, 0);
EXPECT_EQ("some_cluster", route->routeEntry()->clusterName());
// Make sure things forward and don't crash.
// TODO(mattklein123): Make this a real test of behavior.
EXPECT_EQ(std::chrono::milliseconds(0), route->routeEntry()->timeout());
route->routeEntry()->finalizeRequestHeaders(headers, stream_info, true);
route->routeEntry()->priority();
route->routeEntry()->rateLimitPolicy();
route->routeEntry()->retryPolicy();
route->routeEntry()->shadowPolicy();
route->routeEntry()->virtualCluster(headers);
route->routeEntry()->virtualHost();
route->routeEntry()->virtualHost().rateLimitPolicy();
route->routeEntry()->pathMatchCriterion();
route->routeEntry()->hedgePolicy();
route->routeEntry()->maxGrpcTimeout();
route->routeEntry()->grpcTimeoutOffset();
route->routeEntry()->upgradeMap();
route->routeEntry()->internalRedirectAction();
}
}
TEST_F(RouteMatcherTest, ContentType) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
headers:
- name: content-type
exact_match: application/grpc
route:
cluster: local_service_grpc
- match:
prefix: "/"
route:
cluster: local_service
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
EXPECT_EQ("local_service",
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("content-type", "application/grpc");
EXPECT_EQ("local_service_grpc", config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("content-type", "foo");
EXPECT_EQ("local_service", config.route(headers, 0)->routeEntry()->clusterName());
}
}
TEST_F(RouteMatcherTest, GrpcTimeoutOffset) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/foo"
route:
cluster: local_service_grpc
- match:
prefix: "/"
route:
grpc_timeout_offset: 0.01s
cluster: local_service_grpc
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
EXPECT_EQ(
absl::make_optional(std::chrono::milliseconds(10)),
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)->routeEntry()->grpcTimeoutOffset());
}
EXPECT_EQ(absl::nullopt, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->grpcTimeoutOffset());
}
TEST_F(RouteMatcherTest, FractionalRuntime) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
routes:
- match:
prefix: "/"
runtime_fraction:
default_value:
numerator: 50
denominator: MILLION
runtime_key: "bogus_key"
route:
cluster: "something_else"
- match:
prefix: "/"
route:
cluster: "www2"
)EOF";
Runtime::MockSnapshot snapshot;
ON_CALL(factory_context_.runtime_loader_, snapshot()).WillByDefault(ReturnRef(snapshot));
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
EXPECT_CALL(snapshot,
featureEnabled("bogus_key", Matcher<const envoy::type::FractionalPercent&>(_), 41))
.WillRepeatedly(Return(true));
EXPECT_EQ(
"something_else",
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 41)->routeEntry()->clusterName());
EXPECT_CALL(snapshot,
featureEnabled("bogus_key", Matcher<const envoy::type::FractionalPercent&>(_), 43))
.WillRepeatedly(Return(false));
EXPECT_EQ(
"www2",
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 43)->routeEntry()->clusterName());
}
TEST_F(RouteMatcherTest, ShadowClusterNotFound) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
request_mirror_policy:
cluster: some_cluster
cluster: www2
)EOF";
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("www2")))
.WillRepeatedly(Return(&factory_context_.cluster_manager_.thread_local_cluster_));
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("some_cluster")))
.WillRepeatedly(Return(nullptr));
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, ClusterNotFound) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www2
)EOF";
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("www2"))).WillRepeatedly(Return(nullptr));
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, ClusterNotFoundNotChecking) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www2
)EOF";
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("www2"))).WillRepeatedly(Return(nullptr));
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
}
TEST_F(RouteMatcherTest, ClusterNotFoundNotCheckingViaConfig) {
const std::string yaml = R"EOF(
validate_clusters: false
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www
)EOF";
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("www2"))).WillRepeatedly(Return(nullptr));
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
}
TEST_F(RouteMatcherTest, AttemptCountHeader) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
include_request_attempt_count: true
routes:
- match: { prefix: "/"}
route:
cluster: "whatever"
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_TRUE(config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->includeAttemptCount());
}
TEST_F(RouteMatcherTest, ClusterNotFoundResponseCode) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/"}
route:
cluster: "not_found"
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
EXPECT_EQ("not_found", config.route(headers, 0)->routeEntry()->clusterName());
EXPECT_EQ(Http::Code::ServiceUnavailable,
config.route(headers, 0)->routeEntry()->clusterNotFoundResponseCode());
}
TEST_F(RouteMatcherTest, ClusterNotFoundResponseCodeConfig503) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/"}
route:
cluster: "not_found"
cluster_not_found_response_code: SERVICE_UNAVAILABLE
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
EXPECT_EQ("not_found", config.route(headers, 0)->routeEntry()->clusterName());
EXPECT_EQ(Http::Code::ServiceUnavailable,
config.route(headers, 0)->routeEntry()->clusterNotFoundResponseCode());
}
TEST_F(RouteMatcherTest, ClusterNotFoundResponseCodeConfig404) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/"}
route:
cluster: "not_found"
cluster_not_found_response_code: NOT_FOUND
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
EXPECT_EQ("not_found", config.route(headers, 0)->routeEntry()->clusterName());
EXPECT_EQ(Http::Code::NotFound,
config.route(headers, 0)->routeEntry()->clusterNotFoundResponseCode());
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(Shadow)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
request_mirror_policy:
cluster: some_cluster
cluster: www2
- match:
prefix: "/bar"
route:
request_mirror_policy:
cluster: some_cluster2
runtime_key: foo
cluster: www2
- match:
prefix: "/baz"
route:
cluster: www2
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ("some_cluster", config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->shadowPolicy()
.cluster());
EXPECT_EQ("", config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->shadowPolicy()
.runtimeKey());
EXPECT_EQ("some_cluster2", config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->shadowPolicy()
.cluster());
EXPECT_EQ("foo", config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->shadowPolicy()
.runtimeKey());
EXPECT_EQ("", config.route(genHeaders("www.lyft.com", "/baz", "GET"), 0)
->routeEntry()
->shadowPolicy()
.cluster());
EXPECT_EQ("", config.route(genHeaders("www.lyft.com", "/baz", "GET"), 0)
->routeEntry()
->shadowPolicy()
.runtimeKey());
}
class RouteConfigurationV2 : public testing::Test, public ConfigImplTestBase {};
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RequestMirrorPolicy)) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: mirror
domains: [mirror.lyft.com]
routes:
- match: { prefix: "/"}
route:
cluster: foo
request_mirror_policy:
cluster: foo_mirror
runtime_key: will_be_ignored
runtime_fraction:
default_value:
numerator: 20
denominator: HUNDRED
runtime_key: mirror_key
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ("foo_mirror", config.route(genHeaders("mirror.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->shadowPolicy()
.cluster());
// `runtime_fraction` takes precedence over the deprecated `runtime_key` field.
EXPECT_EQ("mirror_key", config.route(genHeaders("mirror.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->shadowPolicy()
.runtimeKey());
const auto& default_value = config.route(genHeaders("mirror.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->shadowPolicy()
.defaultValue();
EXPECT_EQ(20, default_value.numerator());
EXPECT_EQ(envoy::type::FractionalPercent::HUNDRED, default_value.denominator());
}
TEST_F(RouteMatcherTest, Retry) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www2
retry_policy:
retry_on: connect-failure
- match:
prefix: "/bar"
route:
cluster: www2
- match:
prefix: "/"
route:
cluster: www2
retry_policy:
per_try_timeout: 1s
num_retries: 3
retry_on: 5xx,gateway-error,connect-failure,reset
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(std::chrono::milliseconds(0),
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(1U, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE,
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
EXPECT_EQ(std::chrono::milliseconds(0),
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(0U, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(0U, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
EXPECT_EQ(std::chrono::milliseconds(1000),
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(3U, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE | RetryPolicy::RETRY_ON_5XX |
RetryPolicy::RETRY_ON_GATEWAY_ERROR | RetryPolicy::RETRY_ON_RESET,
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
}
TEST_F(RouteMatcherTest, RetryVirtualHostLevel) {
const std::string yaml = R"EOF(
name: RetryVirtualHostLevel
virtual_hosts:
- domains: [www.lyft.com]
name: www
retry_policy: {num_retries: 3, per_try_timeout: 1s, retry_on: '5xx,gateway-error,connect-failure,reset'}
routes:
- match: {prefix: /foo}
route:
cluster: www
retry_policy: {retry_on: connect-failure}
- match: {prefix: /bar}
route: {cluster: www}
- match: {prefix: /}
route: {cluster: www}
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// Route level retry policy takes precedence.
EXPECT_EQ(std::chrono::milliseconds(0),
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(1U, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE,
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
// Virtual Host level retry policy kicks in.
EXPECT_EQ(std::chrono::milliseconds(1000),
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(3U, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE | RetryPolicy::RETRY_ON_5XX |
RetryPolicy::RETRY_ON_GATEWAY_ERROR | RetryPolicy::RETRY_ON_RESET,
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
EXPECT_EQ(std::chrono::milliseconds(1000),
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(3U, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE | RetryPolicy::RETRY_ON_5XX |
RetryPolicy::RETRY_ON_GATEWAY_ERROR | RetryPolicy::RETRY_ON_RESET,
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
}
TEST_F(RouteMatcherTest, GrpcRetry) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www2
retry_policy:
retry_on: connect-failure
- match:
prefix: "/bar"
route:
cluster: www2
- match:
prefix: "/"
route:
cluster: www2
retry_policy:
per_try_timeout: 1s
num_retries: 3
retry_on: 5xx,deadline-exceeded,resource-exhausted
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(std::chrono::milliseconds(0),
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(1U, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_CONNECT_FAILURE,
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
EXPECT_EQ(std::chrono::milliseconds(0),
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(0U, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(0U, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
EXPECT_EQ(std::chrono::milliseconds(1000),
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.perTryTimeout());
EXPECT_EQ(3U, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.numRetries());
EXPECT_EQ(RetryPolicy::RETRY_ON_5XX | RetryPolicy::RETRY_ON_GRPC_DEADLINE_EXCEEDED |
RetryPolicy::RETRY_ON_GRPC_RESOURCE_EXHAUSTED,
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.retryOn());
}
// Test route-specific retry back-off intervals.
TEST_F(RouteMatcherTest, RetryBackOffIntervals) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
cluster: www2
retry_policy:
retry_back_off:
base_interval: 0.050s
- match:
prefix: "/bar"
route:
cluster: www2
retry_policy:
retry_back_off:
base_interval: 0.100s
max_interval: 0.500s
- match:
prefix: "/baz"
route:
cluster: www2
retry_policy:
retry_back_off:
base_interval: 0.0001s # < 1 ms
max_interval: 0.0001s
- match:
prefix: "/"
route:
cluster: www2
retry_policy:
retry_on: connect-failure
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(absl::optional<std::chrono::milliseconds>(50),
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.baseInterval());
EXPECT_EQ(absl::nullopt, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->retryPolicy()
.maxInterval());
EXPECT_EQ(absl::optional<std::chrono::milliseconds>(100),
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.baseInterval());
EXPECT_EQ(absl::optional<std::chrono::milliseconds>(500),
config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->retryPolicy()
.maxInterval());
// Sub-millisecond interval converted to 1 ms.
EXPECT_EQ(absl::optional<std::chrono::milliseconds>(1),
config.route(genHeaders("www.lyft.com", "/baz", "GET"), 0)
->routeEntry()
->retryPolicy()
.baseInterval());
EXPECT_EQ(absl::optional<std::chrono::milliseconds>(1),
config.route(genHeaders("www.lyft.com", "/baz", "GET"), 0)
->routeEntry()
->retryPolicy()
.maxInterval());
EXPECT_EQ(absl::nullopt, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.baseInterval());
EXPECT_EQ(absl::nullopt, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->retryPolicy()
.maxInterval());
}
// Test invalid route-specific retry back-off configs.
TEST_F(RouteMatcherTest, InvalidRetryBackOff) {
const std::string invalid_max = R"EOF(
virtual_hosts:
- name: backoff
domains: ["*"]
routes:
- match: { prefix: "/" }
route:
cluster: backoff
retry_policy:
retry_back_off:
base_interval: 10s
max_interval: 5s
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(invalid_max), factory_context_, true),
EnvoyException, "retry_policy.max_interval must greater than or equal to the base_interval");
}
TEST_F(RouteMatcherTest, HedgeRouteLevel) {
const std::string yaml = R"EOF(
name: HedgeRouteLevel
virtual_hosts:
- domains: [www.lyft.com]
name: www
routes:
- match: {prefix: /foo}
route:
cluster: www
hedge_policy:
initial_requests: 3
additional_request_chance:
numerator: 4
denominator: HUNDRED
- match: {prefix: /bar}
route: {cluster: www}
- match: {prefix: /}
route:
cluster: www
hedge_policy:
hedge_on_per_try_timeout: true
initial_requests: 5
additional_request_chance:
numerator: 40
denominator: HUNDRED
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(3, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(false, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
envoy::type::FractionalPercent percent =
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(4, percent.numerator());
EXPECT_EQ(100, ProtobufPercentHelper::fractionalPercentDenominatorToInt(percent.denominator()));
EXPECT_EQ(1, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(false, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
percent = config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(0, percent.numerator());
EXPECT_EQ(5, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(true, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
percent = config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(40, percent.numerator());
EXPECT_EQ(100, ProtobufPercentHelper::fractionalPercentDenominatorToInt(percent.denominator()));
}
TEST_F(RouteMatcherTest, HedgeVirtualHostLevel) {
const std::string yaml = R"EOF(
name: HedgeVirtualHostLevel
virtual_hosts:
- domains: [www.lyft.com]
name: www
hedge_policy: {initial_requests: 3}
routes:
- match: {prefix: /foo}
route:
cluster: www
hedge_policy: {hedge_on_per_try_timeout: true}
- match: {prefix: /bar}
route:
hedge_policy: {additional_request_chance: {numerator: 30.0, denominator: HUNDRED}}
cluster: www
- match: {prefix: /}
route: {cluster: www}
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// Route level hedge policy takes precedence.
EXPECT_EQ(1, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(true, config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
envoy::type::FractionalPercent percent =
config.route(genHeaders("www.lyft.com", "/foo", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(0, percent.numerator());
// Virtual Host level hedge policy kicks in.
EXPECT_EQ(1, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(false, config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
percent = config.route(genHeaders("www.lyft.com", "/bar", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(30, percent.numerator());
EXPECT_EQ(100, ProtobufPercentHelper::fractionalPercentDenominatorToInt(percent.denominator()));
EXPECT_EQ(3, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.initialRequests());
EXPECT_EQ(false, config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.hedgeOnPerTryTimeout());
percent = config.route(genHeaders("www.lyft.com", "/", "GET"), 0)
->routeEntry()
->hedgePolicy()
.additionalRequestChance();
EXPECT_EQ(0, percent.numerator());
}
TEST_F(RouteMatcherTest, TestBadDefaultConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
- name: www2_staging
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2_staging
internal_only_headers:
- x-lyft-user-id
)EOF";
EXPECT_THROW(
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, TestDuplicateDomainConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
cluster: www2
- name: www2_staging
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
cluster: www2_staging
)EOF";
EXPECT_THROW(
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
// Test to detect if hostname matches are case-insensitive
TEST_F(RouteMatcherTest, TestCaseSensitiveDomainConfig) {
std::string config_with_case_sensitive_domains = R"EOF(
virtual_hosts:
- name: www2
domains: [www.lyft.com]
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: www2_staging
domains: [www.LYFt.cOM]
routes:
- match: { prefix: "/" }
route: { cluster: www2_staging }
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(config_with_case_sensitive_domains),
factory_context_, true),
EnvoyException,
"Only unique values for domains are permitted. Duplicate entry of domain www.lyft.com");
}
TEST_F(RouteMatcherTest, TestDuplicateWildcardDomainConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: www2_staging
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: www2_staging }
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Only a single wildcard domain is permitted");
}
TEST_F(RouteMatcherTest, TestDuplicateSuffixWildcardDomainConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["*.lyft.com"]
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: www2_staging
domains: ["*.LYFT.COM"]
routes:
- match: { prefix: "/" }
route: { cluster: www2_staging }
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"Only unique values for domains are permitted. Duplicate entry of domain *.lyft.com");
}
TEST_F(RouteMatcherTest, TestDuplicatePrefixWildcardDomainConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["bar.*"]
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: www2_staging
domains: ["BAR.*"]
routes:
- match: { prefix: "/" }
route: { cluster: www2_staging }
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"Only unique values for domains are permitted. Duplicate entry of domain bar.*");
}
TEST_F(RouteMatcherTest, TestDomainMatchOrderConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: exact
domains: ["www.example.com", "www.example.cc", "wwww.example.com" ]
routes:
- match: { prefix: "/" }
route: { cluster: exact }
- name: suffix
domains: ["*w.example.com" ]
routes:
- match: { prefix: "/" }
route: { cluster: suffix }
- name: prefix
domains: ["www.example.c*", "ww.example.c*"]
routes:
- match: { prefix: "/" }
route: { cluster: prefix }
- name: default
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: default }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(
"exact",
config.route(genHeaders("www.example.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ(
"exact",
config.route(genHeaders("wwww.example.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("exact",
config.route(genHeaders("www.example.cc", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("suffix",
config.route(genHeaders("ww.example.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("prefix",
config.route(genHeaders("www.example.co", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("default",
config.route(genHeaders("w.example.com", "/", "GET"), 0)->routeEntry()->clusterName());
EXPECT_EQ("default",
config.route(genHeaders("www.example.c", "/", "GET"), 0)->routeEntry()->clusterName());
}
TEST_F(RouteMatcherTest, NoProtocolInHeadersWhenTlsIsRequired) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www
require_tls: all
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
cluster: www
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
// route may be called early in some edge cases and "x-forwarded-proto" will not be set.
Http::TestHeaderMapImpl headers{{":authority", "www.lyft.com"}, {":path", "/"}};
EXPECT_EQ(nullptr, config.route(headers, 0));
}
static Http::TestHeaderMapImpl genRedirectHeaders(const std::string& host, const std::string& path,
bool ssl, bool internal) {
Http::TestHeaderMapImpl headers{
{":authority", host}, {":path", path}, {"x-forwarded-proto", ssl ? "https" : "http"}};
if (internal) {
headers.addCopy("x-envoy-internal", "true");
}
return headers;
}
TEST_F(RouteMatcherTest, RouteName) {
std::string yaml = R"EOF(
virtual_hosts:
- name: "www2"
domains: ["www.lyft.com"]
routes:
- name: "route-test"
match: { prefix: "/"}
route:
cluster: "ufesservice"
- name: redirect
domains: [redirect.lyft.com]
routes:
- name: "route-test-2"
match: { path: /host }
redirect: { host_redirect: new.lyft.com }
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context, false);
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
EXPECT_EQ("route-test", config.route(headers, 0)->routeEntry()->routeName());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
EXPECT_EQ("route-test-2", redirect->routeName());
}
}
TEST_F(RouteMatcherTest, DirectResponse) {
const auto pathname =
TestEnvironment::writeStringToFileForTest("direct_response_body", "Example text 3");
static const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: www2
domains: [www.lyft.com]
require_tls: all
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: api
domains: [api.lyft.com]
require_tls: external_only
routes:
- match: { prefix: "/" }
route: { cluster: www2 }
- name: redirect
domains: [redirect.lyft.com]
routes:
- match: { path: /host }
redirect: { host_redirect: new.lyft.com }
- match: { path: /path }
redirect: { path_redirect: /new_path }
- match: { path: /https }
redirect: { https_redirect: true }
- match: { path: /host_path }
redirect: { host_redirect: new.lyft.com, path_redirect: /new_path }
- match: { path: /host_https }
redirect: { host_redirect: new.lyft.com, https_redirect: true }
- match: { path: /path_https }
redirect: { path_redirect: /new_path, https_redirect: true }
- match: { path: /host_path_https }
redirect: { host_redirect: new.lyft.com, path_redirect: /new_path, https_redirect: true }
- match: { path: /port }
redirect: { port_redirect: 8080 }
- match: { path: /host_port }
redirect: { host_redirect: new.lyft.com, port_redirect: 8080 }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: new.lyft.com, port_redirect: 8080 }
- name: redirect_domain_port_80
domains: [redirect.lyft.com:80]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_https }
redirect: { host_redirect: new.lyft.com, path_redirect: /new_path, https_redirect: true }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: new.lyft.com, port_redirect: 8080 }
- name: redirect_domain_port_443
domains: [redirect.lyft.com:443]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_http }
redirect: { scheme_redirect: http, host_redirect: new.lyft.com, path_redirect: /new_path}
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: new.lyft.com, port_redirect: 8080 }
- name: redirect_domain_port_8080
domains: [redirect.lyft.com:8080]
routes:
- match: { path: /port }
redirect: { port_redirect: 8181 }
- name: redirect_ipv4
domains: [10.0.0.1]
routes:
- match: { path: /port }
redirect: { port_redirect: 8080 }
- match: { path: /host_port }
redirect: { host_redirect: 20.0.0.2, port_redirect: 8080 }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: 20.0.0.2, port_redirect: 8080 }
- name: redirect_ipv4_port_8080
domains: [10.0.0.1:8080]
routes:
- match: { path: /port }
redirect: { port_redirect: 8181 }
- name: redirect_ipv4_port_80
domains: [10.0.0.1:80]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_https }
redirect: { host_redirect: 20.0.0.2, path_redirect: /new_path, https_redirect: true }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: 20.0.0.2, port_redirect: 8080 }
- name: redirect_ipv4_port_443
domains: [10.0.0.1:443]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_http }
redirect: { scheme_redirect: http, host_redirect: 20.0.0.2, path_redirect: /new_path}
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: 20.0.0.2, port_redirect: 8080 }
- name: redirect_ipv6
domains: ["[fe80::1]"]
routes:
- match: { path: /port }
redirect: { port_redirect: 8080 }
- match: { path: /host_port }
redirect: { host_redirect: "[fe80::2]", port_redirect: 8080 }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: "[fe80::2]", port_redirect: 8080 }
- name: redirect_ipv6_port_8080
domains: ["[fe80::1]:8080"]
routes:
- match: { path: /port }
redirect: { port_redirect: 8181 }
- name: redirect_ipv6_port_80
domains: ["[fe80::1]:80"]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_https }
redirect: { host_redirect: "[fe80::2]", path_redirect: /new_path, https_redirect: true }
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: "[fe80::2]", port_redirect: 8080 }
- name: redirect_ipv6_port_443
domains: ["[fe80::1]:443"]
routes:
- match: { path: /ws }
redirect: { scheme_redirect: ws }
- match: { path: /host_path_http }
redirect: { scheme_redirect: http, host_redirect: "[fe80::2]", path_redirect: /new_path}
- match: { path: /scheme_host_port }
redirect: { scheme_redirect: ws, host_redirect: "[fe80::2]", port_redirect: 8080 }
- name: direct
domains: [direct.example.com]
routes:
- match: { prefix: /gone }
direct_response:
status: 410
body: { inline_bytes: "RXhhbXBsZSB0ZXh0IDE=" }
- match: { prefix: /error }
direct_response:
status: 500
body: { inline_string: "Example text 2" }
- match: { prefix: /no_body }
direct_response:
status: 200
- match: { prefix: /static }
direct_response:
status: 200
body: { filename: )EOF" + pathname +
R"EOF(}
- match: { prefix: / }
route: { cluster: www2 }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(nullptr, config.route(genRedirectHeaders("www.foo.com", "/foo", true, true), 0));
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/foo", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/foo", false, false);
EXPECT_EQ("https://www.lyft.com/foo",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
EXPECT_EQ(nullptr, config.route(headers, 0)->decorator());
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("api.lyft.com", "/foo", false, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("api.lyft.com", "/foo", false, false);
EXPECT_EQ("https://api.lyft.com/foo",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host", false, false);
EXPECT_EQ("http://new.lyft.com/host",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("redirect.lyft.com", "/path", true, false);
EXPECT_EQ("https://redirect.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host_path", true, false);
EXPECT_EQ("https://new.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("direct.example.com", "/gone", true, false);
EXPECT_EQ(Http::Code::Gone, config.route(headers, 0)->directResponseEntry()->responseCode());
EXPECT_EQ("Example text 1", config.route(headers, 0)->directResponseEntry()->responseBody());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("direct.example.com", "/error", true, false);
EXPECT_EQ(Http::Code::InternalServerError,
config.route(headers, 0)->directResponseEntry()->responseCode());
EXPECT_EQ("Example text 2", config.route(headers, 0)->directResponseEntry()->responseBody());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("direct.example.com", "/no_body", true, false);
EXPECT_EQ(Http::Code::OK, config.route(headers, 0)->directResponseEntry()->responseCode());
EXPECT_TRUE(config.route(headers, 0)->directResponseEntry()->responseBody().empty());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("direct.example.com", "/static", true, false);
EXPECT_EQ(Http::Code::OK, config.route(headers, 0)->directResponseEntry()->responseCode());
EXPECT_EQ("Example text 3", config.route(headers, 0)->directResponseEntry()->responseBody());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("direct.example.com", "/other", true, false);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/https", false, false);
EXPECT_EQ("https://redirect.lyft.com/https",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
EXPECT_EQ(nullptr, config.route(headers, 0)->perFilterConfig("bar"));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host_https", false, false);
EXPECT_EQ("https://new.lyft.com/host_https",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/path_https", false, false);
EXPECT_EQ("https://redirect.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host_path_https", false, false);
EXPECT_EQ("https://new.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/port", false, false);
EXPECT_EQ("http://redirect.lyft.com:8080/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:8080", "/port", false, false);
EXPECT_EQ("http://redirect.lyft.com:8181/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host_port", false, false);
EXPECT_EQ("http://new.lyft.com:8080/host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/scheme_host_port", false, false);
EXPECT_EQ("ws://new.lyft.com:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:80", "/ws", true, false);
EXPECT_EQ("ws://redirect.lyft.com:80/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:80", "/host_path_https", false, false);
EXPECT_EQ("https://new.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:80", "/scheme_host_port", false, false);
EXPECT_EQ("ws://new.lyft.com:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:443", "/ws", false, false);
EXPECT_EQ("ws://redirect.lyft.com:443/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:443", "/host_path_http", true, false);
EXPECT_EQ("http://new.lyft.com/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com:443", "/scheme_host_port", true, false);
EXPECT_EQ("ws://new.lyft.com:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("10.0.0.1", "/port", false, false);
EXPECT_EQ("http://10.0.0.1:8080/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("10.0.0.1:8080", "/port", false, false);
EXPECT_EQ("http://10.0.0.1:8181/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("10.0.0.1", "/host_port", false, false);
EXPECT_EQ("http://20.0.0.2:8080/host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("10.0.0.1", "/scheme_host_port", false, false);
EXPECT_EQ("ws://20.0.0.2:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("10.0.0.1:80", "/ws", true, false);
EXPECT_EQ("ws://10.0.0.1:80/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("10.0.0.1:80", "/host_path_https", false, false);
EXPECT_EQ("https://20.0.0.2/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("10.0.0.1:80", "/scheme_host_port", false, false);
EXPECT_EQ("ws://20.0.0.2:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("10.0.0.1:443", "/ws", false, false);
EXPECT_EQ("ws://10.0.0.1:443/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("10.0.0.1:443", "/host_path_http", true, false);
EXPECT_EQ("http://20.0.0.2/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("10.0.0.1:443", "/scheme_host_port", true, false);
EXPECT_EQ("ws://20.0.0.2:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("[fe80::1]", "/port", false, false);
EXPECT_EQ("http://[fe80::1]:8080/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("[fe80::1]:8080", "/port", false, false);
EXPECT_EQ("http://[fe80::1]:8181/port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("[fe80::1]", "/host_port", false, false);
EXPECT_EQ("http://[fe80::2]:8080/host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("[fe80::1]", "/scheme_host_port", false, false);
EXPECT_EQ("ws://[fe80::2]:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("[fe80::1]:80", "/ws", true, false);
EXPECT_EQ("ws://[fe80::1]:80/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("[fe80::1]:80", "/host_path_https", false, false);
EXPECT_EQ("https://[fe80::2]/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("[fe80::1]:80", "/scheme_host_port", false, false);
EXPECT_EQ("ws://[fe80::2]:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("[fe80::1]:443", "/ws", false, false);
EXPECT_EQ("ws://[fe80::1]:443/ws",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("[fe80::1]:443", "/host_path_http", true, false);
EXPECT_EQ("http://[fe80::2]/new_path",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("[fe80::1]:443", "/scheme_host_port", true, false);
EXPECT_EQ("ws://[fe80::2]:8080/scheme_host_port",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
}
TEST_F(RouteMatcherTest, ExclusiveRouteEntryOrDirectResponseEntry) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
cluster: www2
- name: redirect
domains:
- redirect.lyft.com
routes:
- match:
prefix: "/foo"
redirect:
host_redirect: new.lyft.com
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/foo", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
EXPECT_EQ("www2", config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("redirect.lyft.com", "/foo", false, false);
EXPECT_EQ("http://new.lyft.com/foo",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
EXPECT_EQ(nullptr, config.route(headers, 0)->routeEntry());
}
}
TEST_F(RouteMatcherTest, ExclusiveWeightedClustersEntryOrDirectResponseEntry) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
weighted_clusters:
clusters:
- name: www2
weight: 100
- name: redirect
domains:
- redirect.lyft.com
routes:
- match:
prefix: "/foo"
redirect:
host_redirect: new.lyft.com
- match:
prefix: "/foo1"
redirect:
host_redirect: "[fe80::1]"
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/foo", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
EXPECT_EQ("www2", config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("redirect.lyft.com", "/foo", false, false);
EXPECT_EQ("http://new.lyft.com/foo",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
EXPECT_EQ(nullptr, config.route(headers, 0)->routeEntry());
}
}
struct Foo : public Envoy::Config::TypedMetadata::Object {};
struct Baz : public Envoy::Config::TypedMetadata::Object {
Baz(std::string n) : name(n) {}
std::string name;
};
class BazFactory : public HttpRouteTypedMetadataFactory {
public:
const std::string name() const override { return "baz"; }
// Returns nullptr (conversion failure) if d is empty.
std::unique_ptr<const Envoy::Config::TypedMetadata::Object>
parse(const ProtobufWkt::Struct& d) const override {
if (d.fields().find("name") != d.fields().end()) {
return std::make_unique<Baz>(d.fields().at("name").string_value());
}
throw EnvoyException("Cannot create a Baz when metadata is empty.");
}
};
TEST_F(RouteMatcherTest, WeightedClusters) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www1
domains: ["www1.lyft.com"]
routes:
- match: { prefix: "/" }
metadata: { filter_metadata: { com.bar.foo: { baz: test_value }, baz: {name: meh} } }
decorator:
operation: hello
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 30
- name: cluster2
weight: 30
- name: cluster3
weight: 40
- name: www2
domains: ["www2.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 2000
- name: cluster2
weight: 3000
- name: cluster3
weight: 5000
total_weight: 10000
- name: www3
domains: ["www3.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
runtime_key_prefix: www3_weights
clusters:
- name: cluster1
weight: 30
- name: cluster2
weight: 30
- name: cluster3
weight: 40
- name: www4
domains: ["www4.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
runtime_key_prefix: www4_weights
clusters:
- name: cluster1
weight: 2000
- name: cluster2
weight: 3000
- name: cluster3
weight: 5000
total_weight: 10000
)EOF";
BazFactory baz_factory;
Registry::InjectFactory<HttpRouteTypedMetadataFactory> registered_factory(baz_factory);
auto& runtime = factory_context_.runtime_loader_;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www1.lyft.com", "/foo", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
}
// Weighted Cluster with no runtime, default total weight
{
Http::TestHeaderMapImpl headers = genHeaders("www1.lyft.com", "/foo", "GET");
EXPECT_EQ("cluster1", config.route(headers, 115)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 445)->routeEntry()->clusterName());
EXPECT_EQ("cluster3", config.route(headers, 560)->routeEntry()->clusterName());
}
// Make sure weighted cluster entries call through to the parent when needed.
{
Http::TestHeaderMapImpl headers = genHeaders("www1.lyft.com", "/foo", "GET");
auto route = config.route(headers, 115);
const RouteEntry* route_entry = route->routeEntry();
EXPECT_EQ(nullptr, route_entry->hashPolicy());
EXPECT_TRUE(route_entry->opaqueConfig().empty());
EXPECT_FALSE(route_entry->autoHostRewrite());
EXPECT_TRUE(route_entry->includeVirtualHostRateLimits());
EXPECT_EQ(Http::Code::ServiceUnavailable, route_entry->clusterNotFoundResponseCode());
EXPECT_EQ(nullptr, route_entry->corsPolicy());
EXPECT_EQ("test_value",
Envoy::Config::Metadata::metadataValue(route_entry->metadata(), "com.bar.foo", "baz")
.string_value());
EXPECT_EQ(nullptr, route_entry->typedMetadata().get<Foo>(baz_factory.name()));
EXPECT_EQ("meh", route_entry->typedMetadata().get<Baz>(baz_factory.name())->name);
EXPECT_EQ("hello", route->decorator()->getOperation());
Http::TestHeaderMapImpl response_headers;
StreamInfo::MockStreamInfo stream_info;
route_entry->finalizeResponseHeaders(response_headers, stream_info);
EXPECT_EQ(response_headers, Http::TestHeaderMapImpl{});
}
// Weighted Cluster with no runtime, total weight = 10000
{
Http::TestHeaderMapImpl headers = genHeaders("www2.lyft.com", "/foo", "GET");
EXPECT_EQ("cluster1", config.route(headers, 1150)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 4500)->routeEntry()->clusterName());
EXPECT_EQ("cluster3", config.route(headers, 8900)->routeEntry()->clusterName());
}
// Weighted Cluster with valid runtime values, default total weight
{
Http::TestHeaderMapImpl headers = genHeaders("www3.lyft.com", "/foo", "GET");
EXPECT_CALL(runtime.snapshot_, featureEnabled("www3", 100, _)).WillRepeatedly(Return(true));
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster1", 30))
.WillRepeatedly(Return(80));
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster2", 30))
.WillRepeatedly(Return(10));
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster3", 40))
.WillRepeatedly(Return(10));
EXPECT_EQ("cluster1", config.route(headers, 45)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 82)->routeEntry()->clusterName());
EXPECT_EQ("cluster3", config.route(headers, 92)->routeEntry()->clusterName());
}
// Weighted Cluster with invalid runtime values, default total weight
{
Http::TestHeaderMapImpl headers = genHeaders("www3.lyft.com", "/foo", "GET");
EXPECT_CALL(runtime.snapshot_, featureEnabled("www3", 100, _)).WillRepeatedly(Return(true));
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster1", 30))
.WillRepeatedly(Return(10));
// We return an invalid value here, one that is greater than 100
// Expect any random value > 10 to always land in cluster2.
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster2", 30))
.WillRepeatedly(Return(120));
EXPECT_CALL(runtime.snapshot_, getInteger("www3_weights.cluster3", 40))
.WillRepeatedly(Return(10));
EXPECT_EQ("cluster1", config.route(headers, 1005)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 82)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 92)->routeEntry()->clusterName());
}
// Weighted Cluster with runtime values, total weight = 10000
{
Http::TestHeaderMapImpl headers = genHeaders("www4.lyft.com", "/foo", "GET");
EXPECT_CALL(runtime.snapshot_, featureEnabled("www4", 100, _)).WillRepeatedly(Return(true));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster1", 2000))
.WillRepeatedly(Return(8000));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster2", 3000))
.WillRepeatedly(Return(1000));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster3", 5000))
.WillRepeatedly(Return(1000));
EXPECT_EQ("cluster1", config.route(headers, 1150)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 8100)->routeEntry()->clusterName());
EXPECT_EQ("cluster3", config.route(headers, 9200)->routeEntry()->clusterName());
}
// Weighted Cluster with invalid runtime values, total weight = 10000
{
Http::TestHeaderMapImpl headers = genHeaders("www4.lyft.com", "/foo", "GET");
EXPECT_CALL(runtime.snapshot_, featureEnabled("www4", 100, _)).WillRepeatedly(Return(true));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster1", 2000))
.WillRepeatedly(Return(1000));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster2", 3000))
.WillRepeatedly(Return(12000));
EXPECT_CALL(runtime.snapshot_, getInteger("www4_weights.cluster3", 5000))
.WillRepeatedly(Return(1000));
EXPECT_EQ("cluster1", config.route(headers, 500)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 1500)->routeEntry()->clusterName());
EXPECT_EQ("cluster2", config.route(headers, 9999)->routeEntry()->clusterName());
}
}
TEST_F(RouteMatcherTest, ExclusiveWeightedClustersOrClusterConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 30
- name: cluster2
weight: 30
- name: cluster3
weight: 40
cluster: www2
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, WeightedClustersMissingClusterList) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
weighted_clusters:
runtime_key_prefix: www2
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, WeightedClustersEmptyClustersList) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
weighted_clusters:
runtime_key_prefix: www2
clusters: []
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, WeightedClustersSumOFWeightsNotEqualToMax) {
std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 3
- name: cluster2
weight: 3
- name: cluster3
weight: 3
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Sum of weights in the weighted_cluster should add up to 100");
yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
total_weight: 99
clusters:
- name: cluster1
weight: 3
- name: cluster2
weight: 3
- name: cluster3
weight: 3
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Sum of weights in the weighted_cluster should add up to 99");
}
TEST_F(RouteMatcherTest, TestWeightedClusterWithMissingWeights) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/"
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 50
- name: cluster2
weight: 50
- name: cluster3
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, TestWeightedClusterInvalidClusterName) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- www.lyft.com
routes:
- match:
prefix: "/foo"
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 33
- name: cluster2
weight: 33
- name: cluster3-invalid
weight: 34
)EOF";
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("cluster1")))
.WillRepeatedly(Return(&factory_context_.cluster_manager_.thread_local_cluster_));
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("cluster2")))
.WillRepeatedly(Return(&factory_context_.cluster_manager_.thread_local_cluster_));
EXPECT_CALL(factory_context_.cluster_manager_, get(Eq("cluster3-invalid")))
.WillRepeatedly(Return(nullptr));
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(RouteMatcherTest, TestWeightedClusterHeaderManipulation) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains: ["www.lyft.com"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
clusters:
- name: cluster1
weight: 50
request_headers_to_add:
- header:
key: x-req-cluster
value: cluster1
response_headers_to_add:
- header:
key: x-resp-cluster
value: cluster1
response_headers_to_remove: [ "x-remove-cluster1" ]
- name: cluster2
weight: 50
request_headers_to_add:
- header:
key: x-req-cluster
value: cluster2
response_headers_to_add:
- header:
key: x-resp-cluster
value: cluster2
response_headers_to_remove: [ "x-remove-cluster2" ]
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Http::TestHeaderMapImpl resp_headers({{"x-remove-cluster1", "value"}});
const RouteEntry* route = config.route(headers, 0)->routeEntry();
EXPECT_EQ("cluster1", route->clusterName());
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("cluster1", headers.get_("x-req-cluster"));
route->finalizeResponseHeaders(resp_headers, stream_info);
EXPECT_EQ("cluster1", resp_headers.get_("x-resp-cluster"));
EXPECT_FALSE(resp_headers.has("x-remove-cluster1"));
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Http::TestHeaderMapImpl resp_headers({{"x-remove-cluster2", "value"}});
const RouteEntry* route = config.route(headers, 55)->routeEntry();
EXPECT_EQ("cluster2", route->clusterName());
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("cluster2", headers.get_("x-req-cluster"));
route->finalizeResponseHeaders(resp_headers, stream_info);
EXPECT_EQ("cluster2", resp_headers.get_("x-resp-cluster"));
EXPECT_FALSE(resp_headers.has("x-remove-cluster2"));
}
}
TEST(NullConfigImplTest, All) {
NullConfigImpl config;
Http::TestHeaderMapImpl headers = genRedirectHeaders("redirect.lyft.com", "/baz", true, false);
EXPECT_EQ(nullptr, config.route(headers, 0));
EXPECT_EQ(0UL, config.internalOnlyHeaders().size());
EXPECT_EQ("", config.name());
}
class BadHttpRouteConfigurationsTest : public testing::Test, public ConfigImplTestBase {};
TEST_F(BadHttpRouteConfigurationsTest, BadRouteConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
fake_entry: fake_type
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(BadHttpRouteConfigurationsTest, BadVirtualHostConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
router:
cluster: my_cluster
routes:
- match:
prefix: "/"
route:
cluster: www2
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
timeout: 1234s
)EOF";
EXPECT_THROW(TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException);
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigPrefixAndPath) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
path: "/foo"
route:
cluster: www2
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"invalid value oneof field 'path_specifier' is already set. Cannot set 'prefix' for type "
"oneof");
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigMissingPathSpecifier) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- route:
cluster: www2
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "RouteValidationError.Match: \\[\"value is required\"\\]");
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigPrefixAndRegex) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
regex: "/[bc]at"
route:
cluster: www2
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"invalid value oneof field 'path_specifier' is already set. Cannot set 'prefix' for type "
"oneof");
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigNoAction) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/api"
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "caused by field: \"action\", reason: is required");
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigPathAndRegex) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
path: "/foo"
regex: "/[bc]at"
route:
cluster: www2
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"invalid value oneof field 'path_specifier' is already set. Cannot set 'path' for type "
"oneof");
}
TEST_F(BadHttpRouteConfigurationsTest, BadRouteEntryConfigPrefixAndPathAndRegex) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
path: "/foo"
regex: "/[bc]at"
route:
cluster: www2
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "invalid value oneof field 'path_specifier' is already set.");
}
TEST_F(RouteMatcherTest, TestOpaqueConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: default
domains:
- "*"
routes:
- match:
prefix: "/api"
route:
cluster: ats
metadata:
filter_metadata:
envoy.router:
name1: value1
name2: value2
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const std::multimap<std::string, std::string>& opaque_config =
config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)->routeEntry()->opaqueConfig();
EXPECT_EQ(opaque_config.find("name1")->second, "value1");
EXPECT_EQ(opaque_config.find("name2")->second, "value2");
}
class RoutePropertyTest : public testing::Test, public ConfigImplTestBase {};
TEST_F(RoutePropertyTest, excludeVHRateLimits) {
std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
)EOF";
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
std::unique_ptr<ConfigImpl> config_ptr;
config_ptr = std::make_unique<TestConfigImpl>(parseRouteConfigurationFromV2Yaml(yaml),
factory_context_, true);
EXPECT_TRUE(config_ptr->route(headers, 0)->routeEntry()->includeVirtualHostRateLimits());
yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
rate_limits:
- actions:
- remote_address: {}
)EOF";
config_ptr = std::make_unique<TestConfigImpl>(parseRouteConfigurationFromV2Yaml(yaml),
factory_context_, true);
EXPECT_FALSE(config_ptr->route(headers, 0)->routeEntry()->includeVirtualHostRateLimits());
yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: www2
include_vh_rate_limits: true
rate_limits:
- actions:
- remote_address: {}
)EOF";
config_ptr = std::make_unique<TestConfigImpl>(parseRouteConfigurationFromV2Yaml(yaml),
factory_context_, true);
EXPECT_TRUE(config_ptr->route(headers, 0)->routeEntry()->includeVirtualHostRateLimits());
}
TEST_F(RoutePropertyTest, DEPRECATED_FEATURE_TEST(TestVHostCorsConfig)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "default"
domains: ["*"]
cors:
allow_origin: ["test-origin"]
allow_origin_regex:
- .*\.envoyproxy\.io
allow_origin_string_match:
- safe_regex:
google_re2: {}
regex: .*\.envoyproxy\.io
allow_methods: "test-methods"
allow_headers: "test-headers"
expose_headers: "test-expose-headers"
max_age: "test-max-age"
allow_credentials: true
filter_enabled:
runtime_key: "cors.www.enabled"
default_value:
numerator: 0
denominator: "HUNDRED"
shadow_enabled:
runtime_key: "cors.www.shadow_enabled"
default_value:
numerator: 100
denominator: "HUNDRED"
routes:
- match:
prefix: "/api"
route:
cluster: "ats"
)EOF";
Runtime::MockSnapshot snapshot;
EXPECT_CALL(snapshot,
featureEnabled("cors.www.enabled", Matcher<const envoy::type::FractionalPercent&>(_)))
.WillOnce(Return(false));
EXPECT_CALL(snapshot, featureEnabled("cors.www.shadow_enabled",
Matcher<const envoy::type::FractionalPercent&>(_)))
.WillOnce(Return(true));
EXPECT_CALL(factory_context_.runtime_loader_, snapshot()).WillRepeatedly(ReturnRef(snapshot));
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
const Router::CorsPolicy* cors_policy =
config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)
->routeEntry()
->virtualHost()
.corsPolicy();
EXPECT_EQ(cors_policy->enabled(), false);
EXPECT_EQ(cors_policy->shadowEnabled(), true);
EXPECT_EQ(3, cors_policy->allowOrigins().size());
EXPECT_EQ(cors_policy->allowMethods(), "test-methods");
EXPECT_EQ(cors_policy->allowHeaders(), "test-headers");
EXPECT_EQ(cors_policy->exposeHeaders(), "test-expose-headers");
EXPECT_EQ(cors_policy->maxAge(), "test-max-age");
EXPECT_EQ(cors_policy->allowCredentials(), true);
}
TEST_F(RoutePropertyTest, DEPRECATED_FEATURE_TEST(TestRouteCorsConfig)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: "default"
domains: ["*"]
routes:
- match:
prefix: "/api"
route:
cluster: "ats"
cors:
allow_origin: ["test-origin"]
allow_methods: "test-methods"
allow_headers: "test-headers"
expose_headers: "test-expose-headers"
max_age: "test-max-age"
allow_credentials: true
filter_enabled:
runtime_key: "cors.www.enabled"
default_value:
numerator: 0
denominator: "HUNDRED"
shadow_enabled:
runtime_key: "cors.www.shadow_enabled"
default_value:
numerator: 100
denominator: "HUNDRED"
)EOF";
Runtime::MockSnapshot snapshot;
EXPECT_CALL(snapshot,
featureEnabled("cors.www.enabled", Matcher<const envoy::type::FractionalPercent&>(_)))
.WillOnce(Return(false));
EXPECT_CALL(snapshot, featureEnabled("cors.www.shadow_enabled",
Matcher<const envoy::type::FractionalPercent&>(_)))
.WillOnce(Return(true));
EXPECT_CALL(factory_context_.runtime_loader_, snapshot()).WillRepeatedly(ReturnRef(snapshot));
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, false);
const Router::CorsPolicy* cors_policy =
config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)->routeEntry()->corsPolicy();
EXPECT_EQ(cors_policy->enabled(), false);
EXPECT_EQ(cors_policy->shadowEnabled(), true);
EXPECT_EQ(1, cors_policy->allowOrigins().size());
EXPECT_EQ(cors_policy->allowMethods(), "test-methods");
EXPECT_EQ(cors_policy->allowHeaders(), "test-headers");
EXPECT_EQ(cors_policy->exposeHeaders(), "test-expose-headers");
EXPECT_EQ(cors_policy->maxAge(), "test-max-age");
EXPECT_EQ(cors_policy->allowCredentials(), true);
}
TEST_F(RoutePropertyTest, DEPRECATED_FEATURE_TEST(TestVHostCorsLegacyConfig)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: default
domains:
- "*"
cors:
allow_origin:
- test-origin
allow_methods: test-methods
allow_headers: test-headers
expose_headers: test-expose-headers
max_age: test-max-age
allow_credentials: true
routes:
- match:
prefix: "/api"
route:
cluster: ats
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const Router::CorsPolicy* cors_policy =
config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)
->routeEntry()
->virtualHost()
.corsPolicy();
EXPECT_EQ(cors_policy->enabled(), true);
EXPECT_EQ(cors_policy->shadowEnabled(), false);
EXPECT_EQ(1, cors_policy->allowOrigins().size());
EXPECT_EQ(cors_policy->allowMethods(), "test-methods");
EXPECT_EQ(cors_policy->allowHeaders(), "test-headers");
EXPECT_EQ(cors_policy->exposeHeaders(), "test-expose-headers");
EXPECT_EQ(cors_policy->maxAge(), "test-max-age");
EXPECT_EQ(cors_policy->allowCredentials(), true);
}
TEST_F(RoutePropertyTest, DEPRECATED_FEATURE_TEST(TestRouteCorsLegacyConfig)) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: default
domains:
- "*"
routes:
- match:
prefix: "/api"
route:
cluster: ats
cors:
allow_origin:
- test-origin
allow_methods: test-methods
allow_headers: test-headers
expose_headers: test-expose-headers
max_age: test-max-age
allow_credentials: true
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const Router::CorsPolicy* cors_policy =
config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)->routeEntry()->corsPolicy();
EXPECT_EQ(cors_policy->enabled(), true);
EXPECT_EQ(cors_policy->shadowEnabled(), false);
EXPECT_EQ(1, cors_policy->allowOrigins().size());
EXPECT_EQ(cors_policy->allowMethods(), "test-methods");
EXPECT_EQ(cors_policy->allowHeaders(), "test-headers");
EXPECT_EQ(cors_policy->exposeHeaders(), "test-expose-headers");
EXPECT_EQ(cors_policy->maxAge(), "test-max-age");
EXPECT_EQ(cors_policy->allowCredentials(), true);
}
TEST_F(RoutePropertyTest, TestBadCorsConfig) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: default
domains:
- "*"
routes:
- match:
prefix: "/api"
route:
cluster: ats
cors:
enabled: 0
)EOF";
EXPECT_THROW_WITH_REGEX(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Unable to parse JSON as proto .*: invalid value 0 for type TYPE_BOOL");
}
TEST_F(RouteMatcherTest, Decorator) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/foo"
route:
cluster: foo
decorator:
operation: myFoo
- match:
prefix: "/bar"
route:
cluster: bar
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET");
Router::RouteConstSharedPtr route = config.route(headers, 0);
Tracing::MockSpan span;
EXPECT_CALL(span, setOperation(Eq("myFoo")));
route->decorator()->apply(span);
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET");
Router::RouteConstSharedPtr route = config.route(headers, 0);
EXPECT_EQ(nullptr, route->decorator());
}
}
class CustomRequestHeadersTest : public testing::Test, public ConfigImplTestBase {};
TEST_F(CustomRequestHeadersTest, AddNewHeader) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- lyft.com
- www.lyft.com
- w.lyft.com
- ww.lyft.com
- wwww.lyft.com
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%"
routes:
- match:
prefix: "/new_endpoint"
route:
prefix_rewrite: "/api/new_endpoint"
cluster: www2
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%"
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%"
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/new_endpoint/foo", "GET");
const RouteEntry* route = config.route(headers, 0)->routeEntry();
route->finalizeRequestHeaders(headers, stream_info, true);
EXPECT_EQ("127.0.0.1", headers.get_("x-client-ip"));
}
TEST_F(CustomRequestHeadersTest, CustomHeaderWrongFormat) {
const std::string yaml = R"EOF(
virtual_hosts:
- name: www2
domains:
- lyft.com
- www.lyft.com
- w.lyft.com
- ww.lyft.com
- wwww.lyft.com
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%"
routes:
- match:
prefix: "/new_endpoint"
route:
prefix_rewrite: "/api/new_endpoint"
cluster: www2
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT"
request_headers_to_add:
- header:
key: x-client-ip
value: "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT"
)EOF";
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException,
"Invalid header configuration. Un-terminated variable expression "
"'DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT'");
}
TEST(MetadataMatchCriteriaImpl, Create) {
auto v1 = ProtobufWkt::Value();
v1.set_string_value("v1");
auto v2 = ProtobufWkt::Value();
v2.set_number_value(2.0);
auto v3 = ProtobufWkt::Value();
v3.set_bool_value(true);
auto metadata_struct = ProtobufWkt::Struct();
auto mutable_fields = metadata_struct.mutable_fields();
mutable_fields->insert({"a", v1});
mutable_fields->insert({"b", v2});
mutable_fields->insert({"c", v3});
auto matches = MetadataMatchCriteriaImpl(metadata_struct);
EXPECT_EQ(matches.metadataMatchCriteria().size(), 3);
auto it = matches.metadataMatchCriteria().begin();
EXPECT_EQ((*it)->name(), "a");
EXPECT_EQ((*it)->value().value().string_value(), "v1");
it++;
EXPECT_EQ((*it)->name(), "b");
EXPECT_EQ((*it)->value().value().number_value(), 2.0);
it++;
EXPECT_EQ((*it)->name(), "c");
EXPECT_EQ((*it)->value().value().bool_value(), true);
}
TEST(MetadataMatchCriteriaImpl, Merge) {
auto pv1 = ProtobufWkt::Value();
pv1.set_string_value("v1");
auto pv2 = ProtobufWkt::Value();
pv2.set_number_value(2.0);
auto pv3 = ProtobufWkt::Value();
pv3.set_bool_value(true);
auto parent_struct = ProtobufWkt::Struct();
auto parent_fields = parent_struct.mutable_fields();
parent_fields->insert({"a", pv1});
parent_fields->insert({"b", pv2});
parent_fields->insert({"c", pv3});
auto parent_matches = MetadataMatchCriteriaImpl(parent_struct);
auto v1 = ProtobufWkt::Value();
v1.set_string_value("override1");
auto v2 = ProtobufWkt::Value();
v2.set_string_value("v2");
auto v3 = ProtobufWkt::Value();
v3.set_string_value("override3");
auto metadata_struct = ProtobufWkt::Struct();
auto mutable_fields = metadata_struct.mutable_fields();
mutable_fields->insert({"a", v1});
mutable_fields->insert({"b++", v2});
mutable_fields->insert({"c", v3});
MetadataMatchCriteriaConstPtr matches = parent_matches.mergeMatchCriteria(metadata_struct);
EXPECT_EQ(matches->metadataMatchCriteria().size(), 4);
auto it = matches->metadataMatchCriteria().begin();
EXPECT_EQ((*it)->name(), "a");
EXPECT_EQ((*it)->value().value().string_value(), "override1");
it++;
EXPECT_EQ((*it)->name(), "b");
EXPECT_EQ((*it)->value().value().number_value(), 2.0);
it++;
EXPECT_EQ((*it)->name(), "b++");
EXPECT_EQ((*it)->value().value().string_value(), "v2");
it++;
EXPECT_EQ((*it)->name(), "c");
EXPECT_EQ((*it)->value().value().string_value(), "override3");
}
class RouteEntryMetadataMatchTest : public testing::Test, public ConfigImplTestBase {};
TEST_F(RouteEntryMetadataMatchTest, ParsesMetadata) {
auto route_config = envoy::api::v2::RouteConfiguration();
auto* vhost = route_config.add_virtual_hosts();
vhost->set_name("vhost");
vhost->add_domains("www.lyft.com");
// route provides metadata matches combined from RouteAction and WeightedCluster
auto* route = vhost->add_routes();
route->mutable_match()->set_prefix("/both");
auto* route_action = route->mutable_route();
auto* weighted_cluster = route_action->mutable_weighted_clusters()->add_clusters();
weighted_cluster->set_name("www1");
weighted_cluster->mutable_weight()->set_value(100);
Envoy::Config::Metadata::mutableMetadataValue(*weighted_cluster->mutable_metadata_match(),
Envoy::Config::MetadataFilters::get().ENVOY_LB,
"r1_wc_key")
.set_string_value("r1_wc_value");
Envoy::Config::Metadata::mutableMetadataValue(*route_action->mutable_metadata_match(),
Envoy::Config::MetadataFilters::get().ENVOY_LB,
"r1_key")
.set_string_value("r1_value");
// route provides metadata matches from WeightedCluster only
route = vhost->add_routes();
route->mutable_match()->set_prefix("/cluster-only");
route_action = route->mutable_route();
weighted_cluster = route_action->mutable_weighted_clusters()->add_clusters();
weighted_cluster->set_name("www2");
weighted_cluster->mutable_weight()->set_value(100);
Envoy::Config::Metadata::mutableMetadataValue(*weighted_cluster->mutable_metadata_match(),
Envoy::Config::MetadataFilters::get().ENVOY_LB,
"r2_wc_key")
.set_string_value("r2_wc_value");
// route provides metadata matches from RouteAction only
route = vhost->add_routes();
route->mutable_match()->set_prefix("/route-only");
route_action = route->mutable_route();
route_action->set_cluster("www3");
Envoy::Config::Metadata::mutableMetadataValue(*route_action->mutable_metadata_match(),
Envoy::Config::MetadataFilters::get().ENVOY_LB,
"r3_key")
.set_string_value("r3_value");
// route provides metadata matches from RouteAction (but WeightedCluster exists)
route = vhost->add_routes();
route->mutable_match()->set_prefix("/cluster-passthrough");
route_action = route->mutable_route();
weighted_cluster = route_action->mutable_weighted_clusters()->add_clusters();
weighted_cluster->set_name("www4");
weighted_cluster->mutable_weight()->set_value(100);
Envoy::Config::Metadata::mutableMetadataValue(*route_action->mutable_metadata_match(),
Envoy::Config::MetadataFilters::get().ENVOY_LB,
"r4_key")
.set_string_value("r4_value");
TestConfigImpl config(route_config, factory_context_, true);
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/both", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
auto* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www1", route_entry->clusterName());
auto* matches = route_entry->metadataMatchCriteria();
EXPECT_NE(matches, nullptr);
EXPECT_EQ(matches->metadataMatchCriteria().size(), 2);
EXPECT_EQ(matches->metadataMatchCriteria().at(0)->name(), "r1_key");
EXPECT_EQ(matches->metadataMatchCriteria().at(1)->name(), "r1_wc_key");
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("www.lyft.com", "/cluster-only", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
auto* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www2", route_entry->clusterName());
auto* matches = route_entry->metadataMatchCriteria();
EXPECT_NE(matches, nullptr);
EXPECT_EQ(matches->metadataMatchCriteria().size(), 1);
EXPECT_EQ(matches->metadataMatchCriteria().at(0)->name(), "r2_wc_key");
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("www.lyft.com", "/route-only", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
auto* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www3", route_entry->clusterName());
auto* matches = route_entry->metadataMatchCriteria();
EXPECT_NE(matches, nullptr);
EXPECT_EQ(matches->metadataMatchCriteria().size(), 1);
EXPECT_EQ(matches->metadataMatchCriteria().at(0)->name(), "r3_key");
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("www.lyft.com", "/cluster-passthrough", true, true);
EXPECT_EQ(nullptr, config.route(headers, 0)->directResponseEntry());
auto* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ("www4", route_entry->clusterName());
auto* matches = route_entry->metadataMatchCriteria();
EXPECT_NE(matches, nullptr);
EXPECT_EQ(matches->metadataMatchCriteria().size(), 1);
EXPECT_EQ(matches->metadataMatchCriteria().at(0)->name(), "r4_key");
}
}
class ConfigUtilityTest : public testing::Test, public ConfigImplTestBase {};
TEST_F(ConfigUtilityTest, ParseResponseCode) {
const std::vector<
std::pair<envoy::api::v2::route::RedirectAction::RedirectResponseCode, Http::Code>>
test_set = {
std::make_pair(envoy::api::v2::route::RedirectAction::MOVED_PERMANENTLY,
Http::Code::MovedPermanently),
std::make_pair(envoy::api::v2::route::RedirectAction::FOUND, Http::Code::Found),
std::make_pair(envoy::api::v2::route::RedirectAction::SEE_OTHER, Http::Code::SeeOther),
std::make_pair(envoy::api::v2::route::RedirectAction::TEMPORARY_REDIRECT,
Http::Code::TemporaryRedirect),
std::make_pair(envoy::api::v2::route::RedirectAction::PERMANENT_REDIRECT,
Http::Code::PermanentRedirect)};
for (const auto& test_case : test_set) {
EXPECT_EQ(test_case.second, ConfigUtility::parseRedirectResponseCode(test_case.first));
}
}
TEST_F(ConfigUtilityTest, ParseDirectResponseBody) {
envoy::api::v2::route::Route route;
EXPECT_EQ(EMPTY_STRING, ConfigUtility::parseDirectResponseBody(route, *api_));
route.mutable_direct_response()->mutable_body()->set_filename("missing_file");
EXPECT_THROW_WITH_MESSAGE(ConfigUtility::parseDirectResponseBody(route, *api_), EnvoyException,
"response body file missing_file does not exist");
std::string body(4097, '*');
auto filename = TestEnvironment::writeStringToFileForTest("body", body);
route.mutable_direct_response()->mutable_body()->set_filename(filename);
std::string expected_message("response body file " + filename +
" size is 4097 bytes; maximum is 4096");
EXPECT_THROW_WITH_MESSAGE(ConfigUtility::parseDirectResponseBody(route, *api_), EnvoyException,
expected_message);
}
TEST_F(RouteConfigurationV2, RedirectCode) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: redirect
domains: [redirect.lyft.com]
routes:
- match: { prefix: "/"}
redirect: { host_redirect: new.lyft.com, response_code: TEMPORARY_REDIRECT }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
EXPECT_EQ(nullptr, config.route(genRedirectHeaders("www.foo.com", "/foo", true, true), 0));
{
Http::TestHeaderMapImpl headers = genRedirectHeaders("redirect.lyft.com", "/foo", false, false);
EXPECT_EQ("http://new.lyft.com/foo",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
EXPECT_EQ(Http::Code::TemporaryRedirect,
config.route(headers, 0)->directResponseEntry()->responseCode());
}
}
// Test the parsing of direct response configurations within routes.
TEST_F(RouteConfigurationV2, DirectResponse) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: direct
domains: [example.com]
routes:
- match: { prefix: "/"}
direct_response: { status: 200, body: { inline_string: "content" } }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const auto* direct_response =
config.route(genHeaders("example.com", "/", "GET"), 0)->directResponseEntry();
EXPECT_NE(nullptr, direct_response);
EXPECT_EQ(Http::Code::OK, direct_response->responseCode());
EXPECT_STREQ("content", direct_response->responseBody().c_str());
}
// Test the parsing of a direct response configuration where the response body is too large.
TEST_F(RouteConfigurationV2, DirectResponseTooLarge) {
std::string response_body(4097, 'A');
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: direct
domains: [example.com]
routes:
- match: { prefix: "/"}
direct_response:
status: 200
body:
inline_string: )EOF" +
response_body + "\n";
EXPECT_THROW_WITH_MESSAGE(TestConfigImpl invalid_config(parseRouteConfigurationFromV2Yaml(yaml),
factory_context_, true),
EnvoyException, "response body size is 4097 bytes; maximum is 4096");
}
void checkPathMatchCriterion(const Route* route, const std::string& expected_matcher,
PathMatchType expected_type) {
ASSERT_NE(nullptr, route);
const auto route_entry = route->routeEntry();
ASSERT_NE(nullptr, route_entry);
const auto& match_criterion = route_entry->pathMatchCriterion();
EXPECT_EQ(expected_matcher, match_criterion.matcher());
EXPECT_EQ(expected_type, match_criterion.matchType());
}
// Test loading broken config throws EnvoyException.
TEST_F(RouteConfigurationV2, BrokenTypedMetadata) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/"}
route: { cluster: www2 }
metadata: { filter_metadata: { com.bar.foo: { baz: test_value },
baz: {} } }
)EOF";
BazFactory baz_factory;
Registry::InjectFactory<HttpRouteTypedMetadataFactory> registered_factory(baz_factory);
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
Envoy::EnvoyException, "Cannot create a Baz when metadata is empty.");
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RouteConfigGetters)) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { regex: "/rege[xy]" }
route: { cluster: ww2 }
- match: { path: "/exact-path" }
route: { cluster: ww2 }
- match: { prefix: "/"}
route: { cluster: www2 }
metadata: { filter_metadata: { com.bar.foo: { baz: test_value }, baz: {name: bluh} } }
)EOF";
BazFactory baz_factory;
Registry::InjectFactory<HttpRouteTypedMetadataFactory> registered_factory(baz_factory);
const TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
checkPathMatchCriterion(config.route(genHeaders("www.foo.com", "/regex", "GET"), 0).get(),
"/rege[xy]", PathMatchType::Regex);
checkPathMatchCriterion(config.route(genHeaders("www.foo.com", "/exact-path", "GET"), 0).get(),
"/exact-path", PathMatchType::Exact);
const auto route = config.route(genHeaders("www.foo.com", "/", "GET"), 0);
checkPathMatchCriterion(route.get(), "/", PathMatchType::Prefix);
const auto route_entry = route->routeEntry();
const auto& metadata = route_entry->metadata();
const auto& typed_metadata = route_entry->typedMetadata();
EXPECT_EQ("test_value",
Envoy::Config::Metadata::metadataValue(metadata, "com.bar.foo", "baz").string_value());
EXPECT_NE(nullptr, typed_metadata.get<Baz>(baz_factory.name()));
EXPECT_EQ("bluh", typed_metadata.get<Baz>(baz_factory.name())->name);
EXPECT_EQ("bar", symbol_table_->toString(route_entry->virtualHost().statName()));
EXPECT_EQ("foo", route_entry->virtualHost().routeConfig().name());
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RouteTracingConfig)) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { regex: "/first" }
tracing:
client_sampling:
numerator: 1
route: { cluster: ww2 }
- match: { regex: "/second" }
tracing:
overall_sampling:
numerator: 1
route: { cluster: ww2 }
- match: { path: "/third" }
tracing:
client_sampling:
numerator: 1
random_sampling:
numerator: 200
denominator: 1
overall_sampling:
numerator: 3
route: { cluster: ww2 }
)EOF";
BazFactory baz_factory;
Registry::InjectFactory<HttpRouteTypedMetadataFactory> registered_factory(baz_factory);
const TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const auto route1 = config.route(genHeaders("www.foo.com", "/first", "GET"), 0);
const auto route2 = config.route(genHeaders("www.foo.com", "/second", "GET"), 0);
const auto route3 = config.route(genHeaders("www.foo.com", "/third", "GET"), 0);
// Check default values for random and overall sampling
EXPECT_EQ(100, route1->tracingConfig()->getRandomSampling().numerator());
EXPECT_EQ(0, route1->tracingConfig()->getRandomSampling().denominator());
EXPECT_EQ(100, route1->tracingConfig()->getOverallSampling().numerator());
EXPECT_EQ(0, route1->tracingConfig()->getOverallSampling().denominator());
// Check default values for client sampling
EXPECT_EQ(100, route2->tracingConfig()->getClientSampling().numerator());
EXPECT_EQ(0, route2->tracingConfig()->getClientSampling().denominator());
EXPECT_EQ(1, route3->tracingConfig()->getClientSampling().numerator());
EXPECT_EQ(0, route3->tracingConfig()->getClientSampling().denominator());
EXPECT_EQ(200, route3->tracingConfig()->getRandomSampling().numerator());
EXPECT_EQ(1, route3->tracingConfig()->getRandomSampling().denominator());
EXPECT_EQ(3, route3->tracingConfig()->getOverallSampling().numerator());
EXPECT_EQ(0, route3->tracingConfig()->getOverallSampling().denominator());
}
// Test to check Prefix Rewrite for redirects
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RedirectPrefixRewrite)) {
std::string RedirectPrefixRewrite = R"EOF(
name: AllRedirects
virtual_hosts:
- name: redirect
domains: [redirect.lyft.com]
routes:
- match: { prefix: "/prefix"}
redirect: { prefix_rewrite: "/new/prefix" }
- match: { path: "/path/" }
redirect: { prefix_rewrite: "/new/path/" }
- match: { prefix: "/host/prefix" }
redirect: { host_redirect: new.lyft.com, prefix_rewrite: "/new/prefix"}
- match: { regex: "/[r][e][g][e][x].*"}
redirect: { prefix_rewrite: "/new/regex-prefix/" }
- match: { prefix: "/http/prefix"}
redirect: { prefix_rewrite: "/https/prefix" , https_redirect: true }
- match: { prefix: "/ignore-this/"}
redirect: { prefix_rewrite: "/" }
- match: { prefix: "/ignore-this"}
redirect: { prefix_rewrite: "/" }
- match: { prefix: "/ignore-substring"}
redirect: { prefix_rewrite: "/" }
- match: { prefix: "/service-hello/"}
redirect: { prefix_rewrite: "/" }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(RedirectPrefixRewrite), factory_context_,
true);
EXPECT_EQ(nullptr, config.route(genRedirectHeaders("www.foo.com", "/foo", true, true), 0));
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/prefix/some/path/?lang=eng&con=US", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/new/prefix/some/path/?lang=eng&con=US",
redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/path/", true, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("https://redirect.lyft.com/new/path/", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host/prefix/1", true, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("https://new.lyft.com/new/prefix/1", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/regex/hello/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/new/regex-prefix/", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/http/prefix/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("https://redirect.lyft.com/https/prefix/", redirect->newPath(headers));
}
{
// The following matches to the redirect action match value equals to `/ignore-this` instead of
// `/ignore-this/`.
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/ignore-this", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/", redirect->newPath(headers));
}
{
// The following matches to the redirect action match value equals to `/ignore-this/` instead of
// `/ignore-this`.
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/ignore-this/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/", redirect->newPath(headers));
}
{
// The same as previous test request, the following matches to the redirect action match value
// equals to `/ignore-this/` instead of `/ignore-this`.
Http::TestHeaderMapImpl headers = genRedirectHeaders(
"redirect.lyft.com", "/ignore-this/however/use/the/rest/of/this/path", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/however/use/the/rest/of/this/path",
redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/ignore-this/use/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/use/", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/ignore-substringto/use/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/to/use/", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/ignore-substring-to/use/", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/-to/use/", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/service-hello/a/b/c", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/a/b/c", redirect->newPath(headers));
}
}
// Test to check Strip Query for redirect messages
TEST_F(RouteConfigurationV2, RedirectStripQuery) {
std::string RouteDynPathRedirect = R"EOF(
name: AllRedirects
virtual_hosts:
- name: redirect
domains: [redirect.lyft.com]
routes:
- match: { prefix: "/query/true"}
redirect: { prefix_rewrite: "/new/prefix", strip_query: "true" }
- match: { prefix: "/query/false" }
redirect: { prefix_rewrite: "/new/prefix", strip_query: "false" }
- match: { path: "/host/query-default" }
redirect: { host_redirect: new.lyft.com }
- match: { path: "/path/redirect/"}
redirect: { path_redirect: "/new/path-redirect/" }
- match: { prefix: "/all/combinations"}
redirect: { host_redirect: "new.lyft.com", prefix_rewrite: "/new/prefix" , https_redirect: "true", strip_query: "true" }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(RouteDynPathRedirect), factory_context_,
true);
EXPECT_EQ(nullptr, config.route(genRedirectHeaders("www.foo.com", "/foo", true, true), 0));
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/query/true?lang=eng&con=US", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("http://redirect.lyft.com/new/prefix", redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders(
"redirect.lyft.com", "/query/false/some/path?lang=eng&con=US", true, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("https://redirect.lyft.com/new/prefix/some/path?lang=eng&con=US",
redirect->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/host/query-default?lang=eng&con=US", true, false);
EXPECT_EQ("https://new.lyft.com/host/query-default?lang=eng&con=US",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers =
genRedirectHeaders("redirect.lyft.com", "/path/redirect/", true, false);
EXPECT_EQ("https://redirect.lyft.com/new/path-redirect/",
config.route(headers, 0)->directResponseEntry()->newPath(headers));
}
{
Http::TestHeaderMapImpl headers = genRedirectHeaders(
"redirect.lyft.com", "/all/combinations/here/we/go?key=value", false, false);
const DirectResponseEntry* redirect = config.route(headers, 0)->directResponseEntry();
redirect->rewritePathHeader(headers, true);
EXPECT_EQ("https://new.lyft.com/new/prefix/here/we/go", redirect->newPath(headers));
}
}
TEST_F(RouteMatcherTest, DEPRECATED_FEATURE_TEST(HeaderMatchedRoutingV2)) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
headers:
- name: test_header
exact_match: test
route:
cluster: local_service_with_headers
- match:
prefix: "/"
headers:
- name: test_header_multiple1
exact_match: test1
- name: test_header_multiple2
exact_match: test2
route:
cluster: local_service_with_multiple_headers
- match:
prefix: "/"
headers:
- name: test_header_presence
route:
cluster: local_service_with_empty_headers
- match:
prefix: "/"
headers:
- name: test_header_pattern
regex_match: "^user=test-\\d+$"
route:
cluster: local_service_with_header_pattern_set_regex
- match:
prefix: "/"
headers:
- name: test_header_pattern
exact_match: "^customer=test-\\d+$"
route:
cluster: local_service_with_header_pattern_unset_regex
- match:
prefix: "/"
headers:
- name: test_header_range
range_match:
start: -9223372036854775808
end: -10
route:
cluster: local_service_with_header_range_test1
- match:
prefix: "/"
headers:
- name: test_header_multiple_range
range_match:
start: -10
end: 1
- name: test_header_multiple_exact
exact_match: test
route:
cluster: local_service_with_header_range_test2
- match:
prefix: "/"
headers:
- name: test_header_range
range_match:
start: 1
end: 10
route:
cluster: local_service_with_header_range_test3
- match:
prefix: "/"
headers:
- name: test_header_range
range_match:
start: 9223372036854775801
end: 9223372036854775807
route:
cluster: local_service_with_header_range_test4
- match:
prefix: "/"
headers:
- name: test_header_range
exact_match: "9223372036854775807"
route:
cluster: local_service_with_header_range_test5
- match:
prefix: "/"
route:
cluster: local_service_without_headers
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
{
EXPECT_EQ("local_service_without_headers",
config.route(genHeaders("www.lyft.com", "/", "GET"), 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header", "test");
EXPECT_EQ("local_service_with_headers", config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_multiple1", "test1");
headers.addCopy("test_header_multiple2", "test2");
EXPECT_EQ("local_service_with_multiple_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("non_existent_header", "foo");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_presence", "test");
EXPECT_EQ("local_service_with_empty_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_pattern", "user=test-1223");
EXPECT_EQ("local_service_with_header_pattern_set_regex",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_pattern", "customer=test-1223");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "-9223372036854775808");
EXPECT_EQ("local_service_with_header_range_test1",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_multiple_range", "-9");
headers.addCopy("test_header_multiple_exact", "test");
EXPECT_EQ("local_service_with_header_range_test2",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "9");
EXPECT_EQ("local_service_with_header_range_test3",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "9223372036854775807");
EXPECT_EQ("local_service_with_header_range_test5",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_multiple_range", "-9");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
{
Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/", "GET");
headers.addCopy("test_header_range", "19");
EXPECT_EQ("local_service_without_headers",
config.route(headers, 0)->routeEntry()->clusterName());
}
}
TEST_F(RouteConfigurationV2,
DEPRECATED_FEATURE_TEST(RegexPrefixWithNoRewriteWorksWhenPathChanged)) {
// Setup regex route entry. the regex is trivial, that's ok as we only want to test that
// path change works.
std::string RegexRewrite = R"EOF(
name: RegexNoMatch
virtual_hosts:
- name: regex
domains: [regex.lyft.com]
routes:
- match: { regex: "/regex"}
route: { cluster: some-cluster }
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(RegexRewrite), factory_context_, true);
{
// Get our regex route entry
Http::TestHeaderMapImpl headers = genRedirectHeaders("regex.lyft.com", "/regex", true, false);
const RouteEntry* route_entry = config.route(headers, 0)->routeEntry();
// simulate a filter changing the path
headers.remove(":path");
headers.addCopy(":path", "/not-the-original-regex");
// no re-write was specified; so this should not throw
NiceMock<Envoy::StreamInfo::MockStreamInfo> stream_info;
EXPECT_NO_THROW(route_entry->finalizeRequestHeaders(headers, stream_info, false));
}
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(NoIdleTimeout)) {
const std::string NoIdleTimeout = R"EOF(
name: NoIdleTimeout
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(NoIdleTimeout), factory_context_, true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const RouteEntry* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ(absl::nullopt, route_entry->idleTimeout());
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(ZeroIdleTimeout)) {
const std::string ZeroIdleTimeout = R"EOF(
name: ZeroIdleTimeout
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
idle_timeout: 0s
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(ZeroIdleTimeout), factory_context_, true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const RouteEntry* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ(0, route_entry->idleTimeout().value().count());
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(ExplicitIdleTimeout)) {
const std::string ExplicitIdleTimeout = R"EOF(
name: ExplicitIdleTimeout
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
idle_timeout: 7s
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(ExplicitIdleTimeout), factory_context_,
true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const RouteEntry* route_entry = config.route(headers, 0)->routeEntry();
EXPECT_EQ(7 * 1000, route_entry->idleTimeout().value().count());
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RetriableStatusCodes)) {
const std::string ExplicitIdleTimeout = R"EOF(
name: RetriableStatusCodes
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
retry_policy:
retriable_status_codes: [100, 200]
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(ExplicitIdleTimeout), factory_context_,
true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const auto& retry_policy = config.route(headers, 0)->routeEntry()->retryPolicy();
const std::vector<uint32_t> expected_codes{100, 200};
EXPECT_EQ(expected_codes, retry_policy.retriableStatusCodes());
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(UpgradeConfigs)) {
const std::string UpgradeYaml = R"EOF(
name: RetriableStatusCodes
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
upgrade_configs:
- upgrade_type: Websocket
- upgrade_type: disabled
enabled: false
)EOF";
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(UpgradeYaml), factory_context_, true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const RouteEntry::UpgradeMap& upgrade_map = config.route(headers, 0)->routeEntry()->upgradeMap();
EXPECT_TRUE(upgrade_map.find("websocket")->second);
EXPECT_TRUE(upgrade_map.find("foo") == upgrade_map.end());
EXPECT_FALSE(upgrade_map.find("disabled")->second);
}
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(DuplicateUpgradeConfigs)) {
const std::string yaml = R"EOF(
name: RetriableStatusCodes
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
upgrade_configs:
- upgrade_type: Websocket
- upgrade_type: WebSocket
enabled: false
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Duplicate upgrade WebSocket");
}
// Verifies that we're creating a new instance of the retry plugins on each call instead of always
// returning the same one.
TEST_F(RouteConfigurationV2, DEPRECATED_FEATURE_TEST(RetryPluginsAreNotReused)) {
const std::string ExplicitIdleTimeout = R"EOF(
name: RetriableStatusCodes
virtual_hosts:
- name: regex
domains: [idle.lyft.com]
routes:
- match: { regex: "/regex"}
route:
cluster: some-cluster
retry_policy:
retry_host_predicate:
- name: envoy.test_host_predicate
retry_priority:
name: envoy.test_retry_priority
)EOF";
Upstream::MockRetryPriority priority{{}, {}};
Upstream::MockRetryPriorityFactory priority_factory(priority);
Registry::InjectFactory<Upstream::RetryPriorityFactory> inject_priority_factory(priority_factory);
Upstream::TestRetryHostPredicateFactory host_predicate_factory;
Registry::InjectFactory<Upstream::RetryHostPredicateFactory> inject_predicate_factory(
host_predicate_factory);
TestConfigImpl config(parseRouteConfigurationFromV2Yaml(ExplicitIdleTimeout), factory_context_,
true);
Http::TestHeaderMapImpl headers = genRedirectHeaders("idle.lyft.com", "/regex", true, false);
const auto& retry_policy = config.route(headers, 0)->routeEntry()->retryPolicy();
const auto priority1 = retry_policy.retryPriority();
const auto priority2 = retry_policy.retryPriority();
EXPECT_NE(priority1, priority2);
const auto predicates1 = retry_policy.retryHostPredicates();
const auto predicates2 = retry_policy.retryHostPredicates();
EXPECT_NE(predicates1, predicates2);
}
class PerFilterConfigsTest : public testing::Test, public ConfigImplTestBase {
public:
PerFilterConfigsTest()
: registered_factory_(factory_), registered_default_factory_(default_factory_) {}
struct DerivedFilterConfig : public RouteSpecificFilterConfig {
ProtobufWkt::Timestamp config_;
};
class TestFilterConfig : public Extensions::HttpFilters::Common::EmptyHttpFilterConfig {
public:
TestFilterConfig() : EmptyHttpFilterConfig("test.filter") {}
Http::FilterFactoryCb createFilter(const std::string&,
Server::Configuration::FactoryContext&) override {
NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
}
ProtobufTypes::MessagePtr createEmptyRouteConfigProto() override {
return ProtobufTypes::MessagePtr{new ProtobufWkt::Timestamp()};
}
Router::RouteSpecificFilterConfigConstSharedPtr
createRouteSpecificFilterConfig(const Protobuf::Message& message,
Server::Configuration::FactoryContext&) override {
auto obj = std::make_shared<DerivedFilterConfig>();
obj->config_.MergeFrom(message);
return obj;
}
};
class DefaultTestFilterConfig : public Extensions::HttpFilters::Common::EmptyHttpFilterConfig {
public:
DefaultTestFilterConfig() : EmptyHttpFilterConfig("test.default.filter") {}
Http::FilterFactoryCb createFilter(const std::string&,
Server::Configuration::FactoryContext&) override {
NOT_IMPLEMENTED_GCOVR_EXCL_LINE;
}
ProtobufTypes::MessagePtr createEmptyRouteConfigProto() override {
return ProtobufTypes::MessagePtr{new ProtobufWkt::Timestamp()};
}
};
void checkEach(const std::string& yaml, uint32_t expected_entry, uint32_t expected_route,
uint32_t expected_vhost) {
const TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const auto route = config.route(genHeaders("www.foo.com", "/", "GET"), 0);
const auto* route_entry = route->routeEntry();
const auto& vhost = route_entry->virtualHost();
check(route_entry->perFilterConfigTyped<DerivedFilterConfig>(factory_.name()), expected_entry,
"route entry");
check(route->perFilterConfigTyped<DerivedFilterConfig>(factory_.name()), expected_route,
"route");
check(vhost.perFilterConfigTyped<DerivedFilterConfig>(factory_.name()), expected_vhost,
"virtual host");
}
void check(const DerivedFilterConfig* cfg, uint32_t expected_seconds, std::string source) {
EXPECT_NE(nullptr, cfg) << "config should not be null for source: " << source;
EXPECT_EQ(expected_seconds, cfg->config_.seconds())
<< "config value does not match expected for source: " << source;
}
void checkNoPerFilterConfig(const std::string& yaml) {
const TestConfigImpl config(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true);
const auto route = config.route(genHeaders("www.foo.com", "/", "GET"), 0);
const auto* route_entry = route->routeEntry();
const auto& vhost = route_entry->virtualHost();
EXPECT_EQ(nullptr,
route_entry->perFilterConfigTyped<DerivedFilterConfig>(default_factory_.name()));
EXPECT_EQ(nullptr, route->perFilterConfigTyped<DerivedFilterConfig>(default_factory_.name()));
EXPECT_EQ(nullptr, vhost.perFilterConfigTyped<DerivedFilterConfig>(default_factory_.name()));
}
TestFilterConfig factory_;
Registry::InjectFactory<Server::Configuration::NamedHttpFilterConfigFactory> registered_factory_;
DefaultTestFilterConfig default_factory_;
Registry::InjectFactory<Server::Configuration::NamedHttpFilterConfigFactory>
registered_default_factory_;
};
TEST_F(PerFilterConfigsTest, TypedConfigFilterError) {
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
per_filter_config: { unknown.filter: {} }
typed_per_filter_config:
unknown.filter:
"@type": type.googleapis.com/google.protobuf.Timestamp
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Only one of typed_configs or configs can be specified");
}
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
per_filter_config: { unknown.filter: {} }
typed_per_filter_config:
unknown.filter:
"@type": type.googleapis.com/google.protobuf.Timestamp
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Only one of typed_configs or configs can be specified");
}
}
TEST_F(PerFilterConfigsTest, UnknownFilter) {
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
per_filter_config: { unknown.filter: {} }
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Didn't find a registered implementation for name: 'unknown.filter'");
}
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
typed_per_filter_config:
unknown.filter:
"@type": type.googleapis.com/google.protobuf.Timestamp
)EOF";
EXPECT_THROW_WITH_MESSAGE(
TestConfigImpl(parseRouteConfigurationFromV2Yaml(yaml), factory_context_, true),
EnvoyException, "Didn't find a registered implementation for name: 'unknown.filter'");
}
}
// Test that a trivially specified NamedHttpFilterConfigFactory ignores per_filter_config without
// error.
TEST_F(PerFilterConfigsTest, DefaultFilterImplementation) {
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
per_filter_config: { test.default.filter: { seconds: 123} }
)EOF";
checkNoPerFilterConfig(yaml);
}
{
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
typed_per_filter_config:
test.default.filter:
"@type": type.googleapis.com/google.protobuf.Timestamp
value:
seconds: 123
)EOF";
checkNoPerFilterConfig(yaml);
}
}
TEST_F(PerFilterConfigsTest, RouteLocalConfig) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
per_filter_config: { test.filter: { seconds: 123 } }
per_filter_config: { test.filter: { seconds: 456 } }
)EOF";
checkEach(yaml, 123, 123, 456);
}
TEST_F(PerFilterConfigsTest, RouteLocalTypedConfig) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route: { cluster: baz }
typed_per_filter_config:
test.filter:
"@type": type.googleapis.com/google.protobuf.Timestamp
value:
seconds: 123
typed_per_filter_config:
test.filter:
"@type": type.googleapis.com/google.protobuf.Struct
value:
seconds: 456
)EOF";
checkEach(yaml, 123, 123, 456);
}
TEST_F(PerFilterConfigsTest, WeightedClusterConfig) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
clusters:
- name: baz
weight: 100
per_filter_config: { test.filter: { seconds: 789 } }
per_filter_config: { test.filter: { seconds: 1011 } }
)EOF";
checkEach(yaml, 789, 789, 1011);
}
TEST_F(PerFilterConfigsTest, WeightedClusterFallthroughConfig) {
const std::string yaml = R"EOF(
name: foo
virtual_hosts:
- name: bar
domains: ["*"]
routes:
- match: { prefix: "/" }
route:
weighted_clusters:
clusters:
- name: baz
weight: 100
per_filter_config: { test.filter: { seconds: 1213 } }
per_filter_config: { test.filter: { seconds: 1415 } }
)EOF";
checkEach(yaml, 1213, 1213, 1415);
}
} // namespace
} // namespace Router
} // namespace Envoy
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Merge developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "chain.h"
#include "chainparams.h"
#include "main.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include <math.h>
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader* pblock)
{
const CBlockIndex* BlockLastSolved = pindexLast;
const CBlockIndex* BlockReading = pindexLast;
int64_t nActualTimespan = 0;
int64_t LastBlockTime = 0;
int64_t PastBlocksMin = 24;
int64_t PastBlocksMax = 24;
int64_t CountBlocks = 0;
uint256 PastDifficultyAverage;
uint256 PastDifficultyAveragePrev;
//in testnet all but last 20 blocks before LAST_POW_BLOCK are mindiff
//if (Params().NetworkID() == CBaseChainParams::TESTNET && pindexLast->nHeight < (Params().LAST_POW_BLOCK() - 20))
// return Params().ProofOfWorkLimit().GetCompact();
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin)
return Params().ProofOfWorkLimit().GetCompact();
if (pindexLast->nHeight > Params().LAST_POW_BLOCK())
{
// effectively chainparams.cpp for PoS
uint256 bnTargetLimit = (~uint256(0) >> 24);
int64_t nTargetSpacing = Params().TargetSpacing();
int64_t nTargetTimespan = Params().TargetTimespan();
int64_t nActualSpacing = 0;
if (pindexLast->nHeight != 0)
nActualSpacing = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime();
if (nActualSpacing < 0)
nActualSpacing = 1;
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
int64_t nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew <= 0 || bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) {
break;
}
CountBlocks++;
if (CountBlocks <= PastBlocksMin) {
if (CountBlocks == 1) {
PastDifficultyAverage.SetCompact(BlockReading->nBits);
} else {
PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1);
}
PastDifficultyAveragePrev = PastDifficultyAverage;
}
if (LastBlockTime > 0) {
int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
nActualTimespan += Diff;
}
LastBlockTime = BlockReading->GetBlockTime();
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
uint256 bnNew(PastDifficultyAverage);
int64_t _nTargetTimespan = CountBlocks * Params().TargetSpacing();
if (nActualTimespan < _nTargetTimespan / 3)
nActualTimespan = _nTargetTimespan / 3;
if (nActualTimespan > _nTargetTimespan * 3)
nActualTimespan = _nTargetTimespan * 3;
// Retarget
bnNew *= nActualTimespan;
bnNew /= _nTargetTimespan;
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
bool fNegative;
bool fOverflow;
uint256 bnTarget;
if (Params().SkipProofOfWorkCheck())
return true;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget)
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
uint256 GetBlockProof(const CBlockIndex& block)
{
uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
|
// AC
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#define maxN 10002
typedef int maxn;
typedef long maxa;
maxn n, root[maxN], d[maxN];
maxa m, L[maxN], R[maxN];
bool st[maxN];
std::vector <maxa> V;
void Prepare() {
std::cin >> m >> n;
for(maxn i = 0; i < n; i++) {
std::string s;
std::cin >> L[i] >> R[i] >> s;
st[i] = s[0] == 'o';
}
}
maxn Root(const maxn x) {
maxn rt = root[x] == x ? x : Root(root[x]);
d[x] ^= d[root[x]];
return (root[x] = rt);
}
maxn Process() {
for(maxn i = 0; i < n; i++) {
V.push_back(L[i] - 1);
V.push_back(R[i]);
}
std::sort(V.begin(), V.end());
V.resize(std::unique(V.begin(), V.end()) - V.begin());
for(maxn i = 0; i < V.size(); i++)
root[i] = i, d[i] = 0;
for(maxn i = 0; i < n; i++) {
maxn l = std::lower_bound(V.begin(), V.end(), L[i] - 1) - V.begin();
maxn r = std::lower_bound(V.begin(), V.end(), R[i]) - V.begin();
maxn lp = Root(l), rp = Root(r);
if (lp == rp) {
if (d[l] ^ d[r] != st[i]) return i;
}
else {
d[lp] = st[i] ^ d[l] ^ d[r];
root[lp] = rp;
}
}
return n;
}
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
std::cout << Process();
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/base/module_system_test.h"
#include "grit/renderer_resources.h"
namespace extensions {
namespace {
class EventUnittest : public ModuleSystemTest {
virtual void SetUp() OVERRIDE {
ModuleSystemTest::SetUp();
module_system_->RunString("chrome = {};", "setup-chrome");
RegisterModule("event", IDR_EVENT_BINDINGS_JS);
RegisterModule("schemaUtils", IDR_SCHEMA_UTILS_JS);
RegisterModule("utils", IDR_UTILS_JS);
RegisterModule("json_schema", IDR_JSON_SCHEMA_JS);
// Mock out the native handler for event_bindings. These mocks will fail if
// any invariants maintained by the real event_bindings are broken.
OverrideNativeHandler("event_bindings",
"var assert = requireNative('assert');"
"var attachedListeners = exports.attachedListeners = {};"
"var attachedFilteredListeners = "
" exports.attachedFilteredListeners = {};"
"var nextId = 0;"
"var idToName = {};"
"exports.AttachEvent = function(eventName) {"
" assert.AssertFalse(!!attachedListeners[eventName]);"
" attachedListeners[eventName] = 1;"
"};"
"exports.DetachEvent = function(eventName) {"
" assert.AssertTrue(!!attachedListeners[eventName]);"
" delete attachedListeners[eventName];"
"};"
"exports.IsEventAttached = function(eventName) {"
" return !!attachedListeners[eventName];"
"};"
"exports.AttachFilteredEvent = function(name, filters) {"
" var id = nextId++;"
" idToName[id] = name;"
" attachedFilteredListeners[name] ="
" attachedFilteredListeners[name] || [];"
" attachedFilteredListeners[name][id] = filters;"
" return id;"
"};"
"exports.DetachFilteredEvent = function(id, manual) {"
" var i = attachedFilteredListeners[idToName[id]].indexOf(id);"
" attachedFilteredListeners[idToName[id]].splice(i, 1);"
"};"
"exports.HasFilteredListener = function(name) {"
" return attachedFilteredListeners[name].length;"
"};");
OverrideNativeHandler("chrome_hidden",
"var chromeHidden = {};"
"exports.GetChromeHidden = function() { return chromeHidden; };");
OverrideNativeHandler("chrome",
"var chrome = {};"
"exports.GetChrome = function() { return chrome; };");
OverrideNativeHandler("sendRequest",
"exports.sendRequest = function() {};");
OverrideNativeHandler("apiDefinitions",
"exports.GetExtensionAPIDefinition = function() {};");
OverrideNativeHandler("logging",
"exports.DCHECK = function() {};");
OverrideNativeHandler("schema_registry",
"exports.GetSchema = function() {};");
}
};
TEST_F(EventUnittest, TestNothing) {
ExpectNoAssertionsMade();
}
TEST_F(EventUnittest, AddRemoveTwoListeners) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"var assert = requireNative('assert');"
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var eventBindings = requireNative('event_bindings');"
"var myEvent = new Event('named-event');"
"var cb1 = function() {};"
"var cb2 = function() {};"
"myEvent.addListener(cb1);"
"myEvent.addListener(cb2);"
"myEvent.removeListener(cb1);"
"assert.AssertTrue(!!eventBindings.attachedListeners['named-event']);"
"myEvent.removeListener(cb2);"
"assert.AssertFalse(!!eventBindings.attachedListeners['named-event']);");
module_system_->Require("test");
}
TEST_F(EventUnittest, OnUnloadDetachesAllListeners) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"var assert = requireNative('assert');"
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var eventBindings = requireNative('event_bindings');"
"var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();"
"var myEvent = new Event('named-event');"
"var cb1 = function() {};"
"var cb2 = function() {};"
"myEvent.addListener(cb1);"
"myEvent.addListener(cb2);"
"chromeHidden.dispatchOnUnload();"
"assert.AssertFalse(!!eventBindings.attachedListeners['named-event']);");
module_system_->Require("test");
}
TEST_F(EventUnittest, OnUnloadDetachesAllListenersEvenDupes) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"var assert = requireNative('assert');"
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var eventBindings = requireNative('event_bindings');"
"var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();"
"var myEvent = new Event('named-event');"
"var cb1 = function() {};"
"myEvent.addListener(cb1);"
"myEvent.addListener(cb1);"
"chromeHidden.dispatchOnUnload();"
"assert.AssertFalse(!!eventBindings.attachedListeners['named-event']);");
module_system_->Require("test");
}
TEST_F(EventUnittest, EventsThatSupportRulesMustHaveAName) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var eventOpts = {supportsRules: true};"
"var assert = requireNative('assert');"
"var caught = false;"
"try {"
" var myEvent = new Event(undefined, undefined, eventOpts);"
"} catch (e) {"
" caught = true;"
"}"
"assert.AssertTrue(caught);");
module_system_->Require("test");
}
TEST_F(EventUnittest, NamedEventDispatch) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();"
"var assert = requireNative('assert');"
"var e = new Event('myevent');"
"var called = false;"
"e.addListener(function() { called = true; });"
"chromeHidden.Event.dispatchEvent('myevent', []);"
"assert.AssertTrue(called);");
module_system_->Require("test");
}
TEST_F(EventUnittest, AddListenerWithFiltersThrowsErrorByDefault) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var e = new Event('myevent');"
"var filter = [{"
" url: {hostSuffix: 'google.com'},"
"}];"
"var caught = false;"
"try {"
" e.addListener(function() {}, filter);"
"} catch (e) {"
" caught = true;"
"}"
"assert.AssertTrue(caught);");
module_system_->Require("test");
}
TEST_F(EventUnittest, FilteredEventsAttachment) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var bindings = requireNative('event_bindings');"
"var eventOpts = {supportsListeners: true, supportsFilters: true};"
"var e = new Event('myevent', undefined, eventOpts);"
"var cb = function() {};"
"var filters = {url: [{hostSuffix: 'google.com'}]};"
"e.addListener(cb, filters);"
"assert.AssertTrue(bindings.HasFilteredListener('myevent'));"
"e.removeListener(cb);"
"assert.AssertFalse(bindings.HasFilteredListener('myevent'));");
module_system_->Require("test");
}
TEST_F(EventUnittest, DetachFilteredEvent) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var bindings = requireNative('event_bindings');"
"var eventOpts = {supportsListeners: true, supportsFilters: true};"
"var e = new Event('myevent', undefined, eventOpts);"
"var cb1 = function() {};"
"var cb2 = function() {};"
"var filters = {url: [{hostSuffix: 'google.com'}]};"
"e.addListener(cb1, filters);"
"e.addListener(cb2, filters);"
"e.detach_();"
"assert.AssertFalse(bindings.HasFilteredListener('myevent'));");
module_system_->Require("test");
}
TEST_F(EventUnittest, AttachAndRemoveSameFilteredEventListener) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var bindings = requireNative('event_bindings');"
"var eventOpts = {supportsListeners: true, supportsFilters: true};"
"var e = new Event('myevent', undefined, eventOpts);"
"var cb = function() {};"
"var filters = {url: [{hostSuffix: 'google.com'}]};"
"e.addListener(cb, filters);"
"e.addListener(cb, filters);"
"assert.AssertTrue(bindings.HasFilteredListener('myevent'));"
"e.removeListener(cb);"
"assert.AssertTrue(bindings.HasFilteredListener('myevent'));"
"e.removeListener(cb);"
"assert.AssertFalse(bindings.HasFilteredListener('myevent'));");
module_system_->Require("test");
}
TEST_F(EventUnittest, AddingFilterWithUrlFieldNotAListThrowsException) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var eventOpts = {supportsListeners: true, supportsFilters: true};"
"var e = new Event('myevent', undefined, eventOpts);"
"var cb = function() {};"
"var filters = {url: {hostSuffix: 'google.com'}};"
"var caught = false;"
"try {"
" e.addListener(cb, filters);"
"} catch (e) {"
" caught = true;"
"}"
"assert.AssertTrue(caught);");
module_system_->Require("test");
}
TEST_F(EventUnittest, MaxListeners) {
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system_.get());
RegisterModule("test",
"require('event');"
"var Event = requireNative('chrome').GetChrome().Event;"
"var assert = requireNative('assert');"
"var eventOpts = {supportsListeners: true, maxListeners: 1};"
"var e = new Event('myevent', undefined, eventOpts);"
"var cb = function() {};"
"var caught = false;"
"try {"
" e.addListener(cb);"
"} catch (e) {"
" caught = true;"
"}"
"assert.AssertTrue(!caught);"
"try {"
" e.addListener(cb);"
"} catch (e) {"
" caught = true;"
"}"
"assert.AssertTrue(caught);");
module_system_->Require("test");
}
} // namespace
} // namespace extensions
|
// Copyright 2015 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/signature.h"
#include "src/bit-vector.h"
#include "src/flags.h"
#include "src/handles.h"
#include "src/zone/zone-containers.h"
#include "src/wasm/ast-decoder.h"
#include "src/wasm/decoder.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-opcodes.h"
#include "src/ostreams.h"
#include "src/compiler/wasm-compiler.h"
namespace v8 {
namespace internal {
namespace wasm {
#if DEBUG
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
#else
#define TRACE(...)
#endif
#define CHECK_PROTOTYPE_OPCODE(flag) \
if (module_ && module_->origin == kAsmJsOrigin) { \
error("Opcode not supported for asmjs modules"); \
} \
if (!FLAG_##flag) { \
error("Invalid opcode (enable with --" #flag ")"); \
break; \
}
// TODO(titzer): this is only for intermediate migration.
#define IMPLICIT_FUNCTION_END 1
// An SsaEnv environment carries the current local variable renaming
// as well as the current effect and control dependency in the TF graph.
// It maintains a control state that tracks whether the environment
// is reachable, has reached a control end, or has been merged.
struct SsaEnv {
enum State { kControlEnd, kUnreachable, kReached, kMerged };
State state;
TFNode* control;
TFNode* effect;
TFNode** locals;
bool go() { return state >= kReached; }
void Kill(State new_state = kControlEnd) {
state = new_state;
locals = nullptr;
control = nullptr;
effect = nullptr;
}
void SetNotMerged() {
if (state == kMerged) state = kReached;
}
};
// An entry on the value stack.
struct Value {
const byte* pc;
TFNode* node;
LocalType type;
};
struct TryInfo : public ZoneObject {
SsaEnv* catch_env;
TFNode* exception;
explicit TryInfo(SsaEnv* c) : catch_env(c), exception(nullptr) {}
};
struct MergeValues {
uint32_t arity;
union {
Value* array;
Value first;
} vals; // Either multiple values or a single value.
Value& first() {
DCHECK_GT(arity, 0u);
return arity == 1 ? vals.first : vals.array[0];
}
};
static Value* NO_VALUE = nullptr;
enum ControlKind { kControlIf, kControlBlock, kControlLoop, kControlTry };
// An entry on the control stack (i.e. if, block, loop).
struct Control {
const byte* pc;
ControlKind kind;
int stack_depth; // stack height at the beginning of the construct.
SsaEnv* end_env; // end environment for the construct.
SsaEnv* false_env; // false environment (only for if).
TryInfo* try_info; // Information used for compiling try statements.
int32_t previous_catch; // The previous Control (on the stack) with a catch.
// Values merged into the end of this control construct.
MergeValues merge;
inline bool is_if() const { return kind == kControlIf; }
inline bool is_block() const { return kind == kControlBlock; }
inline bool is_loop() const { return kind == kControlLoop; }
inline bool is_try() const { return kind == kControlTry; }
// Named constructors.
static Control Block(const byte* pc, int stack_depth, SsaEnv* end_env,
int32_t previous_catch) {
return {pc, kControlBlock, stack_depth, end_env,
nullptr, nullptr, previous_catch, {0, {NO_VALUE}}};
}
static Control If(const byte* pc, int stack_depth, SsaEnv* end_env,
SsaEnv* false_env, int32_t previous_catch) {
return {pc, kControlIf, stack_depth, end_env,
false_env, nullptr, previous_catch, {0, {NO_VALUE}}};
}
static Control Loop(const byte* pc, int stack_depth, SsaEnv* end_env,
int32_t previous_catch) {
return {pc, kControlLoop, stack_depth, end_env,
nullptr, nullptr, previous_catch, {0, {NO_VALUE}}};
}
static Control Try(const byte* pc, int stack_depth, SsaEnv* end_env,
Zone* zone, SsaEnv* catch_env, int32_t previous_catch) {
DCHECK_NOT_NULL(catch_env);
TryInfo* try_info = new (zone) TryInfo(catch_env);
return {pc, kControlTry, stack_depth, end_env,
nullptr, try_info, previous_catch, {0, {NO_VALUE}}};
}
};
// Macros that build nodes only if there is a graph and the current SSA
// environment is reachable from start. This avoids problems with malformed
// TF graphs when decoding inputs that have unreachable code.
#define BUILD(func, ...) \
(build() ? CheckForException(builder_->func(__VA_ARGS__)) : nullptr)
#define BUILD0(func) (build() ? CheckForException(builder_->func()) : nullptr)
struct LaneOperand {
uint8_t lane;
unsigned length;
inline LaneOperand(Decoder* decoder, const byte* pc) {
lane = decoder->checked_read_u8(pc, 2, "lane");
length = 1;
}
};
// Generic Wasm bytecode decoder with utilities for decoding operands,
// lengths, etc.
class WasmDecoder : public Decoder {
public:
WasmDecoder(ModuleEnv* module, FunctionSig* sig, const byte* start,
const byte* end)
: Decoder(start, end),
module_(module),
sig_(sig),
total_locals_(0),
local_types_(nullptr) {}
ModuleEnv* module_;
FunctionSig* sig_;
size_t total_locals_;
ZoneVector<LocalType>* local_types_;
inline bool Validate(const byte* pc, LocalIndexOperand& operand) {
if (operand.index < total_locals_) {
if (local_types_) {
operand.type = local_types_->at(operand.index);
} else {
operand.type = kAstStmt;
}
return true;
}
error(pc, pc + 1, "invalid local index: %u", operand.index);
return false;
}
inline bool Validate(const byte* pc, GlobalIndexOperand& operand) {
ModuleEnv* m = module_;
if (m && m->module && operand.index < m->module->globals.size()) {
operand.global = &m->module->globals[operand.index];
operand.type = operand.global->type;
return true;
}
error(pc, pc + 1, "invalid global index: %u", operand.index);
return false;
}
inline bool Complete(const byte* pc, CallFunctionOperand& operand) {
ModuleEnv* m = module_;
if (m && m->module && operand.index < m->module->functions.size()) {
operand.sig = m->module->functions[operand.index].sig;
return true;
}
return false;
}
inline bool Validate(const byte* pc, CallFunctionOperand& operand) {
if (Complete(pc, operand)) {
return true;
}
error(pc, pc + 1, "invalid function index: %u", operand.index);
return false;
}
inline bool Complete(const byte* pc, CallIndirectOperand& operand) {
ModuleEnv* m = module_;
if (m && m->module && operand.index < m->module->signatures.size()) {
operand.sig = m->module->signatures[operand.index];
return true;
}
return false;
}
inline bool Validate(const byte* pc, CallIndirectOperand& operand) {
uint32_t table_index = 0;
if (!module_->IsValidTable(table_index)) {
error("function table has to exist to execute call_indirect");
return false;
}
if (Complete(pc, operand)) {
return true;
}
error(pc, pc + 1, "invalid signature index: #%u", operand.index);
return false;
}
inline bool Validate(const byte* pc, BreakDepthOperand& operand,
ZoneVector<Control>& control) {
if (operand.depth < control.size()) {
operand.target = &control[control.size() - operand.depth - 1];
return true;
}
error(pc, pc + 1, "invalid break depth: %u", operand.depth);
return false;
}
bool Validate(const byte* pc, BranchTableOperand& operand,
size_t block_depth) {
// TODO(titzer): add extra redundant validation for br_table here?
return true;
}
inline bool Validate(const byte* pc, LaneOperand& operand) {
if (operand.lane < 0 || operand.lane > 3) {
error(pc_, pc_ + 2, "invalid extract lane value");
return false;
} else {
return true;
}
}
unsigned OpcodeLength(const byte* pc) {
switch (static_cast<byte>(*pc)) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
MemoryAccessOperand operand(this, pc, UINT32_MAX);
return 1 + operand.length;
}
case kExprBr:
case kExprBrIf: {
BreakDepthOperand operand(this, pc);
return 1 + operand.length;
}
case kExprSetGlobal:
case kExprGetGlobal: {
GlobalIndexOperand operand(this, pc);
return 1 + operand.length;
}
case kExprCallFunction: {
CallFunctionOperand operand(this, pc);
return 1 + operand.length;
}
case kExprCallIndirect: {
CallIndirectOperand operand(this, pc);
return 1 + operand.length;
}
case kExprTry:
case kExprIf: // fall thru
case kExprLoop:
case kExprBlock: {
BlockTypeOperand operand(this, pc);
return 1 + operand.length;
}
case kExprSetLocal:
case kExprTeeLocal:
case kExprGetLocal:
case kExprCatch: {
LocalIndexOperand operand(this, pc);
return 1 + operand.length;
}
case kExprBrTable: {
BranchTableOperand operand(this, pc);
BranchTableIterator iterator(this, operand);
return 1 + iterator.length();
}
case kExprI32Const: {
ImmI32Operand operand(this, pc);
return 1 + operand.length;
}
case kExprI64Const: {
ImmI64Operand operand(this, pc);
return 1 + operand.length;
}
case kExprGrowMemory:
case kExprMemorySize: {
MemoryIndexOperand operand(this, pc);
return 1 + operand.length;
}
case kExprI8Const:
return 2;
case kExprF32Const:
return 5;
case kExprF64Const:
return 9;
case kSimdPrefix: {
byte simd_index = checked_read_u8(pc, 1, "simd_index");
WasmOpcode opcode =
static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index);
switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
return 2;
}
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
return 3;
}
default:
error("invalid SIMD opcode");
return 2;
}
}
default:
return 1;
}
}
};
static const int32_t kNullCatch = -1;
// The full WASM decoder for bytecode. Both verifies bytecode and generates
// a TurboFan IR graph.
class WasmFullDecoder : public WasmDecoder {
public:
WasmFullDecoder(Zone* zone, TFBuilder* builder, const FunctionBody& body)
: WasmDecoder(body.module, body.sig, body.start, body.end),
zone_(zone),
builder_(builder),
base_(body.base),
local_type_vec_(zone),
stack_(zone),
control_(zone),
last_end_found_(false),
current_catch_(kNullCatch) {
local_types_ = &local_type_vec_;
}
bool Decode() {
base::ElapsedTimer decode_timer;
if (FLAG_trace_wasm_decode_time) {
decode_timer.Start();
}
stack_.clear();
control_.clear();
if (end_ < pc_) {
error("function body end < start");
return false;
}
DecodeLocalDecls();
InitSsaEnv();
DecodeFunctionBody();
if (failed()) return TraceFailed();
#if IMPLICIT_FUNCTION_END
// With implicit end support (old style), the function block
// remains on the stack. Other control blocks are an error.
if (control_.size() > 1) {
error(pc_, control_.back().pc, "unterminated control structure");
return TraceFailed();
}
// Assume an implicit end to the function body block.
if (control_.size() == 1) {
Control* c = &control_.back();
if (ssa_env_->go()) {
FallThruTo(c);
}
if (c->end_env->go()) {
// Push the end values onto the stack.
stack_.resize(c->stack_depth);
if (c->merge.arity == 1) {
stack_.push_back(c->merge.vals.first);
} else {
for (unsigned i = 0; i < c->merge.arity; i++) {
stack_.push_back(c->merge.vals.array[i]);
}
}
TRACE(" @%-8d #xx:%-20s|", startrel(pc_), "ImplicitReturn");
SetEnv("function:end", c->end_env);
DoReturn();
TRACE("\n");
}
}
#else
if (!control_.empty()) {
error(pc_, control_.back().pc, "unterminated control structure");
return TraceFailed();
}
if (!last_end_found_) {
error("function body must end with \"end\" opcode.");
return false;
}
#endif
if (FLAG_trace_wasm_decode_time) {
double ms = decode_timer.Elapsed().InMillisecondsF();
PrintF("wasm-decode %s (%0.3f ms)\n\n", ok() ? "ok" : "failed", ms);
} else {
TRACE("wasm-decode %s\n\n", ok() ? "ok" : "failed");
}
return true;
}
bool TraceFailed() {
TRACE("wasm-error module+%-6d func+%d: %s\n\n", baserel(error_pc_),
startrel(error_pc_), error_msg_.get());
return false;
}
bool DecodeLocalDecls(AstLocalDecls& decls) {
DecodeLocalDecls();
if (failed()) return false;
decls.decls_encoded_size = pc_offset();
decls.local_types.reserve(local_type_vec_.size());
for (size_t pos = 0; pos < local_type_vec_.size();) {
uint32_t count = 0;
LocalType type = local_type_vec_[pos];
while (pos < local_type_vec_.size() && local_type_vec_[pos] == type) {
pos++;
count++;
}
decls.local_types.push_back(std::pair<LocalType, uint32_t>(type, count));
}
decls.total_local_count = static_cast<uint32_t>(local_type_vec_.size());
return true;
}
BitVector* AnalyzeLoopAssignmentForTesting(const byte* pc,
size_t num_locals) {
total_locals_ = num_locals;
local_type_vec_.reserve(num_locals);
if (num_locals > local_type_vec_.size()) {
local_type_vec_.insert(local_type_vec_.end(),
num_locals - local_type_vec_.size(), kAstI32);
}
return AnalyzeLoopAssignment(pc);
}
private:
static const size_t kErrorMsgSize = 128;
Zone* zone_;
TFBuilder* builder_;
const byte* base_;
SsaEnv* ssa_env_;
ZoneVector<LocalType> local_type_vec_; // types of local variables.
ZoneVector<Value> stack_; // stack of values.
ZoneVector<Control> control_; // stack of blocks, loops, and ifs.
bool last_end_found_;
int32_t current_catch_;
TryInfo* current_try_info() { return control_[current_catch_].try_info; }
inline bool build() { return builder_ && ssa_env_->go(); }
void InitSsaEnv() {
TFNode* start = nullptr;
SsaEnv* ssa_env = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
size_t size = sizeof(TFNode*) * EnvironmentCount();
ssa_env->state = SsaEnv::kReached;
ssa_env->locals =
size > 0 ? reinterpret_cast<TFNode**>(zone_->New(size)) : nullptr;
if (builder_) {
start = builder_->Start(static_cast<int>(sig_->parameter_count() + 1));
// Initialize local variables.
uint32_t index = 0;
while (index < sig_->parameter_count()) {
ssa_env->locals[index] = builder_->Param(index, local_type_vec_[index]);
index++;
}
while (index < local_type_vec_.size()) {
LocalType type = local_type_vec_[index];
TFNode* node = DefaultValue(type);
while (index < local_type_vec_.size() &&
local_type_vec_[index] == type) {
// Do a whole run of like-typed locals at a time.
ssa_env->locals[index++] = node;
}
}
builder_->set_module(module_);
}
ssa_env->control = start;
ssa_env->effect = start;
SetEnv("initial", ssa_env);
if (builder_) {
builder_->StackCheck(position());
}
}
TFNode* DefaultValue(LocalType type) {
switch (type) {
case kAstI32:
return builder_->Int32Constant(0);
case kAstI64:
return builder_->Int64Constant(0);
case kAstF32:
return builder_->Float32Constant(0);
case kAstF64:
return builder_->Float64Constant(0);
case kAstS128:
return builder_->CreateS128Value(0);
default:
UNREACHABLE();
return nullptr;
}
}
char* indentation() {
static const int kMaxIndent = 64;
static char bytes[kMaxIndent + 1];
for (int i = 0; i < kMaxIndent; ++i) bytes[i] = ' ';
bytes[kMaxIndent] = 0;
if (stack_.size() < kMaxIndent / 2) {
bytes[stack_.size() * 2] = 0;
}
return bytes;
}
// Decodes the locals declarations, if any, populating {local_type_vec_}.
void DecodeLocalDecls() {
DCHECK_EQ(0u, local_type_vec_.size());
// Initialize {local_type_vec} from signature.
if (sig_) {
local_type_vec_.reserve(sig_->parameter_count());
for (size_t i = 0; i < sig_->parameter_count(); ++i) {
local_type_vec_.push_back(sig_->GetParam(i));
}
}
// Decode local declarations, if any.
uint32_t entries = consume_u32v("local decls count");
TRACE("local decls count: %u\n", entries);
while (entries-- > 0 && pc_ < limit_) {
uint32_t count = consume_u32v("local count");
if (count > kMaxNumWasmLocals) {
error(pc_ - 1, "local count too large");
return;
}
byte code = consume_u8("local type");
LocalType type;
switch (code) {
case kLocalI32:
type = kAstI32;
break;
case kLocalI64:
type = kAstI64;
break;
case kLocalF32:
type = kAstF32;
break;
case kLocalF64:
type = kAstF64;
break;
case kLocalS128:
type = kAstS128;
break;
default:
error(pc_ - 1, "invalid local type");
return;
}
local_type_vec_.insert(local_type_vec_.end(), count, type);
}
total_locals_ = local_type_vec_.size();
}
// Decodes the body of a function.
void DecodeFunctionBody() {
TRACE("wasm-decode %p...%p (module+%d, %d bytes) %s\n",
reinterpret_cast<const void*>(start_),
reinterpret_cast<const void*>(limit_), baserel(pc_),
static_cast<int>(limit_ - start_), builder_ ? "graph building" : "");
{
// Set up initial function block.
SsaEnv* break_env = ssa_env_;
SetEnv("initial env", Steal(break_env));
PushBlock(break_env);
Control* c = &control_.back();
c->merge.arity = static_cast<uint32_t>(sig_->return_count());
if (c->merge.arity == 1) {
c->merge.vals.first = {pc_, nullptr, sig_->GetReturn(0)};
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] = {pc_, nullptr, sig_->GetReturn(i)};
}
}
}
if (pc_ >= limit_) return; // Nothing to do.
while (true) { // decoding loop.
unsigned len = 1;
WasmOpcode opcode = static_cast<WasmOpcode>(*pc_);
if (!WasmOpcodes::IsPrefixOpcode(opcode)) {
TRACE(" @%-8d #%02x:%-20s|", startrel(pc_), opcode,
WasmOpcodes::ShortOpcodeName(opcode));
}
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
} else {
// Complex bytecode.
switch (opcode) {
case kExprNop:
break;
case kExprBlock: {
// The break environment is the outer environment.
BlockTypeOperand operand(this, pc_);
SsaEnv* break_env = ssa_env_;
PushBlock(break_env);
SetEnv("block:start", Steal(break_env));
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprThrow: {
CHECK_PROTOTYPE_OPCODE(wasm_eh_prototype);
Value value = Pop(0, kAstI32);
BUILD(Throw, value.node);
break;
}
case kExprTry: {
CHECK_PROTOTYPE_OPCODE(wasm_eh_prototype);
BlockTypeOperand operand(this, pc_);
SsaEnv* outer_env = ssa_env_;
SsaEnv* try_env = Steal(outer_env);
SsaEnv* catch_env = UnreachableEnv();
PushTry(outer_env, catch_env);
SetEnv("try_catch:start", try_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprCatch: {
CHECK_PROTOTYPE_OPCODE(wasm_eh_prototype);
LocalIndexOperand operand(this, pc_);
len = 1 + operand.length;
if (control_.empty()) {
error("catch does not match any try");
break;
}
Control* c = &control_.back();
if (!c->is_try()) {
error("catch does not match any try");
break;
}
if (c->try_info->catch_env == nullptr) {
error(pc_, "catch already present for try with catch");
break;
}
if (ssa_env_->go()) {
MergeValuesInto(c);
}
stack_.resize(c->stack_depth);
DCHECK_NOT_NULL(c->try_info);
SsaEnv* catch_env = c->try_info->catch_env;
c->try_info->catch_env = nullptr;
SetEnv("catch:begin", catch_env);
current_catch_ = c->previous_catch;
if (Validate(pc_, operand)) {
if (ssa_env_->locals) {
TFNode* exception_as_i32 =
BUILD(Catch, c->try_info->exception, position());
ssa_env_->locals[operand.index] = exception_as_i32;
}
}
break;
}
case kExprLoop: {
BlockTypeOperand operand(this, pc_);
SsaEnv* finish_try_env = Steal(ssa_env_);
// The continue environment is the inner environment.
SsaEnv* loop_body_env = PrepareForLoop(pc_, finish_try_env);
SetEnv("loop:start", loop_body_env);
ssa_env_->SetNotMerged();
PushLoop(finish_try_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprIf: {
// Condition on top of stack. Split environments for branches.
BlockTypeOperand operand(this, pc_);
Value cond = Pop(0, kAstI32);
TFNode* if_true = nullptr;
TFNode* if_false = nullptr;
BUILD(BranchNoHint, cond.node, &if_true, &if_false);
SsaEnv* end_env = ssa_env_;
SsaEnv* false_env = Split(ssa_env_);
false_env->control = if_false;
SsaEnv* true_env = Steal(ssa_env_);
true_env->control = if_true;
PushIf(end_env, false_env);
SetEnv("if:true", true_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprElse: {
if (control_.empty()) {
error("else does not match any if");
break;
}
Control* c = &control_.back();
if (!c->is_if()) {
error(pc_, c->pc, "else does not match an if");
break;
}
if (c->false_env == nullptr) {
error(pc_, c->pc, "else already present for if");
break;
}
FallThruTo(c);
// Switch to environment for false branch.
stack_.resize(c->stack_depth);
SetEnv("if_else:false", c->false_env);
c->false_env = nullptr; // record that an else is already seen
break;
}
case kExprEnd: {
if (control_.empty()) {
error("end does not match any if, try, or block");
return;
}
const char* name = "block:end";
Control* c = &control_.back();
if (c->is_loop()) {
// A loop just leaves the values on the stack.
TypeCheckLoopFallThru(c);
PopControl();
SetEnv("loop:end", ssa_env_);
break;
}
if (c->is_if()) {
if (c->false_env != nullptr) {
// End the true branch of a one-armed if.
Goto(c->false_env, c->end_env);
if (ssa_env_->go() &&
static_cast<int>(stack_.size()) != c->stack_depth) {
error("end of if expected empty stack");
stack_.resize(c->stack_depth);
}
if (c->merge.arity > 0) {
error("non-void one-armed if");
}
name = "if:merge";
} else {
// End the false branch of a two-armed if.
name = "if_else:merge";
}
} else if (c->is_try()) {
name = "try:end";
// validate that catch was seen.
if (c->try_info->catch_env != nullptr) {
error(pc_, "missing catch in try");
break;
}
}
FallThruTo(c);
SetEnv(name, c->end_env);
// Push the end values onto the stack.
stack_.resize(c->stack_depth);
if (c->merge.arity == 1) {
stack_.push_back(c->merge.vals.first);
} else {
for (unsigned i = 0; i < c->merge.arity; i++) {
stack_.push_back(c->merge.vals.array[i]);
}
}
PopControl();
if (control_.empty()) {
// If the last (implicit) control was popped, check we are at end.
if (pc_ + 1 != end_) {
error(pc_, pc_ + 1, "trailing code after function end");
}
last_end_found_ = true;
if (ssa_env_->go()) {
// The result of the block is the return value.
TRACE(" @%-8d #xx:%-20s|", startrel(pc_), "ImplicitReturn");
DoReturn();
TRACE("\n");
}
return;
}
break;
}
case kExprSelect: {
Value cond = Pop(2, kAstI32);
Value fval = Pop();
Value tval = Pop();
if (tval.type == kAstStmt || tval.type != fval.type) {
if (tval.type != kAstEnd && fval.type != kAstEnd) {
error("type mismatch in select");
break;
}
}
if (build()) {
DCHECK(tval.type != kAstEnd);
DCHECK(fval.type != kAstEnd);
DCHECK(cond.type != kAstEnd);
TFNode* controls[2];
builder_->BranchNoHint(cond.node, &controls[0], &controls[1]);
TFNode* merge = builder_->Merge(2, controls);
TFNode* vals[2] = {tval.node, fval.node};
TFNode* phi = builder_->Phi(tval.type, 2, vals, merge);
Push(tval.type, phi);
ssa_env_->control = merge;
} else {
Push(tval.type, nullptr);
}
break;
}
case kExprBr: {
BreakDepthOperand operand(this, pc_);
if (Validate(pc_, operand, control_)) {
BreakTo(operand.depth);
}
len = 1 + operand.length;
EndControl();
break;
}
case kExprBrIf: {
BreakDepthOperand operand(this, pc_);
Value cond = Pop(0, kAstI32);
if (ok() && Validate(pc_, operand, control_)) {
SsaEnv* fenv = ssa_env_;
SsaEnv* tenv = Split(fenv);
fenv->SetNotMerged();
BUILD(BranchNoHint, cond.node, &tenv->control, &fenv->control);
ssa_env_ = tenv;
BreakTo(operand.depth);
ssa_env_ = fenv;
}
len = 1 + operand.length;
break;
}
case kExprBrTable: {
BranchTableOperand operand(this, pc_);
BranchTableIterator iterator(this, operand);
if (Validate(pc_, operand, control_.size())) {
Value key = Pop(0, kAstI32);
if (failed()) break;
SsaEnv* break_env = ssa_env_;
if (operand.table_count > 0) {
// Build branches to the various blocks based on the table.
TFNode* sw = BUILD(Switch, operand.table_count + 1, key.node);
SsaEnv* copy = Steal(break_env);
ssa_env_ = copy;
while (ok() && iterator.has_next()) {
uint32_t i = iterator.cur_index();
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (target >= control_.size()) {
error(pos, "improper branch in br_table");
break;
}
ssa_env_ = Split(copy);
ssa_env_->control = (i == operand.table_count)
? BUILD(IfDefault, sw)
: BUILD(IfValue, i, sw);
BreakTo(target);
}
if (failed()) break;
} else {
// Only a default target. Do the equivalent of br.
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (target >= control_.size()) {
error(pos, "improper branch in br_table");
break;
}
BreakTo(target);
}
// br_table ends the control flow like br.
ssa_env_ = break_env;
}
len = 1 + iterator.length();
break;
}
case kExprReturn: {
DoReturn();
break;
}
case kExprUnreachable: {
BUILD(Unreachable, position());
EndControl();
break;
}
case kExprI8Const: {
ImmI8Operand operand(this, pc_);
Push(kAstI32, BUILD(Int32Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprI32Const: {
ImmI32Operand operand(this, pc_);
Push(kAstI32, BUILD(Int32Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprI64Const: {
ImmI64Operand operand(this, pc_);
Push(kAstI64, BUILD(Int64Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprF32Const: {
ImmF32Operand operand(this, pc_);
Push(kAstF32, BUILD(Float32Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprF64Const: {
ImmF64Operand operand(this, pc_);
Push(kAstF64, BUILD(Float64Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprGetLocal: {
LocalIndexOperand operand(this, pc_);
if (Validate(pc_, operand)) {
if (build()) {
Push(operand.type, ssa_env_->locals[operand.index]);
} else {
Push(operand.type, nullptr);
}
}
len = 1 + operand.length;
break;
}
case kExprSetLocal: {
LocalIndexOperand operand(this, pc_);
if (Validate(pc_, operand)) {
Value val = Pop(0, local_type_vec_[operand.index]);
if (ssa_env_->locals) ssa_env_->locals[operand.index] = val.node;
}
len = 1 + operand.length;
break;
}
case kExprTeeLocal: {
LocalIndexOperand operand(this, pc_);
if (Validate(pc_, operand)) {
Value val = Pop(0, local_type_vec_[operand.index]);
if (ssa_env_->locals) ssa_env_->locals[operand.index] = val.node;
Push(val.type, val.node);
}
len = 1 + operand.length;
break;
}
case kExprDrop: {
Pop();
break;
}
case kExprGetGlobal: {
GlobalIndexOperand operand(this, pc_);
if (Validate(pc_, operand)) {
Push(operand.type, BUILD(GetGlobal, operand.index));
}
len = 1 + operand.length;
break;
}
case kExprSetGlobal: {
GlobalIndexOperand operand(this, pc_);
if (Validate(pc_, operand)) {
if (operand.global->mutability) {
Value val = Pop(0, operand.type);
BUILD(SetGlobal, operand.index, val.node);
} else {
error(pc_, pc_ + 1, "immutable global #%u cannot be assigned",
operand.index);
}
}
len = 1 + operand.length;
break;
}
case kExprI32LoadMem8S:
len = DecodeLoadMem(kAstI32, MachineType::Int8());
break;
case kExprI32LoadMem8U:
len = DecodeLoadMem(kAstI32, MachineType::Uint8());
break;
case kExprI32LoadMem16S:
len = DecodeLoadMem(kAstI32, MachineType::Int16());
break;
case kExprI32LoadMem16U:
len = DecodeLoadMem(kAstI32, MachineType::Uint16());
break;
case kExprI32LoadMem:
len = DecodeLoadMem(kAstI32, MachineType::Int32());
break;
case kExprI64LoadMem8S:
len = DecodeLoadMem(kAstI64, MachineType::Int8());
break;
case kExprI64LoadMem8U:
len = DecodeLoadMem(kAstI64, MachineType::Uint8());
break;
case kExprI64LoadMem16S:
len = DecodeLoadMem(kAstI64, MachineType::Int16());
break;
case kExprI64LoadMem16U:
len = DecodeLoadMem(kAstI64, MachineType::Uint16());
break;
case kExprI64LoadMem32S:
len = DecodeLoadMem(kAstI64, MachineType::Int32());
break;
case kExprI64LoadMem32U:
len = DecodeLoadMem(kAstI64, MachineType::Uint32());
break;
case kExprI64LoadMem:
len = DecodeLoadMem(kAstI64, MachineType::Int64());
break;
case kExprF32LoadMem:
len = DecodeLoadMem(kAstF32, MachineType::Float32());
break;
case kExprF64LoadMem:
len = DecodeLoadMem(kAstF64, MachineType::Float64());
break;
case kExprI32StoreMem8:
len = DecodeStoreMem(kAstI32, MachineType::Int8());
break;
case kExprI32StoreMem16:
len = DecodeStoreMem(kAstI32, MachineType::Int16());
break;
case kExprI32StoreMem:
len = DecodeStoreMem(kAstI32, MachineType::Int32());
break;
case kExprI64StoreMem8:
len = DecodeStoreMem(kAstI64, MachineType::Int8());
break;
case kExprI64StoreMem16:
len = DecodeStoreMem(kAstI64, MachineType::Int16());
break;
case kExprI64StoreMem32:
len = DecodeStoreMem(kAstI64, MachineType::Int32());
break;
case kExprI64StoreMem:
len = DecodeStoreMem(kAstI64, MachineType::Int64());
break;
case kExprF32StoreMem:
len = DecodeStoreMem(kAstF32, MachineType::Float32());
break;
case kExprF64StoreMem:
len = DecodeStoreMem(kAstF64, MachineType::Float64());
break;
case kExprGrowMemory: {
MemoryIndexOperand operand(this, pc_);
if (module_->origin != kAsmJsOrigin) {
Value val = Pop(0, kAstI32);
Push(kAstI32, BUILD(GrowMemory, val.node));
} else {
error("grow_memory is not supported for asmjs modules");
}
len = 1 + operand.length;
break;
}
case kExprMemorySize: {
MemoryIndexOperand operand(this, pc_);
Push(kAstI32, BUILD(CurrentMemoryPages));
len = 1 + operand.length;
break;
}
case kExprCallFunction: {
CallFunctionOperand operand(this, pc_);
if (Validate(pc_, operand)) {
TFNode** buffer = PopArgs(operand.sig);
TFNode** rets = nullptr;
BUILD(CallDirect, operand.index, buffer, &rets, position());
PushReturns(operand.sig, rets);
}
len = 1 + operand.length;
break;
}
case kExprCallIndirect: {
CallIndirectOperand operand(this, pc_);
if (Validate(pc_, operand)) {
Value index = Pop(0, kAstI32);
TFNode** buffer = PopArgs(operand.sig);
if (buffer) buffer[0] = index.node;
TFNode** rets = nullptr;
BUILD(CallIndirect, operand.index, buffer, &rets, position());
PushReturns(operand.sig, rets);
}
len = 1 + operand.length;
break;
}
case kSimdPrefix: {
CHECK_PROTOTYPE_OPCODE(wasm_simd_prototype);
len++;
byte simd_index = checked_read_u8(pc_, 1, "simd index");
opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index);
TRACE(" @%-4d #%02x #%02x:%-20s|", startrel(pc_), kSimdPrefix,
simd_index, WasmOpcodes::ShortOpcodeName(opcode));
len += DecodeSimdOpcode(opcode);
break;
}
case kAtomicPrefix: {
if (!module_ || module_->origin != kAsmJsOrigin) {
error("Atomics are allowed only in AsmJs modules");
break;
}
if (!FLAG_wasm_atomics_prototype) {
error("Invalid opcode (enable with --wasm_atomics_prototype)");
break;
}
len = 2;
byte atomic_opcode = checked_read_u8(pc_, 1, "atomic index");
opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_opcode);
sig = WasmOpcodes::AtomicSignature(opcode);
if (sig) {
BuildAtomicOperator(opcode);
}
break;
}
default: {
// Deal with special asmjs opcodes.
if (module_ && module_->origin == kAsmJsOrigin) {
sig = WasmOpcodes::AsmjsSignature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
}
} else {
error("Invalid opcode");
return;
}
}
}
}
#if DEBUG
if (FLAG_trace_wasm_decoder) {
for (size_t i = 0; i < stack_.size(); ++i) {
Value& val = stack_[i];
WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc);
if (WasmOpcodes::IsPrefixOpcode(opcode)) {
opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1));
}
PrintF(" %c@%d:%s", WasmOpcodes::ShortNameOf(val.type),
static_cast<int>(val.pc - start_),
WasmOpcodes::ShortOpcodeName(opcode));
switch (opcode) {
case kExprI32Const: {
ImmI32Operand operand(this, val.pc);
PrintF("[%d]", operand.value);
break;
}
case kExprGetLocal: {
LocalIndexOperand operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
default:
break;
}
}
PrintF("\n");
}
#endif
pc_ += len;
if (pc_ >= limit_) {
// End of code reached or exceeded.
if (pc_ > limit_ && ok()) error("Beyond end of code");
return;
}
} // end decode loop
}
void EndControl() { ssa_env_->Kill(SsaEnv::kControlEnd); }
void SetBlockType(Control* c, BlockTypeOperand& operand) {
c->merge.arity = operand.arity;
if (c->merge.arity == 1) {
c->merge.vals.first = {pc_, nullptr, operand.read_entry(0)};
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] = {pc_, nullptr, operand.read_entry(i)};
}
}
}
TFNode** PopArgs(FunctionSig* sig) {
if (build()) {
int count = static_cast<int>(sig->parameter_count());
TFNode** buffer = builder_->Buffer(count + 1);
buffer[0] = nullptr; // reserved for code object or function index.
for (int i = count - 1; i >= 0; i--) {
buffer[i + 1] = Pop(i, sig->GetParam(i)).node;
}
return buffer;
} else {
int count = static_cast<int>(sig->parameter_count());
for (int i = count - 1; i >= 0; i--) {
Pop(i, sig->GetParam(i));
}
return nullptr;
}
}
LocalType GetReturnType(FunctionSig* sig) {
return sig->return_count() == 0 ? kAstStmt : sig->GetReturn();
}
void PushBlock(SsaEnv* end_env) {
const int stack_depth = static_cast<int>(stack_.size());
control_.emplace_back(
Control::Block(pc_, stack_depth, end_env, current_catch_));
}
void PushLoop(SsaEnv* end_env) {
const int stack_depth = static_cast<int>(stack_.size());
control_.emplace_back(
Control::Loop(pc_, stack_depth, end_env, current_catch_));
}
void PushIf(SsaEnv* end_env, SsaEnv* false_env) {
const int stack_depth = static_cast<int>(stack_.size());
control_.emplace_back(
Control::If(pc_, stack_depth, end_env, false_env, current_catch_));
}
void PushTry(SsaEnv* end_env, SsaEnv* catch_env) {
const int stack_depth = static_cast<int>(stack_.size());
control_.emplace_back(Control::Try(pc_, stack_depth, end_env, zone_,
catch_env, current_catch_));
current_catch_ = static_cast<int32_t>(control_.size() - 1);
}
void PopControl() { control_.pop_back(); }
int DecodeLoadMem(LocalType type, MachineType mem_type) {
MemoryAccessOperand operand(this, pc_,
ElementSizeLog2Of(mem_type.representation()));
Value index = Pop(0, kAstI32);
TFNode* node = BUILD(LoadMem, type, mem_type, index.node, operand.offset,
operand.alignment, position());
Push(type, node);
return 1 + operand.length;
}
int DecodeStoreMem(LocalType type, MachineType mem_type) {
MemoryAccessOperand operand(this, pc_,
ElementSizeLog2Of(mem_type.representation()));
Value val = Pop(1, type);
Value index = Pop(0, kAstI32);
BUILD(StoreMem, mem_type, index.node, operand.offset, operand.alignment,
val.node, position());
return 1 + operand.length;
}
unsigned ExtractLane(WasmOpcode opcode, LocalType type) {
LaneOperand operand(this, pc_);
if (Validate(pc_, operand)) {
TFNode* input = Pop(0, LocalType::kSimd128).node;
TFNode* node = BUILD(SimdExtractLane, opcode, operand.lane, input);
Push(type, node);
}
return operand.length;
}
unsigned DecodeSimdOpcode(WasmOpcode opcode) {
unsigned len = 0;
switch (opcode) {
case kExprI32x4ExtractLane: {
len = ExtractLane(opcode, LocalType::kWord32);
break;
}
case kExprF32x4ExtractLane: {
len = ExtractLane(opcode, LocalType::kFloat32);
break;
}
default: {
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig != nullptr) {
compiler::NodeVector inputs(sig->parameter_count(), zone_);
for (size_t i = sig->parameter_count(); i > 0; i--) {
Value val = Pop(static_cast<int>(i - 1), sig->GetParam(i - 1));
inputs[i - 1] = val.node;
}
TFNode* node = BUILD(SimdOp, opcode, inputs);
Push(GetReturnType(sig), node);
} else {
error("invalid simd opcode");
}
}
}
return len;
}
void BuildAtomicOperator(WasmOpcode opcode) { UNIMPLEMENTED(); }
void DoReturn() {
int count = static_cast<int>(sig_->return_count());
TFNode** buffer = nullptr;
if (build()) buffer = builder_->Buffer(count);
// Pop return values off the stack in reverse order.
for (int i = count - 1; i >= 0; i--) {
Value val = Pop(i, sig_->GetReturn(i));
if (buffer) buffer[i] = val.node;
}
BUILD(Return, count, buffer);
EndControl();
}
void Push(LocalType type, TFNode* node) {
if (type != kAstStmt && type != kAstEnd) {
stack_.push_back({pc_, node, type});
}
}
void PushReturns(FunctionSig* sig, TFNode** rets) {
for (size_t i = 0; i < sig->return_count(); i++) {
// When verifying only, then {rets} will be null, so push null.
Push(sig->GetReturn(i), rets ? rets[i] : nullptr);
}
}
const char* SafeOpcodeNameAt(const byte* pc) {
if (pc >= end_) return "<end>";
return WasmOpcodes::ShortOpcodeName(static_cast<WasmOpcode>(*pc));
}
Value Pop(int index, LocalType expected) {
if (!ssa_env_->go()) {
// Unreachable code is essentially not typechecked.
return {pc_, nullptr, expected};
}
Value val = Pop();
if (val.type != expected) {
if (val.type != kAstEnd) {
error(pc_, val.pc, "%s[%d] expected type %s, found %s of type %s",
SafeOpcodeNameAt(pc_), index, WasmOpcodes::TypeName(expected),
SafeOpcodeNameAt(val.pc), WasmOpcodes::TypeName(val.type));
}
}
return val;
}
Value Pop() {
if (!ssa_env_->go()) {
// Unreachable code is essentially not typechecked.
return {pc_, nullptr, kAstEnd};
}
size_t limit = control_.empty() ? 0 : control_.back().stack_depth;
if (stack_.size() <= limit) {
Value val = {pc_, nullptr, kAstStmt};
error(pc_, pc_, "%s found empty stack", SafeOpcodeNameAt(pc_));
return val;
}
Value val = stack_.back();
stack_.pop_back();
return val;
}
Value PopUpTo(int stack_depth) {
if (!ssa_env_->go()) {
// Unreachable code is essentially not typechecked.
return {pc_, nullptr, kAstEnd};
}
if (stack_depth == static_cast<int>(stack_.size())) {
Value val = {pc_, nullptr, kAstStmt};
return val;
} else {
DCHECK_LE(stack_depth, static_cast<int>(stack_.size()));
Value val = Pop();
stack_.resize(stack_depth);
return val;
}
}
int baserel(const byte* ptr) {
return base_ ? static_cast<int>(ptr - base_) : 0;
}
int startrel(const byte* ptr) { return static_cast<int>(ptr - start_); }
void BreakTo(unsigned depth) {
if (!ssa_env_->go()) return;
Control* c = &control_[control_.size() - depth - 1];
if (c->is_loop()) {
// This is the inner loop block, which does not have a value.
Goto(ssa_env_, c->end_env);
} else {
// Merge the value(s) into the end of the block.
if (c->stack_depth + c->merge.arity > stack_.size()) {
error(
pc_, pc_,
"expected at least %d values on the stack for br to @%d, found %d",
c->merge.arity, startrel(c->pc),
static_cast<int>(stack_.size() - c->stack_depth));
return;
}
MergeValuesInto(c);
}
}
void FallThruTo(Control* c) {
if (!ssa_env_->go()) return;
// Merge the value(s) into the end of the block.
int arity = static_cast<int>(c->merge.arity);
if (c->stack_depth + arity != static_cast<int>(stack_.size())) {
error(pc_, pc_, "expected %d elements on the stack for fallthru to @%d",
arity, startrel(c->pc));
return;
}
MergeValuesInto(c);
}
inline Value& GetMergeValueFromStack(Control* c, int i) {
return stack_[stack_.size() - c->merge.arity + i];
}
void TypeCheckLoopFallThru(Control* c) {
if (!ssa_env_->go()) return;
// Fallthru must match arity exactly.
int arity = static_cast<int>(c->merge.arity);
if (c->stack_depth + arity != static_cast<int>(stack_.size())) {
error(pc_, pc_, "expected %d elements on the stack for fallthru to @%d",
arity, startrel(c->pc));
return;
}
// Typecheck the values left on the stack.
for (unsigned i = 0; i < c->merge.arity; i++) {
Value& val = GetMergeValueFromStack(c, i);
Value& old =
c->merge.arity == 1 ? c->merge.vals.first : c->merge.vals.array[i];
if (val.type != old.type) {
error(pc_, pc_, "type error in merge[%d] (expected %s, got %s)", i,
WasmOpcodes::TypeName(old.type), WasmOpcodes::TypeName(val.type));
return;
}
}
}
void MergeValuesInto(Control* c) {
SsaEnv* target = c->end_env;
bool first = target->state == SsaEnv::kUnreachable;
Goto(ssa_env_, target);
for (unsigned i = 0; i < c->merge.arity; i++) {
Value& val = GetMergeValueFromStack(c, i);
Value& old =
c->merge.arity == 1 ? c->merge.vals.first : c->merge.vals.array[i];
if (val.type != old.type) {
error(pc_, pc_, "type error in merge[%d] (expected %s, got %s)", i,
WasmOpcodes::TypeName(old.type), WasmOpcodes::TypeName(val.type));
return;
}
if (builder_) {
old.node =
first ? val.node : CreateOrMergeIntoPhi(old.type, target->control,
old.node, val.node);
} else {
old.node = nullptr;
}
}
}
void SetEnv(const char* reason, SsaEnv* env) {
#if DEBUG
if (FLAG_trace_wasm_decoder) {
char state = 'X';
if (env) {
switch (env->state) {
case SsaEnv::kReached:
state = 'R';
break;
case SsaEnv::kUnreachable:
state = 'U';
break;
case SsaEnv::kMerged:
state = 'M';
break;
case SsaEnv::kControlEnd:
state = 'E';
break;
}
}
PrintF(" env = %p, state = %c, reason = %s", static_cast<void*>(env),
state, reason);
if (env && env->control) {
PrintF(", control = ");
compiler::WasmGraphBuilder::PrintDebugName(env->control);
}
PrintF("\n");
}
#endif
ssa_env_ = env;
if (builder_) {
builder_->set_control_ptr(&env->control);
builder_->set_effect_ptr(&env->effect);
}
}
TFNode* CheckForException(TFNode* node) {
if (node == nullptr) {
return nullptr;
}
const bool inside_try_scope = current_catch_ != kNullCatch;
if (!inside_try_scope) {
return node;
}
TFNode* if_success = nullptr;
TFNode* if_exception = nullptr;
if (!builder_->ThrowsException(node, &if_success, &if_exception)) {
return node;
}
SsaEnv* success_env = Steal(ssa_env_);
success_env->control = if_success;
SsaEnv* exception_env = Split(success_env);
exception_env->control = if_exception;
TryInfo* try_info = current_try_info();
Goto(exception_env, try_info->catch_env);
TFNode* exception = try_info->exception;
if (exception == nullptr) {
DCHECK_EQ(SsaEnv::kReached, try_info->catch_env->state);
try_info->exception = if_exception;
} else {
DCHECK_EQ(SsaEnv::kMerged, try_info->catch_env->state);
try_info->exception =
CreateOrMergeIntoPhi(kAstI32, try_info->catch_env->control,
try_info->exception, if_exception);
}
SetEnv("if_success", success_env);
return node;
}
void Goto(SsaEnv* from, SsaEnv* to) {
DCHECK_NOT_NULL(to);
if (!from->go()) return;
switch (to->state) {
case SsaEnv::kUnreachable: { // Overwrite destination.
to->state = SsaEnv::kReached;
to->locals = from->locals;
to->control = from->control;
to->effect = from->effect;
break;
}
case SsaEnv::kReached: { // Create a new merge.
to->state = SsaEnv::kMerged;
if (!builder_) break;
// Merge control.
TFNode* controls[] = {to->control, from->control};
TFNode* merge = builder_->Merge(2, controls);
to->control = merge;
// Merge effects.
if (from->effect != to->effect) {
TFNode* effects[] = {to->effect, from->effect, merge};
to->effect = builder_->EffectPhi(2, effects, merge);
}
// Merge SSA values.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
TFNode* a = to->locals[i];
TFNode* b = from->locals[i];
if (a != b) {
TFNode* vals[] = {a, b};
to->locals[i] = builder_->Phi(local_type_vec_[i], 2, vals, merge);
}
}
break;
}
case SsaEnv::kMerged: {
if (!builder_) break;
TFNode* merge = to->control;
// Extend the existing merge.
builder_->AppendToMerge(merge, from->control);
// Merge effects.
if (builder_->IsPhiWithMerge(to->effect, merge)) {
builder_->AppendToPhi(to->effect, from->effect);
} else if (to->effect != from->effect) {
uint32_t count = builder_->InputCount(merge);
TFNode** effects = builder_->Buffer(count);
for (uint32_t j = 0; j < count - 1; j++) {
effects[j] = to->effect;
}
effects[count - 1] = from->effect;
to->effect = builder_->EffectPhi(count, effects, merge);
}
// Merge locals.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
TFNode* tnode = to->locals[i];
TFNode* fnode = from->locals[i];
if (builder_->IsPhiWithMerge(tnode, merge)) {
builder_->AppendToPhi(tnode, fnode);
} else if (tnode != fnode) {
uint32_t count = builder_->InputCount(merge);
TFNode** vals = builder_->Buffer(count);
for (uint32_t j = 0; j < count - 1; j++) {
vals[j] = tnode;
}
vals[count - 1] = fnode;
to->locals[i] =
builder_->Phi(local_type_vec_[i], count, vals, merge);
}
}
break;
}
default:
UNREACHABLE();
}
return from->Kill();
}
TFNode* CreateOrMergeIntoPhi(LocalType type, TFNode* merge, TFNode* tnode,
TFNode* fnode) {
DCHECK_NOT_NULL(builder_);
if (builder_->IsPhiWithMerge(tnode, merge)) {
builder_->AppendToPhi(tnode, fnode);
} else if (tnode != fnode) {
uint32_t count = builder_->InputCount(merge);
TFNode** vals = builder_->Buffer(count);
for (uint32_t j = 0; j < count - 1; j++) vals[j] = tnode;
vals[count - 1] = fnode;
return builder_->Phi(type, count, vals, merge);
}
return tnode;
}
SsaEnv* PrepareForLoop(const byte* pc, SsaEnv* env) {
if (!builder_) return Split(env);
if (!env->go()) return Split(env);
env->state = SsaEnv::kMerged;
env->control = builder_->Loop(env->control);
env->effect = builder_->EffectPhi(1, &env->effect, env->control);
builder_->Terminate(env->effect, env->control);
if (FLAG_wasm_loop_assignment_analysis) {
BitVector* assigned = AnalyzeLoopAssignment(pc);
if (failed()) return env;
if (assigned != nullptr) {
// Only introduce phis for variables assigned in this loop.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
if (!assigned->Contains(i)) continue;
env->locals[i] = builder_->Phi(local_type_vec_[i], 1, &env->locals[i],
env->control);
}
SsaEnv* loop_body_env = Split(env);
builder_->StackCheck(position(), &(loop_body_env->effect),
&(loop_body_env->control));
return loop_body_env;
}
}
// Conservatively introduce phis for all local variables.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
env->locals[i] =
builder_->Phi(local_type_vec_[i], 1, &env->locals[i], env->control);
}
SsaEnv* loop_body_env = Split(env);
builder_->StackCheck(position(), &(loop_body_env->effect),
&(loop_body_env->control));
return loop_body_env;
}
// Create a complete copy of the {from}.
SsaEnv* Split(SsaEnv* from) {
DCHECK_NOT_NULL(from);
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
size_t size = sizeof(TFNode*) * EnvironmentCount();
result->control = from->control;
result->effect = from->effect;
if (from->go()) {
result->state = SsaEnv::kReached;
result->locals =
size > 0 ? reinterpret_cast<TFNode**>(zone_->New(size)) : nullptr;
memcpy(result->locals, from->locals, size);
} else {
result->state = SsaEnv::kUnreachable;
result->locals = nullptr;
}
return result;
}
// Create a copy of {from} that steals its state and leaves {from}
// unreachable.
SsaEnv* Steal(SsaEnv* from) {
DCHECK_NOT_NULL(from);
if (!from->go()) return UnreachableEnv();
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
result->state = SsaEnv::kReached;
result->locals = from->locals;
result->control = from->control;
result->effect = from->effect;
from->Kill(SsaEnv::kUnreachable);
return result;
}
// Create an unreachable environment.
SsaEnv* UnreachableEnv() {
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
result->state = SsaEnv::kUnreachable;
result->control = nullptr;
result->effect = nullptr;
result->locals = nullptr;
return result;
}
int EnvironmentCount() {
if (builder_) return static_cast<int>(local_type_vec_.size());
return 0; // if we aren't building a graph, don't bother with SSA renaming.
}
virtual void onFirstError() {
limit_ = start_; // Terminate decoding loop.
builder_ = nullptr; // Don't build any more nodes.
TRACE(" !%s\n", error_msg_.get());
}
BitVector* AnalyzeLoopAssignment(const byte* pc) {
if (pc >= limit_) return nullptr;
if (*pc != kExprLoop) return nullptr;
BitVector* assigned =
new (zone_) BitVector(static_cast<int>(local_type_vec_.size()), zone_);
int depth = 0;
// Iteratively process all AST nodes nested inside the loop.
while (pc < limit_ && ok()) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
unsigned length = 1;
switch (opcode) {
case kExprLoop:
case kExprIf:
case kExprBlock:
case kExprTry:
length = OpcodeLength(pc);
depth++;
break;
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand operand(this, pc);
if (assigned->length() > 0 &&
operand.index < static_cast<uint32_t>(assigned->length())) {
// Unverified code might have an out-of-bounds index.
assigned->Add(operand.index);
}
length = 1 + operand.length;
break;
}
case kExprEnd:
depth--;
break;
default:
length = OpcodeLength(pc);
break;
}
if (depth <= 0) break;
pc += length;
}
return ok() ? assigned : nullptr;
}
inline wasm::WasmCodePosition position() {
int offset = static_cast<int>(pc_ - start_);
DCHECK_EQ(pc_ - start_, offset); // overflows cannot happen
return offset;
}
inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) {
TFNode* node;
switch (sig->parameter_count()) {
case 1: {
Value val = Pop(0, sig->GetParam(0));
node = BUILD(Unop, opcode, val.node, position());
break;
}
case 2: {
Value rval = Pop(1, sig->GetParam(1));
Value lval = Pop(0, sig->GetParam(0));
node = BUILD(Binop, opcode, lval.node, rval.node, position());
break;
}
default:
UNREACHABLE();
node = nullptr;
break;
}
Push(GetReturnType(sig), node);
}
};
bool DecodeLocalDecls(AstLocalDecls& decls, const byte* start,
const byte* end) {
AccountingAllocator allocator;
Zone tmp(&allocator, ZONE_NAME);
FunctionBody body = {nullptr, nullptr, nullptr, start, end};
WasmFullDecoder decoder(&tmp, nullptr, body);
return decoder.DecodeLocalDecls(decls);
}
BytecodeIterator::BytecodeIterator(const byte* start, const byte* end,
AstLocalDecls* decls)
: Decoder(start, end) {
if (decls != nullptr) {
if (DecodeLocalDecls(*decls, start, end)) {
pc_ += decls->decls_encoded_size;
if (pc_ > end_) pc_ = end_;
}
}
}
DecodeResult VerifyWasmCode(AccountingAllocator* allocator,
FunctionBody& body) {
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, nullptr, body);
decoder.Decode();
return decoder.toResult<DecodeStruct*>(nullptr);
}
DecodeResult BuildTFGraph(AccountingAllocator* allocator, TFBuilder* builder,
FunctionBody& body) {
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, builder, body);
decoder.Decode();
return decoder.toResult<DecodeStruct*>(nullptr);
}
unsigned OpcodeLength(const byte* pc, const byte* end) {
WasmDecoder decoder(nullptr, nullptr, pc, end);
return decoder.OpcodeLength(pc);
}
void PrintAstForDebugging(const byte* start, const byte* end) {
AccountingAllocator allocator;
OFStream os(stdout);
PrintAst(&allocator, FunctionBodyForTesting(start, end), os, nullptr);
}
bool PrintAst(AccountingAllocator* allocator, const FunctionBody& body,
std::ostream& os,
std::vector<std::tuple<uint32_t, int, int>>* offset_table) {
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, nullptr, body);
int line_nr = 0;
// Print the function signature.
if (body.sig) {
os << "// signature: " << *body.sig << std::endl;
++line_nr;
}
// Print the local declarations.
AstLocalDecls decls(&zone);
BytecodeIterator i(body.start, body.end, &decls);
if (body.start != i.pc()) {
os << "// locals: ";
for (auto p : decls.local_types) {
LocalType type = p.first;
uint32_t count = p.second;
os << " " << count << " " << WasmOpcodes::TypeName(type);
}
os << std::endl;
++line_nr;
for (const byte* locals = body.start; locals < i.pc(); locals++) {
os << (locals == body.start ? "0x" : " 0x") << AsHex(*locals, 2) << ",";
}
os << std::endl;
++line_nr;
}
os << "// body: " << std::endl;
++line_nr;
unsigned control_depth = 0;
for (; i.has_next(); i.next()) {
unsigned length = decoder.OpcodeLength(i.pc());
WasmOpcode opcode = i.current();
if (opcode == kExprElse) control_depth--;
int num_whitespaces = control_depth < 32 ? 2 * control_depth : 64;
if (offset_table) {
offset_table->push_back(
std::make_tuple(i.pc_offset(), line_nr, num_whitespaces));
}
// 64 whitespaces
const char* padding =
" ";
os.write(padding, num_whitespaces);
os << "k" << WasmOpcodes::OpcodeName(opcode) << ",";
for (size_t j = 1; j < length; ++j) {
os << " " << AsHex(i.pc()[j], 2) << ",";
}
switch (opcode) {
case kExprElse:
os << " // @" << i.pc_offset();
control_depth++;
break;
case kExprLoop:
case kExprIf:
case kExprBlock:
case kExprTry: {
BlockTypeOperand operand(&i, i.pc());
os << " // @" << i.pc_offset();
for (unsigned i = 0; i < operand.arity; i++) {
os << " " << WasmOpcodes::TypeName(operand.read_entry(i));
}
control_depth++;
break;
}
case kExprEnd:
os << " // @" << i.pc_offset();
control_depth--;
break;
case kExprBr: {
BreakDepthOperand operand(&i, i.pc());
os << " // depth=" << operand.depth;
break;
}
case kExprBrIf: {
BreakDepthOperand operand(&i, i.pc());
os << " // depth=" << operand.depth;
break;
}
case kExprBrTable: {
BranchTableOperand operand(&i, i.pc());
os << " // entries=" << operand.table_count;
break;
}
case kExprCallIndirect: {
CallIndirectOperand operand(&i, i.pc());
os << " // sig #" << operand.index;
if (decoder.Complete(i.pc(), operand)) {
os << ": " << *operand.sig;
}
break;
}
case kExprCallFunction: {
CallFunctionOperand operand(&i, i.pc());
os << " // function #" << operand.index;
if (decoder.Complete(i.pc(), operand)) {
os << ": " << *operand.sig;
}
break;
}
default:
break;
}
os << std::endl;
++line_nr;
}
return decoder.ok();
}
BitVector* AnalyzeLoopAssignmentForTesting(Zone* zone, size_t num_locals,
const byte* start, const byte* end) {
FunctionBody body = {nullptr, nullptr, nullptr, start, end};
WasmFullDecoder decoder(zone, nullptr, body);
return decoder.AnalyzeLoopAssignmentForTesting(start, num_locals);
}
} // namespace wasm
} // namespace internal
} // namespace v8
|
// Copyright 2014 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.
// This clang plugin checks various invariants of the Blink garbage
// collection infrastructure.
//
// Errors are described at:
// http://www.chromium.org/developers/blink-gc-plugin-errors
#include "BlinkGCPluginConsumer.h"
#include "BlinkGCPluginOptions.h"
#include "Config.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using namespace clang;
class BlinkGCPluginAction : public PluginASTAction {
public:
BlinkGCPluginAction() {}
protected:
// Overridden from PluginASTAction:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance& instance,
llvm::StringRef ref) override {
return llvm::make_unique<BlinkGCPluginConsumer>(instance, options_);
}
bool ParseArgs(const CompilerInstance&,
const std::vector<std::string>& args) override {
for (const auto& arg : args) {
if (arg == "dump-graph") {
options_.dump_graph = true;
} else if (arg == "warn-unneeded-finalizer") {
options_.warn_unneeded_finalizer = true;
} else if (arg == "enable-weak-members-in-unmanaged-classes") {
options_.enable_weak_members_in_unmanaged_classes = true;
} else if (arg == "warn-trace-wrappers-missing-base-dispatch") {
options_.warn_trace_wrappers_missing_base_dispatch = true;
} else {
llvm::errs() << "Unknown blink-gc-plugin argument: " << arg << "\n";
return false;
}
}
return true;
}
private:
BlinkGCPluginOptions options_;
};
static FrontendPluginRegistry::Add<BlinkGCPluginAction> X(
"blink-gc-plugin",
"Check Blink GC invariants");
|
//
// FILE NAME: CQCMEng_LoggerClass.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/01/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the info and value classes to create a macro level
// class which supports logging for CML classes.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCMEng_.hpp"
#include "CQCMEng_LoggerClass_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TCQCLoggerVal,TMEngClassVal)
RTTIDecls(TCQCLoggerInfo,TMEngClassInfo)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace
{
namespace CQCMacroEng_Logger
{
// -----------------------------------------------------------------------
// The names for the types that we support here. Each derivative has to
// be able to return strings that contain its name and full name.
// -----------------------------------------------------------------------
const TString strLogger(L"CQCLogger");
const TString strLoggerClassPath(L"MEng.System.CQC.Runtime.CQCLogger");
const TString strLoggerBasePath(L"MEng.System.CQC.Runtime");
}
}
// ---------------------------------------------------------------------------
// CLASS: TCQCLoggerVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQCLoggerVal: Constuctors and Destructor
// ---------------------------------------------------------------------------
TCQCLoggerVal::TCQCLoggerVal(const TString& strName
, const tCIDLib::TCard2 c2ClassId
, const tCIDMacroEng::EConstTypes eConst) :
TMEngClassVal(strName, c2ClassId, eConst)
{
}
TCQCLoggerVal::~TCQCLoggerVal()
{
}
// ---------------------------------------------------------------------------
// CLASS: TCQCLoggerInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQCLoggerInfo: Public, static methods
// ---------------------------------------------------------------------------
const TString& TCQCLoggerInfo::strClassPath()
{
return CQCMacroEng_Logger::strLoggerClassPath;
}
// ---------------------------------------------------------------------------
// TCQCLoggerInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TCQCLoggerInfo::TCQCLoggerInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
CQCMacroEng_Logger::strLogger
, CQCMacroEng_Logger::strLoggerBasePath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2MethId_DefCtor(kCIDMacroEng::c2BadId)
, m_c2MethId_LogExcept(kCIDMacroEng::c2BadId)
, m_c2MethId_LogExceptP(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsgP(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg1(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg1P(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg2(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg2P(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg3(kCIDMacroEng::c2BadId)
, m_c2MethId_LogMsg3P(kCIDMacroEng::c2BadId)
, m_pmeciExcept(nullptr)
, m_pmecvStrm(nullptr)
{
}
TCQCLoggerInfo::~TCQCLoggerInfo()
{
// Clean up our output stream
try
{
delete m_pmecvStrm;
}
catch(const TError& errToCatch)
{
if (facCQCKit().bShouldLog(errToCatch))
TModule::LogEventObj(errToCatch);
}
}
// ---------------------------------------------------------------------------
// TCQCLoggerInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TCQCLoggerInfo::Init(TCIDMacroEngine& meOwner)
{
// Add the default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.CQC.Runtime.CQCLogger"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Look up the exception class which we reference
m_pmeciExcept = meOwner.pmeciFindAs<TMEngExceptInfo>
(
TMEngExceptInfo::strPath(), kCIDLib::True
);
//
// A convenience to log a cause exception with a msg, and another variation
// that takes position info.
//
{
TMEngMethodInfo methiNew
(
L"LogExcept"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Exception", m_pmeciExcept->c2Id());
m_c2MethId_LogExcept = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogExceptP"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Exception", m_pmeciExcept->c2Id());
methiNew.c2AddInParm(L"ClassPath", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"LineNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_LogExceptP = c2AddMethodInfo(methiNew);
}
//
// We support a couple variations on logging, for just the message
// or the message with 1, 2 or 3 replacement tokens. And we have
// another set of those that also take the calling class path and
// line number.
//
{
TMEngMethodInfo methiNew
(
L"LogMsg"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
m_c2MethId_LogMsg = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsgP"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"ClassPath", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"LineNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_LogMsgP = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg1"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
m_c2MethId_LogMsg1 = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg1P"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"ClassPath", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"LineNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_LogMsg1P = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg2"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token2", tCIDMacroEng::EIntrinsics::Formattable);
m_c2MethId_LogMsg2 = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg2P"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token2", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"ClassPath", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"LineNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_LogMsg2P = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg3"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token2", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token3", tCIDMacroEng::EIntrinsics::Formattable);
m_c2MethId_LogMsg3 = c2AddMethodInfo(methiNew);
}
{
TMEngMethodInfo methiNew
(
L"LogMsg3P"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.c2AddInParm(L"MsgToLog", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"Token1", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token2", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"Token3", tCIDMacroEng::EIntrinsics::Formattable);
methiNew.c2AddInParm(L"ClassPath", tCIDMacroEng::EIntrinsics::String);
methiNew.c2AddInParm(L"LineNum", tCIDMacroEng::EIntrinsics::Card4);
m_c2MethId_LogMsg3P = c2AddMethodInfo(methiNew);
}
//
// Create a macro level string out stream, which we will us for the
// logging methods and possibly others, which take one or more
// formattable objects to replace tokens with. We don't want to
// have to create this on every log event.
//
TMEngClassInfo& meciStrm = meOwner.meciFind
(
tCIDMacroEng::EIntrinsics::StringOutStream
);
m_pmecvStrm = static_cast<TMEngTextOutStreamVal*>
(
meciStrm.pmecvMakeStorage
(
L"TempStream"
, meOwner
, tCIDMacroEng::EConstTypes::NonConst
)
);
//
// Give it a stream, since we won't be constructing it at the macro
// language level, which normally is how it gets one.
//
m_pmecvStrm->SetStream
(
new TTextStringOutStream(1024UL)
, tCIDLib::EAdoptOpts::Adopt
);
}
TMEngClassVal*
TCQCLoggerInfo::pmecvMakeStorage(const TString& strName
, TCIDMacroEngine&
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TCQCLoggerVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TCQCLoggerInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TCQCLoggerInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
// Don't need this so far
// TCQCLoggerVal& mecvActual = static_cast<TCQCLoggerVal&>(mecvInstance);
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_DefCtor)
{
// Nothing to do
}
else if ((c2MethId == m_c2MethId_LogExcept)
|| (c2MethId == m_c2MethId_LogExceptP))
{
TMEngExceptVal& mecvExcept
= meOwner.mecvStackAtAs<TMEngExceptVal>(c4FirstInd + 1);
// Format out the exception info. We pass it as the extra text
TString strErrText(L"CLASS: ", 256UL);
strErrText.Append(mecvExcept.strSrcClassPath());
strErrText.Append(L", LINE: ");
strErrText.AppendFormatted(mecvExcept.c4LineNum());
strErrText.Append(L", ERR: ");
strErrText.Append(mecvExcept.strErrorText());
//
// We either use the current class/line or the one passed if it's a
// 'P' type call.
//
const tCIDLib::TBoolean bPType(c2MethId == m_c2MethId_LogExceptP);
TError errToLog
(
facCIDMacroEng().strName()
, bPType ? meOwner.strClassPathForId(mecvInstance.c2ClassId())
: meOwner.strStackValAt(c4FirstInd + 2)
, bPType ? mecvExcept.c4LineNum() : meOwner.c4StackValAt(c4FirstInd + 3)
, mecvExcept.c4ErrorNum()
, meOwner.strStackValAt(c4FirstInd)
, strErrText
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
);
TModule::LogEventObj(errToLog);
}
else if ((c2MethId == m_c2MethId_LogMsg)
|| (c2MethId == m_c2MethId_LogMsgP)
|| (c2MethId == m_c2MethId_LogMsg1)
|| (c2MethId == m_c2MethId_LogMsg1P)
|| (c2MethId == m_c2MethId_LogMsg2)
|| (c2MethId == m_c2MethId_LogMsg2P)
|| (c2MethId == m_c2MethId_LogMsg3)
|| (c2MethId == m_c2MethId_LogMsg3P))
{
//
// Get the message to a temp first. We may have to do token
// replacement here. We have a helper to do this and he figures
// out if there are any and how many there are.
//
m_strMsg = meOwner.strStackValAt(c4FirstInd);
if ((c2MethId != m_c2MethId_LogMsg)
&& (c2MethId != m_c2MethId_LogMsgP))
{
ReplaceTokens
(
meOwner
, m_strMsg
, c2MethId
, c4FirstInd + 1
);
}
//
// For one set we use our own class path and line number. For the
// other we take the passed ones.
//
if ((c2MethId == m_c2MethId_LogMsg)
|| (c2MethId == m_c2MethId_LogMsg1)
|| (c2MethId == m_c2MethId_LogMsg2)
|| (c2MethId == m_c2MethId_LogMsg3))
{
TError errToLog
(
facCQCKit().strName()
, meOwner.strClassPathForId(mecvInstance.c2ClassId())
, meOwner.c4CurLine()
, m_strMsg
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
);
TModule::LogEventObj(errToLog);
}
else
{
//
// The class/line number values come after the tokens, so
// we have to adjust for that to get to the right params.
//
tCIDLib::TCard4 c4ClsOfs;
if (c2MethId == m_c2MethId_LogMsgP)
c4ClsOfs = 1;
else if (c2MethId == m_c2MethId_LogMsg1P)
c4ClsOfs = 2;
else if (c2MethId == m_c2MethId_LogMsg2P)
c4ClsOfs = 3;
else if (c2MethId == m_c2MethId_LogMsg3P)
c4ClsOfs = 4;
else
{
CIDAssert2(L"Invalid method id in CML logger class");
}
TError errToLog
(
facCQCKit().strName()
, meOwner.strStackValAt(c4FirstInd + c4ClsOfs)
, meOwner.c4StackValAt(c4FirstInd + c4ClsOfs + 1)
, m_strMsg
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
);
TModule::LogEventObj(errToLog);
}
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TCQCLoggerInfo: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TCQCLoggerInfo::ReplaceTokens( TCIDMacroEngine& meOwner
, TString& strMsg
, const tCIDLib::TCard2 c2MethId
, const tCIDLib::TCard4 c4FirstInd)
{
// Get the actual C++ stream out as it's real type
TTextStringOutStream& strmActual = static_cast<TTextStringOutStream&>
(
m_pmecvStrm->strmTarget(meOwner)
);
// Figure out how many tokens
tCIDLib::TCard4 c4Tokens = 0;
if ((c2MethId == m_c2MethId_LogMsg1) || (c2MethId == m_c2MethId_LogMsg1P))
c4Tokens = 1;
else if ((c2MethId == m_c2MethId_LogMsg2) || (c2MethId == m_c2MethId_LogMsg2P))
c4Tokens = 2;
else if ((c2MethId == m_c2MethId_LogMsg3) || (c2MethId == m_c2MethId_LogMsg3P))
c4Tokens = 3;
tCIDLib::TCh chToken(kCIDLib::chDigit1);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Tokens; c4Index++)
{
// Reset the output stream for this round
strmActual.Reset();
//
// Get the current formattable object. One gets us down to the actual
// top item, then add the current index to get to the current one.
//
TMEngFormattableVal& mecvCur = meOwner.mecvStackAtAs<TMEngFormattableVal>
(
c4FirstInd + c4Index
);
TMEngClassInfo& meciTarget = meOwner.meciFind(mecvCur.c2ClassId());
//
// Generate a macro level call to format this guy to the stream. Tell
// the call stack that the stream is a 'repush', though its not, so
// that it won't try to delete it on us.
//
meOwner.PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const);
meOwner.PushValue(m_pmecvStrm, tCIDMacroEng::EStackItems::Parm, kCIDLib::True);
meOwner.meciPushMethodCall
(
meciTarget.c2Id()
, TMEngFormattableInfo::c2FormatToId()
);
meciTarget.Invoke
(
meOwner
, mecvCur
, TMEngFormattableInfo::c2FormatToId()
, tCIDMacroEng::EDispatch::Poly
);
//
// We cheated this one, so we have to pop the method item as well
// the parm and return!
//
meOwner.MultiPop(3);
// And now replace the current token with this result. Flush first!
strmActual.Flush();
strMsg.eReplaceToken(strmActual.strData(), chToken);
// Move up to the next token digit
chToken++;
}
}
|
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_OPENGEX_IMPORTER
#include "AssetLib/OpenGEX/OpenGEXImporter.h"
#include "PostProcessing/MakeVerboseFormat.h"
#include <assimp/DefaultIOSystem.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/StringComparison.h>
#include <openddlparser/OpenDDLParser.h>
#include <assimp/scene.h>
#include <assimp/ai_assert.h>
#include <assimp/importerdesc.h>
#include <vector>
static const aiImporterDesc desc = {
"Open Game Engine Exchange",
"",
"",
"",
aiImporterFlags_SupportTextFlavour,
0,
0,
0,
0,
"ogex"
};
namespace Grammar {
static const std::string MetricType = "Metric";
static const std::string Metric_DistanceType = "distance";
static const std::string Metric_AngleType = "angle";
static const std::string Metric_TimeType = "time";
static const std::string Metric_UpType = "up";
static const std::string NameType = "Name";
static const std::string ObjectRefType = "ObjectRef";
static const std::string MaterialRefType = "MaterialRef";
static const std::string MetricKeyType = "key";
static const std::string GeometryNodeType = "GeometryNode";
static const std::string CameraNodeType = "CameraNode";
static const std::string LightNodeType = "LightNode";
static const std::string GeometryObjectType = "GeometryObject";
static const std::string CameraObjectType = "CameraObject";
static const std::string LightObjectType = "LightObject";
static const std::string TransformType = "Transform";
static const std::string MeshType = "Mesh";
static const std::string VertexArrayType = "VertexArray";
static const std::string IndexArrayType = "IndexArray";
static const std::string MaterialType = "Material";
static const std::string ColorType = "Color";
static const std::string ParamType = "Param";
static const std::string TextureType = "Texture";
static const std::string AttenType = "Atten";
static const std::string DiffuseColorToken = "diffuse";
static const std::string SpecularColorToken = "specular";
static const std::string EmissionColorToken = "emission";
static const std::string DiffuseTextureToken = "diffuse";
static const std::string DiffuseSpecularTextureToken = "specular";
static const std::string SpecularPowerTextureToken = "specular_power";
static const std::string EmissionTextureToken = "emission";
static const std::string OpacyTextureToken = "opacity";
static const std::string TransparencyTextureToken = "transparency";
static const std::string NormalTextureToken = "normal";
enum TokenType {
NoneType = -1,
MetricToken,
NameToken,
ObjectRefToken,
MaterialRefToken,
MetricKeyToken,
GeometryNodeToken,
CameraNodeToken,
LightNodeToken,
GeometryObjectToken,
CameraObjectToken,
LightObjectToken,
TransformToken,
MeshToken,
VertexArrayToken,
IndexArrayToken,
MaterialToken,
ColorToken,
ParamToken,
TextureToken,
AttenToken
};
static const std::string ValidMetricToken[ 4 ] = {
Metric_DistanceType,
Metric_AngleType,
Metric_TimeType,
Metric_UpType
};
static int isValidMetricType( const char *token ) {
if( nullptr == token ) {
return false;
}
int idx( -1 );
for( size_t i = 0; i < 4; i++ ) {
if( ValidMetricToken[ i ] == token ) {
idx = (int) i;
break;
}
}
return idx;
}
static TokenType matchTokenType( const char *tokenType ) {
if( MetricType == tokenType ) {
return MetricToken;
} else if( NameType == tokenType ) {
return NameToken;
} else if( ObjectRefType == tokenType ) {
return ObjectRefToken;
} else if( MaterialRefType == tokenType ) {
return MaterialRefToken;
} else if( MetricKeyType == tokenType ) {
return MetricKeyToken;
} else if ( GeometryNodeType == tokenType ) {
return GeometryNodeToken;
} else if ( CameraNodeType == tokenType ) {
return CameraNodeToken;
} else if ( LightNodeType == tokenType ) {
return LightNodeToken;
} else if ( GeometryObjectType == tokenType ) {
return GeometryObjectToken;
} else if ( CameraObjectType == tokenType ) {
return CameraObjectToken;
} else if ( LightObjectType == tokenType ) {
return LightObjectToken;
} else if( TransformType == tokenType ) {
return TransformToken;
} else if( MeshType == tokenType ) {
return MeshToken;
} else if( VertexArrayType == tokenType ) {
return VertexArrayToken;
} else if( IndexArrayType == tokenType ) {
return IndexArrayToken;
} else if( MaterialType == tokenType ) {
return MaterialToken;
} else if ( ColorType == tokenType ) {
return ColorToken;
} else if ( ParamType == tokenType ) {
return ParamToken;
} else if( TextureType == tokenType ) {
return TextureToken;
} else if ( AttenType == tokenType ) {
return AttenToken;
}
return NoneType;
}
} // Namespace Grammar
namespace Assimp {
namespace OpenGEX {
USE_ODDLPARSER_NS
//------------------------------------------------------------------------------------------------
static void propId2StdString( Property *prop, std::string &name, std::string &key ) {
name = key = "";
if ( nullptr == prop ) {
return;
}
if ( nullptr != prop->m_key ) {
#ifdef ASSIMP_USE_HUNTER
name = prop->m_key->m_text.m_buffer;
#else
name = prop->m_key->m_buffer;
#endif
if ( Value::ddl_string == prop->m_value->m_type ) {
key = prop->m_value->getString();
}
}
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::VertexContainer::VertexContainer()
: m_numColors( 0 )
, m_colors( nullptr )
, m_numUVComps()
, m_textureCoords() {
// empty
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::VertexContainer::~VertexContainer() {
delete[] m_colors;
for(auto &texcoords : m_textureCoords) {
delete [] texcoords;
}
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::RefInfo::RefInfo( aiNode *node, Type type, std::vector<std::string> &names )
: m_node( node )
, m_type( type )
, m_Names( names ) {
// empty
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::RefInfo::~RefInfo() {
// empty
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::OpenGEXImporter()
: m_root( nullptr )
, m_nodeChildMap()
, m_meshCache()
, m_mesh2refMap()
, m_material2refMap()
, m_ctx( nullptr )
, m_metrics()
, m_currentNode( nullptr )
, m_currentVertices()
, m_currentMesh( nullptr )
, m_currentMaterial( nullptr )
, m_currentLight( nullptr )
, m_currentCamera( nullptr )
, m_tokenType( Grammar::NoneType )
, m_materialCache()
, m_cameraCache()
, m_lightCache()
, m_nodeStack()
, m_unresolvedRefStack() {
// empty
}
//------------------------------------------------------------------------------------------------
OpenGEXImporter::~OpenGEXImporter() {
m_ctx = nullptr;
}
//------------------------------------------------------------------------------------------------
bool OpenGEXImporter::CanRead( const std::string &file, IOSystem *pIOHandler, bool checkSig ) const {
bool canRead( false );
if( !checkSig ) {
canRead = SimpleExtensionCheck( file, "ogex" );
} else {
static const char *token[] = { "Metric", "GeometryNode", "VertexArray (attrib", "IndexArray" };
canRead = BaseImporter::SearchFileHeaderForToken( pIOHandler, file, token, 4 );
}
return canRead;
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::InternReadFile( const std::string &filename, aiScene *pScene, IOSystem *pIOHandler ) {
// open source file
IOStream *file = pIOHandler->Open( filename, "rb" );
if( !file ) {
throw DeadlyImportError( "Failed to open file ", filename );
}
std::vector<char> buffer;
TextFileToBuffer( file, buffer );
pIOHandler->Close( file );
OpenDDLParser myParser;
myParser.setBuffer( &buffer[ 0 ], buffer.size() );
bool success( myParser.parse() );
if( success ) {
m_ctx = myParser.getContext();
pScene->mRootNode = new aiNode;
pScene->mRootNode->mName.Set( filename );
handleNodes( m_ctx->m_root, pScene );
}
copyMeshes( pScene );
copyCameras( pScene );
copyLights( pScene );
copyMaterials( pScene );
resolveReferences();
createNodeTree( pScene );
}
//------------------------------------------------------------------------------------------------
const aiImporterDesc *OpenGEXImporter::GetInfo() const {
return &desc;
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::SetupProperties( const Importer *pImp ) {
if( nullptr == pImp ) {
return;
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleNodes( DDLNode *node, aiScene *pScene ) {
if( nullptr == node ) {
return;
}
DDLNode::DllNodeList childs = node->getChildNodeList();
for( DDLNode::DllNodeList::iterator it = childs.begin(); it != childs.end(); ++it ) {
Grammar::TokenType tokenType( Grammar::matchTokenType( ( *it )->getType().c_str() ) );
switch( tokenType ) {
case Grammar::MetricToken:
handleMetricNode( *it, pScene );
break;
case Grammar::NameToken:
handleNameNode( *it, pScene );
break;
case Grammar::ObjectRefToken:
handleObjectRefNode( *it, pScene );
break;
case Grammar::MaterialRefToken:
handleMaterialRefNode( *it, pScene );
break;
case Grammar::MetricKeyToken:
break;
case Grammar::GeometryNodeToken:
handleGeometryNode( *it, pScene );
break;
case Grammar::CameraNodeToken:
handleCameraNode( *it, pScene );
break;
case Grammar::LightNodeToken:
handleLightNode( *it, pScene );
break;
case Grammar::GeometryObjectToken:
handleGeometryObject( *it, pScene );
break;
case Grammar::CameraObjectToken:
handleCameraObject( *it, pScene );
break;
case Grammar::LightObjectToken:
handleLightObject( *it, pScene );
break;
case Grammar::TransformToken:
handleTransformNode( *it, pScene );
break;
case Grammar::MeshToken:
handleMeshNode( *it, pScene );
break;
case Grammar::VertexArrayToken:
handleVertexArrayNode( *it, pScene );
break;
case Grammar::IndexArrayToken:
handleIndexArrayNode( *it, pScene );
break;
case Grammar::MaterialToken:
handleMaterialNode( *it, pScene );
break;
case Grammar::ColorToken:
handleColorNode( *it, pScene );
break;
case Grammar::ParamToken:
handleParamNode( *it, pScene );
break;
case Grammar::TextureToken:
handleTextureNode( *it, pScene );
break;
default:
break;
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleMetricNode( DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == node || nullptr == m_ctx ) {
return;
}
if( m_ctx->m_root != node->getParent() ) {
return;
}
Property *prop( node->getProperties() );
while( nullptr != prop ) {
if( nullptr != prop->m_key ) {
if( Value::ddl_string == prop->m_value->m_type ) {
std::string valName( ( char* ) prop->m_value->m_data );
int type( Grammar::isValidMetricType( valName.c_str() ) );
if( Grammar::NoneType != type ) {
Value *val( node->getValue() );
if( nullptr != val ) {
if( Value::ddl_float == val->m_type ) {
m_metrics[ type ].m_floatValue = val->getFloat();
} else if( Value::ddl_int32 == val->m_type ) {
m_metrics[ type ].m_intValue = val->getInt32();
} else if( Value::ddl_string == val->m_type ) {
m_metrics[type].m_stringValue = std::string( val->getString() );
} else {
throw DeadlyImportError( "OpenGEX: invalid data type for Metric node." );
}
}
}
}
}
prop = prop->m_next;
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleNameNode( DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == m_currentNode ) {
throw DeadlyImportError( "No current node for name." );
return;
}
Value *val( node->getValue() );
if( nullptr != val ) {
if( Value::ddl_string != val->m_type ) {
throw DeadlyImportError( "OpenGEX: invalid data type for value in node name." );
return;
}
const std::string name( val->getString() );
if( m_tokenType == Grammar::GeometryNodeToken || m_tokenType == Grammar::LightNodeToken
|| m_tokenType == Grammar::CameraNodeToken ) {
m_currentNode->mName.Set( name.c_str() );
} else if( m_tokenType == Grammar::MaterialToken ) {
aiString aiName;
aiName.Set( name );
m_currentMaterial->AddProperty( &aiName, AI_MATKEY_NAME );
m_material2refMap[ name ] = m_materialCache.size() - 1;
}
}
}
//------------------------------------------------------------------------------------------------
static void getRefNames( DDLNode *node, std::vector<std::string> &names ) {
ai_assert( nullptr != node );
Reference *ref = node->getReferences();
if( nullptr != ref ) {
for( size_t i = 0; i < ref->m_numRefs; i++ ) {
Name *currentName( ref->m_referencedName[ i ] );
if( nullptr != currentName && nullptr != currentName->m_id ) {
#ifdef ASSIMP_USE_HUNTER
const std::string name( currentName->m_id->m_text.m_buffer );
#else
const std::string name( currentName->m_id->m_buffer );
#endif
if( !name.empty() ) {
names.push_back( name );
}
}
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleObjectRefNode( DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == m_currentNode ) {
throw DeadlyImportError( "No parent node for name." );
return;
}
std::vector<std::string> objRefNames;
getRefNames( node, objRefNames );
// when we are dealing with a geometry node prepare the mesh cache
if ( m_tokenType == Grammar::GeometryNodeToken ) {
m_currentNode->mNumMeshes = static_cast<unsigned int>(objRefNames.size());
m_currentNode->mMeshes = new unsigned int[ objRefNames.size() ];
if ( !objRefNames.empty() ) {
m_unresolvedRefStack.push_back( std::unique_ptr<RefInfo>( new RefInfo( m_currentNode, RefInfo::MeshRef, objRefNames ) ) );
}
} else if ( m_tokenType == Grammar::LightNodeToken ) {
// TODO!
} else if ( m_tokenType == Grammar::CameraNodeToken ) {
// TODO!
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleMaterialRefNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == m_currentNode ) {
throw DeadlyImportError( "No parent node for name." );
return;
}
std::vector<std::string> matRefNames;
getRefNames( node, matRefNames );
if( !matRefNames.empty() ) {
m_unresolvedRefStack.push_back( std::unique_ptr<RefInfo>( new RefInfo( m_currentNode, RefInfo::MaterialRef, matRefNames ) ) );
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleGeometryNode( DDLNode *node, aiScene *pScene ) {
aiNode *newNode = new aiNode;
pushNode( newNode, pScene );
m_tokenType = Grammar::GeometryNodeToken;
m_currentNode = newNode;
handleNodes( node, pScene );
popNode();
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleCameraNode( DDLNode *node, aiScene *pScene ) {
aiCamera *camera( new aiCamera );
m_cameraCache.push_back( camera );
m_currentCamera = camera;
aiNode *newNode = new aiNode;
pushNode( newNode, pScene );
m_tokenType = Grammar::CameraNodeToken;
m_currentNode = newNode;
handleNodes( node, pScene );
popNode();
m_currentCamera->mName.Set( newNode->mName.C_Str() );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleLightNode( ODDLParser::DDLNode *node, aiScene *pScene ) {
aiLight *light( new aiLight );
m_lightCache.push_back( light );
m_currentLight = light;
aiNode *newNode = new aiNode;
m_tokenType = Grammar::LightNodeToken;
m_currentNode = newNode;
pushNode( newNode, pScene );
handleNodes( node, pScene );
popNode();
m_currentLight->mName.Set( newNode->mName.C_Str() );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleGeometryObject( DDLNode *node, aiScene *pScene ) {
// parameters will be parsed normally in the tree, so just go for it
handleNodes( node, pScene );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleCameraObject( ODDLParser::DDLNode *node, aiScene *pScene ) {
// parameters will be parsed normally in the tree, so just go for it
handleNodes( node, pScene );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleLightObject( ODDLParser::DDLNode *node, aiScene *pScene ) {
aiLight *light( new aiLight );
m_lightCache.push_back( light );
std::string objName = node->getName();
if ( !objName.empty() ) {
light->mName.Set( objName );
}
m_currentLight = light;
Property *prop( node->findPropertyByName( "type" ) );
if ( nullptr != prop ) {
if ( nullptr != prop->m_value ) {
std::string typeStr( prop->m_value->getString() );
if ( "point" == typeStr ) {
m_currentLight->mType = aiLightSource_POINT;
} else if ( "spot" == typeStr ) {
m_currentLight->mType = aiLightSource_SPOT;
} else if ( "infinite" == typeStr ) {
m_currentLight->mType = aiLightSource_DIRECTIONAL;
}
}
}
// parameters will be parsed normally in the tree, so just go for it
handleNodes( node, pScene );
}
//------------------------------------------------------------------------------------------------
static void setMatrix( aiNode *node, DataArrayList *transformData ) {
ai_assert( nullptr != node );
ai_assert( nullptr != transformData );
float m[ 16 ];
size_t i( 1 );
Value *next( transformData->m_dataList->m_next );
m[ 0 ] = transformData->m_dataList->getFloat();
while( next != nullptr ) {
m[ i ] = next->getFloat();
next = next->m_next;
i++;
}
ai_assert(i == 16);
node->mTransformation.a1 = m[ 0 ];
node->mTransformation.a2 = m[ 4 ];
node->mTransformation.a3 = m[ 8 ];
node->mTransformation.a4 = m[ 12 ];
node->mTransformation.b1 = m[ 1 ];
node->mTransformation.b2 = m[ 5 ];
node->mTransformation.b3 = m[ 9 ];
node->mTransformation.b4 = m[ 13 ];
node->mTransformation.c1 = m[ 2 ];
node->mTransformation.c2 = m[ 6 ];
node->mTransformation.c3 = m[ 10 ];
node->mTransformation.c4 = m[ 14 ];
node->mTransformation.d1 = m[ 3 ];
node->mTransformation.d2 = m[ 7 ];
node->mTransformation.d3 = m[ 11 ];
node->mTransformation.d4 = m[ 15 ];
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleTransformNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == m_currentNode ) {
throw DeadlyImportError( "No parent node for name." );
return;
}
DataArrayList *transformData( node->getDataArrayList() );
if( nullptr != transformData ) {
if( transformData->m_numItems != 16 ) {
throw DeadlyImportError( "Invalid number of data for transform matrix." );
return;
}
setMatrix( m_currentNode, transformData );
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleMeshNode( ODDLParser::DDLNode *node, aiScene *pScene ) {
m_currentMesh = new aiMesh;
const size_t meshidx( m_meshCache.size() );
// ownership is transferred but a reference remains in m_currentMesh
m_meshCache.emplace_back( m_currentMesh );
Property *prop = node->getProperties();
if( nullptr != prop ) {
std::string propName, propKey;
propId2StdString( prop, propName, propKey );
if( "primitive" == propName ) {
if ( "points" == propKey ) {
m_currentMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
} else if ( "lines" == propKey ) {
m_currentMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
} else if( "triangles" == propKey ) {
m_currentMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
} else if ( "quads" == propKey ) {
m_currentMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
} else {
ASSIMP_LOG_WARN_F( propKey, " is not supported primitive type." );
}
}
}
handleNodes( node, pScene );
DDLNode *parent( node->getParent() );
if( nullptr != parent ) {
const std::string &name = parent->getName();
m_mesh2refMap[ name ] = meshidx;
}
}
//------------------------------------------------------------------------------------------------
enum MeshAttribute {
None,
Position,
Color,
Normal,
TexCoord
};
static const std::string PosToken = "position";
static const std::string ColToken = "color";
static const std::string NormalToken = "normal";
static const std::string TexCoordToken = "texcoord";
//------------------------------------------------------------------------------------------------
static MeshAttribute getAttributeByName( const char *attribName ) {
ai_assert( nullptr != attribName );
if ( 0 == strncmp( PosToken.c_str(), attribName, PosToken.size() ) ) {
return Position;
} else if ( 0 == strncmp( ColToken.c_str(), attribName, ColToken.size() ) ) {
return Color;
} else if( 0 == strncmp( NormalToken.c_str(), attribName, NormalToken.size() ) ) {
return Normal;
} else if( 0 == strncmp( TexCoordToken.c_str(), attribName, TexCoordToken.size() ) ) {
return TexCoord;
}
return None;
}
//------------------------------------------------------------------------------------------------
static void fillVector3( aiVector3D *vec3, Value *vals ) {
ai_assert( nullptr != vec3 );
ai_assert( nullptr != vals );
float x( 0.0f ), y( 0.0f ), z( 0.0f );
Value *next( vals );
x = next->getFloat();
next = next->m_next;
y = next->getFloat();
next = next->m_next;
if( nullptr != next ) {
z = next->getFloat();
}
vec3->Set( x, y, z );
}
//------------------------------------------------------------------------------------------------
static void fillColor4( aiColor4D *col4, Value *vals ) {
ai_assert( nullptr != col4 );
ai_assert( nullptr != vals );
Value *next( vals );
col4->r = next->getFloat();
next = next->m_next;
if (!next) {
throw DeadlyImportError( "OpenGEX: Not enough values to fill 4-element color, only 1" );
}
col4->g = next->getFloat();
next = next->m_next;
if (!next) {
throw DeadlyImportError( "OpenGEX: Not enough values to fill 4-element color, only 2" );
}
col4->b = next->getFloat();
next = next->m_next;
if (!next) {
throw DeadlyImportError( "OpenGEX: Not enough values to fill 4-element color, only 3" );
}
col4->a = next->getFloat();
}
//------------------------------------------------------------------------------------------------
static size_t countDataArrayListItems( DataArrayList *vaList ) {
size_t numItems( 0 );
if( nullptr == vaList ) {
return numItems;
}
DataArrayList *next( vaList );
while( nullptr != next ) {
if( nullptr != vaList->m_dataList ) {
numItems++;
}
next = next->m_next;
}
return numItems;
}
//------------------------------------------------------------------------------------------------
static void copyVectorArray( size_t numItems, DataArrayList *vaList, aiVector3D *vectorArray ) {
for( size_t i = 0; i < numItems; i++ ) {
Value *next( vaList->m_dataList );
fillVector3( &vectorArray[ i ], next );
vaList = vaList->m_next;
}
}
//------------------------------------------------------------------------------------------------
static void copyColor4DArray( size_t numItems, DataArrayList *vaList, aiColor4D *colArray ) {
for ( size_t i = 0; i < numItems; i++ ) {
Value *next( vaList->m_dataList );
fillColor4( &colArray[ i ], next );
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleVertexArrayNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == node ) {
throw DeadlyImportError( "No parent node for name." );
return;
}
Property *prop( node->getProperties() );
if( nullptr != prop ) {
std::string propName, propKey;
propId2StdString( prop, propName, propKey );
MeshAttribute attribType( getAttributeByName( propKey.c_str() ) );
if( None == attribType ) {
return;
}
DataArrayList *vaList = node->getDataArrayList();
if( nullptr == vaList ) {
return;
}
const size_t numItems( countDataArrayListItems( vaList ) );
if( Position == attribType ) {
m_currentVertices.m_vertices.resize( numItems );
copyVectorArray( numItems, vaList, m_currentVertices.m_vertices.data() );
} else if ( Color == attribType ) {
m_currentVertices.m_numColors = numItems;
m_currentVertices.m_colors = new aiColor4D[ numItems ];
copyColor4DArray( numItems, vaList, m_currentVertices.m_colors );
} else if( Normal == attribType ) {
m_currentVertices.m_normals.resize( numItems );
copyVectorArray( numItems, vaList, m_currentVertices.m_normals.data() );
} else if( TexCoord == attribType ) {
m_currentVertices.m_numUVComps[ 0 ] = numItems;
m_currentVertices.m_textureCoords[ 0 ] = new aiVector3D[ numItems ];
copyVectorArray( numItems, vaList, m_currentVertices.m_textureCoords[ 0 ] );
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleIndexArrayNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == node ) {
throw DeadlyImportError( "No parent node for name." );
return;
}
if( nullptr == m_currentMesh ) {
throw DeadlyImportError( "No current mesh for index data found." );
return;
}
DataArrayList *vaList = node->getDataArrayList();
if( nullptr == vaList ) {
return;
}
const size_t numItems( countDataArrayListItems( vaList ) );
m_currentMesh->mNumFaces = static_cast<unsigned int>(numItems);
m_currentMesh->mFaces = new aiFace[ numItems ];
m_currentMesh->mNumVertices = static_cast<unsigned int>(numItems * 3);
m_currentMesh->mVertices = new aiVector3D[ m_currentMesh->mNumVertices ];
bool hasColors( false );
if ( m_currentVertices.m_numColors > 0 ) {
m_currentMesh->mColors[0] = new aiColor4D[ m_currentVertices.m_numColors ];
hasColors = true;
}
bool hasNormalCoords( false );
if ( !m_currentVertices.m_normals.empty() ) {
m_currentMesh->mNormals = new aiVector3D[ m_currentMesh->mNumVertices ];
hasNormalCoords = true;
}
bool hasTexCoords( false );
if ( m_currentVertices.m_numUVComps[ 0 ] > 0 ) {
m_currentMesh->mTextureCoords[ 0 ] = new aiVector3D[ m_currentMesh->mNumVertices ];
hasTexCoords = true;
}
unsigned int index( 0 );
for( size_t i = 0; i < m_currentMesh->mNumFaces; i++ ) {
aiFace ¤t( m_currentMesh->mFaces[ i ] );
current.mNumIndices = 3;
current.mIndices = new unsigned int[ current.mNumIndices ];
Value *next( vaList->m_dataList );
for( size_t indices = 0; indices < current.mNumIndices; indices++ ) {
const int idx( next->getUnsignedInt32() );
ai_assert( static_cast<size_t>( idx ) <= m_currentVertices.m_vertices.size() );
ai_assert( index < m_currentMesh->mNumVertices );
aiVector3D &pos = ( m_currentVertices.m_vertices[ idx ] );
m_currentMesh->mVertices[ index ].Set( pos.x, pos.y, pos.z );
if ( hasColors ) {
aiColor4D &col = m_currentVertices.m_colors[ idx ];
m_currentMesh->mColors[ 0 ][ index ] = col;
}
if ( hasNormalCoords ) {
aiVector3D &normal = ( m_currentVertices.m_normals[ idx ] );
m_currentMesh->mNormals[ index ].Set( normal.x, normal.y, normal.z );
}
if ( hasTexCoords ) {
aiVector3D &tex = ( m_currentVertices.m_textureCoords[ 0 ][ idx ] );
m_currentMesh->mTextureCoords[ 0 ][ index ].Set( tex.x, tex.y, tex.z );
}
current.mIndices[ indices ] = index;
index++;
next = next->m_next;
}
vaList = vaList->m_next;
}
}
//------------------------------------------------------------------------------------------------
static void getColorRGB3( aiColor3D *pColor, DataArrayList *colList ) {
if( nullptr == pColor || nullptr == colList ) {
return;
}
ai_assert( 3 == colList->m_numItems );
Value *val( colList->m_dataList );
pColor->r = val->getFloat();
val = val->getNext();
pColor->g = val->getFloat();
val = val->getNext();
pColor->b = val->getFloat();
}
//------------------------------------------------------------------------------------------------
static void getColorRGB4( aiColor4D *pColor, DataArrayList *colList ) {
if ( nullptr == pColor || nullptr == colList ) {
return;
}
ai_assert( 4 == colList->m_numItems );
Value *val( colList->m_dataList );
pColor->r = val->getFloat();
val = val->getNext();
pColor->g = val->getFloat();
val = val->getNext();
pColor->b = val->getFloat();
val = val->getNext();
pColor->a = val->getFloat();
}
//------------------------------------------------------------------------------------------------
enum ColorType {
NoneColor = 0,
DiffuseColor,
SpecularColor,
EmissionColor,
LightColor
};
//------------------------------------------------------------------------------------------------
static ColorType getColorType( Text *id ) {
if ( nullptr == id ) {
return NoneColor;
}
if( *id == Grammar::DiffuseColorToken ) {
return DiffuseColor;
} else if( *id == Grammar::SpecularColorToken ) {
return SpecularColor;
} else if( *id == Grammar::EmissionColorToken ) {
return EmissionColor;
} else if ( *id == "light" ) {
return LightColor;
}
return NoneColor;
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleMaterialNode( ODDLParser::DDLNode *node, aiScene *pScene ) {
m_currentMaterial = new aiMaterial;
m_materialCache.push_back( m_currentMaterial );
m_tokenType = Grammar::MaterialToken;
handleNodes( node, pScene );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleColorNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == node ) {
return;
}
Property *prop = node->findPropertyByName( "attrib" );
if( nullptr != prop ) {
if( nullptr != prop->m_value ) {
DataArrayList *colList( node->getDataArrayList() );
if( nullptr == colList ) {
return;
}
aiColor3D col;
if ( 3 == colList->m_numItems ) {
aiColor3D col3;
getColorRGB3( &col3, colList );
col = col3;
} else {
aiColor4D col4;
getColorRGB4( &col4, colList );
col.r = col4.r;
col.g = col4.g;
col.b = col4.b;
}
#ifdef ASSIMP_USE_HUNTER
const ColorType colType( getColorType( &prop->m_key->m_text ) );
#else
const ColorType colType( getColorType( prop->m_key ) );
#endif
if( DiffuseColor == colType ) {
m_currentMaterial->AddProperty( &col, 1, AI_MATKEY_COLOR_DIFFUSE );
} else if( SpecularColor == colType ) {
m_currentMaterial->AddProperty( &col, 1, AI_MATKEY_COLOR_SPECULAR );
} else if( EmissionColor == colType ) {
m_currentMaterial->AddProperty( &col, 1, AI_MATKEY_COLOR_EMISSIVE );
} else if ( LightColor == colType ) {
m_currentLight->mColorDiffuse = col;
}
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleTextureNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if( nullptr == node ) {
return;
}
Property *prop = node->findPropertyByName( "attrib" );
if( nullptr != prop ) {
if( nullptr != prop->m_value ) {
Value *val( node->getValue() );
if( nullptr != val ) {
aiString tex;
tex.Set( val->getString() );
if( prop->m_value->getString() == Grammar::DiffuseTextureToken ) {
m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE( 0 ) );
} else if( prop->m_value->getString() == Grammar::SpecularPowerTextureToken ) {
m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_SPECULAR( 0 ) );
} else if( prop->m_value->getString() == Grammar::EmissionTextureToken ) {
m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_EMISSIVE( 0 ) );
} else if( prop->m_value->getString() == Grammar::OpacyTextureToken ) {
m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_OPACITY( 0 ) );
} else if( prop->m_value->getString() == Grammar::TransparencyTextureToken ) {
// ToDo!
// m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE( 0 ) );
} else if( prop->m_value->getString() == Grammar::NormalTextureToken ) {
m_currentMaterial->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS( 0 ) );
} else {
ai_assert( false );
}
}
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleParamNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if ( nullptr == node ) {
return;
}
Property *prop = node->findPropertyByName( "attrib" );
if ( nullptr == prop ) {
return;
}
if ( nullptr != prop->m_value ) {
Value *val( node->getValue() );
if ( nullptr == val ) {
return;
}
const float floatVal( val->getFloat() );
if ( 0 == ASSIMP_strincmp( "fov", prop->m_value->getString(), 3 ) ) {
m_currentCamera->mHorizontalFOV = floatVal;
} else if ( 0 == ASSIMP_strincmp( "near", prop->m_value->getString(), 4 ) ) {
m_currentCamera->mClipPlaneNear = floatVal;
} else if ( 0 == ASSIMP_strincmp( "far", prop->m_value->getString(), 3 ) ) {
m_currentCamera->mClipPlaneFar = floatVal;
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleAttenNode( ODDLParser::DDLNode *node, aiScene * /*pScene*/ ) {
if ( nullptr == node ) {
return;
}
Property *prop = node->findPropertyByName( "curve" );
if ( nullptr != prop ) {
if ( nullptr != prop->m_value ) {
Value *val( node->getValue() );
const float floatVal( val->getFloat() );
if ( 0 == strncmp( "scale", prop->m_value->getString(), strlen( "scale" ) ) ) {
m_currentLight->mAttenuationQuadratic = floatVal;
}
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::copyMeshes( aiScene *pScene ) {
ai_assert( nullptr != pScene );
if( m_meshCache.empty() ) {
return;
}
pScene->mNumMeshes = static_cast<unsigned int>(m_meshCache.size());
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ];
for (unsigned int i = 0; i < pScene->mNumMeshes; i++) {
pScene->mMeshes[i] = m_meshCache[i].release();
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::copyCameras( aiScene *pScene ) {
ai_assert( nullptr != pScene );
if ( m_cameraCache.empty() ) {
return;
}
pScene->mNumCameras = static_cast<unsigned int>(m_cameraCache.size());
pScene->mCameras = new aiCamera*[ pScene->mNumCameras ];
std::copy( m_cameraCache.begin(), m_cameraCache.end(), pScene->mCameras );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::copyLights( aiScene *pScene ) {
ai_assert( nullptr != pScene );
if ( m_lightCache.empty() ) {
return;
}
pScene->mNumLights = static_cast<unsigned int>(m_lightCache.size());
pScene->mLights = new aiLight*[ pScene->mNumLights ];
std::copy( m_lightCache.begin(), m_lightCache.end(), pScene->mLights );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::copyMaterials( aiScene *pScene ) {
ai_assert( nullptr != pScene );
if ( m_materialCache.empty() ) {
return;
}
pScene->mNumMaterials = static_cast<unsigned int>(m_materialCache.size());
pScene->mMaterials = new aiMaterial*[ pScene->mNumMaterials ];
std::copy( m_materialCache.begin(), m_materialCache.end(), pScene->mMaterials );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::resolveReferences() {
if( m_unresolvedRefStack.empty() ) {
return;
}
RefInfo *currentRefInfo( nullptr );
for( auto it = m_unresolvedRefStack.begin(); it != m_unresolvedRefStack.end(); ++it ) {
currentRefInfo = it->get();
if( nullptr != currentRefInfo ) {
aiNode *node( currentRefInfo->m_node );
if( RefInfo::MeshRef == currentRefInfo->m_type ) {
for( size_t i = 0; i < currentRefInfo->m_Names.size(); ++i ) {
const std::string &name( currentRefInfo->m_Names[ i ] );
ReferenceMap::const_iterator curIt( m_mesh2refMap.find( name ) );
if (m_mesh2refMap.end() != curIt) {
unsigned int meshIdx = static_cast<unsigned int>(m_mesh2refMap[ name ]);
node->mMeshes[ i ] = meshIdx;
}
}
} else if( RefInfo::MaterialRef == currentRefInfo->m_type ) {
for ( size_t i = 0; i < currentRefInfo->m_Names.size(); ++i ) {
const std::string name( currentRefInfo->m_Names[ i ] );
ReferenceMap::const_iterator curIt(m_material2refMap.find(name));
if (m_material2refMap.end() != curIt) {
if ( nullptr != m_currentMesh ) {
unsigned int matIdx = static_cast< unsigned int >( m_material2refMap[ name ] );
if ( m_currentMesh->mMaterialIndex != 0 ) {
ASSIMP_LOG_WARN( "Override of material reference in current mesh by material reference." );
}
m_currentMesh->mMaterialIndex = matIdx;
} else {
ASSIMP_LOG_WARN( "Cannot resolve material reference, because no current mesh is there." );
}
}
}
} else {
throw DeadlyImportError( "Unknown reference info to resolve." );
}
}
}
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::createNodeTree( aiScene *pScene ) {
if( nullptr == m_root ) {
return;
}
if( m_root->m_children.empty() ) {
return;
}
pScene->mRootNode->mNumChildren = static_cast<unsigned int>(m_root->m_children.size());
pScene->mRootNode->mChildren = new aiNode*[ pScene->mRootNode->mNumChildren ];
std::copy( m_root->m_children.begin(), m_root->m_children.end(), pScene->mRootNode->mChildren );
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::pushNode( aiNode *node, aiScene *pScene ) {
ai_assert( nullptr != pScene );
if ( nullptr == node ) {
return;
}
ChildInfo *info( nullptr );
if( m_nodeStack.empty() ) {
node->mParent = pScene->mRootNode;
NodeChildMap::iterator it( m_nodeChildMap.find( node->mParent ) );
if( m_nodeChildMap.end() == it ) {
info = new ChildInfo;
m_root = info;
m_nodeChildMap[ node->mParent ] = std::unique_ptr<ChildInfo>(info);
} else {
info = it->second.get();
}
info->m_children.push_back( node );
} else {
aiNode *parent( m_nodeStack.back() );
ai_assert( nullptr != parent );
node->mParent = parent;
NodeChildMap::iterator it( m_nodeChildMap.find( node->mParent ) );
if( m_nodeChildMap.end() == it ) {
info = new ChildInfo;
m_nodeChildMap[ node->mParent ] = std::unique_ptr<ChildInfo>(info);
} else {
info = it->second.get();
}
info->m_children.push_back( node );
}
m_nodeStack.push_back( node );
}
//------------------------------------------------------------------------------------------------
aiNode *OpenGEXImporter::popNode() {
if( m_nodeStack.empty() ) {
return nullptr;
}
aiNode *node( top() );
m_nodeStack.pop_back();
return node;
}
//------------------------------------------------------------------------------------------------
aiNode *OpenGEXImporter::top() const {
if( m_nodeStack.empty() ) {
return nullptr;
}
return m_nodeStack.back();
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::clearNodeStack() {
m_nodeStack.clear();
}
//------------------------------------------------------------------------------------------------
} // Namespace OpenGEX
} // Namespace Assimp
#endif // ASSIMP_BUILD_NO_OPENGEX_IMPORTER
|
#include <Core.h>
#include <Graphics/CommandList.h>
#include <Graphics/Graphics.h>
#include <Logger/Log.h>
#include <gtest/gtest.h>
#include "TestHelper.h"
TEST(FPS, Update) {
auto config = Altseed2TestConfig(Altseed2::CoreModules::None);
EXPECT_TRUE(config != nullptr);
EXPECT_TRUE(Altseed2::Core::Initialize(u"test", 640, 480, config));
auto instance = Altseed2::Core::GetInstance();
static const int loopCount = 10;
instance->SetFramerateMode(Altseed2::FramerateMode::Variable);
instance->SetTargetFPS(10000000);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
for (auto i = 0; i < loopCount; i++) {
instance->DoEvent();
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"VariableFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
}
instance->SetTargetFPS(60);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
for (auto i = 0; i < loopCount; i++) {
instance->DoEvent();
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"VariableFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
}
instance->SetFramerateMode(Altseed2::FramerateMode::Constant);
instance->SetTargetFPS(60);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
instance->DoEvent();
for (auto i = 0; i < loopCount; i++) {
instance->DoEvent();
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"ConstantFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
EXPECT_TRUE(static_cast<int>(fps) <= 60);
}
Altseed2::Core::Terminate();
}
TEST(FPS, WithGraphics) {
auto config = Altseed2TestConfig(Altseed2::CoreModules::Graphics);
EXPECT_TRUE(config != nullptr);
EXPECT_TRUE(Altseed2::Core::Initialize(u"test", 640, 480, config));
auto instance = Altseed2::Core::GetInstance();
static const int loopCount = 50;
instance->SetFramerateMode(Altseed2::FramerateMode::Variable);
instance->SetTargetFPS(100000);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
Altseed2::RenderPassParameter renderPassParameter;
renderPassParameter.ClearColor = Altseed2::Color(50, 50, 50, 255);
renderPassParameter.IsColorCleared = true;
renderPassParameter.IsDepthCleared = true;
for (auto i = 0; i < loopCount && instance->DoEvent(); i++) {
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->BeginFrame(renderPassParameter));
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"VariableFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->EndFrame());
}
instance->SetTargetFPS(60);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
for (auto i = 0; i < loopCount && instance->DoEvent(); i++) {
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->BeginFrame(renderPassParameter));
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"VariableFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->EndFrame());
}
instance->SetFramerateMode(Altseed2::FramerateMode::Constant);
instance->SetTargetFPS(60);
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"TargetFPS: {0}", instance->GetTargetFPS());
instance->DoEvent();
for (auto i = 0; i < loopCount && instance->DoEvent(); i++) {
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->BeginFrame(renderPassParameter));
auto delta = instance->GetDeltaSecond();
auto fps = instance->GetCurrentFPS();
Altseed2::Log::GetInstance()->Trace(Altseed2::LogCategory::User, u"ConstantFPS: 'DeltaSecond:{0}, FPS:{1}'", delta, fps);
EXPECT_TRUE(static_cast<int>(fps) <= 60);
EXPECT_TRUE(Altseed2::Graphics::GetInstance()->EndFrame());
}
Altseed2::Core::Terminate();
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. 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 of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef MODEL_SITEGROUNDTEMPERATURESHALLOW_HPP
#define MODEL_SITEGROUNDTEMPERATURESHALLOW_HPP
#include <vector>
#include "ModelAPI.hpp"
#include "ModelObject.hpp"
#include "../utilities/time/Date.hpp"
namespace openstudio {
namespace model {
namespace detail {
class SiteGroundTemperatureShallow_Impl;
} // detail
/** SiteGroundTemperatureShallow is a ModelObject that wraps the OpenStudio IDD object 'OS_Site_GroundTemperature_Shallow'. */
class MODEL_API SiteGroundTemperatureShallow : public ModelObject {
public:
/** @name Constructors and Destructors */
//@{
explicit SiteGroundTemperatureShallow(Model& model);
virtual ~SiteGroundTemperatureShallow() {}
//@}
/** @name Static Methods */
//@{
static IddObjectType iddObjectType();
//@}
/** @name Getters */
//@{
double januarySurfaceGroundTemperature() const;
bool isJanuarySurfaceGroundTemperatureDefaulted() const;
double februarySurfaceGroundTemperature() const;
bool isFebruarySurfaceGroundTemperatureDefaulted() const;
double marchSurfaceGroundTemperature() const;
bool isMarchSurfaceGroundTemperatureDefaulted() const;
double aprilSurfaceGroundTemperature() const;
bool isAprilSurfaceGroundTemperatureDefaulted() const;
double maySurfaceGroundTemperature() const;
bool isMaySurfaceGroundTemperatureDefaulted() const;
double juneSurfaceGroundTemperature() const;
bool isJuneSurfaceGroundTemperatureDefaulted() const;
double julySurfaceGroundTemperature() const;
bool isJulySurfaceGroundTemperatureDefaulted() const;
double augustSurfaceGroundTemperature() const;
bool isAugustSurfaceGroundTemperatureDefaulted() const;
double septemberSurfaceGroundTemperature() const;
bool isSeptemberSurfaceGroundTemperatureDefaulted() const;
double octoberSurfaceGroundTemperature() const;
bool isOctoberSurfaceGroundTemperatureDefaulted() const;
double novemberSurfaceGroundTemperature() const;
bool isNovemberSurfaceGroundTemperatureDefaulted() const;
double decemberSurfaceGroundTemperature() const;
bool isDecemberSurfaceGroundTemperatureDefaulted() const;
double getTemperatureByMonth(int month) const;
double getTemperatureByMonth(const openstudio::MonthOfYear & month) const;
bool isMonthDefaulted(int month) const;
bool isMonthDefaulted(const openstudio::MonthOfYear & month) const;
std::vector<double> getAllMonthlyTemperatures() const;
//@}
/** @name Setters */
//@{
bool setJanuarySurfaceGroundTemperature(double januarySurfaceGroundTemperature);
void resetJanuarySurfaceGroundTemperature();
bool setFebruarySurfaceGroundTemperature(double februarySurfaceGroundTemperature);
void resetFebruarySurfaceGroundTemperature();
bool setMarchSurfaceGroundTemperature(double marchSurfaceGroundTemperature);
void resetMarchSurfaceGroundTemperature();
bool setAprilSurfaceGroundTemperature(double aprilSurfaceGroundTemperature);
void resetAprilSurfaceGroundTemperature();
bool setMaySurfaceGroundTemperature(double maySurfaceGroundTemperature);
void resetMaySurfaceGroundTemperature();
bool setJuneSurfaceGroundTemperature(double juneSurfaceGroundTemperature);
void resetJuneSurfaceGroundTemperature();
bool setJulySurfaceGroundTemperature(double julySurfaceGroundTemperature);
void resetJulySurfaceGroundTemperature();
bool setAugustSurfaceGroundTemperature(double augustSurfaceGroundTemperature);
void resetAugustSurfaceGroundTemperature();
bool setSeptemberSurfaceGroundTemperature(double septemberSurfaceGroundTemperature);
void resetSeptemberSurfaceGroundTemperature();
bool setOctoberSurfaceGroundTemperature(double octoberSurfaceGroundTemperature);
void resetOctoberSurfaceGroundTemperature();
bool setNovemberSurfaceGroundTemperature(double novemberSurfaceGroundTemperature);
void resetNovemberSurfaceGroundTemperature();
bool setDecemberSurfaceGroundTemperature(double decemberSurfaceGroundTemperature);
void resetDecemberSurfaceGroundTemperature();
bool setTemperatureByMonth(int month, double temperature);
bool setTemperatureByMonth(const openstudio::MonthOfYear & month, double temperature);
void resetTemperatureByMonth(int month);
void resetTemperatureByMonth(const openstudio::MonthOfYear & month);
void resetAllMonths();
bool setAllMonthlyTemperatures(const std::vector<double> &monthly_temperatures);
//@}
protected:
/// @cond
typedef detail::SiteGroundTemperatureShallow_Impl ImplType;
friend class Model;
friend class openstudio::IdfObject;
friend class detail::SiteGroundTemperatureShallow_Impl;
explicit SiteGroundTemperatureShallow(std::shared_ptr<detail::SiteGroundTemperatureShallow_Impl> impl);
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.SiteGroundTemperatureShallow");
};
/** \relates SiteGroundTemperatureShallow*/
typedef boost::optional<SiteGroundTemperatureShallow> OptionalSiteGroundTemperatureShallow;
/** \relates SiteGroundTemperatureShallow*/
typedef std::vector<SiteGroundTemperatureShallow> SiteGroundTemperatureShallowVector;
} // model
} // openstudio
#endif // MODEL_SITEGROUNDTEMPERATURESHALLOW_HPP
|
// CFixDuplicateOption.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "BitMaskEnum.h"
#include "FixDuplicateOption.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// FixDuplicateOption
/////////////////////////////////////////////////////////////////////////////
// Constructor
CFixDuplicateOption::CFixDuplicateOption( )
: CBitMaskEnum( )
{
}
/////////////////////////////////////////////////////////////////////////////
// Destructor
//CFixDuplicateOption::~CFixDuplicateOption( )
//{
//}
/////////////////////////////////////////////////////////////////////////////
// Member functions
CString CFixDuplicateOption::GetName()
{
return CFixDuplicateOption::GetName(m_dwItemEnum);
}
DWORD CFixDuplicateOption::GetDefaultSelect()
{
return CFixDuplicateOption::GetDefaultSelect(m_dwItemEnum);
}
CString CFixDuplicateOption::GetDescription()
{
return CFixDuplicateOption::GetDescription(m_dwItemEnum);
}
BOOL CFixDuplicateOption::GetHidden()
{
return CFixDuplicateOption::GetHidden(m_dwItemEnum);
}
CString CFixDuplicateOption::GetDescription(DWORD dwItem)
{
switch( dwItem )
{
// case CFixDuplicateOption::DeleteOptions :
// return "Options";
// break;
case CFixDuplicateOption::DeletePersonComments :
return "Comments";
break;
case CFixDuplicateOption::DeleteRoster :
return "Roster";
break;
case CFixDuplicateOption::DeleteEventRecord :
return "Event Records";
break;
case CFixDuplicateOption::DeleteParticipantForSeries :
return "Participant Details For Series";
break;
case CFixDuplicateOption::DeleteResults :
return "Results";
break;
case CFixDuplicateOption::DeletePostResults :
return "Post-Event Results";
break;
case CFixDuplicateOption::DeletePreResults :
return "Pre-Event Results";
break;
case CFixDuplicateOption::DeleteFinancial :
return "Financial";
break;
// case CFixDuplicateOption::DeleteSecurityGroup :
case CFixDuplicateOption::DeleteSecurityPerson :
case CFixDuplicateOption::DeleteSecurityPersonSeries :
return "Security";
break;
default :
return "";
break;
}
}
DWORD CFixDuplicateOption::GetDefaultSelect(DWORD dwItem)
{
switch( dwItem )
{
// case CFixDuplicateOption::DeleteOptions :
case CFixDuplicateOption::DeleteEventRecord :
case CFixDuplicateOption::DeleteParticipantForSeries :
case CFixDuplicateOption::DeleteFinancial :
// case CFixDuplicateOption::DeleteSecurityGroup :
case CFixDuplicateOption::DeleteSecurityPerson :
case CFixDuplicateOption::DeleteSecurityPersonSeries :
return dwItem;
break;
case CFixDuplicateOption::DeletePersonComments :
case CFixDuplicateOption::DeleteRoster :
case CFixDuplicateOption::DeleteResults :
case CFixDuplicateOption::DeletePostResults :
case CFixDuplicateOption::DeletePreResults :
return 0;
break;
default :
return 0;
break;
}
}
CString CFixDuplicateOption::GetName(DWORD dwItem)
{
switch( dwItem )
{
// case CFixDuplicateOption::DeleteOptions :
// return "Options";
// break;
case CFixDuplicateOption::DeletePersonComments :
return "PersonComments";
break;
case CFixDuplicateOption::DeleteRoster :
return "Roster";
break;
case CFixDuplicateOption::DeleteEventRecord :
return "EventRecord";
break;
case CFixDuplicateOption::DeleteParticipantForSeries :
return "ParticipantForSeries";
break;
case CFixDuplicateOption::DeleteResults :
return "Results";
break;
case CFixDuplicateOption::DeletePostResults :
return "PostResults";
break;
case CFixDuplicateOption::DeletePreResults :
return "PreResults";
break;
case CFixDuplicateOption::DeleteFinancial :
return "Financial";
break;
// case CFixDuplicateOption::DeleteSecurityGroup :
// return "SecurityGroup";
// break;
case CFixDuplicateOption::DeleteSecurityPerson :
return "SecurityPerson";
break;
case CFixDuplicateOption::DeleteSecurityPersonSeries :
return "SecurityPersonSeries";
break;
default :
return "";
break;
}
}
BOOL CFixDuplicateOption::GetHidden(DWORD dwItem)
{
switch( dwItem )
{
// case CFixDuplicateOption::DeleteOptions :
case CFixDuplicateOption::DeletePersonComments :
case CFixDuplicateOption::DeleteRoster :
case CFixDuplicateOption::DeleteEventRecord :
case CFixDuplicateOption::DeleteParticipantForSeries :
case CFixDuplicateOption::DeleteResults :
case CFixDuplicateOption::DeletePostResults :
case CFixDuplicateOption::DeletePreResults :
case CFixDuplicateOption::DeleteFinancial :
// case CFixDuplicateOption::DeleteSecurityGroup :
case CFixDuplicateOption::DeleteSecurityPerson :
return TRUE;
break;
case CFixDuplicateOption::DeleteSecurityPersonSeries :
return FALSE;
break;
default :
return FALSE;
break;
}
}
|
/**
* Copyright (c) 2022 W. Akira Mizutani
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <btl.h>
#include <sml/quaternion.h>
#include <sml/transform.h>
#include <sml/vector3.h>
#include <type_traits>
using sml::Quat;
using sml::Transform;
using sml::Vec3;
DESCRIBE_CLASS(Transform) {
DESCRIBE_TEST(rotated, RotatedBy45Degrees, ReturnExpectedAngularResult) {
const Vec3 v({1, 1, 1});
const Quat q =
Transform::quaternion_from_rotation(Vec3::y_axis(), static_cast<float>(M_PI_4));
const Vec3 result = Transform::rotated(v, q);
const double expected_cosine = std::sqrt(2.0);
const double resulting_angle = result.x / result.y;
// We check with this wide a range because of float point error
ASSERT_ARE_EQUAL(resulting_angle, expected_cosine);
};
DESCRIBE_TEST(rotated, RotatedBy45Degrees, ReturnExpectedLengthResult) {
const Vec3 v({3, 4, 0});
const Quat q =
Transform::quaternion_from_rotation(Vec3::z_axis(), static_cast<float>(M_PI_4));
const Vec3 result = Transform::rotated(v, q);
const float expected = 5.f;
// We check with this wide a range because of float point error
ASSERT_ARE_EQUAL(result.length(), expected);
};
}
|
//===- GPUToSPIRV.cp - MLIR SPIR-V lowering passes ------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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.
// =============================================================================
//
// This file implements a pass to convert a kernel function in the GPU Dialect
// into a spv.module operation
//
//===----------------------------------------------------------------------===//
#include "mlir/Conversion/StandardToSPIRV/ConvertStandardToSPIRV.h"
#include "mlir/Dialect/GPU/GPUDialect.h"
#include "mlir/Dialect/SPIRV/SPIRVDialect.h"
#include "mlir/Dialect/SPIRV/SPIRVOps.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
namespace {
/// Pattern to convert a kernel function in GPU dialect (a FuncOp with the
/// attribute gpu.kernel) within a spv.module.
class KernelFnConversion final : public SPIRVOpLowering<FuncOp> {
public:
using SPIRVOpLowering<FuncOp>::SPIRVOpLowering;
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override;
};
} // namespace
PatternMatchResult
KernelFnConversion::matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const {
auto funcOp = cast<FuncOp>(op);
FuncOp newFuncOp;
if (!gpu::GPUDialect::isKernel(funcOp)) {
return succeeded(lowerFunction(funcOp, operands, &typeConverter, rewriter,
newFuncOp))
? matchSuccess()
: matchFailure();
}
if (failed(lowerAsEntryFunction(funcOp, operands, &typeConverter, rewriter,
newFuncOp))) {
return matchFailure();
}
newFuncOp.getOperation()->removeAttr(Identifier::get(
gpu::GPUDialect::getKernelFuncAttrName(), op->getContext()));
return matchSuccess();
}
namespace {
/// Pass to lower GPU Dialect to SPIR-V. The pass only converts those functions
/// that have the "gpu.kernel" attribute, i.e. those functions that are
/// referenced in gpu::LaunchKernelOp operations. For each such function
///
/// 1) Create a spirv::ModuleOp, and clone the function into spirv::ModuleOp
/// (the original function is still needed by the gpu::LaunchKernelOp, so cannot
/// replace it).
///
/// 2) Lower the body of the spirv::ModuleOp.
class GPUToSPIRVPass : public ModulePass<GPUToSPIRVPass> {
void runOnModule() override;
};
} // namespace
void GPUToSPIRVPass::runOnModule() {
auto context = &getContext();
auto module = getModule();
SmallVector<Operation *, 4> spirvModules;
for (auto funcOp : module.getOps<FuncOp>()) {
if (gpu::GPUDialect::isKernel(funcOp)) {
OpBuilder builder(module.getBodyRegion());
// Create a new spirv::ModuleOp for this function, and clone the
// function into it.
// TODO : Generalize this to account for different extensions,
// capabilities, extended_instruction_sets, other addressing models
// and memory models.
auto spvModule = builder.create<spirv::ModuleOp>(
funcOp.getLoc(),
builder.getI32IntegerAttr(
static_cast<int32_t>(spirv::AddressingModel::Logical)),
builder.getI32IntegerAttr(
static_cast<int32_t>(spirv::MemoryModel::VulkanKHR)));
OpBuilder moduleBuilder(spvModule.getOperation()->getRegion(0));
moduleBuilder.clone(*funcOp.getOperation());
spirvModules.push_back(spvModule);
}
}
/// Dialect conversion to lower the functions with the spirv::ModuleOps.
SPIRVBasicTypeConverter basicTypeConverter(context);
SPIRVTypeConverter typeConverter(&basicTypeConverter);
OwningRewritePatternList patterns;
patterns.insert<KernelFnConversion>(context, typeConverter);
populateStandardToSPIRVPatterns(context, patterns);
ConversionTarget target(*context);
target.addLegalDialect<spirv::SPIRVDialect>();
target.addDynamicallyLegalOp<FuncOp>([&](FuncOp Op) {
return basicTypeConverter.isSignatureLegal(Op.getType());
});
if (failed(applyFullConversion(spirvModules, target, patterns,
&typeConverter))) {
return signalPassFailure();
}
}
ModulePassBase *createGPUToSPIRVPass() { return new GPUToSPIRVPass(); }
static PassRegistration<GPUToSPIRVPass>
pass("convert-gpu-to-spirv", "Convert GPU dialect to SPIR-V dialect");
|
/**
* This file is part of the ExaHyPE project.
* Copyright (c) 2016 http://exahype.eu
* All rights reserved.
*
* The project has received funding from the European Union's Horizon
* 2020 research and innovation programme under grant agreement
* No 671698. For copyrights and licensing, please consult the webpage.
*
* Released under the BSD 3 Open Source License.
* For the full license text, see LICENSE.txt
**/
#include "exahype/tests/kernels/c/GenericEulerKernelTest.h"
#include "../testdata/generic_euler_testdata.h"
#include "kernels/KernelUtils.h"
#include "kernels/aderdg/generic/Kernels.h"
#if DIMENSIONS == 3
namespace exahype {
namespace tests {
namespace c {
void GenericEulerKernelTest::flux(const double *const Q, double **F) {
double *f = F[0];
double *g = F[1];
double *h = F[2];
const double GAMMA = 1.4;
const double irho = 1.0 / Q[0];
const double p =
(GAMMA - 1) *
(Q[4] - 0.5 * (Q[1] * Q[1] + Q[2] * Q[2] + Q[3] * Q[3]) * irho);
f[0] = Q[1];
f[1] = irho * Q[1] * Q[1] + p;
f[2] = irho * Q[1] * Q[2];
f[3] = irho * Q[1] * Q[3];
f[4] = irho * Q[1] * (Q[4] + p);
g[0] = Q[2];
g[1] = irho * Q[2] * Q[1];
g[2] = irho * Q[2] * Q[2] + p;
g[3] = irho * Q[2] * Q[3];
g[4] = irho * Q[2] * (Q[4] + p);
h[0] = Q[3];
h[1] = irho * Q[3] * Q[1];
h[2] = irho * Q[3] * Q[2];
h[3] = irho * Q[3] * Q[3] + p;
h[4] = irho * Q[3] * (Q[4] + p);
}
void GenericEulerKernelTest::algebraicSource(const tarch::la::Vector<DIMENSIONS, double>& cellCenter, double t, const double *const Q, double *S) {
S[0] = 0.0;
S[1] = 0.0;
S[2] = 0.0;
S[3] = 0.0;
S[4] = 0.0;
}
void GenericEulerKernelTest::eigenvalues(const double *const Q,
const int normalNonZeroIndex,
double *lambda) {
const double GAMMA = 1.4;
double irho = 1.0 / Q[0];
double p = (GAMMA - 1) *
(Q[4] - 0.5 * (Q[1] * Q[1] + Q[2] * Q[2] + Q[3] * Q[3]) * irho);
double u_n = Q[normalNonZeroIndex + 1] * irho;
double c = std::sqrt(GAMMA * p * irho);
lambda[0] = u_n - c;
lambda[1] = u_n;
lambda[2] = u_n;
lambda[3] = u_n;
lambda[4] = u_n + c;
}
void GenericEulerKernelTest::nonConservativeProduct(const double *const Q,
const double *const gradQ,
double *BgradQ) {
// Sven: I have no clue what these data shall do, but
// ensure len(BgradQ)==len(Q).
BgradQ[0] = 0;
BgradQ[1] = 0;
BgradQ[2] = 0;
BgradQ[3] = 0;
BgradQ[4] = 0;
// Q[5]
// gradQ[2][5]
// BgradQ[2][5]
if (!_setNcpAndMatrixBToZero) {
BgradQ[0] = Q[0];
BgradQ[1] = Q[3];
BgradQ[2] = 3.0;
BgradQ[3] = gradQ[0];
BgradQ[4] = 0.7;
}
} // ncp
void GenericEulerKernelTest::coefficientMatrix(const double *const Q,
const int normalNonZero, double *Bn) {
std::fill_n(Bn, 5 * 5, 0);
// if (!_setNcpAndMatrixBToZero) {
// // 3D compressible Euler equations
// double *B1 = new double[5 * 5];
// double *B2 = new double[5 * 5];
// double *B3 = new double[5 * 5];
//
// std::memset(B1, 0, 5 * 5 * sizeof(double));
// std::memset(B2, 0, 5 * 5 * sizeof(double));
// std::memset(B3, 0, 5 * 5 * sizeof(double));
//
// // Bn = B1 if normalNonZero == 0
// // B2 if normalNonZero == 1
// // B3 if normalNonZero == 2
// std::memcpy(Bn, (normalNonZero == 0) ? B1 : (normalNonZero == 1) ? B2 : B3,
// 5 * 5 * sizeof(double));
//
// delete[] B1;
// delete[] B2;
// delete[] B3;
// }
} // matrixb
void GenericEulerKernelTest::testPDEFluxes() {
logInfo("testPDEFluxes()", "Test PDE-related functions, DIM=3");
double Q[5] = {1., 0.1, 0.2, 0.3, 3.5}; // pressure = 1.372
double f[5], g[5], h[5];
double *F[3] = {f, g, h};
flux(Q, F);
for (int i = 0; i < 5; i++) {
validateNumericalEqualsWithParams1(
f[i], ::exahype::tests::testdata::generic_euler::testPDEFluxes::f[i],
i);
}
for (int i = 0; i < 5; i++) {
validateNumericalEqualsWithParams1(
g[i], ::exahype::tests::testdata::generic_euler::testPDEFluxes::g[i],
i);
}
for (int i = 0; i < 5; i++) {
validateNumericalEqualsWithParams1(
h[i], ::exahype::tests::testdata::generic_euler::testPDEFluxes::h[i],
i);
}
} // testPDEFluxes
void GenericEulerKernelTest::testVolumeIntegralLinear() {
logInfo("testVolumeIntegralLinear()",
"Test volume integral linear, ORDER=3, DIM=3");
// output:
double lduh[320]; // intentionally left uninitialised
// input:
const tarch::la::Vector<DIMENSIONS, double> dx(0.5, 0.5,
0.5); // mesh spacing
double lFhi[960] = {0.0}; // nVar * nDOFx * nDOFy * nDOFz * dim
// lFhi = [ lFhi_x | lFhi_y | lFhi_z ], 320 entries each
double *lFhi_x = &lFhi[0];
double *lFhi_y = &lFhi[320];
double *lFhi_z = &lFhi[640];
// seed direction
for (int i = 0; i < 320; i += 5) {
lFhi_x[i + 1] = 1.;
lFhi_y[i + 2] = 2.;
lFhi_z[i + 3] = 3.;
}
kernels::aderdg::generic::c::volumeIntegralLinear<GenericEulerKernelTest,false,false,NumberOfVariables,Order+1>(
lduh, lFhi, dx);
for (int i = 0; i < 320; i++) {
validateNumericalEqualsWithEpsWithParams1(
lduh[i], ::exahype::tests::testdata::generic_euler::
testVolumeIntegralLinear::lduh[i],
eps, i);
}
} // testVolumeIntegralLinear
void GenericEulerKernelTest::testVolumeIntegralNonlinear() {
logInfo("testVolumeIntegralNonlinear()",
"Test volume integral nonlinear, ORDER=3, DIM=3");
logWarning("testVolumeIntegralNonlinear()",
"Test is currently disabled since input data is not suitable.");
// input:
double lFhi[1280] = {0.0}; // nVar * nDOFx * nDOFy * nDOFz * (dim + 1)
// lFhi = [ lFhi_x | lFhi_y | lFhi_z | lShi], 320 entries each
double *lFhi_x = lFhi;
double *lFhi_y = lFhi+320;
double *lFhi_z = lFhi+640;
double *lShi = lFhi+960;
// seed direction
for (int i = 0; i < 320; i += 5) {
lFhi_x[i + 1] = 1.;
lFhi_y[i + 2] = 1.;
lFhi_z[i + 3] = 1.;
}
std::fill_n(lShi, 320, 0.0);
// kernels::aderdg::generic::c::volumeIntegralNonlinear<true,true,NumberOfVariables,Order+1>(
// lduh, lFhi, dx[0]);
//
// for (int i = 0; i < 320; i++) {
// validateNumericalEqualsWithEpsWithParams1(
// lduh[i], ::exahype::tests::testdata::generic_euler::
// testVolumeIntegralNonlinear::lduh[i],
// eps, i);
// }
} // testVolumeIntegralNonlinear
void GenericEulerKernelTest::testSurfaceIntegralLinear() {
logInfo("testSurfaceIntegralLinear()",
"Test surface integral linear, ORDER=3, DIM=3");
// inputs:
const double dx[3] = {0.1, 0.1, 0.1}; // mesh spacing
double lFhbnd[6 * 80] = {0.0}; // 480
double *FLeft = lFhbnd;
double *FRight = lFhbnd + 80;
double *FFront = lFhbnd + 160;
double *FBack = lFhbnd + 240;
double *FBottom = lFhbnd + 320;
double *FTop = lFhbnd + 400;
for (int i = 0; i < 80; i += 5) {
// in x orientation 1
FLeft[i + 1] = 1.;
FRight[i + 1] = 1.;
// in y orientation 1
FFront[i + 2] = 1.;
FBack[i + 2] = 1.;
// in z direction 1
FBottom[i + 3] = 1.;
FTop[i + 3] = 1.;
}
// in/out:
double lduh[320];
for (int i = 0; i < 320; i++) {
lduh[i] = i / 10.;
}
// lFhbnd = [ FLeft | FRight | FFront | FBack | FBottom | FTop ]
kernels::aderdg::generic::c::surfaceIntegralLinear<GenericEulerKernelTest, NumberOfVariables,Order+1>(
lduh, lFhbnd, dx[0]);
for (int i = 0; i < 320; i++) {
validateNumericalEqualsWithEpsWithParams1(
lduh[i], ::exahype::tests::testdata::generic_euler::
testSurfaceIntegralLinear::lduh[i],
eps, i);
}
} // testSurfaceIntegralLinear
void GenericEulerKernelTest::testSurfaceIntegralNonlinear() {
logInfo("testSurfaceIntegralNonlinear()",
"Test surface integral nonlinear, ORDER=3, DIM=3");
// inputs:
const double dx[3] = {0.1, 0.1, 0.1}; // mesh spacing
double lFhbnd[6 * 80] = {0.0}; // 480
double *FLeft = lFhbnd + 0;
double *FRight = lFhbnd + 80;
double *FFront = lFhbnd + 160;
double *FBack = lFhbnd + 240;
double *FBottom = lFhbnd + 320;
double *FTop = lFhbnd + 400;
for (int i = 0; i < 80; i += 5) {
// in x orientation 1
FLeft[i + 1] = 1.;
FRight[i + 1] = 1.;
// in y orientation 1
FFront[i + 2] = 1.;
FBack[i + 2] = 1.;
// in z direction 1
FBottom[i + 3] = 1.;
FTop[i + 3] = 1.;
}
// in/out:
double lduh[320];
for (int i = 0; i < 320; i++) {
lduh[i] = i / 10.;
}
// lFhbnd = [ FLeft | FRight | FFront | FBack | FBottom | FTop ]
kernels::aderdg::generic::c::surfaceIntegralNonlinear<GenericEulerKernelTest,NumberOfVariables,Order+1>(
lduh, lFhbnd, dx[0]);
for (int i = 0; i < 320; i++) {
validateNumericalEqualsWithEpsWithParams1(
lduh[i], ::exahype::tests::testdata::generic_euler::
testSurfaceIntegralNonlinear::lduh[i],
eps, i);
}
} // testSurfaceIntegralNonlinear
/**
* We need to consider material parameters
* in QL,QR,
* We don't need to consider material parameters
* in FL and FR.
*/
//broken, need new linear ncp method
void GenericEulerKernelTest::testRiemannSolverLinear() {
// Rusanov
logInfo("testRiemannSolverLinear()",
"Test Riemann solver linear (Rusanov), ORDER=3, DIM=3");
/*
constexpr int nVar = NumberOfVariables;
constexpr int nPar = NumberOfParameters;
constexpr int nData = nVar+nPar;
constexpr int basisSize = (Order+1);
constexpr int basisSize2 = basisSize*basisSize;
// output (intentionally left uninitialised):
double FL[nVar*basisSize2] = {0.0}; // nDOF(3) * nDOF(2) * nVar
double FR[nVar*basisSize2] = {0.0}; // nDOF(3) * nDOF(2) * nVar
// inputs:
// exahype::tests::testdata::generic_euler::testRiemannSolver::QL[80 =
// nVar * nDOF * nDOF]
// exahype::tests::testdata::generic_euler::testRiemannSolver::QR[80 =
// nVar * nDOF * nDOF]
const double t = 0.0;
const double dt = 1.40831757919882352703e-03;
const int normalNonZero=1; // normalNonZero (only changes result of eigenvalues, matrixb)
// Adapt the striding of test data to the parameters
double QL[nData*basisSize2] = {0.0}; // nData * nDOF(2)
double QR[nData*basisSize2] = {0.0}; // nData * nDOF(2)
for (int i = 0; i < basisSize2; i++) {
for (int m=0; m < nVar; m++) {
const int i_Qbnd = i*nData + m;
const int i_Qbnd_testdata = i*nVar + m;
QL[i_Qbnd]=
exahype::tests::testdata::generic_euler::testRiemannSolver::QL[i_Qbnd_testdata];
QR[i_Qbnd]=
exahype::tests::testdata::generic_euler::testRiemannSolver::QR[i_Qbnd_testdata];
}
}
kernels::aderdg::generic::c::riemannSolverLinear<false,false,false,GenericEulerKernelTest>(
*this,
FL, FR, QL, QR,
t,
dt,
normalNonZero
);
for (int i = 0; i < nVar*basisSize2; i++) {
validateNumericalEqualsWithEpsWithParams1(
FL[i], ::exahype::tests::testdata::generic_euler::
testRiemannSolverLinear::FL[i],
eps, i);
}
for (int i = 0; i < nVar*basisSize2; i++) {
validateNumericalEqualsWithEpsWithParams1(
FR[i], ::exahype::tests::testdata::generic_euler::
testRiemannSolverLinear::FR[i],
eps, i);
}
*/
} // testRiemannSolverLinear
/**
* We need to consider material parameters
* in QL and QR.
* We don't need to consider material parameters
* in FL and FR.
*/
void GenericEulerKernelTest::testRiemannSolverNonlinear() {
logInfo("testRiemannSolverNonlinear()",
"Test Riemann solver nonlinear (Rusanov), ORDER=3, DIM=3");
constexpr int nVar = NumberOfVariables;
constexpr int nPar = NumberOfParameters;
constexpr int nData = nVar+nPar;
constexpr int basisSize = (Order+1);
constexpr int basisSize2 = basisSize*basisSize;
// inout:
double FL[nVar*basisSize2] = {0.0}; // nDOF(3) * nDOF(2) * nVar
double FR[nVar*basisSize2] = {0.0}; // nDOF(3) * nDOF(2) * nVar
for (int i = 0; i < nVar*basisSize2; i++) {
// arbitrary values
FL[i] = static_cast<double>(i + 1);
FR[i] = static_cast<double>(i - 1);
}
// inputs:
// exahype::tests::testdata::generic_euler::testRiemannSolver::QL[80 =
// nVar * nVar * nDOF]
// exahype::tests::testdata::generic_euler::testRiemannSolver::QR[80 =
// nVar * nVar * nDOF]
const double t = 0.0;
const double dt = 1.40831757919882352703e-03;
double QL[nData*basisSize2] = {0.0}; // nData * nDOF(2)
double QR[nData*basisSize2] = {0.0}; // nData * nDOF(2)
// Update striding according to number of parameters
for (int i = 0; i < basisSize2; i++) {
for (int m=0; m < nVar; m++) {
const int i_Qbnd = i*nData + m;
const int i_Qbnd_testdata = i*nVar + m;
QL[i_Qbnd]= ::exahype::tests::testdata::generic_euler::testRiemannSolver::QL[i_Qbnd_testdata];
QR[i_Qbnd]= ::exahype::tests::testdata::generic_euler::testRiemannSolver::QR[i_Qbnd_testdata];
}
}
kernels::aderdg::generic::c::riemannSolverNonlinear<false,false,GenericEulerKernelTest>(
*this,
FL, FR, QL, QR,
t,
dt,
tarch::la::Vector<DIMENSIONS, double>(0.5, 0.5), // dx
1 // normalNonZero
);
for (int i = 0; i < nVar*basisSize2; i++) {
validateNumericalEqualsWithEpsWithParams1(
FL[i], ::exahype::tests::testdata::generic_euler::
testRiemannSolverNonlinear::FL[i],
eps, i);
}
for (int i = 0; i < nVar*basisSize2; i++) {
validateNumericalEqualsWithEpsWithParams1(
FR[i], ::exahype::tests::testdata::generic_euler::
testRiemannSolverNonlinear::FR[i],
eps, i);
};
} // testRiemannSolverNonlinear
/**
* Only luh considers parameters.
* We thus make the test data strides fit.
*
* lduh does not consider parameters.
*/
void GenericEulerKernelTest::testSolutionUpdate() {
logInfo("testSolutionUpdate()", "Test solution update, ORDER=3, DIM=3");
constexpr int nVar = NumberOfVariables;
constexpr int nPar = NumberOfParameters;
constexpr int nData = nVar+nPar;
constexpr int basisSize = (Order+1);
constexpr int basisSize2 = basisSize*basisSize;
constexpr int basisSize3 = basisSize2*basisSize;
// in/out:
double luh[nData*basisSize3] = {0.0};
for (int i = 0; i < nData*basisSize3; i += nData) {
luh[i] = 1.0;
luh[i + 4] = 2.5;
}
// inputs:
const double dt = 1.40831757919882352703e-03;
double lduh[nVar*basisSize3] = {0.0};
for (int i = 0; i < nVar*basisSize3; i++) {
lduh[i] = i;
}
kernels::aderdg::generic::c::solutionUpdate<GenericEulerKernelTest>(*this,luh, luh, lduh, dt);
for (int i = 0; i < basisSize2; i++) {
for (int m = 0; m < nVar; m++) {
int i_luh = i*nData + m;
int i_luh_testdata = i*nVar + m;
validateNumericalEqualsWithEpsWithParams1(
luh[i_luh],
::exahype::tests::testdata::generic_euler::testSolutionUpdate::luh[i_luh_testdata],
eps, i);
}
}
} // testSolutionUpdate
//broken need new linear method
void GenericEulerKernelTest::testSpaceTimePredictorLinear() {
logInfo("testSpaceTimePredictorLinear()",
"Test space time predictor linear, ORDER=3, DIM=3");
/*
// inputs:
// exahype::tests::testdata::generic_euler::testSpaceTimePredictor::luh[320 =
// nVar * nDOFx * nDOFy * nDOFz]
// Actual values for cellCenter/t do not matter, they are only used for
// source terms that depend on time/space.
const tarch::la::Vector<DIMENSIONS, double> cellCenter(0.0, 0.0, 0.0);
const double t = 0.0;
const tarch::la::Vector<DIMENSIONS, double> dx(0.5, 0.5, 0.5);
const double dt = 1.267423918681417E-002;
// Inputs:
double lQi[1600]; // lQi; nVar * nDOFx * nDOFy * nDOFz * (nDOFt+1); nDOF+1 only here
double PSi[1600]; // pointSources
double PSderivatives[1600];
double tmp_PSderivatives[1600];
double lFi[3840+1280]; // lFi+source; nVar * nDOFx * nDOFy * nDOFt * (dim+1)
double gradQ[3840]; // lQi; nVar * nDOFx * nDOFy * nDOFt * dim
// Outputs:
double lQhi[320]; // lQh; nVar * nDOFx * nDOFy * nDOFz
double lFhi[960+320]; // lFh+source; nVar * nDOFx * nDOFy * nDOFz * (dm+1) *
double lQhbnd[480] = {0.0}; // nVar * nDOFy * nDOF_z * 6
double lFhbnd[480] = {0.0}; // nVar * nDOFy * nDOF_z * 6
kernels::aderdg::generic::c::spaceTimePredictorLinear<false,false,false,false,false,GenericEulerKernelTest>(
*this,
lQhbnd, lFhbnd,
lQi,lFi,gradQ,PSi,PSderivatives,tmp_PSderivatives,lQhi,lFhi,
::exahype::tests::testdata::generic_euler::
testSpaceTimePredictor::luh, // TODO(Dominic): Rename namespace to testSpaceTimePredictorLinear?
cellCenter, tarch::la::invertEntries(dx),
t, dt
);
for (int i = 0; i < 320; i++) {
validateNumericalEqualsWithEpsWithParams1(
lQhi[i], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorLinear::lQhi[i],
eps, i);
}
for (int i = 0; i < 960; i++) {
validateNumericalEqualsWithEpsWithParams1(
lFhi[i], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorLinear::lFhi[i],
eps, i);
}
for (int i = 0; i < 480; i++) {
validateNumericalEqualsWithEpsWithParams1(
lQhbnd[i], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorLinear::lQhbnd[i],
eps, i);
}
for (int i = 0; i < 480; i++) {
validateNumericalEqualsWithEpsWithParams1(
lFhbnd[i], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorLinear::lFhbnd[i],
eps, i);
}
*/
} // testSpaceTimePredictorLinear
/*
* We have to consider that we store parameters in
* luh, lQi, lQhi, lQhbnd and have to size
* the arrays accordingly
*/
void GenericEulerKernelTest::testSpaceTimePredictorNonlinear() {
logInfo("testSpaceTimePredictorNonlinear()",
"Test space time predictor nonlinear, ORDER=3, DIM=3");
// inputs:
// exahype::tests::testdata::generic_euler::testSpaceTimePredictor::luh[320 =
// nVar * nDOFx * nDOFy * nDOFz]
const tarch::la::Vector<DIMENSIONS, double> dx(0.05, 0.05, 0.05);
const double timeStepSize = 1.083937460199773E-003;
// These values are only used if the source depends on x or t.
// Hence, the actual values do not matter here.
const tarch::la::Vector<DIMENSIONS, double> x(0.0, 0.0);
const double t = 0.0;
constexpr int nVar = NumberOfVariables;
constexpr int nPar = NumberOfParameters;
constexpr int nData = nVar+nPar;
constexpr int basisSize = (Order+1);
constexpr int basisSize2 = basisSize *basisSize;
constexpr int basisSize3 = basisSize2*basisSize;
constexpr int basisSize4 = basisSize2*basisSize2;
// Inputs:
double lQi[nData*basisSize4];
double rhs[nData*basisSize4];
double lFi[(3 + 1)*nVar*basisSize4]; // also stores the source
double gradQ[3*nVar*basisSize4];
double luh[nData*basisSize3] = {0.0};
for (int i = 0; i < basisSize3; i++) {
for (int m=0; m < nVar; m++) {
const int i_luh = i*nData + m;
const int i_luh_testdata = i*nVar + m;
luh[i_luh] = ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorNonlinear::luh[i_luh_testdata];
}
for (int m=nVar; m < nData; m++) {
const int i_luh = i*nData + m;
luh[i_luh] = 0;
}
}
// Outputs:
// spatial unknowns,flux unknowns
double lQhi[nData*basisSize3] = {0.0}; // nData * nDOFx * nDOFy * nDOFz; // intentionally left uninitialised;
double lFhi[(3+1)*nVar*basisSize3] = {0.0}; // nData * nDOFx * nDOFy * nDOFz * (dim + 1);
double lQhbnd[6 * nData*basisSize2] = {0.0}; // nData * nDOFy * nDOF_z * 6
double lFhbnd[6 * nData*basisSize2] = {0.0}; // nData * nDOFy * nDOF_z * 6
_setNcpAndMatrixBToZero = true;
kernels::aderdg::generic::c::spaceTimePredictorNonlinear<true,true,false, true,false,GenericEulerKernelTest>(
*this,
lQhbnd, nullptr, lFhbnd,
lQi, rhs, lFi, gradQ, lQhi, lFhi,
luh,
x,
tarch::la::invertEntries(dx),
t, timeStepSize
);
_setNcpAndMatrixBToZero = false;
for (int i = 0; i < basisSize4; i++) {
for (int m=0; m < nVar; m++) {
const int i_lQi = i*nData + m;
const int i_lQi_testdata = i*nVar + m;
validateNumericalEqualsWithEpsWithParams1(
lQi[i_lQi], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorNonlinear::lQi[i_lQi_testdata],
eps, i);
}
}
kernels::idx6 idx_lFi(basisSize, basisSize, basisSize, basisSize, (DIMENSIONS + 1),
nVar, __LINE__);
kernels::idx6 idx_lFi_expected(basisSize, basisSize, basisSize, basisSize, DIMENSIONS,
nVar, __LINE__);
for (int i = 0; i < basisSize; i++) {
for (int j = 0; j < basisSize; j++) {
for (int k = 0; k < basisSize; k++) {
for (int l = 0; l < basisSize; l++) {
for (int m = 0; m < 3; m++) { // skip 3 ( = source)
for (int n = 0; n < nVar; n++) {
validateNumericalEqualsWithEpsWithParams1(
lFi[idx_lFi(i, j, k, l, m, n)],
::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorNonlinear::lFi[idx_lFi_expected(
i, j, k, l, m, n)],
eps, idx_lFi(i, j, k, l, m, n));
}
}
}
}
}
}
// lQhbnd
for (int i = 0; i < 6*basisSize2; i++) {
for (int m=0; m < nVar; m++) {
const int i_lQhbnd = i*nData + m;
const int i_lQhbnd_testdata = i*nVar + m;
validateNumericalEqualsWithEpsWithParams1(
lQhbnd[i_lQhbnd], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorNonlinear::lQhbnd[i_lQhbnd_testdata],
eps, i);
}
}
// lFhbnd
for (int i = 0; i < 6*nVar*basisSize2; i++) {
validateNumericalEqualsWithEpsWithParams1(
lFhbnd[i], ::exahype::tests::testdata::generic_euler::
testSpaceTimePredictorNonlinear::lFhbnd[i],
eps, i);
}
} // testSpaceTimePredictorNonlinear
void GenericEulerKernelTest::testFaceUnknownsProjection() {
logInfo("testFaceUnknownsProjection()",
"Test face unknowns projection operators, ORDER=3, DIM=3");
const int nVar = 1;
const int nPar = 1;
const int nData = nVar+nPar;
const int basisSize = 4;
const int basisSize2 = basisSize*basisSize;
// in/out
double lQhbndCoarseOut[basisSize2 * nData] = {0.0};
double lFhbndCoarseOut[basisSize2 * nVar] = {0.0};
double lQhbndFineOut [basisSize2 * nData] = {0.0};
double lFhbndFineOut [basisSize2 * nVar] = {0.0};
// in:
double lQhbndCoarseIn[basisSize2 * nData];
double lFhbndCoarseIn[basisSize2 * nVar];
double lQhbndFineIn [basisSize2 * nData];
double lFhbndFineIn [basisSize2 * nVar];
// Initialise to constant value.
std::fill_n(lQhbndCoarseIn, basisSize2*nData, 1.0); // No, you cannot merge this with the initialisation!
std::fill_n(lQhbndFineIn, basisSize2*nData, 1.0);
std::fill_n(lFhbndCoarseIn, basisSize2*nVar, 1.0);
std::fill_n(lFhbndFineIn, basisSize2*nVar, 1.0);
// Test the prolongation operator.
for (int levelCoarse = 0; levelCoarse < 3; ++levelCoarse) {
for (int levelDelta = 1; levelDelta < 1; ++levelDelta) {
// todo For a levelDelta >= 2, assertionNumericalEquals
// fails since the restriction result is not precise enough anymore.
const int numberOfSubIntervals = tarch::la::aPowI(levelDelta, 3);
tarch::la::Vector<DIMENSIONS - 1, int> subfaceIndex(0);
// Test the restriction operator.
for (int i2 = 0; i2 < numberOfSubIntervals; ++i2) {
for (int i1 = 0; i1 < numberOfSubIntervals; ++i1) {
subfaceIndex[0] = i1;
subfaceIndex[1] = i2;
// Prolongate.
kernels::aderdg::generic::c::faceUnknownsProlongation<GenericEulerKernelTest,NumberOfVariables,NumberOfParameters,Order+1>(
lQhbndFineOut, lFhbndFineOut, lQhbndCoarseIn, lFhbndCoarseIn,
levelCoarse, levelCoarse + levelDelta, subfaceIndex);
// Test prolongated values.
for (int m = 0; m < basisSize * basisSize * nVar; ++m) {
assertionNumericalEquals5(lQhbndFineOut[m], lQhbndFineIn[m], m,
levelCoarse, levelDelta, i1, i2);
assertionNumericalEquals5(lFhbndFineOut[m], lFhbndFineIn[m], m,
levelCoarse, levelDelta, i1, i2);
}
// Restrict.
kernels::aderdg::generic::c::faceUnknownsRestriction<GenericEulerKernelTest,NumberOfVariables,NumberOfParameters,Order+1>(
lQhbndCoarseOut, lFhbndCoarseOut, lQhbndFineIn, lFhbndFineIn,
levelCoarse, levelCoarse + levelDelta, subfaceIndex);
}
// Test restricted values.
for (int m = 0; m < basisSize2 * nData; ++m) {
assertionNumericalEquals3(lQhbndCoarseOut[m], lQhbndCoarseIn[m], m,
levelCoarse, levelDelta);
}
for (int m = 0; m < basisSize2 * nData; ++m) {
assertionNumericalEquals3(lFhbndCoarseOut[m], lFhbndCoarseIn[m], m,
levelCoarse, levelDelta);
}
}
}
}
}
void GenericEulerKernelTest::testVolumeUnknownsProjection() {
logInfo("testVolumeUnknownsProjection()",
"Test volume unknowns projection operators, ORDER=3, DIM=3");
constexpr int nVar = 1;
constexpr int nPar = 1;
constexpr int nData = nVar+nPar;
constexpr int basisSize = 4;
constexpr int basisSize3 = basisSize*basisSize*basisSize;
// in/out
double luhCoarseOut[basisSize3 * nData];
double luhFineOut [basisSize3 * nData];
// in:
double luhCoarseIn[basisSize3 * nData];
double luhFineIn [basisSize3 * nData];
// Initialise to constant value.
for (int i = 0; i < basisSize3 * nData; ++i) {
luhCoarseIn[i] = 1.0;
luhFineIn[i] = 1.0;
}
// Test the prolongation operator.
for (int levelCoarse = 0; levelCoarse < 3; ++levelCoarse) {
for (int levelDelta = 1; levelDelta < 2; ++levelDelta) {
// todo For a levelDelta >= 2, assertionNumericalEquals
// fails since the prolongation result is not precise enough anymore.
const int numberOfSubIntervals = tarch::la::aPowI(levelDelta, 3);
// Test the restriction operator.
tarch::la::Vector<DIMENSIONS, int> subcellIndex(0);
std::fill_n(luhCoarseOut, basisSize3 * nData, 0.0);
for (int i3 = 0; i3 < numberOfSubIntervals; ++i3) {
for (int i2 = 0; i2 < numberOfSubIntervals; ++i2) {
for (int i1 = 0; i1 < numberOfSubIntervals; ++i1) {
subcellIndex[0] = i1;
subcellIndex[1] = i2;
subcellIndex[2] = i3;
// Prolongate.
kernels::aderdg::generic::c::volumeUnknownsProlongation<GenericEulerKernelTest, nVar,nPar,basisSize>(
luhFineOut, luhCoarseIn, levelCoarse, levelCoarse + levelDelta,
subcellIndex);
// Test prolongated values.
for (int m = 0; m < basisSize3 * nData; ++m) {
assertion7(tarch::la::equals(luhFineOut[m], luhFineIn[m], 1e-9), luhFineOut[m], luhFineIn[m], m,
levelCoarse, levelDelta, i1, i2);
}
// Restrict.
kernels::aderdg::generic::c::volumeUnknownsRestriction<GenericEulerKernelTest, nVar,nPar,basisSize>(
luhCoarseOut, luhFineIn, levelCoarse, levelCoarse + levelDelta,
subcellIndex);
}
}
}
// Test restricted values.
for (int m = 0; m < basisSize3 * nData; ++m) {
assertionNumericalEquals3(luhCoarseOut[m], luhCoarseIn[m], m,
levelCoarse, levelDelta);
}
}
}
}
} // namespace c
} // namespace tests
} // namespace exahype
#endif // DIMENSIONS==3
|
/*
* Copyright 1999-2004 The Apache Software 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.
*/
#if !defined(XALAN_OBJECTCACHE_HEADER_GUARD)
#define XALAN_OBJECTCACHE_HEADER_GUARD
#include <algorithm>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/STLHelper.hpp>
XALAN_CPP_NAMESPACE_BEGIN
template<class ObjectType>
class DefaultCacheCreateFunctor
{
public:
ObjectType*
operator()(MemoryManagerType& theManager) const
{
typedef ObjectType ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType();
theGuard.release();
return theResult;
}
};
template<class ObjectType>
class DefaultCacheCreateFunctorMemMgr
{
public:
ObjectType*
operator()(MemoryManagerType& theManager) const
{
typedef ObjectType ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(theManager);
theGuard.release();
return theResult;
}
};
template<class ObjectType>
class DefaultCacheResetFunctor
{
public:
void
operator()(ObjectType*) const
{
}
};
template<class ObjectType>
class ClearCacheResetFunctor
{
public:
void
operator()(ObjectType* theInstance) const
{
theInstance->clear();
}
};
#if defined(XALAN_OBJECT_CACHE_KEEP_BUSY_LIST)
template<
class ObjectType,
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
class CreateFunctorType,
class DeleteFunctorType,
class ResetFunctorType>
#else
class CreateFunctorType = DefaultCacheCreateFunctor<ObjectType>,
class DeleteFunctorType = DeleteFunctor<ObjectType>,
class ResetFunctorType = DefaultCacheResetFunctor<ObjectType> >
#endif
class XalanObjectCache
{
public:
typedef XalanVector<ObjectType*> VectorType;
typedef ObjectType CacheObjectType;
explicit
XalanObjectCache(
MemoryManagerType& theManager,
unsigned int initialListSize = 0) :
m_availableList(theManager),
m_busyList(theManager)
{
m_availableList.reserve(initialListSize);
m_busyList.reserve(initialListSize);
}
~XalanObjectCache()
{
reset();
#if !defined(XALAN_NO_STD_NAMESPACE)
using std::for_each;
#endif
for_each(
m_availableList.begin(),
m_availableList.end(),
m_deleteFunctor(theManager));
}
ObjectType*
get()
{
// We'll always return the back of the free list, since
// that's the cheapest thing.
if (m_availableList.empty() == true)
{
ObjectType* const theNewObject = m_createFunctor(m_availableList.getMemoryManager());
m_busyList.push_back(theNewObject);
return theNewObject;
}
else
{
ObjectType* const theObject = m_availableList.back();
m_busyList.push_back(theObject);
m_availableList.pop_back();
return theObject;
}
}
bool
release(ObjectType* theInstance)
{
#if !defined(XALAN_NO_STD_NAMESPACE)
using std::find;
#endif
typedef typename VectorType::iterator IteratorType;
const IteratorType i =
find(
m_busyList.begin(),
m_busyList.end(),
theInstance);
if (i == m_busyList.end())
{
return false;
}
else
{
m_resetFunctor(theInstance);
m_availableList.push_back(theInstance);
m_busyList.erase(i);
return true;
}
}
void
reset()
{
while (m_busyList.empty() == false)
{
ObjectType* const theInstance = m_busyList.back();
m_resetFunctor(theInstance);
m_availableList.push_back(theInstance);
m_busyList.pop_back();
}
}
// Functors for various operations...
CreateFunctorType m_createFunctor;
DeleteFunctorType m_deleteFunctor;
ResetFunctorType m_resetFunctor;
private:
// There are not defined...
XalanObjectCache(const XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>& theRHS);
XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>&
operator=(const XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>& theRHS);
// Data members...
VectorType m_availableList;
VectorType m_busyList;
};
#else
template<
class ObjectType,
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
class CreateFunctorType,
class DeleteFunctorType,
class ResetFunctorType>
#else
class CreateFunctorType = DefaultCacheCreateFunctor<ObjectType>,
class DeleteFunctorType = DeleteFunctor<ObjectType>,
class ResetFunctorType = DefaultCacheResetFunctor<ObjectType> >
#endif
class XalanObjectCache
{
public:
typedef XalanVector<ObjectType*> VectorType;
typedef ObjectType CacheObjectType;
explicit
XalanObjectCache(MemoryManagerType& theManager,
unsigned int initialListSize = 0) :
m_deleteFunctor(theManager),
m_availableList(theManager)
{
m_availableList.reserve(initialListSize);
}
~XalanObjectCache()
{
reset();
#if !defined(XALAN_NO_STD_NAMESPACE)
using std::for_each;
#endif
for_each(
m_availableList.begin(),
m_availableList.end(),
m_deleteFunctor);
}
ObjectType*
get()
{
// We'll always return the back of the free list, since
// that's the cheapest thing.
if (m_availableList.empty() == true)
{
return m_createFunctor(m_availableList.getMemoryManager());
}
else
{
ObjectType* const theObject = m_availableList.back();
m_availableList.pop_back();
return theObject;
}
}
bool
release(ObjectType* theInstance)
{
m_resetFunctor(theInstance);
m_availableList.push_back(theInstance);
return true;
}
void
reset()
{
}
// Functors for various operations...
CreateFunctorType m_createFunctor;
DeleteFunctorType m_deleteFunctor;
ResetFunctorType m_resetFunctor;
private:
// These are not defined...
XalanObjectCache(const XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>& theRHS);
XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>&
operator=(const XalanObjectCache<ObjectType, CreateFunctorType, DeleteFunctorType, ResetFunctorType>& theRHS);
// Data members...
VectorType m_availableList;
};
#endif
template<class XalanObjectCacheType>
class GuardCachedObject
{
public:
typedef typename XalanObjectCacheType::CacheObjectType CacheObjectType;
GuardCachedObject(XalanObjectCacheType& theCache) :
m_cache(theCache),
m_cachedObject(theCache.get())
{
}
~GuardCachedObject()
{
if (m_cachedObject != 0)
{
m_cache.release(m_cachedObject);
}
}
CacheObjectType*
get() const
{
return m_cachedObject;
}
CacheObjectType*
release()
{
CacheObjectType* const temp = m_cachedObject;
m_cachedObject = 0;
return temp;
}
private:
// Not implemented...
GuardCachedObject(const GuardCachedObject<XalanObjectCacheType>&);
// Data members...
XalanObjectCacheType& m_cache;
CacheObjectType* m_cachedObject;
};
template<class ObjectType>
class XalanObjectCacheDefault :
public XalanObjectCache<
ObjectType,
DefaultCacheCreateFunctor<ObjectType>,
DeleteFunctor<ObjectType>,
DefaultCacheResetFunctor<ObjectType> >
{
public:
typedef XalanObjectCache<
ObjectType,
DefaultCacheCreateFunctor<ObjectType>,
DeleteFunctor<ObjectType>,
DefaultCacheResetFunctor<ObjectType> > BaseClassType;
explicit
XalanObjectCacheDefault(
MemoryManagerType& theManager,
unsigned int initialListSize = 0) :
BaseClassType(theManager, initialListSize)
{
}
};
template<class ObjectType>
class XalanMemoryManagerObjectCacheDefault :
public XalanObjectCache<
ObjectType,
DefaultCacheCreateFunctorMemMgr<ObjectType>,
DeleteFunctor<ObjectType>,
DefaultCacheResetFunctor<ObjectType> >
{
public:
typedef XalanObjectCache<
ObjectType,
DefaultCacheCreateFunctorMemMgr<ObjectType>,
DeleteFunctor<ObjectType>,
DefaultCacheResetFunctor<ObjectType> > BaseClassType;
explicit
XalanMemoryManagerObjectCacheDefault(
MemoryManagerType& theManager,
unsigned int initialListSize = 0) :
BaseClassType(theManager, initialListSize)
{
}
};
XALAN_CPP_NAMESPACE_END
#endif
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/shelf/chrome_shelf_prefs.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/public/cpp/app_list/internal_app_id_constants.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/publishers/extension_apps_util.h"
#include "chrome/browser/ash/crosapi/browser_util.h"
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/prefs/pref_service_syncable_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/ash/default_pinned_apps.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.h"
#include "chrome/browser/ui/ash/shelf/shelf_controller_helper.h"
#include "chrome/browser/web_applications/web_app_id.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/pref_names.h"
#include "components/crx_file/id_util.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/sync/base/user_selectable_type.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/driver/sync_user_settings.h"
#include "components/sync/model/string_ordinal.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "extensions/common/constants.h"
using syncer::UserSelectableOsType;
using syncer::UserSelectableType;
namespace {
const char kDefaultPinnedAppsKey[] = "default";
// This is the default prefix for a chrome app loaded in the primary profile in
// Lacros. Note that "Default" is the name of the directory for the main profile
// in Lacros's --user-data-dir. This is fragile, but is hopefully only needed
// for a brief time while transitioning from ash chrome apps to Lacros chrome
// apps. Note that to support multi-profile chrome apps, we're going to need a
// profile-stable identifier anyways, in the near future.
const char kLacrosChromeAppPrefix[] = "Default###";
bool skip_pinned_apps_from_sync_for_test = false;
bool IsLegacyCameraAppId(const std::string& app_id) {
return app_id ==
"ngmkobaiicipbagcngcmilfkhejlnfci" || // Migration Camera App.
app_id == "goamfaniemdfcajgcmmflhchgkmbngka" || // Google Camera App.
app_id == "obfofkigjfamlldmipdegnjlcpincibc" || // Legacy Camera App.
app_id == "iniodglblcgmngkgdipeiclkdjjpnlbn"; // Internal Camera App.
}
bool IsAppIdArcPackage(const std::string& app_id) {
return app_id.find('.') != app_id.npos;
}
std::vector<std::string> GetActivitiesForPackage(
const std::string& package,
const std::vector<std::string>& all_arc_app_ids,
const ArcAppListPrefs& app_list_pref) {
std::vector<std::string> activities;
for (const std::string& app_id : all_arc_app_ids) {
const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_list_pref.GetApp(app_id);
if (app_info->package_name == package) {
activities.push_back(app_info->activity);
}
}
return activities;
}
std::vector<ash::ShelfID> AppIdsToShelfIDs(
const std::vector<std::string> app_ids) {
std::vector<ash::ShelfID> shelf_ids(app_ids.size());
for (size_t i = 0; i < app_ids.size(); ++i)
shelf_ids[i] = ash::ShelfID(app_ids[i]);
return shelf_ids;
}
struct PinInfo {
PinInfo(const std::string& app_id, const syncer::StringOrdinal& item_ordinal)
: app_id(app_id), item_ordinal(item_ordinal) {}
std::string app_id;
syncer::StringOrdinal item_ordinal;
};
struct ComparePinInfo {
bool operator()(const PinInfo& pin1, const PinInfo& pin2) {
return pin1.item_ordinal.LessThan(pin2.item_ordinal);
}
};
// Helper function that returns the right pref string based on device type.
// This is required because tablet form factor devices do not sync app
// positions and pin preferences.
const std::string GetShelfDefaultPinLayoutPref() {
if (chromeos::switches::IsTabletFormFactor())
return prefs::kShelfDefaultPinLayoutRollsForTabletFormFactor;
return prefs::kShelfDefaultPinLayoutRolls;
}
// Returns true in case default pin layout configuration could be applied
// safely. That means all required components are synced or worked in local
// mode.
bool IsSafeToApplyDefaultPinLayout(Profile* profile) {
const syncer::SyncService* sync_service =
SyncServiceFactory::GetForProfile(profile);
// No |sync_service| in incognito mode.
if (!sync_service)
return true;
// Tablet form-factor devices do not have position sync.
if (chromeos::switches::IsTabletFormFactor())
return true;
const syncer::SyncUserSettings* settings = sync_service->GetUserSettings();
// If App sync is not yet started, don't apply default pin apps once synced
// apps is likely override it. There is a case when App sync is disabled and
// in last case local cache is available immediately.
if (chromeos::features::IsSyncSettingsCategorizationEnabled()) {
if (settings->IsOsSyncFeatureEnabled() &&
settings->GetSelectedOsTypes().Has(UserSelectableOsType::kOsApps) &&
!app_list::AppListSyncableServiceFactory::GetForProfile(profile)
->IsSyncing()) {
return false;
}
} else {
if (sync_service->IsSyncFeatureEnabled() &&
settings->GetSelectedTypes().Has(UserSelectableType::kApps) &&
!app_list::AppListSyncableServiceFactory::GetForProfile(profile)
->IsSyncing()) {
return false;
}
}
// If shelf pin layout rolls preference is not started yet then we cannot say
// if we rolled layout or not.
if (chromeos::features::IsSyncSettingsCategorizationEnabled()) {
if (settings->IsOsSyncFeatureEnabled() &&
settings->GetSelectedOsTypes().Has(
UserSelectableOsType::kOsPreferences) &&
!PrefServiceSyncableFromProfile(profile)->AreOsPrefsSyncing()) {
return false;
}
} else {
if (sync_service->IsSyncFeatureEnabled() &&
settings->GetSelectedTypes().Has(UserSelectableType::kPreferences) &&
!PrefServiceSyncableFromProfile(profile)->IsSyncing()) {
return false;
}
}
return true;
}
} // namespace
const char ChromeShelfPrefs::kPinnedAppsPrefAppIDKey[] = "id";
ChromeShelfPrefs::ChromeShelfPrefs(Profile* profile) : profile_(profile) {}
ChromeShelfPrefs::~ChromeShelfPrefs() {
StopObservingSyncService();
}
void ChromeShelfPrefs::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterListPref(prefs::kPolicyPinnedLauncherApps);
registry->RegisterListPref(
prefs::kShelfDefaultPinLayoutRolls,
user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF);
registry->RegisterListPref(
prefs::kShelfDefaultPinLayoutRollsForTabletFormFactor,
PrefRegistry::NO_REGISTRATION_FLAGS);
}
void ChromeShelfPrefs::InitLocalPref(PrefService* prefs,
const char* local,
const char* synced) {
// Ash's prefs *should* have been propagated to Chrome by now, but maybe not.
// This belongs in Ash, but it can't observe syncing changes: crbug.com/774657
if (prefs->FindPreference(local) && prefs->FindPreference(synced) &&
!prefs->FindPreference(local)->HasUserSetting()) {
prefs->SetString(local, prefs->GetString(synced));
}
}
// Helper that extracts app list from policy preferences.
std::vector<std::string> ChromeShelfPrefs::GetAppsPinnedByPolicy(
ShelfControllerHelper* helper) {
const PrefService* prefs = GetPrefs();
std::vector<std::string> result;
const base::Value* policy_apps =
prefs->GetList(prefs::kPolicyPinnedLauncherApps);
if (!policy_apps || policy_apps->GetList().empty())
return result;
// Obtain here all ids of ARC apps because it takes linear time, and getting
// them in the loop bellow would lead to quadratic complexity.
const ArcAppListPrefs* const arc_app_list_pref = helper->GetArcAppListPrefs();
const std::vector<std::string> all_arc_app_ids(
arc_app_list_pref ? arc_app_list_pref->GetAppIds()
: std::vector<std::string>());
for (const auto& policy_dict_entry : policy_apps->GetList()) {
const std::string* policy_entry =
policy_dict_entry.is_dict()
? policy_dict_entry.FindStringKey(ChromeShelfPrefs::kPinnedAppsPrefAppIDKey)
: nullptr;
if (!policy_entry) {
LOG(ERROR) << "Cannot extract policy app info from prefs.";
continue;
}
if (ash::DemoSession::Get() &&
!ash::DemoSession::Get()->ShouldShowAndroidOrChromeAppInShelf(
*policy_entry)) {
continue;
}
// Handle Chrome App ids
if (crx_file::id_util::IdIsValid(*policy_entry)) {
result.emplace_back(*policy_entry);
continue;
}
// Handle Web App ids
const GURL web_app_url(*policy_entry);
if (web_app_url.is_valid()) {
absl::optional<web_app::AppId> web_app_id =
web_app::WebAppProvider::GetDeprecated(helper->profile())
->registrar()
.LookupExternalAppId(web_app_url);
if (web_app_id.has_value())
result.emplace_back(web_app_id.value());
continue;
}
// Handle Arc++ App ids
if (IsAppIdArcPackage(*policy_entry)) {
if (!arc_app_list_pref)
continue;
// We are dealing with package name, not with 32 characters ID.
const std::string& arc_package = *policy_entry;
const std::vector<std::string> activities = GetActivitiesForPackage(
arc_package, all_arc_app_ids, *arc_app_list_pref);
for (const auto& activity : activities) {
const std::string arc_app_id =
ArcAppListPrefs::GetAppId(arc_package, activity);
result.emplace_back(arc_app_id);
}
continue;
}
}
return result;
}
// Returns pinned app position even if app is not currently visible on device
// that is leftmost item on the shelf. If |exclude_chrome| is true then Chrome
// app is not processed. if nothing pinned found, returns an invalid ordinal.
syncer::StringOrdinal GetFirstPinnedAppPosition(
app_list::AppListSyncableService* syncable_service,
bool exclude_chrome) {
syncer::StringOrdinal position;
for (const auto& sync_peer : syncable_service->sync_items()) {
if (!sync_peer.second->item_pin_ordinal.IsValid())
continue;
if (exclude_chrome && sync_peer.first == extension_misc::kChromeAppId)
continue;
if (!position.IsValid() ||
sync_peer.second->item_pin_ordinal.LessThan(position)) {
position = sync_peer.second->item_pin_ordinal;
}
}
return position;
}
// Helper to create pin position that stays before any synced app, even if
// app is not currently visible on a device.
syncer::StringOrdinal CreateFirstPinPosition(
app_list::AppListSyncableService* syncable_service) {
const syncer::StringOrdinal position =
GetFirstPinnedAppPosition(syncable_service, false /* exclude_chrome */);
return position.IsValid() ? position.CreateBefore()
: syncer::StringOrdinal::CreateInitialOrdinal();
}
// Helper to creates pin position that stays before any synced app, even if
// app is not currently visible on a device.
syncer::StringOrdinal CreateLastPinPosition(Profile* profile) {
syncer::StringOrdinal position;
app_list::AppListSyncableService* syncable_service =
app_list::AppListSyncableServiceFactory::GetForProfile(profile);
for (const auto& sync_peer : syncable_service->sync_items()) {
if (!sync_peer.second->item_pin_ordinal.IsValid())
continue;
if (!position.IsValid() ||
sync_peer.second->item_pin_ordinal.GreaterThan(position)) {
position = sync_peer.second->item_pin_ordinal;
}
}
return position.IsValid() ? position.CreateAfter()
: syncer::StringOrdinal::CreateInitialOrdinal();
}
// Helper to create and insert pins on the shelf for the set of apps defined in
// |app_ids| after Chrome in the first position and before any other pinned app.
// If Chrome is not the first pinned app then apps are pinned before any other
// app.
void InsertPinsAfterChromeAndBeforeFirstPinnedApp(
app_list::AppListSyncableService* syncable_service,
const std::vector<std::string>& app_ids) {
// Chrome must be pinned at this point.
const syncer::StringOrdinal chrome_position =
syncable_service->GetPinPosition(extension_misc::kChromeAppId);
DCHECK(chrome_position.IsValid());
// New pins are inserted after this position.
syncer::StringOrdinal after;
// New pins are inserted before this position.
syncer::StringOrdinal before =
GetFirstPinnedAppPosition(syncable_service, true /* exclude_chrome */);
if (!before.IsValid()) {
before = chrome_position.CreateAfter();
}
if (before.GreaterThan(chrome_position)) {
// Perfect case, Chrome is the first pinned app and we have next pinned app.
after = chrome_position;
} else {
after = before.CreateBefore();
}
for (const auto& app_id : app_ids) {
// Check if we already processed the current app.
if (syncable_service->GetPinPosition(app_id).IsValid())
continue;
const syncer::StringOrdinal position = after.CreateBetween(before);
syncable_service->SetPinPosition(app_id, position);
// Shift after position, next policy pin position will be created after
// current item.
after = position;
}
}
std::vector<ash::ShelfID> ChromeShelfPrefs::GetPinnedAppsFromSync(
ShelfControllerHelper* helper) {
PrefService* prefs = GetPrefs();
app_list::AppListSyncableService* const syncable_service =
GetSyncableService();
// Some unit tests may not have it or service may not be initialized.
if (!syncable_service || !syncable_service->IsInitialized() ||
skip_pinned_apps_from_sync_for_test) {
return std::vector<ash::ShelfID>();
}
ObserveSyncService();
if (ShouldPerformConsistencyMigrations()) {
needs_consistency_migrations_ = false;
EnsureChromePinned(syncable_service);
}
// This migration must be run outside of the consistency migrations block
// since the timing can occur later, after apps have been synced.
if (!DidAddDefaultApps(prefs) && ShouldAddDefaultApps(prefs)) {
AddDefaultApps(prefs, syncable_service);
}
// Handle pins, forced by policy. In case Chrome is first app they are added
// after Chrome, otherwise they are added to the front. Note, we handle apps
// that may not be currently on device. At this case pin position would be
// preallocated and apps will appear on shelf in deterministic order, even if
// their install order differ.
InsertPinsAfterChromeAndBeforeFirstPinnedApp(syncable_service,
GetAppsPinnedByPolicy(helper));
// If Lacros is enabled and allowed for this user type, ensure the Lacros icon
// is pinned. Lacros doesn't support multi-signin, so only add the icon for
// the primary user.
if (crosapi::browser_util::IsLacrosEnabled() &&
chromeos::ProfileHelper::IsPrimaryProfile(profile_)) {
syncer::StringOrdinal lacros_position =
syncable_service->GetPinPosition(extension_misc::kLacrosAppId);
if (!lacros_position.IsValid()) {
// If Lacros isn't already pinned, add it to the right of the Chrome icon.
InsertPinsAfterChromeAndBeforeFirstPinnedApp(
syncable_service, {extension_misc::kLacrosAppId});
}
}
std::vector<PinInfo> pin_infos;
// Empty pins indicates that sync based pin model is used for the first
// time. In the normal workflow we have at least Chrome browser pin info.
for (const auto& sync_peer : syncable_service->sync_items()) {
// A null ordinal means the item has been unpinned.
if (!sync_peer.second->item_pin_ordinal.IsValid())
continue;
std::string app_id = GetShelfId(sync_peer.first);
if (!IsSyncItemValid(app_id, helper)) {
continue;
}
pin_infos.emplace_back(std::move(app_id),
sync_peer.second->item_pin_ordinal);
}
// Sort pins according their ordinals.
std::sort(pin_infos.begin(), pin_infos.end(), ComparePinInfo());
// Convert to ShelfID array.
std::vector<std::string> pins(pin_infos.size());
for (size_t i = 0; i < pin_infos.size(); ++i)
pins[i] = pin_infos[i].app_id;
return AppIdsToShelfIDs(pins);
}
void ChromeShelfPrefs::RemovePinPosition(Profile* profile,
const ash::ShelfID& shelf_id) {
DCHECK(profile);
const std::string& app_id = shelf_id.app_id;
if (!shelf_id.launch_id.empty()) {
VLOG(2) << "Syncing remove pin for '" << app_id
<< "' with non-empty launch id '" << shelf_id.launch_id
<< "' is not supported.";
return;
}
DCHECK(!app_id.empty());
app_list::AppListSyncableService* syncable_service =
app_list::AppListSyncableServiceFactory::GetForProfile(profile);
syncable_service->SetPinPosition(app_id, syncer::StringOrdinal());
}
void ChromeShelfPrefs::SetPinPosition(
const ash::ShelfID& shelf_id,
const ash::ShelfID& shelf_id_before,
const std::vector<ash::ShelfID>& shelf_ids_after) {
const std::string app_id = GetSyncId(shelf_id.app_id);
// No sync ids should begin with the lacros prefix, as it isn't stable.
DCHECK(!base::StartsWith(app_id, kLacrosChromeAppPrefix));
if (!shelf_id.launch_id.empty()) {
VLOG(2) << "Syncing set pin for '" << app_id
<< "' with non-empty launch id '" << shelf_id.launch_id
<< "' is not supported.";
return;
}
const std::string app_id_before = GetSyncId(shelf_id_before.app_id);
DCHECK(!app_id.empty());
DCHECK_NE(app_id, app_id_before);
app_list::AppListSyncableService* syncable_service = GetSyncableService();
// Some unit tests may not have this service.
if (!syncable_service)
return;
syncer::StringOrdinal position_before =
app_id_before.empty() ? syncer::StringOrdinal()
: syncable_service->GetPinPosition(app_id_before);
syncer::StringOrdinal position_after;
for (const auto& shelf_id_after : shelf_ids_after) {
std::string app_id_after = GetSyncId(shelf_id_after.app_id);
DCHECK_NE(app_id_after, app_id);
DCHECK_NE(app_id_after, app_id_before);
syncer::StringOrdinal position =
syncable_service->GetPinPosition(app_id_after);
DCHECK(position.IsValid());
if (!position.IsValid()) {
LOG(ERROR) << "Sync pin position was not found for " << app_id_after;
continue;
}
if (!position_before.IsValid() || !position.Equals(position_before)) {
position_after = position;
break;
}
}
syncer::StringOrdinal pin_position;
if (position_before.IsValid() && position_after.IsValid())
pin_position = position_before.CreateBetween(position_after);
else if (position_before.IsValid())
pin_position = position_before.CreateAfter();
else if (position_after.IsValid())
pin_position = position_after.CreateBefore();
else
pin_position = syncer::StringOrdinal::CreateInitialOrdinal();
syncable_service->SetPinPosition(app_id, pin_position);
}
void ChromeShelfPrefs::SkipPinnedAppsFromSyncForTest() {
skip_pinned_apps_from_sync_for_test = true;
}
void ChromeShelfPrefs::EnsureChromePinned(
app_list::AppListSyncableService* syncable_service) {
syncer::StringOrdinal chrome_position =
syncable_service->GetPinPosition(extension_misc::kChromeAppId);
if (!chrome_position.IsValid()) {
chrome_position = CreateFirstPinPosition(syncable_service);
syncable_service->SetPinPosition(extension_misc::kChromeAppId,
chrome_position);
}
}
bool ChromeShelfPrefs::DidAddDefaultApps(PrefService* pref_service) {
const auto* layouts_rolled =
pref_service->GetList(GetShelfDefaultPinLayoutPref());
DCHECK(layouts_rolled);
return !layouts_rolled->GetList().empty();
}
bool ChromeShelfPrefs::ShouldAddDefaultApps(PrefService* pref_service) {
// Apply default apps in case profile syncing is done. Otherwise there is a
// risk that applied default apps would be overwritten by sync once it is
// completed. prefs::kPolicyPinnedLauncherApps overrides any default layout.
// This also limits applying experimental configuration only for users who
// have the default pin layout specified by |kDefaultPinnedApps| or for
// fresh users who have no pin information at all. Default configuration is
// not applied if any of experimental layout was rolled.
return !pref_service->HasPrefPath(prefs::kPolicyPinnedLauncherApps) &&
IsSafeToApplyDefaultPinLayout(profile_);
}
void ChromeShelfPrefs::AddDefaultApps(
PrefService* pref_service,
app_list::AppListSyncableService* syncable_service) {
VLOG(1) << "Roll default shelf pin layout " << kDefaultPinnedAppsKey;
std::vector<std::string> default_app_ids;
for (const char* default_app_id : GetDefaultPinnedAppsForFormFactor())
default_app_ids.push_back(default_app_id);
InsertPinsAfterChromeAndBeforeFirstPinnedApp(syncable_service,
default_app_ids);
ListPrefUpdate update(pref_service, GetShelfDefaultPinLayoutPref());
update->Append(kDefaultPinnedAppsKey);
}
void ChromeShelfPrefs::AttachProfile(Profile* profile) {
profile_ = profile;
needs_consistency_migrations_ = true;
StopObservingSyncService();
}
bool ChromeShelfPrefs::ShouldPerformConsistencyMigrations() {
return needs_consistency_migrations_;
}
app_list::AppListSyncableService* const ChromeShelfPrefs::GetSyncableService() {
return app_list::AppListSyncableServiceFactory::GetForProfile(profile_);
}
PrefService* ChromeShelfPrefs::GetPrefs() {
return profile_->GetPrefs();
}
bool ChromeShelfPrefs::IsSyncItemValid(const std::string& id,
ShelfControllerHelper* helper) {
return id == extension_misc::kChromeAppId ||
helper->IsValidIDForCurrentUser(id);
}
void ChromeShelfPrefs::ObserveSyncService() {
if (!observed_sync_service_) {
observed_sync_service_ = GetSyncableService();
observed_sync_service_->AddObserverAndStart(this);
}
}
bool ChromeShelfPrefs::IsStandaloneBrowserPublishingChromeApps() {
return crosapi::browser_util::IsLacrosChromeAppsEnabled();
}
apps::mojom::AppType ChromeShelfPrefs::GetAppType(const std::string& app_id) {
apps::AppServiceProxy* proxy =
apps::AppServiceProxyFactory::GetForProfile(profile_);
return proxy->AppRegistryCache().GetAppType(app_id);
}
bool ChromeShelfPrefs::IsAshExtensionApp(const std::string& app_id) {
bool should_run_in_lacros = false;
apps::AppServiceProxy* proxy =
apps::AppServiceProxyFactory::GetForProfile(profile_);
proxy->AppRegistryCache().ForOneApp(
app_id, [&should_run_in_lacros](const apps::AppUpdate& update) {
should_run_in_lacros =
update.IsPlatformApp() == apps::mojom::OptionalBool::kTrue;
});
return should_run_in_lacros;
}
bool ChromeShelfPrefs::IsAshKeepListApp(const std::string& app_id) {
return apps::ExtensionAppRunsInAsh(app_id);
}
std::string ChromeShelfPrefs::GetShelfId(const std::string& sync_id) {
// No sync ids should begin with the lacros prefix, as it isn't stable.
DCHECK(!base::StartsWith(sync_id, kLacrosChromeAppPrefix));
// If Lacros is not publishing chrome apps, no transformation is necessary.
if (!IsStandaloneBrowserPublishingChromeApps())
return sync_id;
// If this app is on the ash keep list, immediately return it. Even if there's
// a lacros chrome app that matches this id, we still want to use the ash
// version.
if (apps::ExtensionAppRunsInAsh(sync_id))
return sync_id;
std::string transformed_app_id = kLacrosChromeAppPrefix + sync_id;
// If this is an ash extension app, we add a fixed prefix. This is based on
// the logic in lacros_extension_apps_utility and is not version-skew stable.
if (IsAshExtensionApp(sync_id)) {
return transformed_app_id;
}
// Now we have to check if the sync id corresponds to a lacros extension app.
if (GetAppType(transformed_app_id) ==
apps::mojom::AppType::kStandaloneBrowserExtension) {
return transformed_app_id;
}
// This is not an extension app for either ash or Lacros.
return sync_id;
}
std::string ChromeShelfPrefs::GetSyncId(const std::string& shelf_id) {
// If Lacros is not publishing chrome apps, no transformation is necessary.
if (!IsStandaloneBrowserPublishingChromeApps())
return shelf_id;
// If this is a lacros chrome app, then we must remove the prefix.
std::string prefix_removed = shelf_id;
base::ReplaceFirstSubstringAfterOffset(&prefix_removed, /*start_offset=*/0,
kLacrosChromeAppPrefix, "");
apps::mojom::AppType type = GetAppType(shelf_id);
if (type == apps::mojom::AppType::kStandaloneBrowserExtension) {
return prefix_removed;
}
// If removing the prefix turns this into an ash chrome app, then we must
// remove the prefix.
type = GetAppType(prefix_removed);
if (type == apps::mojom::AppType::kExtension) {
return prefix_removed;
}
// Do not remove the prefix otherwise.
return shelf_id;
}
void ChromeShelfPrefs::OnSyncModelUpdated() {
needs_consistency_migrations_ = true;
}
void ChromeShelfPrefs::StopObservingSyncService() {
if (observed_sync_service_) {
observed_sync_service_->RemoveObserver(this);
observed_sync_service_ = nullptr;
}
}
|
/*
* This file is part of bogus, a C++ sparse block matrix library.
*
* Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
*
* 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 BOGUS_EIGEN_SPARSE_LINEAR_SOLVERS_HPP
#define BOGUS_EIGEN_SPARSE_LINEAR_SOLVERS_HPP
/* Depending on your version of Eigen, this file may make use of LGPL licensed code.
See Eigen/src/Sparse/SimplicialCholesky.h for more information
*/
#include "SparseHeader.hpp"
#define BOGUS_WITH_EIGEN_STABLE_SPARSE_API
#ifdef BOGUS_WITH_EIGEN_STABLE_SPARSE_API
#include "EigenLinearSolvers.hpp"
#include "../Utils/LinearSolverBase.hpp"
#include "../Utils/NaiveSharedPtr.hpp"
#include <Eigen/OrderingMethods>
#ifndef EIGEN_MPL2_ONLY
#include <Eigen/SparseCholesky>
#define BOGUS_WITH_EIGEN_SPARSE_LDLT
#endif
#if EIGEN_VERSION_AT_LEAST(3,1,92)
#include <Eigen/SparseLU>
#define BOGUS_WITH_EIGEN_SPARSE_LU
#endif
#ifndef BOGUS_EIGEN_SPARSE_LDLT_IMPL
#define BOGUS_EIGEN_SPARSE_LDLT_IMPL(Derived) Eigen::SimplicialLDLT<Derived>
#endif
#ifndef BOGUS_EIGEN_SPARSE_LU_IMPL
#define BOGUS_EIGEN_SPARSE_LU_IMPL(Derived) Eigen::SparseLU<Derived, Eigen::COLAMDOrdering<int> >
#endif
namespace bogus {
template < typename Derived, typename ImplType >
struct LinearSolverTraits< Factorization< Eigen::SparseMatrixBase< Derived >, ImplType > >
{
typedef typename Derived::PlainObject MatrixType ;
typedef ImplType FactType ;
template < typename RhsT > struct Result {
typedef typename EigenSolveResult< FactType, RhsT >::Type Type ;
} ;
template < typename RhsT >
struct Result< Eigen::MatrixBase< RhsT > > {
typedef typename Result< RhsT >::Type Type ;
} ;
} ;
template < typename Derived, typename FactType >
struct Factorization< Eigen::SparseMatrixBase< Derived >, FactType >
: public LinearSolverBase< Factorization< Eigen::SparseMatrixBase< Derived >, FactType > >
{
typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
typedef LinearSolverTraits< Factorization< MatrixType, FactType > > Traits ;
Factorization() {}
template< typename OtherDerived >
explicit Factorization ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
: m_fact( new typename Traits::FactType( mat ) )
{}
template< typename OtherDerived >
Factorization& compute ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
{
m_fact.reset( new typename Traits::FactType( mat ) ) ;
return *this ;
}
template < typename RhsT, typename ResT >
void solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const
{
assert( m_fact ) ;
res = m_fact->solve( rhs ) ;
}
template < typename RhsT >
typename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type
solve( const Eigen::MatrixBase< RhsT >& rhs ) const
{
assert( m_fact ) ;
return m_fact->solve( rhs ) ;
}
const typename Traits::FactType& factorization() const {
return *m_fact ;
}
protected:
BOGUS_SHARED_PTR( typename Traits::FactType, m_fact ) ;
} ;
template < typename Derived, typename FactType >
struct EigenSparseFactorization : public Factorization<
Eigen::SparseMatrixBase< Derived >,
FactType >
{
EigenSparseFactorization() {}
explicit EigenSparseFactorization ( const Eigen::SparseMatrixBase< Derived >& mat )
: Factorization< Eigen::SparseMatrixBase< Derived >, FactType >( mat )
{}
} ;
// LDLT
#ifdef BOGUS_WITH_EIGEN_SPARSE_LDLT
#if ! EIGEN_VERSION_AT_LEAST(3,2,90)
template < typename MatrixType, typename RhsType >
struct EigenSolveResult< Eigen::SimplicialLDLT< MatrixType >, RhsType >
{
typedef Eigen::SimplicialLDLT< MatrixType > FactType ;
typedef Eigen::internal::solve_retval< Eigen::SimplicialCholeskyBase< FactType >, RhsType > Type ;
};
#endif
#endif
template < typename Derived >
struct LinearSolverTraits< LDLT< Eigen::SparseMatrixBase< Derived > > >
: public LinearSolverTraits< Factorization<Eigen::SparseMatrixBase<Derived>, BOGUS_EIGEN_SPARSE_LDLT_IMPL(Derived) > >
{
} ;
template < typename Derived >
struct LinearSolverTraits< LU< Eigen::SparseMatrixBase< Derived > > >
: public LinearSolverTraits< Factorization<Eigen::SparseMatrixBase<Derived>, BOGUS_EIGEN_SPARSE_LU_IMPL(Derived) > >
{
} ;
template < typename Derived >
struct LDLT< Eigen::SparseMatrixBase< Derived > >
: public Factorization< Eigen::SparseMatrixBase< Derived >,
typename LinearSolverTraits< LDLT< Eigen::SparseMatrixBase< Derived > > >::FactType >
{
typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
typedef LinearSolverTraits< LDLT< MatrixType > > Traits ;
typedef Factorization< MatrixType, typename Traits::FactType > Base ;
LDLT() : Base() {}
template< typename OtherDerived >
explicit LDLT ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
: Base( mat )
{}
} ;
template < typename Scalar, int _Options = 0, typename _Index = int >
struct SparseLDLT : public LDLT< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >
{
SparseLDLT() {}
template< typename OtherDerived >
explicit SparseLDLT ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
: LDLT< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >( mat )
{}
} ;
template < typename Derived >
struct LU< Eigen::SparseMatrixBase< Derived > >
: public Factorization< Eigen::SparseMatrixBase< Derived >,
typename LinearSolverTraits< LU< Eigen::SparseMatrixBase< Derived > > >::FactType >
{
typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
typedef LinearSolverTraits< LU< MatrixType > > Traits ;
typedef Factorization< MatrixType, typename Traits::FactType > Base ;
LU() : Base() {}
template< typename OtherDerived >
explicit LU ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
: Base( mat )
{}
} ;
template < typename Scalar, int _Options = 0, typename _Index = int >
struct SparseLU : public LU< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >
{
SparseLU() {}
template< typename OtherDerived >
explicit SparseLU ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
: LU< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >( mat )
{}
} ;
} //namespace bogus
#endif // EIGEN_STABLE_API
#endif //HPP
|
#include "linux_parser.h"
#include <dirent.h>
#include <unistd.h>
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
using std::stof;
using std::string;
using std::to_string;
using std::vector;
namespace fs = std::filesystem;
// DONE: An example of how to read data from the filesystem
void LinuxParser::OperatingSystem(string& os) {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
os = value;
}
}
}
filestream.close();
}
}
// DONE: An example of how to read data from the filesystem
void LinuxParser::Kernel(string& kernel) {
string os, version;
string line;
std::ifstream filestream(kProcDirectory + kVersionFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
filestream.close();
}
}
// BONUS: Update this to use std::filesystem
void LinuxParser::Pids(vector<int>& pids) {
for (const auto& filename : fs::directory_iterator(kProcDirectory))
if (fs::is_directory(filename)) {
string directory(filename.path());
directory.erase(0, kProcDirectory.length());
if (std::all_of(directory.begin(), directory.end(), isdigit)) {
int pid = stoi(directory);
pids.push_back(pid);
}
}
}
// DONE: Read and return the system memory utilization
void LinuxParser::MemoryUtilization(LinuxParser::Memory& memory) {
// This function should read only the memory values, the actual calculation
// should be done in system.cpp
std::ifstream filestream(kProcDirectory + kMeminfoFilename);
string line, key, unit;
int idx{0};
float value{0.0};
if (filestream.is_open()) {
// Get the values first, then we make the calculation.
while (getline(filestream, line)) {
// Maybe redundant, but it ensures we are reading the correct element.
std::istringstream ss(line);
ss >> key >> value >> unit;
auto it = std::find(memory.keywords.begin(), memory.keywords.end(), key);
if (it != memory.keywords.end()) {
idx = it - memory.keywords.begin();
memory.values[idx] = value;
}
}
filestream.close();
}
}
// DONE: Read and return the system uptime
void LinuxParser::UpTime(long& uptime) {
string line;
std::ifstream filestream(kProcDirectory + kUptimeFilename);
if (filestream.is_open()) {
getline(filestream, line);
uptime = stof(line.substr(0, line.find(" ")));
filestream.close();
}
}
// DONE: Read and return the number of jiffies for the system
long LinuxParser::Jiffies() { return ActiveJiffies() + IdleJiffies(); }
// DONE: Read and return the number of active jiffies for a PID
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::ActiveJiffies(int pid) {
string line;
string value;
long activeJiffies{0};
int count{0};
std::ifstream filestream(kProcDirectory + to_string(pid) + kStatFilename);
if (filestream.is_open()) {
getline(filestream, line);
std::istringstream ss(line);
while (ss >> value) {
if (count >= 13 && count <= 16) activeJiffies += stol(value);
count++;
}
filestream.close();
}
return activeJiffies;
}
// DONE: Read and return the number of active jiffies for the system
long LinuxParser::ActiveJiffies() {
string line;
long jiffies[10] = {};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
getline(filestream, line);
line = line.substr(3);
std::istringstream ss(line);
ss >> jiffies[CPUFields::kUser_] >> jiffies[CPUFields::kNice_] >>
jiffies[CPUFields::kSystem_] >> jiffies[CPUFields::kIdle_] >>
jiffies[CPUFields::kIOwait_] >> jiffies[CPUFields::kIRQ_] >>
jiffies[CPUFields::kSoftIRQ_] >> jiffies[CPUFields::kSteal_] >>
jiffies[CPUFields::kGuest_] >> jiffies[CPUFields::kGuestNice_];
filestream.close();
}
return jiffies[CPUFields::kUser_] + jiffies[CPUFields::kNice_] +
jiffies[CPUFields::kSystem_] + jiffies[CPUFields::kIRQ_] +
jiffies[CPUFields::kSoftIRQ_] + jiffies[CPUFields::kSteal_];
}
// DONE: Read and return the number of idle jiffies for the system
long LinuxParser::IdleJiffies() {
string line;
long jiffies[10] = {};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
getline(filestream, line);
line = line.substr(3);
std::istringstream ss(line);
ss >> jiffies[CPUFields::kUser_] >> jiffies[CPUFields::kNice_] >>
jiffies[CPUFields::kSystem_] >> jiffies[CPUFields::kIdle_] >>
jiffies[CPUFields::kIOwait_] >> jiffies[CPUFields::kIRQ_] >>
jiffies[CPUFields::kSoftIRQ_] >> jiffies[CPUFields::kSteal_] >>
jiffies[CPUFields::kGuest_] >> jiffies[CPUFields::kGuestNice_];
}
filestream.close();
return jiffies[CPUFields::kIdle_] + jiffies[CPUFields::kIOwait_];
}
// DONE: Read and return the aggregate CPU values
void LinuxParser::CpuUtilization(float (&values)[10]) {
string line;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
getline(filestream,
line); // first line contains the aggregate information.
line = line.substr(3);
std::istringstream ss(line);
ss >> values[CPUFields::kUser_] >> values[CPUFields::kNice_] >>
values[CPUFields::kSystem_] >> values[CPUFields::kIdle_] >>
values[CPUFields::kIOwait_] >> values[CPUFields::kIRQ_] >>
values[CPUFields::kSoftIRQ_] >> values[CPUFields::kSteal_] >>
values[CPUFields::kGuest_] >> values[CPUFields::kGuestNice_];
filestream.close();
}
}
void LinuxParser::CpuUtilization(float (&values)[10], int kCPU) {
string line;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (getline(filestream, line)) {
if (line.find("cpu" + to_string(kCPU)) != std::string::npos) {
line = line.substr(3);
std::istringstream ss(line);
ss >> values[CPUFields::kUser_] >> values[CPUFields::kNice_] >>
values[CPUFields::kSystem_] >> values[CPUFields::kIdle_] >>
values[CPUFields::kIOwait_] >> values[CPUFields::kIRQ_] >>
values[CPUFields::kSoftIRQ_] >> values[CPUFields::kSteal_] >>
values[CPUFields::kGuest_] >> values[CPUFields::kGuestNice_];
}
}
filestream.close();
}
}
// DONE: Read and return the total number of processes
void LinuxParser::TotalProcesses(int& processes) {
string line;
const string keyword{"processes"};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (getline(filestream, line))
if (line.find(keyword) != string::npos)
processes = stoi(line.substr(keyword.length() + 1));
filestream.close();
}
}
// DONE: Read and return the number of running processes
void LinuxParser::RunningProcesses(int& running_processes) {
string line;
const string keyword{"procs_running"};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (getline(filestream, line))
if (line.find(keyword) != string::npos)
running_processes = stoi(line.substr(keyword.length() + 1));
filestream.close();
}
}
void LinuxParser::NumCores(int& cores) {
string line;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (getline(filestream, line))
if (line.find("cpu") != std::string::npos) cores++;
filestream.close();
}
}
// DONE: Read and return the command associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Command(int pid) {
string command;
std::ifstream filestream(kProcDirectory + to_string(pid) + kCmdlineFilename);
if (filestream.is_open()) {
getline(filestream, command);
filestream.close();
}
return command;
}
// DONE: Read and return the memory used by a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Ram(int pid) {
string line;
string tag;
string units;
float ram;
std::ifstream filestream(kProcDirectory + to_string(pid) + kStatusFilename);
if (filestream.is_open()) {
while (getline(filestream, line)) {
if (line.find("VmSize:") != std::string::npos) {
std::istringstream ss(line);
ss >> tag >> ram >> units;
}
}
filestream.close();
}
return to_string(ram / 1000);
}
// TODO: Read and return the user ID associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Uid(int pid) {
string line;
string tag;
string uid;
std::ifstream filestream(kProcDirectory + to_string(pid) + kStatusFilename);
return string();
}
// TODO: Read and return the user associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::User(int pid [[maybe_unused]]) { return string(); }
// TODO: Read and return the uptime of a process
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::UpTime(int pid) {
string line;
string value;
float start_time{0};
float uptime_sys{0};
int count{1};
std::ifstream filestream(kProcDirectory + to_string(pid) + kStatFilename);
if (filestream.is_open()) {
getline(filestream, line);
std::istringstream ss(line);
ss >> uptime_sys;
while (ss >> value && count++ < 22)
;
ss >> start_time;
}
return (long)(uptime_sys - (start_time / sysconf(_SC_CLK_TCK)));
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_05.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
Template File: sources-sink-05.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sink: cpy
* BadSink : Copy string to data using wcscpy()
* Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING L"AAAAAAAAAA"
/* The two variables below are not defined as "const", but are never
assigned any other value, so a tool should be able to identify that
reads of these will always return their initialized values. */
static int staticTrue = 1; /* true */
static int staticFalse = 0; /* false */
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_05
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
data = NULL;
if(staticTrue)
{
/* FLAW: Did not leave space for a null terminator */
data = new wchar_t[10];
}
{
wchar_t source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
wcscpy(data, source);
printWLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */
static void goodG2B1()
{
wchar_t * data;
data = NULL;
if(staticFalse)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate space for a null terminator */
data = new wchar_t[10+1];
}
{
wchar_t source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
wcscpy(data, source);
printWLine(data);
delete [] data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
wchar_t * data;
data = NULL;
if(staticTrue)
{
/* FIX: Allocate space for a null terminator */
data = new wchar_t[10+1];
}
{
wchar_t source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
wcscpy(data, source);
printWLine(data);
delete [] data;
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#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 CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_05; /* 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
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "common.h"
#include "../Mocks/StorageEngineMock.h"
#if USE_ENTERPRISE
#include "Enterprise/Ldap/LdapFeature.h"
#endif
#include "Basics/files.h"
#include "Cluster/ClusterFeature.h"
#include "V8/v8-globals.h"
#include "V8Server/V8DealerFeature.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/LogicalView.h"
#include "VocBase/ManagedDocumentResult.h"
#include "Transaction/StandaloneContext.h"
#include "Utils/OperationOptions.h"
#include "Utils/SingleCollectionTransaction.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "IResearch/IResearchCommon.h"
#include "IResearch/IResearchFeature.h"
#include "IResearch/IResearchFilterFactory.h"
#include "IResearch/IResearchView.h"
#include "IResearch/IResearchAnalyzerFeature.h"
#include "Logger/Logger.h"
#include "Logger/LogTopic.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "RestServer/FlushFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/SystemDatabaseFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "Sharding/ShardingFeature.h"
#include "Basics/VelocyPackHelper.h"
#include "Aql/Ast.h"
#include "Aql/Query.h"
#include "3rdParty/iresearch/tests/tests_config.hpp"
#include "IResearch/VelocyPackHelper.h"
#include "analysis/analyzers.hpp"
#include "analysis/token_attributes.hpp"
#include "utils/utf8_path.hpp"
#include <velocypack/Iterator.h>
extern const char* ARGV0; // defined in main.cpp
namespace {
// -----------------------------------------------------------------------------
// --SECTION-- setup / tear-down
// -----------------------------------------------------------------------------
class IResearchQueryExistsTest : public ::testing::Test {
protected:
StorageEngineMock engine;
arangodb::application_features::ApplicationServer server;
std::vector<std::pair<arangodb::application_features::ApplicationFeature*, bool>> features;
IResearchQueryExistsTest(): engine(server), server(nullptr, nullptr) {
arangodb::EngineSelectorFeature::ENGINE = &engine;
arangodb::tests::init(true);
// suppress INFO {authentication} Authentication is turned on (system only), authentication for unix sockets is turned on
// suppress WARNING {authentication} --server.jwt-secret is insecure. Use --server.jwt-secret-keyfile instead
arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::ERR);
// suppress log messages since tests check error conditions
arangodb::LogTopic::setLogLevel(arangodb::Logger::AQL.name(), arangodb::LogLevel::ERR); // suppress WARNING {aql} Suboptimal AqlItemMatrix index lookup:
arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::ERR); // suppress WARNING DefaultCustomTypeHandler called
arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::FATAL);
irs::logger::output_le(iresearch::logger::IRL_FATAL, stderr);
// setup required application features
features.emplace_back(new arangodb::FlushFeature(server), false);
features.emplace_back(new arangodb::SystemDatabaseFeature(server), true); // required by IResearchFilterFactory::extractAnalyzerFromArg(...) and IResearchAnalyzerFeature
features.emplace_back(new arangodb::V8DealerFeature(server), false); // required for DatabaseFeature::createDatabase(...)
features.emplace_back(new arangodb::ViewTypesFeature(server), true);
features.emplace_back(new arangodb::AuthenticationFeature(server), true);
features.emplace_back(new arangodb::DatabasePathFeature(server), false);
features.emplace_back(new arangodb::DatabaseFeature(server), false);
features.emplace_back(new arangodb::ShardingFeature(server), false);
features.emplace_back(new arangodb::QueryRegistryFeature(server), false); // must be first
arangodb::application_features::ApplicationServer::server->addFeature(features.back().first); // need QueryRegistryFeature feature to be added now in order to create the system database
features.emplace_back(new arangodb::TraverserEngineRegistryFeature(server), false); // must be before AqlFeature
features.emplace_back(new arangodb::AqlFeature(server), true);
features.emplace_back(new arangodb::aql::OptimizerRulesFeature(server), true);
features.emplace_back(new arangodb::aql::AqlFunctionFeature(server), true); // required for IResearchAnalyzerFeature
features.emplace_back(new arangodb::iresearch::IResearchAnalyzerFeature(server), true);
features.emplace_back(new arangodb::iresearch::IResearchFeature(server), true);
#if USE_ENTERPRISE
features.emplace_back(new arangodb::LdapFeature(server), false); // required for AuthenticationFeature with USE_ENTERPRISE
#endif
// required for V8DealerFeature::prepare(), ClusterFeature::prepare() not required
arangodb::application_features::ApplicationServer::server->addFeature(
new arangodb::ClusterFeature(server)
);
for (auto& f : features) {
arangodb::application_features::ApplicationServer::server->addFeature(f.first);
}
for (auto& f : features) {
f.first->prepare();
}
auto const databases = VPackParser::fromJson(std::string("[ { \"name\": \"") + arangodb::StaticStrings::SystemDatabase + "\" } ]");
auto* dbFeature = arangodb::application_features::ApplicationServer::lookupFeature<
arangodb::DatabaseFeature
>("Database");
dbFeature->loadDatabases(databases->slice());
for (auto& f : features) {
if (f.second) {
f.first->start();
}
}
auto* analyzers = arangodb::application_features::ApplicationServer::lookupFeature<
arangodb::iresearch::IResearchAnalyzerFeature
>();
arangodb::iresearch::IResearchAnalyzerFeature::EmplaceResult result;
TRI_vocbase_t* vocbase;
dbFeature->createDatabase(1, "testVocbase", vocbase); // required for IResearchAnalyzerFeature::emplace(...)
analyzers->emplace(
result, "testVocbase::text_en", "text",
VPackParser::fromJson("{ \"locale\": \"en.UTF-8\", \"stopwords\": [ ] }")->slice(),
{ irs::frequency::type(), irs::norm::type(), irs::position::type() }); // cache analyzer
auto* dbPathFeature = arangodb::application_features::ApplicationServer::getFeature<arangodb::DatabasePathFeature>("DatabasePath");
arangodb::tests::setDatabasePath(*dbPathFeature); // ensure test data is stored in a unique directory
}
~IResearchQueryExistsTest() {
arangodb::AqlFeature(server).stop(); // unset singleton instance
arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::DEFAULT);
arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::DEFAULT);
arangodb::LogTopic::setLogLevel(arangodb::Logger::AQL.name(), arangodb::LogLevel::DEFAULT);
arangodb::application_features::ApplicationServer::server = nullptr;
// destroy application features
for (auto& f : features) {
if (f.second) {
f.first->stop();
}
}
for (auto& f : features) {
f.first->unprepare();
}
arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::DEFAULT);
arangodb::EngineSelectorFeature::ENGINE = nullptr;
}
}; // IResearchQuerySetup
}
// -----------------------------------------------------------------------------
// --SECTION-- test suite
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief setup
////////////////////////////////////////////////////////////////////////////////
TEST_F(IResearchQueryExistsTest, test) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, 1, "testVocbase");
std::vector<arangodb::velocypack::Builder> insertedDocs;
arangodb::LogicalView* view;
// create collection0
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testCollection0\" }");
auto collection = vocbase.createCollection(createJson->slice());
ASSERT_TRUE((nullptr != collection));
std::vector<std::shared_ptr<arangodb::velocypack::Builder>> docs {
VPackParser::fromJson("{ \"seq\": -6, \"value\": null }"),
VPackParser::fromJson("{ \"seq\": -5, \"value\": true }"),
VPackParser::fromJson("{ \"seq\": -4, \"value\": \"abc\" }"),
VPackParser::fromJson("{ \"seq\": -3, \"value\": 3.14 }"),
VPackParser::fromJson("{ \"seq\": -2, \"value\": [ 1, \"abc\" ] }"),
VPackParser::fromJson("{ \"seq\": -1, \"value\": { \"a\": 7, \"b\": \"c\" } }"),
};
arangodb::OperationOptions options;
options.returnNew = true;
arangodb::SingleCollectionTransaction trx(
arangodb::transaction::StandaloneContext::Create(vocbase),
*collection,
arangodb::AccessMode::Type::WRITE
);
EXPECT_TRUE((trx.begin().ok()));
for (auto& entry: docs) {
auto res = trx.insert(collection->name(), entry->slice(), options);
EXPECT_TRUE((res.ok()));
insertedDocs.emplace_back(res.slice().get("new"));
}
EXPECT_TRUE((trx.commit().ok()));
}
// create collection1
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testCollection1\" }");
auto collection = vocbase.createCollection(createJson->slice());
ASSERT_TRUE((nullptr != collection));
irs::utf8_path resource;
resource/=irs::string_ref(arangodb::tests::testResourceDir);
resource/=irs::string_ref("simple_sequential.json");
auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8());
auto slice = builder.slice();
ASSERT_TRUE(slice.isArray());
arangodb::OperationOptions options;
options.returnNew = true;
arangodb::SingleCollectionTransaction trx(
arangodb::transaction::StandaloneContext::Create(vocbase),
*collection,
arangodb::AccessMode::Type::WRITE
);
EXPECT_TRUE((trx.begin().ok()));
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto res = trx.insert(collection->name(), itr.value(), options);
EXPECT_TRUE((res.ok()));
insertedDocs.emplace_back(res.slice().get("new"));
}
EXPECT_TRUE((trx.commit().ok()));
}
// create view
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_TRUE((false == !logicalView));
view = logicalView.get();
auto* impl = dynamic_cast<arangodb::iresearch::IResearchView*>(view);
ASSERT_TRUE((false == !impl));
auto updateJson = VPackParser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, \"trackListPositions\": true, \"storeValues\": \"id\"},"
"\"testCollection1\": { \"includeAllFields\": true, \"storeValues\": \"id\" }"
"}}"
);
EXPECT_TRUE((impl->properties(updateJson->slice(), true).ok()));
std::set<TRI_voc_cid_t> cids;
impl->visitCollections([&cids](TRI_voc_cid_t cid)->bool { cids.emplace(cid); return true; });
EXPECT_TRUE((2 == cids.size()));
EXPECT_TRUE((arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH 1 ==1 OPTIONS { waitForSync: true } RETURN d").result.ok())); // commit
}
// test non-existent (any)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.missing) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (any) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['missing']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (bool)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (bool) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (boolean)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (boolean) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (numeric)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (numeric) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (null)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (null) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (string)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.seq, 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (string) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['seq'], 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (text analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.seq, 'analyzer', 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (text analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.seq, 'analyzer'), 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (analyzer) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['seq'], 'analyzer'), 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (array)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value[2]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (array) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'][2]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (object)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value.d) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (object) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']['d']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[0].slice(),
insertedDocs[1].slice(),
insertedDocs[2].slice(),
insertedDocs[3].slice(),
insertedDocs[4].slice(),
insertedDocs[5].slice(),
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[0].slice(),
insertedDocs[1].slice(),
insertedDocs[2].slice(),
insertedDocs[3].slice(),
insertedDocs[4].slice(),
insertedDocs[5].slice(),
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (bool)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (bool) with bound params
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\" }")
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (bool) with bound view name
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN @@testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\", \"@testView\": \"testView\" }")
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (bool) with invalid bound view name
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN @@testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\", \"@testView\": \"invlaidViewName\" }")
);
ASSERT_TRUE(result.result.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND));
}
// test existent (bool) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (boolean)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (boolean) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[1].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (numeric)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[3].slice(),
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (numeric) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[3].slice(),
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (numeric) via [], limit 5
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[3].slice(),
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice()
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq LIMIT 5 RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (null)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[0].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (null) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[0].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (string)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.value, 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any string)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.value, 'string'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any string)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any string) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['value'], 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['value'], 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (identity analyzer) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[2].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (array)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[4].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value[1]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (array) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[4].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'][1]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (object)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[5].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value.b) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (object) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[5].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']['b']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
}
TEST_F(IResearchQueryExistsTest, StoreMaskPartially) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, 1, "testVocbase");
std::vector<arangodb::velocypack::Builder> insertedDocs;
arangodb::LogicalView* view;
// create collection0
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testCollection0\" }");
auto collection = vocbase.createCollection(createJson->slice());
ASSERT_TRUE((nullptr != collection));
std::vector<std::shared_ptr<arangodb::velocypack::Builder>> docs {
VPackParser::fromJson("{ \"seq\": -6, \"value\": null }"),
VPackParser::fromJson("{ \"seq\": -5, \"value\": true }"),
VPackParser::fromJson("{ \"seq\": -4, \"value\": \"abc\" }"),
VPackParser::fromJson("{ \"seq\": -3, \"value\": 3.14 }"),
VPackParser::fromJson("{ \"seq\": -2, \"value\": [ 1, \"abc\" ] }"),
VPackParser::fromJson("{ \"seq\": -1, \"value\": { \"a\": 7, \"b\": \"c\" } }"),
};
arangodb::OperationOptions options;
options.returnNew = true;
arangodb::SingleCollectionTransaction trx(
arangodb::transaction::StandaloneContext::Create(vocbase),
*collection,
arangodb::AccessMode::Type::WRITE
);
EXPECT_TRUE((trx.begin().ok()));
for (auto& entry: docs) {
auto res = trx.insert(collection->name(), entry->slice(), options);
EXPECT_TRUE((res.ok()));
insertedDocs.emplace_back(res.slice().get("new"));
}
EXPECT_TRUE((trx.commit().ok()));
}
// create collection1
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testCollection1\" }");
auto collection = vocbase.createCollection(createJson->slice());
ASSERT_TRUE((nullptr != collection));
irs::utf8_path resource;
resource/=irs::string_ref(arangodb::tests::testResourceDir);
resource/=irs::string_ref("simple_sequential.json");
auto builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(resource.utf8());
auto slice = builder.slice();
ASSERT_TRUE(slice.isArray());
arangodb::OperationOptions options;
options.returnNew = true;
arangodb::SingleCollectionTransaction trx(
arangodb::transaction::StandaloneContext::Create(vocbase),
*collection,
arangodb::AccessMode::Type::WRITE
);
EXPECT_TRUE((trx.begin().ok()));
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto res = trx.insert(collection->name(), itr.value(), options);
EXPECT_TRUE((res.ok()));
insertedDocs.emplace_back(res.slice().get("new"));
}
EXPECT_TRUE((trx.commit().ok()));
}
// create view
{
auto createJson = VPackParser::fromJson("{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_TRUE((false == !logicalView));
view = logicalView.get();
auto* impl = dynamic_cast<arangodb::iresearch::IResearchView*>(view);
ASSERT_TRUE((false == !impl));
auto updateJson = VPackParser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, \"trackListPositions\": true },"
"\"testCollection1\": { \"includeAllFields\": true, \"storeValues\": \"id\" }"
"}}"
);
EXPECT_TRUE((impl->properties(updateJson->slice(), true).ok()));
std::set<TRI_voc_cid_t> cids;
impl->visitCollections([&cids](TRI_voc_cid_t cid)->bool { cids.emplace(cid); return true; });
EXPECT_TRUE((2 == cids.size()));
EXPECT_TRUE((arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH 1 ==1 OPTIONS { waitForSync: true } RETURN d").result.ok())); // commit
}
// test non-existent (any)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.missing) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (any) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['missing']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (bool)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (bool) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (boolean)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (boolean) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (numeric)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (numeric) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (null)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.name, 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (null) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['name'], 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (string)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.seq, 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (string) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['seq'], 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (text analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.seq, 'analyzer', 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (text analyzer)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.seq, 'analyzer'), 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (analyzer) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['seq'], 'analyzer'), 'text_en') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (array)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value[2]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (array) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'][2]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (object)
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value.d) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test non-existent (object) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']['d']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (any) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (bool)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (bool) with bound params
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\" }")
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (bool) with bound view name
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN @@testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\", \"@testView\": \"testView\" }")
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (bool) with invalid bound view name
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN @@testView SEARCH EXISTS(d.value, @type) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d",
VPackParser::fromJson("{ \"type\" : \"bool\", \"@testView\": \"invlaidViewName\" }")
);
ASSERT_TRUE(result.result.is(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND));
}
// test existent (bool) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'bool') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (boolean)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (boolean) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'boolean') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (numeric)
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (numeric) via []
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
insertedDocs[11].slice(),
insertedDocs[12].slice(),
insertedDocs[13].slice(),
insertedDocs[14].slice(),
insertedDocs[15].slice(),
insertedDocs[16].slice(),
insertedDocs[17].slice(),
insertedDocs[18].slice(),
insertedDocs[19].slice(),
insertedDocs[20].slice(),
insertedDocs[21].slice(),
insertedDocs[22].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (numeric) via [], limit 5
{
std::vector<arangodb::velocypack::Slice> expected = {
insertedDocs[6].slice(),
insertedDocs[7].slice(),
insertedDocs[8].slice(),
insertedDocs[9].slice(),
insertedDocs[10].slice(),
};
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'numeric') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq LIMIT 5 RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
size_t i = 0;
for (arangodb::velocypack::ArrayIterator itr(slice); itr.valid(); ++itr) {
auto const resolved = itr.value().resolveExternals();
EXPECT_TRUE((i < expected.size()));
EXPECT_TRUE((0 == arangodb::basics::VelocyPackHelper::compare(expected[i++], resolved, true)));
}
EXPECT_TRUE((i == expected.size()));
}
// test existent (null)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (null) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'null') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (string)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.value, 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (any string)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d.value, 'string'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (any string)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (any string) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'string') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value, 'analyzer') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['value'], 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH ANALYZER(EXISTS(d['value'], 'analyzer'), 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (identity analyzer) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'], 'analyzer', 'identity') SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (array)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value[1]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (array) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value'][1]) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (object)
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d.value.b) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
// test existent (object) via []
{
auto result = arangodb::tests::executeQuery(
vocbase,
"FOR d IN testView SEARCH EXISTS(d['value']['b']) SORT BM25(d) ASC, TFIDF(d) DESC, d.seq RETURN d"
);
ASSERT_TRUE(result.result.ok());
auto slice = result.data->slice();
EXPECT_TRUE(slice.isArray());
EXPECT_TRUE(0 == slice.length());
}
}
|
#include "home_mpdualarmwid.h"
#include "ui_home_mpdualarmwid.h"
Home_MpduAlarmWid::Home_MpduAlarmWid(QWidget *parent) :
QWidget(parent),
ui(new Ui::Home_MpduAlarmWid)
{
ui->setupUi(this);
set_background_icon(this,":/image/back.jpg");
QTimer::singleShot(15,this,SLOT(initFunSlot()));
}
Home_MpduAlarmWid::~Home_MpduAlarmWid()
{
delete ui;
}
void Home_MpduAlarmWid::initFunSlot()
{
mItem = Cfg::bulid()->item;
mObj = Dev_Mpdu::bulid(this);
mDev = mObj->getDev();
initData();
}
void Home_MpduAlarmWid::initData()
{
sObjCfg *obj = &(mDev->cfg);
ui->outputMinSpin->setValue(obj->output.min);
ui->outputMaxSpin->setValue(obj->output.max);
ui->outputCrMinSpin->setValue(obj->output.crMin);
ui->outputCrMaxSpin->setValue(obj->output.crMax);
ui->curMinSpin->setValue(obj->cur.min);
ui->curMaxSpin->setValue(obj->cur.max);
ui->curCrMinSpin->setValue(obj->cur.crMin);
ui->curCrMaxSpin->setValue(obj->cur.crMax);
ui->volMinSpin->setValue(obj->vol.min);
ui->volMaxSpin->setValue(obj->vol.max);
ui->temMinSpin->setValue(obj->tem.min);
ui->temMaxSpin->setValue(obj->tem.max);
ui->humMinSpin->setValue(obj->hum.min);
ui->humMaxSpin->setValue(obj->hum.max);
ui->ratedVolSpin->setValue(obj->rateVol);
}
void Home_MpduAlarmWid::updateData()
{
sObjCfg *obj = &(mDev->cfg);
obj->output.min = ui->outputMinSpin->value();
obj->output.max = ui->outputMaxSpin->value();
obj->output.crMin = ui->outputCrMinSpin->value();
obj->output.crMax = ui->outputCrMaxSpin->value();
obj->cur.min = ui->curMinSpin->value();
obj->cur.max = ui->curMaxSpin->value();
obj->cur.crMin = ui->curCrMinSpin->value();
obj->cur.crMax = ui->curCrMaxSpin->value();
obj->vol.min = ui->volMinSpin->value();
obj->vol.max = ui->volMaxSpin->value();
obj->tem.min = ui->temMinSpin->value();
obj->tem.max = ui->temMaxSpin->value();
obj->hum.min = ui->humMinSpin->value();
obj->hum.max = ui->humMaxSpin->value();
obj->rateVol = ui->ratedVolSpin->value();
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/bookmarks/bookmark_utils.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/ui/app_list/app_list_util.h"
#include "chrome/browser/ui/bookmarks/bookmark_editor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/simple_message_box.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_node_data.h"
#include "components/search/search.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/web_contents.h"
#include "net/base/net_util.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension_set.h"
#endif
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
namespace chrome {
int num_bookmark_urls_before_prompting = 15;
namespace {
// The ways in which extensions may customize the bookmark shortcut.
enum BookmarkShortcutDisposition {
BOOKMARK_SHORTCUT_DISPOSITION_UNCHANGED,
BOOKMARK_SHORTCUT_DISPOSITION_REMOVED,
BOOKMARK_SHORTCUT_DISPOSITION_OVERRIDE_REQUESTED
};
// Iterator that iterates through a set of BookmarkNodes returning the URLs
// for nodes that are urls, or the URLs for the children of non-url urls.
// This does not recurse through all descendants, only immediate children.
// The following illustrates
// typical usage:
// OpenURLIterator iterator(nodes);
// while (iterator.has_next()) {
// const GURL* url = iterator.NextURL();
// // do something with |urll|.
// }
class OpenURLIterator {
public:
explicit OpenURLIterator(const std::vector<const BookmarkNode*>& nodes)
: child_index_(0),
next_(NULL),
parent_(nodes.begin()),
end_(nodes.end()) {
FindNext();
}
bool has_next() { return next_ != NULL;}
const GURL* NextURL() {
if (!has_next()) {
NOTREACHED();
return NULL;
}
const GURL* next = next_;
FindNext();
return next;
}
private:
// Seach next node which has URL.
void FindNext() {
for (; parent_ < end_; ++parent_, child_index_ = 0) {
if ((*parent_)->is_url()) {
next_ = &(*parent_)->url();
++parent_;
child_index_ = 0;
return;
} else {
for (; child_index_ < (*parent_)->child_count(); ++child_index_) {
const BookmarkNode* child = (*parent_)->GetChild(child_index_);
if (child->is_url()) {
next_ = &child->url();
++child_index_;
return;
}
}
}
}
next_ = NULL;
}
int child_index_;
const GURL* next_;
std::vector<const BookmarkNode*>::const_iterator parent_;
const std::vector<const BookmarkNode*>::const_iterator end_;
DISALLOW_COPY_AND_ASSIGN(OpenURLIterator);
};
bool ShouldOpenAll(gfx::NativeWindow parent,
const std::vector<const BookmarkNode*>& nodes) {
int child_count = 0;
OpenURLIterator iterator(nodes);
while (iterator.has_next()) {
iterator.NextURL();
child_count++;
}
if (child_count < num_bookmark_urls_before_prompting)
return true;
return ShowMessageBox(parent,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
l10n_util::GetStringFUTF16(IDS_BOOKMARK_BAR_SHOULD_OPEN_ALL,
base::IntToString16(child_count)),
MESSAGE_BOX_TYPE_QUESTION) == MESSAGE_BOX_RESULT_YES;
}
// Returns the total number of descendants nodes.
int ChildURLCountTotal(const BookmarkNode* node) {
int result = 0;
for (int i = 0; i < node->child_count(); ++i) {
const BookmarkNode* child = node->GetChild(i);
result++;
if (child->is_folder())
result += ChildURLCountTotal(child);
}
return result;
}
// Returns in |urls|, the url and title pairs for each open tab in browser.
void GetURLsForOpenTabs(Browser* browser,
std::vector<std::pair<GURL, base::string16> >* urls) {
for (int i = 0; i < browser->tab_strip_model()->count(); ++i) {
std::pair<GURL, base::string16> entry;
GetURLAndTitleToBookmark(browser->tab_strip_model()->GetWebContentsAt(i),
&(entry.first), &(entry.second));
urls->push_back(entry);
}
}
// Indicates how the bookmark shortcut has been changed by extensions associated
// with |profile|, if at all.
BookmarkShortcutDisposition GetBookmarkShortcutDisposition(Profile* profile) {
#if defined(ENABLE_EXTENSIONS)
extensions::CommandService* command_service =
extensions::CommandService::Get(profile);
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile);
if (!registry)
return BOOKMARK_SHORTCUT_DISPOSITION_UNCHANGED;
const extensions::ExtensionSet& extension_set =
registry->enabled_extensions();
// This flag tracks whether any extension wants the disposition to be
// removed.
bool removed = false;
for (extensions::ExtensionSet::const_iterator i = extension_set.begin();
i != extension_set.end();
++i) {
// Use the overridden disposition if any extension wants it.
if (command_service->RequestsBookmarkShortcutOverride(i->get()))
return BOOKMARK_SHORTCUT_DISPOSITION_OVERRIDE_REQUESTED;
if (!removed &&
extensions::CommandService::RemovesBookmarkShortcut(i->get())) {
removed = true;
}
}
if (removed)
return BOOKMARK_SHORTCUT_DISPOSITION_REMOVED;
#endif
return BOOKMARK_SHORTCUT_DISPOSITION_UNCHANGED;
}
} // namespace
void OpenAll(gfx::NativeWindow parent,
content::PageNavigator* navigator,
const std::vector<const BookmarkNode*>& nodes,
WindowOpenDisposition initial_disposition,
content::BrowserContext* browser_context) {
if (!ShouldOpenAll(parent, nodes))
return;
// Opens all |nodes| of type URL and any children of |nodes| that are of type
// URL. |navigator| is the PageNavigator used to open URLs. After the first
// url is opened |opened_first_url| is set to true and |navigator| is set to
// the PageNavigator of the last active tab. This is done to handle a window
// disposition of new window, in which case we want subsequent tabs to open in
// that window.
bool opened_first_url = false;
WindowOpenDisposition disposition = initial_disposition;
OpenURLIterator iterator(nodes);
while (iterator.has_next()) {
const GURL* url = iterator.NextURL();
// When |initial_disposition| is OFF_THE_RECORD, a node which can't be
// opened in incognito window, it is detected using |browser_context|, is
// not opened.
if (initial_disposition == OFF_THE_RECORD &&
!IsURLAllowedInIncognito(*url, browser_context))
continue;
content::WebContents* opened_tab = navigator->OpenURL(
content::OpenURLParams(*url, content::Referrer(), disposition,
ui::PAGE_TRANSITION_AUTO_BOOKMARK, false));
if (!opened_first_url) {
opened_first_url = true;
disposition = NEW_BACKGROUND_TAB;
// We opened the first URL which may have opened a new window or clobbered
// the current page, reset the navigator just to be sure. |opened_tab| may
// be NULL in tests.
if (opened_tab)
navigator = opened_tab;
}
}
}
void OpenAll(gfx::NativeWindow parent,
content::PageNavigator* navigator,
const BookmarkNode* node,
WindowOpenDisposition initial_disposition,
content::BrowserContext* browser_context) {
std::vector<const BookmarkNode*> nodes;
nodes.push_back(node);
OpenAll(parent, navigator, nodes, initial_disposition, browser_context);
}
bool ConfirmDeleteBookmarkNode(const BookmarkNode* node,
gfx::NativeWindow window) {
DCHECK(node && node->is_folder() && !node->empty());
return ShowMessageBox(window,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
l10n_util::GetStringFUTF16Int(IDS_BOOKMARK_EDITOR_CONFIRM_DELETE,
ChildURLCountTotal(node)),
MESSAGE_BOX_TYPE_QUESTION) == MESSAGE_BOX_RESULT_YES;
}
void ShowBookmarkAllTabsDialog(Browser* browser) {
Profile* profile = browser->profile();
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
DCHECK(model && model->loaded());
const BookmarkNode* parent = model->GetParentForNewNodes();
BookmarkEditor::EditDetails details =
BookmarkEditor::EditDetails::AddFolder(parent, parent->child_count());
GetURLsForOpenTabs(browser, &(details.urls));
DCHECK(!details.urls.empty());
BookmarkEditor::Show(browser->window()->GetNativeWindow(), profile, details,
BookmarkEditor::SHOW_TREE);
}
bool HasBookmarkURLs(const std::vector<const BookmarkNode*>& selection) {
OpenURLIterator iterator(selection);
return iterator.has_next();
}
bool HasBookmarkURLsAllowedInIncognitoMode(
const std::vector<const BookmarkNode*>& selection,
content::BrowserContext* browser_context) {
OpenURLIterator iterator(selection);
while (iterator.has_next()) {
const GURL* url = iterator.NextURL();
if (IsURLAllowedInIncognito(*url, browser_context))
return true;
}
return false;
}
GURL GetURLToBookmark(content::WebContents* web_contents) {
DCHECK(web_contents);
return IsInstantNTP(web_contents) ?
GURL(kChromeUINewTabURL) : web_contents->GetURL();
}
void GetURLAndTitleToBookmark(content::WebContents* web_contents,
GURL* url,
base::string16* title) {
*url = GetURLToBookmark(web_contents);
*title = web_contents->GetTitle();
}
void ToggleBookmarkBarWhenVisible(content::BrowserContext* browser_context) {
PrefService* prefs = user_prefs::UserPrefs::Get(browser_context);
const bool always_show =
!prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar);
// The user changed when the bookmark bar is shown, update the preferences.
prefs->SetBoolean(bookmarks::prefs::kShowBookmarkBar, always_show);
}
base::string16 FormatBookmarkURLForDisplay(const GURL& url,
const PrefService* prefs) {
std::string languages;
if (prefs)
languages = prefs->GetString(prefs::kAcceptLanguages);
// Because this gets re-parsed by FixupURL(), it's safe to omit the scheme
// and trailing slash, and unescape most characters. However, it's
// important not to drop any username/password, or unescape anything that
// changes the URL's meaning.
return net::FormatUrl(
url, languages,
net::kFormatUrlOmitAll & ~net::kFormatUrlOmitUsernamePassword,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
}
bool IsAppsShortcutEnabled(Profile* profile,
chrome::HostDesktopType host_desktop_type) {
// Supervised users can not have apps installed currently so there's no need
// to show the apps shortcut.
if (profile->IsSupervised())
return false;
// Don't show the apps shortcut in ash since the app launcher is enabled.
if (host_desktop_type == chrome::HOST_DESKTOP_TYPE_ASH)
return false;
return chrome::IsInstantExtendedAPIEnabled() && !profile->IsOffTheRecord();
}
bool ShouldShowAppsShortcutInBookmarkBar(
Profile* profile,
chrome::HostDesktopType host_desktop_type) {
return IsAppsShortcutEnabled(profile, host_desktop_type) &&
profile->GetPrefs()->GetBoolean(
bookmarks::prefs::kShowAppsShortcutInBookmarkBar);
}
bool ShouldRemoveBookmarkThisPageUI(Profile* profile) {
return GetBookmarkShortcutDisposition(profile) ==
BOOKMARK_SHORTCUT_DISPOSITION_REMOVED;
}
bool ShouldRemoveBookmarkOpenPagesUI(Profile* profile) {
#if defined(ENABLE_EXTENSIONS)
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile);
if (!registry)
return false;
const extensions::ExtensionSet& extension_set =
registry->enabled_extensions();
for (extensions::ExtensionSet::const_iterator i = extension_set.begin();
i != extension_set.end();
++i) {
if (extensions::CommandService::RemovesBookmarkOpenPagesShortcut(i->get()))
return true;
}
#endif
return false;
}
int GetBookmarkDragOperation(content::BrowserContext* browser_context,
const BookmarkNode* node) {
PrefService* prefs = user_prefs::UserPrefs::Get(browser_context);
Profile* profile = Profile::FromBrowserContext(browser_context);
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
int move = ui::DragDropTypes::DRAG_MOVE;
if (!prefs->GetBoolean(bookmarks::prefs::kEditBookmarksEnabled) ||
!model->client()->CanBeEditedByUser(node)) {
move = ui::DragDropTypes::DRAG_NONE;
}
if (node->is_url())
return ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK | move;
return ui::DragDropTypes::DRAG_COPY | move;
}
int GetPreferredBookmarkDropOperation(int source_operations, int operations) {
int common_ops = (source_operations & operations);
if (!common_ops)
return ui::DragDropTypes::DRAG_NONE;
if (ui::DragDropTypes::DRAG_COPY & common_ops)
return ui::DragDropTypes::DRAG_COPY;
if (ui::DragDropTypes::DRAG_LINK & common_ops)
return ui::DragDropTypes::DRAG_LINK;
if (ui::DragDropTypes::DRAG_MOVE & common_ops)
return ui::DragDropTypes::DRAG_MOVE;
return ui::DragDropTypes::DRAG_NONE;
}
int GetBookmarkDropOperation(Profile* profile,
const ui::DropTargetEvent& event,
const bookmarks::BookmarkNodeData& data,
const BookmarkNode* parent,
int index) {
const base::FilePath& profile_path = profile->GetPath();
if (data.IsFromProfilePath(profile_path) && data.size() > 1)
// Currently only accept one dragged node at a time.
return ui::DragDropTypes::DRAG_NONE;
if (!IsValidBookmarkDropLocation(profile, data, parent, index))
return ui::DragDropTypes::DRAG_NONE;
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
if (!model->client()->CanBeEditedByUser(parent))
return ui::DragDropTypes::DRAG_NONE;
const BookmarkNode* dragged_node =
data.GetFirstNode(model, profile->GetPath());
if (dragged_node) {
// User is dragging from this profile.
if (!model->client()->CanBeEditedByUser(dragged_node)) {
// Do a copy instead of a move when dragging bookmarks that the user can't
// modify.
return ui::DragDropTypes::DRAG_COPY;
}
return ui::DragDropTypes::DRAG_MOVE;
}
// User is dragging from another app, copy.
return GetPreferredBookmarkDropOperation(event.source_operations(),
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK);
}
bool IsValidBookmarkDropLocation(Profile* profile,
const bookmarks::BookmarkNodeData& data,
const BookmarkNode* drop_parent,
int index) {
if (!drop_parent->is_folder()) {
NOTREACHED();
return false;
}
if (!data.is_valid())
return false;
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
if (!model->client()->CanBeEditedByUser(drop_parent))
return false;
const base::FilePath& profile_path = profile->GetPath();
if (data.IsFromProfilePath(profile_path)) {
std::vector<const BookmarkNode*> nodes = data.GetNodes(model, profile_path);
for (size_t i = 0; i < nodes.size(); ++i) {
// Don't allow the drop if the user is attempting to drop on one of the
// nodes being dragged.
const BookmarkNode* node = nodes[i];
int node_index = (drop_parent == node->parent()) ?
drop_parent->GetIndexOf(nodes[i]) : -1;
if (node_index != -1 && (index == node_index || index == node_index + 1))
return false;
// drop_parent can't accept a child that is an ancestor.
if (drop_parent->HasAncestor(node))
return false;
}
return true;
}
// From another profile, always accept.
return true;
}
} // namespace chrome
|
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <chrono>
#include <condition_variable>
#include <ctime>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include "log.h"
using namespace std;
using namespace logger;
void logger::default_logger_handler_func(const string& s)
{
cout << s + "\n";
}
LogHelper::LogHelper(LOG_TYPE type,
const char* file,
int line,
function<void(const string&)> handler_func)
: m_handler_func(handler_func)
{
switch (type)
{
case LOG_TYPE::_LOG_TYPE_ERROR: m_stream << "[ERR] "; break;
case LOG_TYPE::_LOG_TYPE_WARNING: m_stream << "[WARN] "; break;
case LOG_TYPE::_LOG_TYPE_INFO: m_stream << "[INFO] "; break;
case LOG_TYPE::_LOG_TYPE_DEBUG: m_stream << "[DEBUG] "; break;
}
time_t tt = chrono::system_clock::to_time_t(chrono::system_clock::now());
auto tm = gmtime(&tt);
if (tm)
{
char buffer[256];
strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%Sz", tm);
m_stream << buffer << " ";
}
m_stream << file;
m_stream << " " << line;
m_stream << "\t";
}
LogHelper::~LogHelper()
{
if (m_handler_func)
{
m_handler_func(m_stream.str());
}
// Logger::log_item(m_stream.str());
}
#if defined(__linux) || defined(__APPLE__)
std::string logger::get_timestamp()
{
// get current time
auto now = std::chrono::system_clock::now();
// get number of nanoseconds for the current second
// (remainder after division into seconds)
auto ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()) % 1000000;
// convert to std::time_t in order to convert to std::tm (broken time)
auto timer = std::chrono::system_clock::to_time_t(now);
// convert to broken time
char buffer[256];
buffer[0] = 0;
std::tm* bt = std::localtime(&timer);
if (bt)
{
strftime(buffer, sizeof(buffer), "%H:%M:%S", bt);
}
std::ostringstream timestamp;
timestamp << buffer;
timestamp << '.' << std::setfill('0') << std::setw(3) << ns.count();
return timestamp.str();
}
void logger::LogPrintf(const char* fmt, ...)
{
va_list args1;
va_start(args1, fmt);
va_list args2;
va_copy(args2, args1);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
std::vector<char> buf(1 + std::vsnprintf(nullptr, 0, fmt, args1));
va_end(args1);
std::vsnprintf(buf.data(), buf.size(), fmt, args2);
#pragma GCC diagnostic pop
va_end(args2);
#ifdef NGRAPH_DISTRIBUTED_ENABLE
logger::Distributed dist;
std::printf("%s [RANK: %d]: %s\n", get_timestamp().c_str(), dist.get_rank(), buf.data());
#else
std::printf("%s %s\n", get_timestamp().c_str(), buf.data());
#endif
}
// This function will be executed only once during startup (loading of the DSO)
static bool CheckLoggingLevel()
{
if (std::getenv("NGRAPH_DISABLE_LOGGING") != nullptr)
{
return true;
}
return false;
}
bool logger::DISABLE_LOGGING = CheckLoggingLevel();
#endif
|
/*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* This shows an example on how to use on_edges syntax with multiple input fields
* (with location type edge) that are needed in the reduction over the edges of a cell
* An typical operator that needs this functionality is the divergence where we need
* sum_reduce(edges) {sign_edge * lengh_edge}
* The sign of the edge indicates whether flows go inward or outward (with respect the center of the cell).
*/
#include <gtest/gtest.h>
#include <gridtools/stencil_composition/stencil_composition.hpp>
#include <gridtools/tools/regression_fixture.hpp>
#include "neighbours_of.hpp"
using namespace gridtools;
struct test_on_edges_functor {
using in1 = in_accessor<0, enumtype::edges, extent<1, -1, 1, -1>>;
using in2 = in_accessor<1, enumtype::edges, extent<1, -1, 1, -1>>;
using out = inout_accessor<2, enumtype::edges>;
using param_list = make_param_list<in1, in2, out>;
using location = enumtype::edges;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation eval) {
eval(out{}) = eval(
on_edges([](float_type in1, float_type in2, float_type res) { return in1 + in2 * float_type{.1} + res; },
float_type{},
in1{},
in2{}));
}
};
using stencil_on_edges_multiplefields = regression_fixture<1>;
TEST_F(stencil_on_edges_multiplefields, test) {
auto in1 = [](int_t i, int_t c, int_t j, int_t k) { return i + c + j + k; };
auto in2 = [](int_t i, int_t c, int_t j, int_t k) { return i / 2 + c + j / 2 + k / 2; };
auto ref = [=](int_t i, int_t c, int_t j, int_t k) {
float_type res{};
for (auto &&item : neighbours_of<edges, edges>(i, c, j, k))
res += item.call(in1) + .1 * item.call(in2);
return res;
};
arg<0, edges> p_in1;
arg<1, edges> p_in2;
arg<2, edges> p_out;
auto out = make_storage<edges>();
auto comp = make_computation(p_in1 = make_storage<edges>(in1),
p_in2 = make_storage<edges>(in2),
p_out = out,
make_multistage(execute::forward(), make_stage<test_on_edges_functor>(p_in1, p_in2, p_out)));
comp.run();
verify(make_storage<edges>(ref), out);
benchmark(comp);
}
|
// Copyright (c) 2014-2018, The Monero Project
//
// 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 of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER 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 <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string.hpp>
#include "common/command_line.h"
#include "common/varint.h"
#include "cryptonote_core/tx_pool.h"
#include "cryptonote_core/cryptonote_core.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/blockchain_db.h"
#include "blockchain_db/db_types.h"
#include "version.h"
#undef EVOLUTION_DEFAULT_LOG_CATEGORY
#define EVOLUTION_DEFAULT_LOG_CATEGORY "bcutil"
namespace po = boost::program_options;
using namespace epee;
using namespace cryptonote;
struct output_data
{
uint64_t amount;
uint64_t index;
mutable bool coinbase;
mutable uint64_t height;
output_data(uint64_t a, uint64_t i, bool cb, uint64_t h): amount(a), index(i), coinbase(cb), height(h) {}
bool operator==(const output_data &other) const { return other.amount == amount && other.index == index; }
void info(bool c, uint64_t h) const { coinbase = c; height =h; }
};
namespace std
{
template<> struct hash<output_data>
{
size_t operator()(const output_data &od) const
{
const uint64_t data[2] = {od.amount, od.index};
crypto::hash h;
crypto::cn_fast_hash(data, 2 * sizeof(uint64_t), h);
return reinterpret_cast<const std::size_t &>(h);
}
};
}
struct reference
{
uint64_t height;
uint64_t ring_size;
uint64_t position;
reference(uint64_t h, uint64_t rs, uint64_t p): height(h), ring_size(rs), position(p) {}
};
int main(int argc, char* argv[])
{
TRY_ENTRY();
epee::string_tools::set_module_name_and_folder(argv[0]);
std::string default_db_type = "lmdb";
std::string available_dbs = cryptonote::blockchain_db_types(", ");
available_dbs = "available: " + available_dbs;
uint32_t log_level = 0;
tools::on_startup();
boost::filesystem::path output_file_path;
po::options_description desc_cmd_only("Command line options");
po::options_description desc_cmd_sett("Command line options and settings options");
const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
const command_line::arg_descriptor<std::string> arg_database = {
"database", available_dbs.c_str(), default_db_type
};
const command_line::arg_descriptor<bool> arg_rct_only = {"rct-only", "Only work on ringCT outputs", false};
const command_line::arg_descriptor<std::string> arg_input = {"input", ""};
command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
command_line::add_arg(desc_cmd_sett, arg_log_level);
command_line::add_arg(desc_cmd_sett, arg_database);
command_line::add_arg(desc_cmd_sett, arg_rct_only);
command_line::add_arg(desc_cmd_sett, arg_input);
command_line::add_arg(desc_cmd_only, command_line::arg_help);
po::options_description desc_options("Allowed options");
desc_options.add(desc_cmd_only).add(desc_cmd_sett);
po::positional_options_description positional_options;
positional_options.add(arg_input.name, -1);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_options, [&]()
{
auto parser = po::command_line_parser(argc, argv).options(desc_options).positional(positional_options);
po::store(parser.run(), vm);
po::notify(vm);
return true;
});
if (! r)
return 1;
if (command_line::get_arg(vm, command_line::arg_help))
{
std::cout << "Evolution '" << EVOLUTION_RELEASE_NAME << "' (v" << EVOLUTION_VERSION_FULL << ")" << ENDL << ENDL;
std::cout << desc_options << std::endl;
return 1;
}
mlog_configure(mlog_get_default_log_path("evolution-blockchain-usage.log"), true);
if (!command_line::is_arg_defaulted(vm, arg_log_level))
mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
else
mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
LOG_PRINT_L0("Starting...");
bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
bool opt_rct_only = command_line::get_arg(vm, arg_rct_only);
std::string db_type = command_line::get_arg(vm, arg_database);
if (!cryptonote::blockchain_valid_db_type(db_type))
{
std::cerr << "Invalid database type: " << db_type << std::endl;
return 1;
}
// If we wanted to use the memory pool, we would set up a fake_core.
// Use Blockchain instead of lower-level BlockchainDB for two reasons:
// 1. Blockchain has the init() method for easy setup
// 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
//
// cannot match blockchain_storage setup above with just one line,
// e.g.
// Blockchain* core_storage = new Blockchain(NULL);
// because unlike blockchain_storage constructor, which takes a pointer to
// tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
const std::string input = command_line::get_arg(vm, arg_input);
std::unique_ptr<Blockchain> core_storage;
tx_memory_pool m_mempool(*core_storage);
core_storage.reset(new Blockchain(m_mempool));
BlockchainDB* db = new_db(db_type);
if (db == NULL)
{
LOG_ERROR("Attempted to use non-existent database type: " << db_type);
throw std::runtime_error("Attempting to use non-existent database type");
}
LOG_PRINT_L0("database: " << db_type);
const std::string filename = input;
LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
try
{
db->open(filename, DBF_RDONLY);
}
catch (const std::exception& e)
{
LOG_PRINT_L0("Error opening database: " << e.what());
return 1;
}
r = core_storage->init(db, net_type);
CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
LOG_PRINT_L0("Source blockchain storage initialized OK");
LOG_PRINT_L0("Building usage patterns...");
size_t done = 0;
std::unordered_map<output_data, std::list<reference>> outputs;
std::unordered_map<uint64_t,uint64_t> indices;
LOG_PRINT_L0("Reading blockchain from " << input);
core_storage->for_all_transactions([&](const crypto::hash &hash, const cryptonote::transaction &tx)->bool
{
const bool coinbase = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
const uint64_t height = core_storage->get_db().get_tx_block_height(hash);
// create new outputs
for (const auto &out: tx.vout)
{
if (opt_rct_only && out.amount)
continue;
uint64_t index = indices[out.amount]++;
output_data od(out.amount, indices[out.amount], coinbase, height);
auto itb = outputs.emplace(od, std::list<reference>());
itb.first->first.info(coinbase, height);
}
for (const auto &in: tx.vin)
{
if (in.type() != typeid(txin_to_key))
continue;
const auto &txin = boost::get<txin_to_key>(in);
if (opt_rct_only && txin.amount != 0)
continue;
const std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
for (size_t n = 0; n < txin.key_offsets.size(); ++n)
{
output_data od(txin.amount, absolute[n], coinbase, height);
outputs[od].push_back(reference(height, txin.key_offsets.size(), n));
}
}
return true;
}, true);
std::unordered_map<uint64_t, uint64_t> counts;
size_t total = 0;
for (const auto &out: outputs)
{
counts[out.second.size()]++;
total++;
}
if (total > 0)
{
for (const auto &c: counts)
{
float percent = 100.f * c.second / total;
MINFO(std::to_string(c.second) << " outputs used " << c.first << " times (" << percent << "%)");
}
}
else
{
MINFO("No outputs to process");
}
LOG_PRINT_L0("Blockchain usage exported OK");
return 0;
CATCH_ENTRY("Export error", 1);
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml
Template File: sources-sink-82a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sinks: loop
* BadSink : Copy data to string using a loop
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82.h"
namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
data = (wchar_t *)malloc(100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
wmemset(data, L'A', 100-1); /* fill with L'A's */
data[100-1] = L'\0'; /* null terminate */
CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82_base* baseObject = new CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82_bad;
baseObject->action(data);
delete baseObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
data = (wchar_t *)malloc(100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_82_base* baseObject = new CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_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 CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_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
|
//=================================================================================================
/*!
// \file src/mathtest/dvecsveccross/VHaVCb.cpp
// \brief Source file for the VHaVCb dense vector/sparse vector cross product math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/HybridVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecsveccross/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHaVCb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
typedef blaze::HybridVector<TypeA,3UL> VHa;
typedef blaze::CompressedVector<TypeB> VCb;
// Creator type definitions
typedef blazetest::Creator<VHa> CVHa;
typedef blazetest::Creator<VCb> CVCb;
// Running the tests
for( size_t i=0UL; i<=3UL; ++i ) {
RUN_DVECSVECCROSS_OPERATION_TEST( CVHa( 3UL ), CVCb( 3UL, i ) );
}
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/sparse vector cross product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/************************************************************************
Net.cc
************************************************************************/
#include "P_Net.h"
#include <utility>
RecRawStatBlock *net_rsb = nullptr;
// All in milli-seconds
int net_config_poll_timeout = -1; // This will get set via either command line or records.config.
int net_event_period = 10;
int net_accept_period = 10;
int net_retry_delay = 10;
int net_throttle_delay = 50; /* milliseconds */
static inline void
configure_net()
{
REC_RegisterConfigUpdateFunc("proxy.config.net.connections_throttle", change_net_connections_throttle, nullptr);
REC_ReadConfigInteger(fds_throttle, "proxy.config.net.connections_throttle");
REC_EstablishStaticConfigInt32(net_retry_delay, "proxy.config.net.retry_delay");
REC_EstablishStaticConfigInt32(net_throttle_delay, "proxy.config.net.throttle_delay");
// These are not reloadable
REC_ReadConfigInteger(net_event_period, "proxy.config.net.event_period");
REC_ReadConfigInteger(net_accept_period, "proxy.config.net.accept_period");
}
static inline void
register_net_stats()
{
const std::pair<const char *, Net_Stats> persistent[] = {
{"proxy.process.net.calls_to_read", net_calls_to_read_stat},
{"proxy.process.net.calls_to_read_nodata", net_calls_to_read_nodata_stat},
{"proxy.process.net.calls_to_readfromnet", net_calls_to_readfromnet_stat},
{"proxy.process.net.calls_to_readfromnet_afterpoll", net_calls_to_readfromnet_afterpoll_stat},
{"proxy.process.net.calls_to_write", net_calls_to_write_stat},
{"proxy.process.net.calls_to_write_nodata", net_calls_to_write_nodata_stat},
{"proxy.process.net.calls_to_writetonet", net_calls_to_writetonet_stat},
{"proxy.process.net.calls_to_writetonet_afterpoll", net_calls_to_writetonet_afterpoll_stat},
{"proxy.process.net.inactivity_cop_lock_acquire_failure", inactivity_cop_lock_acquire_failure_stat},
{"proxy.process.net.net_handler_run", net_handler_run_stat},
{"proxy.process.net.read_bytes", net_read_bytes_stat},
{"proxy.process.net.write_bytes", net_write_bytes_stat},
{"proxy.process.net.fastopen_out.attempts", net_fastopen_attempts_stat},
{"proxy.process.net.fastopen_out.successes", net_fastopen_successes_stat},
{"proxy.process.socks.connections_successful", socks_connections_successful_stat},
{"proxy.process.socks.connections_unsuccessful", socks_connections_unsuccessful_stat},
};
const std::pair<const char *, Net_Stats> non_persistent[] = {
{"proxy.process.net.accepts_currently_open", net_accepts_currently_open_stat},
{"proxy.process.net.connections_currently_open", net_connections_currently_open_stat},
{"proxy.process.net.default_inactivity_timeout_applied", default_inactivity_timeout_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_count", keep_alive_queue_timeout_count_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_total", keep_alive_queue_timeout_total_stat},
{"proxy.process.socks.connections_currently_open", socks_connections_currently_open_stat},
};
for (auto &p : persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_PERSISTENT, p.second, RecRawStatSyncSum);
}
for (auto &p : non_persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_NON_PERSISTENT, p.second, RecRawStatSyncSum);
}
NET_CLEAR_DYN_STAT(net_handler_run_stat);
NET_CLEAR_DYN_STAT(net_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(net_accepts_currently_open_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_nodata_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_nodata_stat);
NET_CLEAR_DYN_STAT(socks_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_total_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_count_stat);
NET_CLEAR_DYN_STAT(default_inactivity_timeout_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.tcp.total_accepts", RECD_INT, RECP_NON_PERSISTENT,
static_cast<int>(net_tcp_accept_stat), RecRawStatSyncSum);
NET_CLEAR_DYN_STAT(net_tcp_accept_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_in", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_in_stat, RecRawStatSyncSum);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_out", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_out_stat, RecRawStatSyncSum);
}
void
ink_net_init(ModuleVersion version)
{
static int init_called = 0;
ink_release_assert(!checkModuleVersion(version, NET_SYSTEM_MODULE_VERSION));
if (!init_called) {
// do one time stuff
// create a stat block for NetStats
net_rsb = RecAllocateRawStatBlock((int)Net_Stat_Count);
configure_net();
register_net_stats();
}
init_called = 1;
}
|
// Copyright 2019, Intel Corporation
#include "base/util/logging.h"
#include "base/util/throw.h"
#include "tile/pmlc/pmlc.h"
int main(int argc, char* argv[]) {
using vertexai::tile::pmlc::Main;
try {
START_EASYLOGGINGPP(argc, argv);
Main();
return 0;
} catch (const std::exception& ex) {
std::cerr << "Caught unhandled exception: " << ex.what() << std::endl;
auto stacktrace = boost::get_error_info<traced>(ex);
if (stacktrace) {
std::cerr << *stacktrace << std::endl;
}
return -1;
} catch (...) {
std::cerr << "Caught unhandled exception" << std::endl;
return -1;
}
}
|
#include<bits/stdc++.h>
using namespace std;
/// DFS, O( V + E )
/// The graph: https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
map<int,vector<int> >g;
map<int,bool>seen;
void dfs(int v){
seen[v]=1;
cout<<v<<" ";
for(auto u:g[v]){
if(!seen[u])dfs(u);
}
}
int main(){
g[0].push_back(1);
g[0].push_back(2);
g[1].push_back(2);
g[2].push_back(0);
g[2].push_back(3);
g[3].push_back(3);
dfs(2);
}
|
//===-test_isinf_dnnl.cc-----------------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// 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.
// =============================================================================
// clang-format off
// Testing CXX Code Gen using ODLA API on dnnl
// RUN: %halo_compiler -target cxx -o %data_path/test_isinf/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_isinf/test_data_set_0/output_0.pb
// RUN: %halo_compiler -target cxx -o %data_path/test_isinf/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_isinf/test_data_set_0/input_0.pb
// RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_isinf/model.onnx -o %t.cc
// RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include
// RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_isinf/test_data_set_0 %odla_link %device_link -lodla_dnnl -o %t_dnnl.exe -Wno-deprecated-declarations
// RUN: %t_dnnl.exe 0.0001 0 dnnl %data_path/test_isinf | FileCheck %s
// CHECK: Result Pass
// clang-format on
#include "test_isinf_dnnl.cc.tmp.main.cc.in"
|
// Copyright 2016 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "NtpSynchronizationChecker.h"
#include "herder/Herder.h"
#include "main/Application.h"
#include "util/NtpWork.h"
#include "util/StatusManager.h"
#include <iostream>
namespace spn
{
std::chrono::hours const NtpSynchronizationChecker::CHECK_FREQUENCY(24);
NtpSynchronizationChecker::NtpSynchronizationChecker(Application& app,
std::string ntpServer)
: WorkParent(app)
, mCheckTimer(app)
, mNtpServer(std::move(ntpServer))
, mIsShutdown(false)
{
}
NtpSynchronizationChecker::~NtpSynchronizationChecker()
{
clearChildren();
}
void
NtpSynchronizationChecker::notify(const std::string&)
{
if (allChildrenSuccessful())
{
clearChildren();
updateStatusManager();
mNtpWork.reset();
scheduleNextCheck();
}
}
void
NtpSynchronizationChecker::updateStatusManager()
{
auto& statusManager = app().getStatusManager();
if (mNtpWork->isSynchronized())
{
statusManager.removeStatusMessage(StatusCategory::NTP);
}
else
{
statusManager.setStatusMessage(
StatusCategory::NTP,
"Local time is not synchronized with NTP time.");
}
}
void
NtpSynchronizationChecker::scheduleNextCheck()
{
std::weak_ptr<NtpSynchronizationChecker> weak =
std::static_pointer_cast<NtpSynchronizationChecker>(shared_from_this());
mCheckTimer.expires_from_now(CHECK_FREQUENCY);
mCheckTimer.async_wait(
[weak]() {
auto self = weak.lock();
if (!self)
{
return;
}
self->start();
},
&VirtualTimer::onFailureNoop);
}
void
NtpSynchronizationChecker::start()
{
if (mIsShutdown)
{
return;
}
mNtpWork = addWork<NtpWork>(mNtpServer, Herder::MAX_TIME_SLIP_SECONDS / 2);
advanceChildren();
}
void
NtpSynchronizationChecker::shutdown()
{
if (mIsShutdown)
{
return;
}
mIsShutdown = true;
clearChildren();
mNtpWork.reset();
}
}
|
#pragma once
#include <queue>
#include <cstdio>
#include <string>
#include <SDL_surface.h>
#include <SDL_thread.h>
#include <SDL_mutex.h>
#include <cxcore.hpp>
#include <lua.hpp>
#include "camera.hh"
#include "util.hh"
#define DB_RESIZED_IMAGE_WIDTH 32
#define DB_RESIZED_IMAGE_HEIGHT 16
#define RESULTS_CLASER_ONSUMERS 2
#define RESULTS_CLASER_ONSUMER_MAIN_ID 0
#define RESULTS_CLASER_ONSUMER_GPIO_ID 1
namespace Image {
struct LuaException : public std::exception {
LuaException(int errcode, std::string p_msg = "") : err(errcode), msg(p_msg) {}
const char* what() const noexcept {
static char ret[1000];
switch (err) {
case LUA_ERRSYNTAX:
return "Lua error: syntax error";
case LUA_ERRMEM:
return "Lua error: not enough memory.";
case LUA_ERRRUN:
snprintf(ret, 1000, "Lua error: runtime error: %s", msg.c_str());
return ret;
case LUA_ERRERR:
return "Lua error: error while running the message handler.";
case LUA_ERRFILE:
return "Lua error: file error.";
default:
snprintf(ret, 1000, "Lua error: unknown error: %d", err);
return ret;
}
}
int err;
std::string msg;
};
struct nnResult {
double empty_prob;
double asian_prob;
double european_prob;
};
class NNManagerThread : public Thread::ThreadBase {
public:
virtual void onStart();
virtual void onEnd();
virtual void loop();
virtual void construct();
~NNManagerThread();
SDL_sem *newresult_sem = NULL;
SDL_mutex *mutex = NULL;
nnResult result;
Camera::Camera *camera;
private:
lua_State *L;
lua_State *thread_state;
};
class NNManager {
public:
NNManager(Camera::Camera *camera);
bool newResult(int src_id);
nnResult getResult(int src_id);
private:
NNManagerThread m_thread;
Thread::ConsumerTracker m_newresult_tracker;
};
void resizeImageForDB(const cv::Mat &src, cv::Mat &dst);
void resizeImageForScreen(const cv::Mat &src, cv::Mat &dst, int width, int height, int &x_pos, int &y_pos);
}
|
/*
First we convert from Roman numerals to decimal.
Then we convert from decimal to the shortest Roman numeral.
Then for each conversion we count how many characters we save, and sum up
all savings for our answer.
*/
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include "io_util.h"
#include "string_util.h"
int main()
{
std::string numerals_string = util::read_file("089_roman.txt");
std::vector<std::string> numerals = util::split(numerals_string, '\n');
std::vector<int> decimals;
std::unordered_map<char, int> values = {
{ 'I', 1 },
{ 'V', 5 },
{ 'X', 10 },
{ 'L', 50 },
{ 'C', 100 },
{ 'D', 500 },
{ 'M', 1000 }
};
for (std::string &numeral : numerals)
{
int decimal = 0;
int i = 0;
while (i < numeral.size())
{
int value = values[numeral[i]];
if (i < numeral.size() - 1 && value < values[numeral[i + 1]])
{
decimal += values[numeral[i + 1]] - value;
i++; // Skip next character.
}
else
{
decimal += value;
}
i++;
}
decimals.emplace_back(decimal);
}
std::vector<std::string> hundreds_numeral = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
std::vector<std::string> tens_numeral = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
std::vector<std::string> ones_numeral = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
std::vector<std::string> shortest_numerals;
for (int &decimal : decimals)
{
std::string numeral = "";
int thousands = decimal / 1000;
for (int i = 0; i < thousands; i++)
numeral += 'M';
numeral += hundreds_numeral[(decimal / 100) % 10];
numeral += hundreds_numeral[(decimal / 10) % 10];
numeral += hundreds_numeral[decimal % 10];
shortest_numerals.emplace_back(numeral);
}
int savings = 0;
for (int i = 0; i < numerals.size(); i++)
{
std::string numeral = numerals[i];
std::string shortest_numeral = shortest_numerals[i];
savings += numeral.length() - shortest_numeral.length();
}
std::cout << savings;
}
|
// Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSON_SERIALIZING_OPTIONS_HPP
#define JSONCONS_JSON_SERIALIZING_OPTIONS_HPP
#include <string>
#include <sstream>
#include <vector>
#include <istream>
#include <ostream>
#include <cstdlib>
#include <limits>
#include <cwchar>
#include <jsoncons/json_exception.hpp>
#include <jsoncons/jsoncons_utilities.hpp>
#include <jsoncons/detail/type_traits_helper.hpp>
namespace jsoncons {
#if !defined(JSONCONS_NO_TO_CHARS)
using chars_format = std::chars_format;
#else
enum class chars_format : uint8_t {fixed=1,scientific=2,hex=4,general=fixed|scientific};
#endif
// floating_point_options
class floating_point_options
{
chars_format format_;
uint8_t precision_;
uint8_t decimal_places_;
public:
floating_point_options()
: format_(chars_format::general), precision_(0), decimal_places_(0)
{
}
floating_point_options(chars_format format, uint8_t precision, uint8_t decimal_places = 0)
: format_(format), precision_(precision), decimal_places_(decimal_places)
{
}
explicit floating_point_options(chars_format format)
: format_(format), precision_(0), decimal_places_(0)
{
}
floating_point_options(const floating_point_options&) = default;
floating_point_options(floating_point_options&&) = default;
floating_point_options& operator=(const floating_point_options& e) = default;
floating_point_options& operator=(floating_point_options&& e) = default;
uint8_t precision() const
{
return precision_;
}
uint8_t decimal_places() const
{
return decimal_places_;
}
chars_format format() const
{
return format_;
}
};
enum class indenting : uint8_t {no_indent = 0, indent = 1};
#if !defined(JSONCONS_NO_DEPRECATED)
enum class block_options {next_line,same_line};
#endif
enum class line_split_kind : uint8_t {same_line,new_line,multi_line};
enum class bignum_chars_format : uint8_t {integer, base10, base64, base64url
#if !defined(JSONCONS_NO_DEPRECATED)
,string
#endif
};
enum class byte_string_chars_format : uint8_t {base64,base64url};
template <class CharT>
class basic_json_read_options
{
public:
typedef std::basic_string<CharT> string_type;
virtual ~basic_json_read_options() = default;
virtual bool can_read_nan_replacement() const = 0;
virtual const string_type& nan_replacement() const = 0;
virtual bool can_read_pos_inf_replacement() const = 0;
virtual const string_type& pos_inf_replacement() const = 0;
virtual bool can_read_neg_inf_replacement() const = 0;
virtual const string_type& neg_inf_replacement() const = 0;
virtual size_t max_nesting_depth() const = 0;
};
template <class CharT>
class basic_json_write_options
{
public:
typedef std::basic_string<CharT> string_type;
virtual ~basic_json_write_options() = default;
virtual bool can_write_nan_replacement() const = 0;
virtual const string_type& nan_replacement() const = 0;
virtual bool can_write_pos_inf_replacement() const = 0;
virtual const string_type& pos_inf_replacement() const = 0;
virtual bool can_write_neg_inf_replacement() const = 0;
virtual const string_type& neg_inf_replacement() const = 0;
virtual size_t max_nesting_depth() const = 0;
virtual byte_string_chars_format byte_string_format() const = 0;
virtual bignum_chars_format bignum_format() const = 0;
virtual line_split_kind object_object_split_lines() const = 0;
virtual line_split_kind array_object_split_lines() const = 0;
virtual line_split_kind object_array_split_lines() const = 0;
virtual line_split_kind array_array_split_lines() const = 0;
virtual int indent() const = 0;
virtual chars_format floating_point_format() const = 0;
virtual uint8_t precision() const = 0;
virtual bool escape_all_non_ascii() const = 0;
virtual bool escape_solidus() const = 0;
};
template <class CharT>
class basic_json_serializing_options : public virtual basic_json_read_options<CharT>,
public virtual basic_json_write_options<CharT>
{
public:
typedef CharT char_type;
typedef basic_string_view<CharT> string_view_type;
typedef std::basic_string<CharT> string_type;
private:
int indent_;
chars_format floating_point_format_;
uint8_t precision_;
bool can_read_nan_replacement_;
bool can_read_pos_inf_replacement_;
bool can_read_neg_inf_replacement_;
string_type nan_replacement_;
string_type pos_inf_replacement_;
string_type neg_inf_replacement_;
bool escape_all_non_ascii_;
bool escape_solidus_;
byte_string_chars_format byte_string_format_;
bignum_chars_format bignum_format_;
line_split_kind object_object_split_lines_;
line_split_kind object_array_split_lines_;
line_split_kind array_array_split_lines_;
line_split_kind array_object_split_lines_;
size_t max_nesting_depth_;
public:
static const size_t default_indent = 4;
// Constructors
basic_json_serializing_options()
: indent_(default_indent),
floating_point_format_(chars_format::hex),
precision_(0),
can_read_nan_replacement_(false),
can_read_pos_inf_replacement_(false),
can_read_neg_inf_replacement_(false),
escape_all_non_ascii_(false),
escape_solidus_(false),
byte_string_format_(byte_string_chars_format::base64url),
bignum_format_(bignum_chars_format::base10),
object_object_split_lines_(line_split_kind::multi_line),
object_array_split_lines_(line_split_kind::same_line),
array_array_split_lines_(line_split_kind::new_line),
array_object_split_lines_(line_split_kind::multi_line),
max_nesting_depth_((std::numeric_limits<size_t>::max)())
{
}
// Properties
byte_string_chars_format byte_string_format() const override {return byte_string_format_;}
basic_json_serializing_options<CharT>& byte_string_format(byte_string_chars_format value) {byte_string_format_ = value; return *this;}
bignum_chars_format bignum_format() const override {return bignum_format_;}
basic_json_serializing_options<CharT>& bignum_format(bignum_chars_format value) {bignum_format_ = value; return *this;}
line_split_kind object_object_split_lines() const override {return object_object_split_lines_;}
basic_json_serializing_options<CharT>& object_object_split_lines(line_split_kind value) {object_object_split_lines_ = value; return *this;}
line_split_kind array_object_split_lines() const override {return array_object_split_lines_;}
basic_json_serializing_options<CharT>& array_object_split_lines(line_split_kind value) {array_object_split_lines_ = value; return *this;}
line_split_kind object_array_split_lines() const override {return object_array_split_lines_;}
basic_json_serializing_options<CharT>& object_array_split_lines(line_split_kind value) {object_array_split_lines_ = value; return *this;}
line_split_kind array_array_split_lines() const override {return array_array_split_lines_;}
basic_json_serializing_options<CharT>& array_array_split_lines(line_split_kind value) {array_array_split_lines_ = value; return *this;}
#if !defined(JSONCONS_NO_DEPRECATED)
block_options array_array_block_option()
{
return (array_array_split_lines_ == line_split_kind::same_line) ? block_options::same_line : block_options::next_line;
}
basic_json_serializing_options<CharT>& array_array_block_option(block_options value)
{
array_array_split_lines_ = (value == block_options::same_line) ? line_split_kind::same_line : line_split_kind::new_line;
return *this;
}
block_options array_object_block_option()
{
return (array_object_split_lines_ == line_split_kind::same_line) ? block_options::same_line : block_options::next_line;
}
basic_json_serializing_options<CharT>& array_object_block_option(block_options value)
{
array_object_split_lines_ = (value == block_options::same_line) ? line_split_kind::same_line : line_split_kind::new_line;
return *this;
}
block_options object_array_block_option()
{
return (object_array_split_lines_ == line_split_kind::same_line) ? block_options::same_line : block_options::next_line;
}
basic_json_serializing_options<CharT>& object_array_block_option(block_options value)
{
object_array_split_lines_ = (value == block_options::same_line) ? line_split_kind::same_line : line_split_kind::new_line;
return *this;
}
block_options object_object_block_option()
{
return (object_object_split_lines_ == line_split_kind::same_line) ? block_options::same_line : block_options::next_line;
}
basic_json_serializing_options<CharT>& object_object_block_option(block_options value)
{
object_object_split_lines_ = (value == block_options::same_line) ? line_split_kind::same_line : line_split_kind::new_line;
return *this;
}
#endif
int indent() const override
{
return indent_;
}
basic_json_serializing_options<CharT>& indent(int value)
{
indent_ = value;
return *this;
}
chars_format floating_point_format() const override
{
return floating_point_format_;
}
basic_json_serializing_options<CharT>& floating_point_format(chars_format value)
{
floating_point_format_ = value;
return *this;
}
uint8_t precision() const override
{
return precision_;
}
basic_json_serializing_options<CharT>& precision(uint8_t value)
{
precision_ = value;
return *this;
}
bool escape_all_non_ascii() const override
{
return escape_all_non_ascii_;
}
basic_json_serializing_options<CharT>& escape_all_non_ascii(bool value)
{
escape_all_non_ascii_ = value;
return *this;
}
bool escape_solidus() const override
{
return escape_solidus_;
}
basic_json_serializing_options<CharT>& escape_solidus(bool value)
{
escape_solidus_ = value;
return *this;
}
bool can_read_nan_replacement() const override {return can_read_nan_replacement_;}
bool can_read_pos_inf_replacement() const override {return can_read_pos_inf_replacement_;}
bool can_read_neg_inf_replacement() const override {return can_read_neg_inf_replacement_;}
bool can_write_nan_replacement() const override {return !nan_replacement_.empty();}
bool can_write_pos_inf_replacement() const override {return !pos_inf_replacement_.empty();}
bool can_write_neg_inf_replacement() const override {return !neg_inf_replacement_.empty();}
basic_json_serializing_options<CharT>& replace_inf(bool replace)
{
can_read_pos_inf_replacement_ = replace;
can_read_neg_inf_replacement_ = replace;
return *this;
}
basic_json_serializing_options<CharT>& replace_pos_inf(bool replace)
{
can_read_pos_inf_replacement_ = replace;
return *this;
}
basic_json_serializing_options<CharT>& replace_neg_inf(bool replace)
{
can_read_neg_inf_replacement_ = replace;
return *this;
}
const string_type& nan_replacement() const override
{
return nan_replacement_;
}
basic_json_serializing_options<CharT>& nan_replacement(const string_view_type& value)
{
nan_replacement_ = string_type(value);
can_read_nan_replacement_ = is_string(value);
return *this;
}
const string_type& pos_inf_replacement() const override
{
return pos_inf_replacement_;
}
basic_json_serializing_options<CharT>& pos_inf_replacement(const string_view_type& value)
{
pos_inf_replacement_ = string_type(value);
can_read_pos_inf_replacement_ = is_string(value);
return *this;
}
const string_type& neg_inf_replacement() const override
{
return neg_inf_replacement_;
}
basic_json_serializing_options<CharT>& neg_inf_replacement(const string_view_type& value)
{
neg_inf_replacement_ = string_type(value);
can_read_neg_inf_replacement_ = is_string(value);
return *this;
}
size_t max_nesting_depth() const override
{
return max_nesting_depth_;
}
void max_nesting_depth(size_t value)
{
max_nesting_depth_ = value;
}
private:
enum class input_state {initial,begin_quote,character,end_quote,escape,error};
bool is_string(const string_view_type& s) const
{
input_state state = input_state::initial;
for (CharT c : s)
{
switch (c)
{
case '\t': case ' ': case '\n': case'\r':
break;
case '\\':
state = input_state::escape;
break;
case '\"':
switch (state)
{
case input_state::initial:
state = input_state::begin_quote;
break;
case input_state::begin_quote:
state = input_state::end_quote;
break;
case input_state::character:
state = input_state::end_quote;
break;
case input_state::end_quote:
state = input_state::error;
break;
case input_state::escape:
state = input_state::character;
break;
default:
state = input_state::character;
break;
}
default:
break;
}
}
return state == input_state::end_quote;
}
};
typedef basic_json_serializing_options<char> json_serializing_options;
typedef basic_json_serializing_options<wchar_t> wjson_serializing_options;
typedef basic_json_read_options<char> json_read_options;
typedef basic_json_read_options<wchar_t> wjson_read_options;
typedef basic_json_write_options<char> json_write_options;
typedef basic_json_write_options<wchar_t> wjson_write_options;
#if !defined(JSONCONS_NO_DEPRECATED)
typedef basic_json_serializing_options<char> output_format;
typedef basic_json_serializing_options<wchar_t> woutput_format;
typedef basic_json_serializing_options<char> serialization_options;
typedef basic_json_serializing_options<wchar_t> wserialization_options;
#endif
}
#endif
|
/*
* The MIT License (MIT)
* Copyright (c) 2018, Benjamin Maier
*
* 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 NON-
* INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "Utilities.h"
#include "ResultClasses.h"
#include "measurements.h"
#include "resampling.h"
#include "resampling.h"
#include "conversion.h"
#include "FW_P_varying.h"
using namespace std;
flockwork_args
get_flockwork_P_args(
edge_changes &list_of_edge_changes,
double dt,
size_t N_time_steps,
double k_over_k_real_scaling,
double gamma_scaling,
double P_scaling,
map < pair < size_t, size_t >, double > &aggregated_network,
const bool ensure_empty_network,
const bool adjust_last_bin_if_dt_does_not_fit,
const bool verbose
)
{
// get references to edge_list and time
vector < vector < pair < size_t, size_t > > > & all_edges_in = list_of_edge_changes.edges_in;
vector < vector < pair < size_t, size_t > > > & all_edges_out = list_of_edge_changes.edges_out;
vector < double > time = list_of_edge_changes.t; //this is a copy
// set initial and final time
double t0 = list_of_edge_changes.t0;
double tmax = list_of_edge_changes.tmax;
// create graph
size_t N = list_of_edge_changes.N;
vector < set < size_t > > G(N);
graph_from_edgelist(G,list_of_edge_changes.edges_initial);
// check w
if ((dt > 0.0) and N_time_steps > 0)
throw domain_error("please provide either positive dt or positive N_time_steps, not both positive");
else if ((dt == 0.0) and N_time_steps == 0)
throw domain_error("please provide either positive dt or positive N_time_steps, not both zero");
else if ((dt > 0.0) and N_time_steps == 0)
{
double _N_t = (tmax - t0) / dt;
double intpart;
// check if this yielded a nice round number
// by checking the rest after the period
if (modf(_N_t,&intpart) != 0.0)
if (adjust_last_bin_if_dt_does_not_fit)
{
// if it did not, change the time of the network
// to be larger than originally.
// This will be changed back later when
// computing gamma and P
N_time_steps = (size_t) ceil(_N_t);
tmax = t0 + N_time_steps * dt;
}
else
throw domain_error("dt does not nicely divide time interval (tmax - t0) in integer parts");
else
N_time_steps = (size_t) _N_t;
}
else if ((dt == 0.0) and N_time_steps > 0)
dt = (tmax - t0) / N_time_steps;
// create iteratos
auto it_edges_in = all_edges_in.begin();
auto it_edges_out = all_edges_out.begin();
auto it_time = time.begin();
// get the observables for the binning process
vector < double > new_time;
vector < size_t > m_in;
vector < size_t > m_out;
vector < size_t > m;
m.push_back( list_of_edge_changes.edges_initial.size() );
new_time.push_back( t0 );
if (tmax < time.back())
throw domain_error("The value tmax is smaller than the last value in the time list.");
if( verbose)
{
cout << "starting binning process with dt = " << dt << " and N_time_steps = " << N_time_steps << endl;
}
// start at new_time = t0 + dt because t0 was already taken care of
for(size_t t_i = 1; t_i < N_time_steps; t_i++)
{
double this_new_time = dt * t_i + t0;
// initialize the counts for this time bin
m_in.push_back(0);
m_out.push_back(0);
if (verbose)
{
cout << "current demanded new time is " << this_new_time << endl;
cout << "current original time is " << (*it_time) << endl;
cout << "upcoming original time is " << (*(it_time+1)) << endl;
}
// while the next (upcoming) time value in the original data
// is smaller than the new demanded time
while (it_time != time.end() and ((*(it_time)) <= this_new_time))
{
if (verbose)
{
cout << "advancing original time" << endl;
cout << "new original time is " << *it_time << endl;
}
for(auto const &edge: *it_edges_in)
{
size_t const & i = edge.first;
size_t const & j = edge.second;
G[ i ].insert( j );
G[ j ].insert( i );
}
for(auto const &edge: *it_edges_out)
{
size_t const & i = edge.first;
size_t const & j = edge.second;
G[ i ].erase( j );
G[ j ].erase( i );
}
m_in.back() += it_edges_in->size();
m_out.back() += it_edges_out->size();
it_time++;
it_edges_in++;
it_edges_out++;
}
size_t num_edges = 0;
for(auto const &neighbors: G)
num_edges += neighbors.size();
num_edges /= 2;
m.push_back( num_edges );
new_time.push_back( this_new_time );
}
// ============== add the last time frame for looping ================
new_time.push_back( dt * N_time_steps + t0 );
// get a sorted edge list
vector < pair < size_t, size_t > > last_edge_list;
edgelist_from_graph(last_edge_list,G);
set < size_t > last_edge_integers = get_edge_integer_set(last_edge_list, N);
set < size_t > edge_integers = get_edge_integer_set(list_of_edge_changes.edges_initial, N);
vector < size_t > incoming_edge_integers;
vector < size_t > outgoing_edge_integers;
// incoming edges are from the set (edges - last_edges)
set_difference(
edge_integers.begin(), edge_integers.end(),
last_edge_integers.begin(), last_edge_integers.end(),
back_inserter(incoming_edge_integers)
);
// outgoing edges are from the set (last_edges - edges)
set_difference(
last_edge_integers.begin(), last_edge_integers.end(),
edge_integers.begin(), edge_integers.end(),
back_inserter(outgoing_edge_integers)
);
m_in.push_back(incoming_edge_integers.size());
m_out.push_back(outgoing_edge_integers.size());
m.push_back( m.front() );
// ========= now go through the observables and compute the parameters =============
auto it_m = m.begin();
auto it_m_in = m_in.begin();
auto it_m_out = m_out.begin();
it_time = new_time.begin();
//initialize parameters
vector < pair < double, double > > gamma;
vector < double > P;
bool last_bin_was_for_emptying = false;
while(it_m_in != m_in.end())
{
size_t & this_m = *it_m;
size_t & this_m_in = *it_m_in;
size_t & this_m_out = *it_m_out;
// if tmax was shifted because dt did not fit, rescale the last
// time dt to the appropriate dt
if (it_m_in + 1 == m_in.end())
{
double this_time = *it_time;
double next_time = list_of_edge_changes.tmax;
dt = next_time - this_time;
}
if ( (this_m == 0) and ( this_m_out > 0) )
{
/* this happens, e.g. in the beginning for cumulated bins. originally,
the network is a null graph, so no edges can go out.
however, when binning, the first cumulative bin might contain
multiple bins where there's already edges. so we trick a bit
and fake and set the first m_in to m_in := m_in - m_out
and the first m_out := 0
*/
if (this_m_in < this_m_out)
this_m_in = 0;
else
this_m_in -= this_m_out;
this_m_out = 0;
}
double _P;
double _g;
double _m_out = (double) this_m_out;
double _m_in = (double) this_m_in;
double _m = ((double) this_m) / k_over_k_real_scaling;
if (this_m_out > 0)
{
// standard case
_g = 0.5 * _m_out / _m / dt * gamma_scaling;
_P = min(
2.0 * _m / (N+2.0*_m) * _m_in / _m_out * P_scaling,
1.0
);
}
else if ( (this_m_out == 0) and (this_m_in > 0) )
{
// secondary case if there's no outgoing edges
double next_m = ((double) *(it_m+1)) / k_over_k_real_scaling;
_P = 2.0 * next_m / (N+2.0*next_m) * P_scaling;
_g = _m_in / ( _P * (N+2.0*_m) * dt) * gamma_scaling;
}
else
{
// tertiary case
_g = 0.0;
_P = 0.0;
}
// if in the beginning of this bin and at the end of this bin
// there's no edges and we want this to be ensured
if ( ( ensure_empty_network ) and
( this_m == 0 ) and
( *(it_m+1) == 0 ) and
( _g == 0.0 ) and
( _P == 0.0 )
)
{
// we want to pick every node in the network at least once, s.t.
// all nodes have zero edges in the end of the time bin.
// This is the classic problem of "how often do I have to pick
// in order to have picked every number at least once" with solution
// <T> = N log(N)
// Since we want <Events([t,t+dt])> = N * log(N), we need
// gamma_per_node = (N log(N)) / (N / dt) such that
// \int_t^{t+dt} dt' gamma_per_node * N = N * log(N)
//
// Also, instead of doing this for two time bins, we double the rate
// and just do it for one time bin
if ( not last_bin_was_for_emptying )
_g = 1 * log(N) / dt;
last_bin_was_for_emptying = true;
}
else
{
last_bin_was_for_emptying = false;
}
gamma.push_back( make_pair( *it_time, _g ) );
P.push_back( _P );
it_m++;
it_m_in++;
it_m_out++;
it_time++;
}
flockwork_args fw_args;
fw_args.N = N;
fw_args.E = list_of_edge_changes.edges_initial;
fw_args.P = P;
fw_args.rewiring_rate = gamma;
fw_args.tmax = list_of_edge_changes.tmax;
fw_args.new_time = new_time;
fw_args.m_in = m_in;
fw_args.m_out = m_out;
fw_args.m = m;
if (aggregated_network.size() > 0)
{
vector < pair < vector < size_t >, vector < double > > > neighbor_affinity(N);
for (auto const & entry: aggregated_network)
{
size_t i = entry.first.first;
size_t j = entry.first.second;
double val = entry.second;
neighbor_affinity[i].first.push_back( j );
neighbor_affinity[i].second.push_back( val );
neighbor_affinity[j].first.push_back( i );
neighbor_affinity[j].second.push_back( val );
}
fw_args.neighbor_affinity = neighbor_affinity;
}
else
{
vector < pair < vector < size_t >, vector < double > > > neighbor_affinity;
fw_args.neighbor_affinity = neighbor_affinity;
}
return fw_args;
}
double k_simulated_over_k_real(
vector < pair < double, double > > &k_original,
vector < pair < double, double > > &k_simulated
)
{
if (k_simulated.size() != k_original.size())
throw length_error("Original network and simulated network differ in number of time points.");
double sum = 0.0;
size_t N_meas = 0;
auto sim = k_simulated.begin();
auto orig = k_original.begin();
for(; sim != k_simulated.end(); ++sim)
{
double &k_s = sim->second;
double &k_o = orig->second;
if ((k_o > 0.0) and (k_s > 0.0))
{
sum += k_s / k_o;
N_meas += 1;
}
//else if ((k_o == 0.0) and (k_s == 0.0))
//{
// sum += 1.0;
// N_meas += 1;
//}
++orig;
}
return sum / (double) N_meas;
}
double k_RMSE(
edge_lists &original_binned,
edge_lists &simulated_binned
)
{
vector < pair < double, double > > k_simulated = mean_degree_from_edge_lists(simulated_binned);
vector < pair < double, double > > k_original = mean_degree_from_edge_lists(original_binned);
if (k_simulated.size() != k_original.size())
throw length_error("Original network and simulated network differ in number of time points.");
double sum = 0.0;
size_t N_meas = 0;
auto sim = k_simulated.begin();
auto orig = k_original.begin();
for(; sim != k_simulated.end(); ++sim)
{
double &k_s = sim->second;
double &k_o = orig->second;
sum += pow( k_s - k_o, 2);
++orig;
++N_meas;
}
return sqrt(sum / (double) N_meas);
}
double estimate_k_scaling_gradient_descent(
edge_changes &original_edge_changes,
double dt_for_inference,
double dt_for_binning,
size_t measurements_per_configuration,
double learning_rate,
double relative_error,
size_t N_eval_max,
bool verbose
)
{
edge_lists original_binned = bin_from_edge_changes(original_edge_changes, dt_for_binning);
vector < pair < double, double > > k_original = mean_degree_from_edge_lists(original_binned);
double this_k_over_k_real_scaling = 1.0;
double last_k_over_k_real_scaling = 0.0;
size_t N_eval = 0;
size_t update_every = 1;
map < pair < size_t, size_t >, double > dummy_network;
while (
( abs(last_k_over_k_real_scaling - this_k_over_k_real_scaling) / this_k_over_k_real_scaling > relative_error )
and
( N_eval < N_eval_max )
)
{
double mean = 0.0;
vector < double > vals;
vector < pair < double, double > > new_k( k_original.size() );
for(unsigned int measurement = 0; measurement < measurements_per_configuration; ++measurement)
{
flockwork_args these_args = get_flockwork_P_args(
original_edge_changes,
dt_for_inference,
0,
this_k_over_k_real_scaling,
1.0,
1.0,
dummy_network,
true,
true,
false
);
edge_changes fw = flockwork_P_varying_rates(
these_args.E,
these_args.N,
these_args.P,
these_args.tmax,
these_args.rewiring_rate,
these_args.tmax
);
edge_lists fw_binned = bin_from_edge_changes(fw, dt_for_binning);
vector < pair < double, double > > this_k = mean_degree_from_edge_lists(fw_binned);
auto this_t_k = this_k.begin();
for(auto &t_k: new_k)
{
t_k.second += this_t_k->second / (double) measurements_per_configuration;
++this_t_k;
}
}
mean = k_simulated_over_k_real(k_original, new_k);
last_k_over_k_real_scaling = this_k_over_k_real_scaling;
double inverse_scaling = 1.0 / this_k_over_k_real_scaling - learning_rate * (1.0-1.0/mean);
this_k_over_k_real_scaling = 1.0 / inverse_scaling;
if (verbose and N_eval % update_every == 0)
{
cout << "== generation: " << N_eval+1 << " ==" << endl;
cout << " k_simulated_over_k_real = " << mean << endl;
cout << " k_scaling = " << this_k_over_k_real_scaling << endl;
cout << " scaling_err = " << abs(last_k_over_k_real_scaling - this_k_over_k_real_scaling) / this_k_over_k_real_scaling << endl;
}
++N_eval;
}
return this_k_over_k_real_scaling;
}
double estimate_k_scaling_gradient_descent_RMSE(
edge_changes &original_edge_changes,
double dt_for_inference,
double dt_for_binning,
size_t measurements_per_configuration,
double learning_rate,
double relative_error,
size_t N_eval_max,
bool verbose
)
{
edge_lists original_binned = bin_from_edge_changes(original_edge_changes, dt_for_binning);
double this_k_over_k_real_scaling = 1.0;
double last_k_over_k_real_scaling = 0.0;
size_t N_eval = 0;
size_t update_every = 1;
map < pair < size_t, size_t >, double > dummy_network;
double last_RMSE;
double d_scaling = 0.1;
double mean = 0.0;
vector < double > vals;
for(unsigned int measurement = 0; measurement < measurements_per_configuration; ++measurement)
{
flockwork_args these_args = get_flockwork_P_args(
original_edge_changes,
dt_for_inference,
0,
this_k_over_k_real_scaling,
1.0,
1.0,
dummy_network,
true,
true,
false
);
edge_changes fw = flockwork_P_varying_rates(
these_args.E,
these_args.N,
these_args.P,
these_args.tmax,
these_args.rewiring_rate,
these_args.tmax
);
edge_lists fw_binned = bin_from_edge_changes(fw, dt_for_binning);
double this_value;
this_value = k_RMSE(original_binned, fw_binned);
mean += this_value;
vals.push_back( this_value );
}
mean /= (double) measurements_per_configuration;
last_RMSE = mean;
this_k_over_k_real_scaling = 1.0 / (1.0 / this_k_over_k_real_scaling - d_scaling);
while (
( abs(last_k_over_k_real_scaling - this_k_over_k_real_scaling) / this_k_over_k_real_scaling > relative_error )
and
( N_eval < N_eval_max )
)
{
double mean = 0.0;
vector < double > vals;
for(unsigned int measurement = 0; measurement < measurements_per_configuration; ++measurement)
{
flockwork_args these_args = get_flockwork_P_args(
original_edge_changes,
dt_for_inference,
0,
this_k_over_k_real_scaling,
1.0,
1.0,
dummy_network,
true,
true,
false
);
edge_changes fw = flockwork_P_varying_rates(
these_args.E,
these_args.N,
these_args.P,
these_args.tmax,
these_args.rewiring_rate,
these_args.tmax
);
edge_lists fw_binned = bin_from_edge_changes(fw, dt_for_binning);
double this_value;
this_value = k_RMSE(original_binned, fw_binned);
mean += this_value;
vals.push_back( this_value );
}
mean /= (double) measurements_per_configuration;
double err = 0.0;
for(auto val = vals.begin(); val != vals.end(); ++val)
err += pow(mean - *val,2);
err /= (double) measurements_per_configuration*(measurements_per_configuration-1);
err = sqrt(err);
last_k_over_k_real_scaling = this_k_over_k_real_scaling;
double inverse_scaling = 1.0 / this_k_over_k_real_scaling - d_scaling;
this_k_over_k_real_scaling = 1.0 / inverse_scaling;
if (verbose and N_eval % update_every == 0)
{
cout << "== generation: " << N_eval+1 << " ==" << endl;
cout << " k_RMSE = " << mean << " +/- " << err << endl;
cout << " k_scaling = " << this_k_over_k_real_scaling << endl;
cout << " scaling_err = " << abs(last_k_over_k_real_scaling - this_k_over_k_real_scaling) / this_k_over_k_real_scaling << endl;
}
++N_eval;
}
return this_k_over_k_real_scaling;
}
pair < vector < double >, vector < double > >
get_node_gamma_and_P(
edge_changes &ec,
vector < pair < double, double > > &gamma,
vector < double > &P,
bool use_event_rate_method
)
{
// get references to edge_list and time
vector < vector < pair < size_t, size_t > > > & all_edges_in = ec.edges_in;
vector < vector < pair < size_t, size_t > > > & all_edges_out = ec.edges_out;
vector < double > &ec_time = ec.t;
// get vectors from gamma and P
vector < double > ab_time;
vector < double > g;
for(auto &g_entry: gamma)
{
ab_time.push_back(g_entry.first);
g.push_back(g_entry.second);
}
// set initial and final time
double tmax = ec.tmax;
// graph observables
size_t N = ec.N;
double Nf(N);
size_t number_of_edges = ec.edges_initial.size();
// intialize the node properties
vector < size_t > k_node(N);
vector < size_t > M_out(N);
vector < size_t > M_in(N);
// intialize the integrals
vector < double > I_out(N);
vector < double > I_out_2(N);
vector < double > I_in_1(N);
vector < double > I_in_2(N);
for(auto const &edge : ec.edges_initial)
{
++k_node[edge.first];
++k_node[edge.second];
}
auto it_e_in = all_edges_in.begin();
auto it_e_out = all_edges_out.begin();
auto it_t_ab = ab_time.begin();
auto it_t_ec = ec_time.begin();
auto it_g = g.begin();
auto it_P = P.begin();
double t = ec.t0;
double t_next_ab;
double t_next_ec;
double t_next;
do
{
// check which is the next event time at which stuff changes
if ((it_t_ab == ab_time.end()) or (it_t_ab+1 == ab_time.end()))
t_next_ab = tmax;
else
t_next_ab = *(it_t_ab+1);
if ((it_t_ec == ec_time.end()) or (it_t_ec+1 == ec_time.end()))
t_next_ec = tmax;
else
t_next_ec = *(it_t_ec+1);
if ( t_next_ec <= t_next_ab )
t_next = t_next_ec;
else
t_next = t_next_ab;
// compute the integrals up to the next change
double dt = t_next - t;
double mean_degree = ((double) number_of_edges) * 2.0 / Nf;
auto i_k = k_node.begin();
auto i_I_out = I_out.begin();
auto i_I_out_2 = I_out_2.begin();
auto i_I_in_1 = I_in_1.begin();
auto i_I_in_2 = I_in_2.begin();
double &_g = *it_g;
double &_P = *it_P;
double a = _g * _P;
double b = _g * (1.0-_P);
while(i_k != k_node.end())
{
double _k = (double) *i_k;
if (use_event_rate_method)
{
(*i_I_out) += a * _k * dt;
(*i_I_out_2) += b * _k * dt;
(*i_I_in_1) += a * (Nf - _k - 1.0) * (_k + 1.0) / (Nf - 1.0) * dt;
(*i_I_in_2) += a * (1.0 + mean_degree) * dt;
} else {
(*i_I_out) += _g * _k * dt;
(*i_I_in_1) += _g * _P * (Nf - _k - 1.0) * (_k + 1.0) / (Nf - 1.0) * dt;
(*i_I_in_2) += _g * _P * (1.0 + mean_degree) * dt;
}
++i_k;
++i_I_out;
++i_I_out_2;
++i_I_in_1;
++i_I_in_2;
}
// advance time
t = t_next;
// change either the network or gamma and P or both
if (t_next_ec <= t_next_ab)
{
// update observables for this advancement
for(auto const &edge : *it_e_in)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
++k_node[u];
++k_node[v];
++M_in[u];
++M_in[v];
number_of_edges++;
}
for(auto const &edge : *it_e_out)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
--k_node[u];
--k_node[v];
++M_out[u];
++M_out[v];
number_of_edges--;
}
// advance network
++it_t_ec;
++it_e_out;
++it_e_in;
}
if (t_next_ab <= t_next_ec)
{
// advance gamma and P
++it_g;
++it_P;
++it_t_ab;
}
} while ((t_next_ab < tmax) or (t_next_ec < tmax));
vector < double > g_node;
vector < double > P_node;
vector < double > a_node;
vector < double > b_node;
for (size_t node = 0; node < N; ++node)
{
if (use_event_rate_method)
{
double this_a = (M_in[node] - I_in_1[node]) / I_in_2[node];
double this_b = (M_out[node] - I_out[node] - I_out_2[node] - this_a * I_out[node]) / I_out_2[node];
if (this_a < 0.0)
this_a = 0.0;
if (this_b < 0.0)
this_b = 0.0;
a_node.push_back(this_a);
b_node.push_back(this_b);
} else
{
double this_g = (M_out[node] - I_out[node]) / I_out[node];
double this_P = (M_in[node] - I_in_1[node]) / I_in_2[node] / this_g;
g_node.push_back(this_g);
P_node.push_back(this_P);
}
}
if (use_event_rate_method)
return make_pair(a_node, b_node);
else
return make_pair(g_node, P_node);
}
flockwork_alpha_beta_args
get_flockwork_alpha_beta_args(
edge_changes &list_of_edge_changes,
double dt,
size_t N_time_steps,
double k_over_k_real_scaling,
double alpha_scaling,
double beta_scaling,
map < pair < size_t, size_t >, double > &aggregated_network,
const bool ensure_empty_network,
const bool consider_looped_network_to_get_final_events,
const bool verbose
)
{
// get references to edge_list and time
vector < vector < pair < size_t, size_t > > > & all_edges_in = list_of_edge_changes.edges_in;
vector < vector < pair < size_t, size_t > > > & all_edges_out = list_of_edge_changes.edges_out;
vector < double > time = list_of_edge_changes.t; //this is a copy
// set initial and final time
double t0 = list_of_edge_changes.t0;
double tmax = list_of_edge_changes.tmax;
double original_tmax = tmax;
// create graph
size_t N = list_of_edge_changes.N;
vector < set < size_t > > G(N);
graph_from_edgelist(G,list_of_edge_changes.edges_initial);
// check w
if ((dt > 0.0) and N_time_steps > 0)
throw domain_error("please provide either positive dt or positive N_time_steps, not both positive");
else if ((dt == 0.0) and N_time_steps == 0)
throw domain_error("please provide either positive dt or positive N_time_steps, not both zero");
else if ((dt > 0.0) and N_time_steps == 0)
{
double _N_t = (tmax - t0) / dt;
double intpart;
// check if this yielded a nice round number
// by checking the rest after the period
if (modf(_N_t,&intpart) != 0.0)
{
// if it did not, change the time of the network
// to be larger than originally.
// This will be changed back later when
// computing gamma and P
N_time_steps = (size_t) ceil(_N_t);
tmax = t0 + N_time_steps * dt;
}
else
N_time_steps = (size_t) _N_t;
}
else if ((dt == 0.0) and N_time_steps > 0)
dt = (tmax - t0) / N_time_steps;
// create iteratos
auto it_edges_in = all_edges_in.begin();
auto it_edges_out = all_edges_out.begin();
auto it_time = time.begin();
// get the observables for the binning process
vector < double > new_time;
vector < size_t > m_in;
vector < size_t > m_out;
vector < double > M;
size_t number_of_edges = list_of_edge_changes.edges_initial.size();
new_time.push_back( t0 );
if (tmax < time.back())
throw domain_error("The value tmax is smaller than the last value in the time list.");
if( verbose)
{
cout << "starting binning process with dt = " << dt << " and N_time_steps = " << N_time_steps << endl;
}
double last_time = t0;
// the demanded new time bin is next one new_time = t0 + dt
for(size_t t_i = 1; t_i < N_time_steps+1; t_i++)
{
double this_new_time = dt * t_i + t0;
// initialize the counts for this time bin
m_in.push_back(0);
m_out.push_back(0);
M.push_back( 0. );
if (verbose)
{
cout << "current demanded new time is " << this_new_time << endl;
cout << "current original time is " << (*it_time) << endl;
cout << "upcoming original time is " << (*(it_time+1)) << endl;
}
// while the next (upcoming) time value in the original data
// is smaller than the new demanded time
while (it_time != time.end() and ((*(it_time)) <= this_new_time))
{
if (verbose)
{
cout << "advancing original time" << endl;
cout << "new original time is " << *it_time << endl;
}
for(auto const &edge: *it_edges_in)
{
size_t const & i = edge.first;
size_t const & j = edge.second;
G[ i ].insert( j );
G[ j ].insert( i );
}
for(auto const &edge: *it_edges_out)
{
size_t const & i = edge.first;
size_t const & j = edge.second;
G[ i ].erase( j );
G[ j ].erase( i );
}
if (verbose)
{
cout << "edges going in = " << it_edges_in->size() << endl;
cout << "edges going out = " << it_edges_out->size() << endl;
}
m_in.back() += it_edges_in->size();
m_out.back() += it_edges_out->size();
M.back() += (*it_time - last_time) * number_of_edges;
number_of_edges += (it_edges_in->size() - it_edges_out->size());
if (verbose)
{
cout << "number of edges = " << number_of_edges << endl;
cout << "dt = " << (*it_time - last_time) << endl;
cout << "M.back() = " << M.back() << endl;
}
last_time = *it_time;
it_time++;
it_edges_in++;
it_edges_out++;
}
if ( (this_new_time == tmax) and original_tmax < tmax)
this_new_time = original_tmax;
M.back() += (this_new_time - last_time) * number_of_edges;
new_time.push_back( this_new_time );
}
// get a sorted edge list
if (consider_looped_network_to_get_final_events)
{
vector < pair < size_t, size_t > > last_edge_list;
edgelist_from_graph(last_edge_list,G);
set < size_t > last_edge_integers = get_edge_integer_set(last_edge_list, N);
set < size_t > edge_integers = get_edge_integer_set(list_of_edge_changes.edges_initial, N);
vector < size_t > incoming_edge_integers;
vector < size_t > outgoing_edge_integers;
// incoming edges are from the set (edges - last_edges)
set_difference(
edge_integers.begin(), edge_integers.end(),
last_edge_integers.begin(), last_edge_integers.end(),
back_inserter(incoming_edge_integers)
);
// outgoing edges are from the set (last_edges - edges)
set_difference(
last_edge_integers.begin(), last_edge_integers.end(),
edge_integers.begin(), edge_integers.end(),
back_inserter(outgoing_edge_integers)
);
m_in.back() += incoming_edge_integers.size();
m_out.back() += outgoing_edge_integers.size();
}
// ==================== SHOW ALL THOSE VALUES ===========================
if (verbose)
{
cout << "the number of demanded time steps was " << N_time_steps << endl;
cout << "the number of covered times in `new_time` was " << new_time.size() << endl << " new_time = [ ";
for(auto const & this_time: new_time)
{
cout << this_time << ", ";
}
cout << "]" << endl;
cout << "the number of covered M values in `M` was " << M.size() << endl << " M = [ ";
for(auto const & _M: M)
{
cout << _M << ", ";
}
cout << "]" << endl;
cout << "the number of covered m_in values in `m_in` was " << m_in.size() << endl << " m_in = [ ";
for(auto const & _m_in: m_in)
{
cout << _m_in << ", ";
}
cout << "]" << endl;
cout << "the number of covered m_out values in `m_out` was " << m_out.size() << endl << " m_out = [ ";
for(auto const & _m_out: m_out)
{
cout << _m_out << ", ";
}
cout << "]" << endl;
}
// ========= now go through the observables and compute the parameters =============
auto it_M = M.begin();
auto it_m_in = m_in.begin();
auto it_m_out = m_out.begin();
it_time = new_time.begin();
//initialize parameters
vector < pair < double, double > > alpha;
vector < double > beta;
bool last_bin_was_for_emptying = false;
while(it_m_in != m_in.end())
{
double & this_M = *it_M;
size_t & this_m_in = *it_m_in;
size_t & this_m_out = *it_m_out;
double this_time = *it_time;
double next_time = *(it_time+1);
dt = next_time - this_time;
if (verbose)
cout << "dt = " << dt << endl;
if ( (this_M == 0.0) and ( this_m_out > 0) )
{
/* this happens, e.g. in the beginning for cumulated bins. originally,
the network is a null graph, so no edges can go out.
however, when binning, the first cumulative bin might contain
multiple bins where there's already edges. so we trick a bit
and fake and set the first m_in to m_in := m_in - m_out
and the first m_out := 0
*/
if (this_m_in < this_m_out)
this_m_in = 0;
else
this_m_in -= this_m_out;
this_m_out = 0;
}
double _a;
double _b;
double _m_out = (double) this_m_out;
double _m_in = (double) this_m_in;
double _M = this_M / k_over_k_real_scaling;
_a = _m_in / (N*dt+2.0*_M);
if ( (_m_out == 0.0) and (_M == 0.0) )
_b = 0.0;
else
_b = (_m_out / 2.0 / _M) - _a;
if (_b < 0.0)
_b = 0.0;
// if in the beginning of this bin and at the end of this bin
// there's no edges and we want this to be ensured
if ( ( ensure_empty_network ) and
( this_M == 0.0 ) and
( *(it_M+1) == 0.0 ) and
( _a == 0.0 ) and
( _b == 0.0 )
)
{
// we want to pick every node in the network at least once, s.t.
// all nodes have zero edges in the end of the time bin.
// This is the classic problem of "how often do I have to pick
// in order to have picked every number at least once" with solution
// <T> = N log(N)
// Since we want <Events([t,t+dt])> = N * log(N), we need
// gamma_per_node = (N log(N)) / (N / dt) such that
// \int_t^{t+dt} dt' gamma_per_node * N = N * log(N)
//
// Also, instead of doing this for two time bins, we double the rate
// and just do it for one time bin
if ( not last_bin_was_for_emptying )
_b = 1 * log(N) / dt;
last_bin_was_for_emptying = true;
}
else
{
last_bin_was_for_emptying = false;
}
alpha.push_back( make_pair( *it_time, _a ) );
beta.push_back( _b );
it_M++;
it_m_in++;
it_m_out++;
it_time++;
}
flockwork_alpha_beta_args fw_args;
fw_args.N = N;
fw_args.E = list_of_edge_changes.edges_initial;
fw_args.disconnection_rate = beta;
fw_args.reconnection_rate = alpha;
fw_args.tmax = list_of_edge_changes.tmax;
fw_args.new_time = new_time;
fw_args.m_in = m_in;
fw_args.m_out = m_out;
fw_args.M = M;
if (aggregated_network.size() > 0)
{
vector < pair < vector < size_t >, vector < double > > > neighbor_affinity(N);
for (auto const & entry: aggregated_network)
{
size_t i = entry.first.first;
size_t j = entry.first.second;
double val = entry.second;
neighbor_affinity[i].first.push_back( j );
neighbor_affinity[i].second.push_back( val );
neighbor_affinity[j].first.push_back( i );
neighbor_affinity[j].second.push_back( val );
}
fw_args.neighbor_affinity = neighbor_affinity;
}
else
{
vector < pair < vector < size_t >, vector < double > > > neighbor_affinity;
fw_args.neighbor_affinity = neighbor_affinity;
}
return fw_args;
}
pair < vector < double >, vector < double > >
get_node_alpha_and_beta(
edge_changes &ec,
vector < pair < double, double > > &alpha,
vector < double > &beta,
double k_over_k_real_scaling,
bool apply_mean_correction,
bool verbose
)
{
// get references to edge_list and time
vector < vector < pair < size_t, size_t > > > & all_edges_in = ec.edges_in;
vector < vector < pair < size_t, size_t > > > & all_edges_out = ec.edges_out;
vector < double > &ec_time = ec.t;
// get vectors from gamma and P
vector < double > ab_time;
vector < double > a;
for(auto &a_entry: alpha)
{
ab_time.push_back(a_entry.first);
a.push_back(a_entry.second);
}
// set initial and final time
double tmax = ec.tmax;
// graph observables
size_t N = ec.N;
double Nf(N);
size_t number_of_edges = ec.edges_initial.size();
// intialize the node properties
vector < size_t > k_node(N);
vector < size_t > M_out(N);
vector < size_t > M_in(N);
// intialize the integrals
vector < double > I_out_1(N);
vector < double > I_out_2(N);
vector < double > I_in_1(N);
vector < double > I_in_2(N);
for(auto const &edge : ec.edges_initial)
{
++k_node[edge.first];
++k_node[edge.second];
}
auto it_e_in = all_edges_in.begin();
auto it_e_out = all_edges_out.begin();
auto it_t_ab = ab_time.begin();
auto it_t_ec = ec_time.begin();
auto it_a = a.begin();
auto it_b = beta.begin();
double t = ec.t0;
double t_next_ab;
double t_next_ec;
double t_next;
if (verbose)
cout << "number of nodes = " << N << endl;
do
{
// check which is the next event time at which stuff changes
if ((it_t_ab == ab_time.end()) or (it_t_ab+1 == ab_time.end()))
t_next_ab = tmax;
else
t_next_ab = *(it_t_ab+1);
if ((it_t_ec == ec_time.end()) or (it_t_ec+1 == ec_time.end()))
t_next_ec = tmax;
else
t_next_ec = *(it_t_ec+1);
if ( t_next_ec <= t_next_ab )
t_next = t_next_ec;
else
t_next = t_next_ab;
// compute the integrals up to the next change
double dt = t_next - t;
double mean_degree = ((double) number_of_edges) * 2.0 / Nf / k_over_k_real_scaling;
auto i_k = k_node.begin();
auto i_I_out_1 = I_out_1.begin();
auto i_I_out_2 = I_out_2.begin();
auto i_I_in_1 = I_in_1.begin();
auto i_I_in_2 = I_in_2.begin();
double &_a = *it_a;
double &_b = *it_b;
//cout << "_a = " << _a << endl;
//cout << "_b = " << _b << endl;
while(i_k != k_node.end())
{
double _k = ((double) *i_k) / k_over_k_real_scaling;
(*i_I_out_1) += _a * _k * dt;
(*i_I_out_2) += _b * _k * dt;
(*i_I_in_1) += _a * (Nf - _k - 1.0) * (_k + 1.0) / (Nf - 1.0) * dt;
(*i_I_in_2) += _a * (1.0 + mean_degree) * dt;
++i_k;
++i_I_out_1;
++i_I_out_2;
++i_I_in_1;
++i_I_in_2;
}
// advance time
t = t_next;
// change either the network or gamma and P or both
if (t_next_ec <= t_next_ab)
{
// update observables for this advancement
for(auto const &edge : *it_e_in)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
++k_node[u];
++k_node[v];
++M_in[u];
++M_in[v];
number_of_edges++;
}
for(auto const &edge : *it_e_out)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
--k_node[u];
--k_node[v];
++M_out[u];
++M_out[v];
number_of_edges--;
}
// advance network
++it_t_ec;
++it_e_out;
++it_e_in;
}
if (t_next_ab <= t_next_ec)
{
// advance <alpha> and <beta>
++it_a;
++it_b;
++it_t_ab;
}
} while ((t_next_ab < tmax) or (t_next_ec < tmax));
vector < double > a_node;
vector < double > b_node;
double Alpha = 0.0;
double Beta = 0.0;
double mean_M_in = 0.0;
double mean_M_out = 0.0;
double mean_I_in_1 = 0.0;
double mean_I_in_2 = 0.0;
double mean_I_out_1 = 0.0;
double mean_I_out_2 = 0.0;
for (size_t node = 0; node < N; ++node)
{
if (verbose)
{
cout << "node = " << node << "; " << "M_in = " << M_in[node] << endl;
cout << "node = " << node << "; " << "M_out = " << M_out[node] << endl;
cout << "node = " << node << "; " << "I_in_1 = " << I_in_1[node] << endl;
cout << "node = " << node << "; " << "I_out_1 = " << I_out_1[node] << endl;
cout << "node = " << node << "; " << "I_in_2 = " << I_in_2[node] << endl;
cout << "node = " << node << "; " << "I_out_2 = " << I_out_2[node] << endl;
}
mean_M_in += M_in[node] / (double) N;
mean_M_out += M_out[node] / (double) N;
mean_I_in_1 += I_in_1[node] / (double) N;
mean_I_out_1 += I_out_1[node] / (double) N;
mean_I_in_2 += I_in_2[node] / (double) N;
mean_I_out_2 += I_out_2[node] / (double) N;
}
//double mean_alpha = mean_M_in / ( mean_I_in_1 + mean_I_in_2 );
//double mean_beta = mean_M_out / ( mean_I_out_1 + mean_I_out_2 ) - mean_alpha;
double mean_alpha = mean_M_in / ( mean_I_in_1 + mean_I_in_2 );
double mean_beta = (mean_M_out*0.5 - mean_alpha) / mean_I_out_2;
for (size_t node = 0; node < N; ++node)
{
/*
cout << "M_in[" << node << "] = " << M_in[node] << endl;
cout << "M_out[" << node << "] = " << M_out[node] << endl;
cout << "I_in_1[" << node << "] = " << I_in_1[node] << endl;
cout << "I_in_2[" << node << "] = " << I_in_2[node] << endl;
cout << "I_out[" << node << "] = " << I_out[node] << endl;
cout << "I_out_2[" << node << "] = " << I_out_2[node] << endl;
*/
double this_a, this_b;
if (not apply_mean_correction)
{
if (I_in_2[node] == 0.0)
this_a = 0.0;
else
this_a = (M_in[node] - I_in_1[node]) / I_in_2[node];
if (I_out_2[node] == 0.0)
this_b = 0.0;
else
this_b = (M_out[node] - I_out_1[node] - I_out_2[node] - this_a * I_out_1[node]) / I_out_2[node];
}
else
{
if (I_in_2[node] == 0.0)
this_a = 0.0;
else
this_a = (M_in[node] - mean_alpha * I_in_1[node]) / I_in_2[node];
if (I_out_2[node] == 0.0)
this_b = 0.0;
else
this_b = (M_out[node] - mean_alpha * I_out_1[node] - mean_beta * I_out_2[node] - this_a * I_out_1[node]) / I_out_2[node];
}
if (verbose)
{
cout << "node " << node << " ; alpha = "<< this_a << endl;
cout << "node " << node << " ; beta = "<< this_b << endl;
}
if (this_a < 0.0)
this_a = 0.0;
if (this_b < 0.0)
this_b = 0.0;
a_node.push_back(this_a);
b_node.push_back(this_b);
Alpha += this_a;
Beta += this_b;
if (verbose)
{
cout << "node " << node << " ; corrected alpha = "<< this_a << endl;
cout << "node " << node << " ; corrected beta = "<< this_b << endl;
}
}
Alpha /= (double) N;
Beta /= (double) N;
for (size_t node = 0; node < N; ++node)
{
if (Alpha > 0.0)
a_node[node] /= Alpha;
if (Beta > 0.0)
b_node[node] /= Beta;
}
return make_pair(a_node, b_node);
}
pair < vector < vector < double > >, vector < vector < double > > >
get_time_dependent_node_alpha_and_beta(
edge_changes &ec,
vector < pair < double, double > > &alpha,
vector < double > &beta,
bool apply_mean_correction
)
{
// get references to edge_list and time
vector < vector < pair < size_t, size_t > > > & all_edges_in = ec.edges_in;
vector < vector < pair < size_t, size_t > > > & all_edges_out = ec.edges_out;
vector < double > &ec_time = ec.t;
// get vectors from gamma and P
vector < double > ab_time;
vector < double > a;
for(auto &a_entry: alpha)
{
ab_time.push_back(a_entry.first);
a.push_back(a_entry.second);
}
// set initial and final time
double tmax = ec.tmax;
// graph observables
size_t N = ec.N;
double Nf(N);
size_t number_of_edges = ec.edges_initial.size();
// intialize the node properties
vector < size_t > k_node(N);
vector < size_t > M_out(N);
vector < size_t > M_in(N);
// intialize the integrals
vector < double > I_out_1(N);
vector < double > I_out_2(N);
vector < double > I_in_1(N);
vector < double > I_in_2(N);
for(auto const &edge : ec.edges_initial)
{
++k_node[edge.first];
++k_node[edge.second];
}
auto it_e_in = all_edges_in.begin();
auto it_e_out = all_edges_out.begin();
auto it_t_ab = ab_time.begin();
auto it_t_ec = ec_time.begin();
auto it_a = a.begin();
auto it_b = beta.begin();
double t = ec.t0;
double t_next_ab;
double t_next_ec;
double t_next;
vector < vector < double > > alpha_t;
vector < vector < double > > beta_t;
do
{
// check which is the next event time at which stuff changes
if ((it_t_ab == ab_time.end()) or (it_t_ab+1 == ab_time.end()))
t_next_ab = tmax;
else
t_next_ab = *(it_t_ab+1);
if ((it_t_ec == ec_time.end()) or (it_t_ec+1 == ec_time.end()))
t_next_ec = tmax;
else
t_next_ec = *(it_t_ec+1);
if ( t_next_ec <= t_next_ab )
t_next = t_next_ec;
else
t_next = t_next_ab;
// compute the integrals up to the next change
double dt = t_next - t;
double mean_degree = ((double) number_of_edges) * 2.0 / Nf;
auto i_k = k_node.begin();
auto i_I_out_1 = I_out_1.begin();
auto i_I_out_2 = I_out_2.begin();
auto i_I_in_1 = I_in_1.begin();
auto i_I_in_2 = I_in_2.begin();
double &_a = *it_a;
double &_b = *it_b;
//cout << "_a = " << _a << endl;
//cout << "_b = " << _b << endl;
while(i_k != k_node.end())
{
double _k = (double) *i_k;
(*i_I_out_1) += _a * _k * dt;
(*i_I_out_2) += _b * _k * dt;
(*i_I_in_1) += _a * (Nf - _k - 1.0) * (_k + 1.0) / (Nf - 1.0) * dt;
(*i_I_in_2) += _a * (1.0 + mean_degree) * dt;
++i_k;
++i_I_out_1;
++i_I_out_2;
++i_I_in_1;
++i_I_in_2;
}
// advance time
t = t_next;
// change either the network or gamma and P or both
if (t_next_ec <= t_next_ab)
{
// update observables for this advancement
for(auto const &edge : *it_e_in)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
++k_node[u];
++k_node[v];
++M_in[u];
++M_in[v];
number_of_edges++;
}
for(auto const &edge : *it_e_out)
{
size_t const &u = edge.first;
size_t const &v = edge.second;
--k_node[u];
--k_node[v];
++M_out[u];
++M_out[v];
number_of_edges--;
}
// advance network
++it_t_ec;
++it_e_out;
++it_e_in;
}
if (t_next_ab <= t_next_ec)
{
vector < double > a_node;
vector < double > b_node;
double Alpha = 0.0;
double Beta = 0.0;
double mean_M_in = 0.0;
double mean_M_out = 0.0;
double mean_I_in_1 = 0.0;
double mean_I_in_2 = 0.0;
double mean_I_out_1 = 0.0;
double mean_I_out_2 = 0.0;
for (size_t node = 0; node < N; ++node)
{
mean_M_in += M_in[node] / (double) N;
mean_M_out += M_out[node] / (double) N;
mean_I_in_1 += I_in_1[node] / (double) N;
mean_I_out_1 += I_out_1[node] / (double) N;
mean_I_in_2 += I_in_2[node] / (double) N;
mean_I_out_2 += I_out_2[node] / (double) N;
}
//double mean_alpha = mean_M_in / ( mean_I_in_1 + mean_I_in_2 );
//double mean_beta = mean_M_out / ( mean_I_out_1 + mean_I_out_2 ) - mean_alpha;
double mean_alpha = mean_M_in / ( mean_I_in_1 + mean_I_in_2 );
double mean_beta = (mean_M_out*0.5 - mean_alpha) / mean_I_out_2;
if (( mean_I_in_1 + mean_I_in_2 ) == 0.0)
mean_alpha = 0.0;
if (( mean_I_out_1 + mean_I_out_2 ) == 0.0)
mean_beta = 0.0;
for (size_t node = 0; node < N; ++node)
{
double this_a, this_b;
if (not apply_mean_correction)
{
if (I_in_2[node] == 0.0)
this_a = 0.0;
else
this_a = (M_in[node] - I_in_1[node]) / I_in_2[node];
if (I_out_2[node] == 0.0)
this_b = 0.0;
else
this_b = (M_out[node] - I_out_1[node] - I_out_2[node] - this_a * I_out_1[node]) / I_out_2[node];
}
else
{
if (I_in_2[node] == 0.0)
this_a = 0.0;
else
this_a = (M_in[node] - mean_alpha * I_in_1[node]) / I_in_2[node];
if (I_out_2[node] == 0.0)
this_b = 0.0;
else
this_b = (M_out[node] - mean_alpha * I_out_1[node] - mean_beta * I_out_2[node] - this_a * I_out_1[node]) / I_out_2[node];
}
if (this_a < 0.0)
this_a = 0.0;
if (this_b < 0.0)
this_b = 0.0;
a_node.push_back(this_a);
b_node.push_back(this_b);
Alpha += this_a;
Beta += this_b;
}
Alpha /= (double) N;
Beta /= (double) N;
for (size_t node = 0; node < N; ++node)
{
if (Alpha > 0.0)
a_node[node] *= (*it_a) / Alpha;
if (Beta > 0.0)
b_node[node] *= (*it_b) / Beta;
// reset the integrals
M_out[node] = 0.0;
M_in[node] = 0.0;
I_out_1[node] = 0.0;
I_out_2[node] = 0.0;
I_in_1[node] = 0.0;
I_in_2[node] = 0.0;
}
alpha_t.push_back(a_node);
beta_t.push_back(b_node);
// advance gamma and P
++it_a;
++it_b;
++it_t_ab;
}
} while ((t_next_ab < tmax) or (t_next_ec < tmax));
return make_pair(alpha_t, beta_t);
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <folly/io/async/AsyncSocket.h>
#include <proxygen/httpserver/HTTPServer.h>
#include <proxygen/httpserver/HTTPServerOptions.h>
#include <proxygen/httpserver/ScopedHTTPServer.h>
#include <thrift/lib/cpp2/transport/http2/client/H2ClientConnection.h>
namespace apache {
namespace thrift {
TEST(H2ClientConnectionTest, ServerCloseSocketImmediate) {
folly::SocketAddress saddr;
saddr.setFromLocalPort(static_cast<uint16_t>(0));
proxygen::HTTPServer::IPConfig cfg{
saddr, proxygen::HTTPServer::Protocol::HTTP2};
auto server =
proxygen::ScopedHTTPServer::start(cfg, proxygen::HTTPServerOptions{});
ASSERT_NE(nullptr, server);
const auto port = server->getPort();
ASSERT_NE(0, port);
folly::EventBase evb;
folly::SocketAddress addr;
addr.setFromLocalPort(port);
folly::AsyncSocket::UniquePtr sock(new folly::AsyncSocket(&evb, addr));
auto conn = H2ClientConnection::newHTTP2Connection(std::move(sock));
EXPECT_TRUE(conn->good());
server.reset(); // server closes connection
evb.loop();
EXPECT_FALSE(conn->good());
EXPECT_EQ(nullptr, conn->getTransport());
}
} // namespace thrift
} // namespace apache
|
/*
* test_Stoploss.cpp
*
* Created on: 2013-3-13
* Author: fasiondog
*/
#ifdef TEST_ALL_IN_ONE
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_MODULE test_hikyuu_trade_sys_suite
#include <boost/test/unit_test.hpp>
#endif
#include <hikyuu/StockManager.h>
#include <hikyuu/trade_sys/stoploss/StoplossBase.h>
using namespace hku;
class StoplossTest: public StoplossBase {
public:
StoplossTest(): StoplossBase("StoplossTest"), m_x(0) {}
virtual ~StoplossTest() {}
virtual price_t getPrice(const Datetime& datetime, price_t price) {
return m_x < 10 ? 0.0 : 1.0;
}
virtual void _reset() {
m_x = 0;
}
virtual StoplossPtr _clone() {
StoplossTest *p = new StoplossTest;
p->m_x = m_x;
return StoplossPtr(p);
}
virtual void _calculate() {}
int getX() const { return m_x;}
void setX(int x) { m_x = x; }
private:
int m_x;
};
/**
* @defgroup test_Stoploss test_Stoploss
* @ingroup test_hikyuu_trade_sys_suite
* @{
*/
/** @par 检测点 */
BOOST_AUTO_TEST_CASE( test_Stoploss) {
/** @arg 基本操作 */
StoplossPtr p(new StoplossTest);
BOOST_CHECK(p->name() == "StoplossTest");
BOOST_CHECK(p->getPrice(Datetime(200101010000), 1.0) == 0.0);
StoplossTest *p_src = (StoplossTest *)p.get();
BOOST_CHECK(p_src->getX() == 0);
p_src->setX(10);
BOOST_CHECK(p->getPrice(Datetime(200101010000), 1.0) == 1.0);
BOOST_CHECK(p_src->getX() == 10);
p->reset();
BOOST_CHECK(p_src->getX() == 0);
/** @arg 测试克隆操作 */
p_src->setX(10);
StoplossPtr p_clone = p->clone();
BOOST_CHECK(p_clone->name() == "StoplossTest");
p_src = (StoplossTest *)p_clone.get();
BOOST_CHECK(p_src->getX() == 10);
BOOST_CHECK(p != p_clone);
}
/** @} */
|
/*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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.
*/
#pragma once
class Opticks ;
template <typename T> class NPY ;
#include "G4Types.hh"
#include "CFG4_API_EXPORT.hh"
#include "CSource.hh"
/**
CPrimaryCollector
===================
Primaries (item shape 4*4, 4 quads)
-------------------------------------
Primary collection is invoked from CSource::collectPrimary(G4PrimaryVertex* vtx)
into the CPrimaryCollector singleton instance.
**/
class CFG4_API CPrimaryCollector
{
public:
static CPrimaryCollector* Instance();
private:
static CPrimaryCollector* INSTANCE ;
public:
CPrimaryCollector();
std::string description() const ;
void Summary(const char* msg="CPrimaryCollector::Summary") const ;
public:
NPY<float>* getPrimary() const ;
void save(const char* path) const ;
public:
//void collectPrimary(G4PrimaryVertex* vertex);
void collectPrimaries(const G4Event* event);
void collectPrimaryVertex(G4int vertex_index, const G4Event* event);
void collectPrimaryVertex(const G4PrimaryVertex* vtx, G4int vertex_index); // for backward compat to CSource collection
void collectPrimaryParticle(G4int vertex_index, G4int primary_index, const G4PrimaryVertex* vtx);
void collectPrimary(
G4double x0,
G4double y0,
G4double z0,
G4double t0,
G4double dir_x,
G4double dir_y,
G4double dir_z,
G4double weight,
G4double pol_x,
G4double pol_y,
G4double pol_z,
G4double kineticEnergy,
int spare,
int vertex_index,
int primary_index,
int pdgcode
);
private:
NPY<float>* m_primary ;
unsigned m_primary_itemsize ;
float* m_primary_values ;
unsigned m_primary_count ;
};
|
// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/CoordinateSystemNode>
#include <osg/Matrixd>
#include <osg/Node>
#include <osg/Vec3d>
#include <osgGA/GUIActionAdapter>
#include <osgGA/GUIEventAdapter>
#include <osgGA/MatrixManipulator>
#include <osgUtil/SceneView>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_ABSTRACT_OBJECT_REFLECTOR(osgGA::MatrixManipulator)
I_DeclaringFile("osgGA/MatrixManipulator");
I_BaseType(osgGA::GUIEventHandler);
I_Method0(const char *, className,
Properties::VIRTUAL,
__C5_char_P1__className,
"return the name of the object's class type. ",
"Must be defined by derived classes. ");
I_Method1(void, setMinimumDistance, IN, float, minimumDistance,
Properties::VIRTUAL,
__void__setMinimumDistance__float,
"set the minimum distance (as ratio) the eye point can be zoomed in towards the center before the center is pushed forward. ",
"");
I_Method0(float, getMinimumDistance,
Properties::NON_VIRTUAL,
__float__getMinimumDistance,
"get the minimum distance (as ratio) the eye point can be zoomed in ",
"");
I_Method1(void, setCoordinateFrameCallback, IN, osgGA::MatrixManipulator::CoordinateFrameCallback *, cb,
Properties::VIRTUAL,
__void__setCoordinateFrameCallback__CoordinateFrameCallback_P1,
"set the coordinate frame which callback tells the manipulator which way is up, east and north. ",
"");
I_Method0(osgGA::MatrixManipulator::CoordinateFrameCallback *, getCoordinateFrameCallback,
Properties::NON_VIRTUAL,
__CoordinateFrameCallback_P1__getCoordinateFrameCallback,
"get the coordinate frame callback which tells the manipulator which way is up, east and north. ",
"");
I_Method0(const osgGA::MatrixManipulator::CoordinateFrameCallback *, getCoordinateFrameCallback,
Properties::NON_VIRTUAL,
__C5_CoordinateFrameCallback_P1__getCoordinateFrameCallback,
"get the coordinate frame callback which tells the manipulator which way is up, east and north. ",
"");
I_Method1(osg::CoordinateFrame, getCoordinateFrame, IN, const osg::Vec3d &, position,
Properties::NON_VIRTUAL,
__osg_CoordinateFrame__getCoordinateFrame__C5_osg_Vec3d_R1,
"get the coordinate frame. ",
"");
I_Method1(osg::Vec3d, getSideVector, IN, const osg::CoordinateFrame &, cf,
Properties::NON_VIRTUAL,
__osg_Vec3d__getSideVector__C5_osg_CoordinateFrame_R1,
"",
"");
I_Method1(osg::Vec3d, getFrontVector, IN, const osg::CoordinateFrame &, cf,
Properties::NON_VIRTUAL,
__osg_Vec3d__getFrontVector__C5_osg_CoordinateFrame_R1,
"",
"");
I_Method1(osg::Vec3d, getUpVector, IN, const osg::CoordinateFrame &, cf,
Properties::NON_VIRTUAL,
__osg_Vec3d__getUpVector__C5_osg_CoordinateFrame_R1,
"",
"");
I_Method1(void, setByMatrix, IN, const osg::Matrixd &, matrix,
Properties::PURE_VIRTUAL,
__void__setByMatrix__C5_osg_Matrixd_R1,
"set the position of the matrix manipulator using a 4x4 Matrix. ",
"");
I_Method1(void, setByInverseMatrix, IN, const osg::Matrixd &, matrix,
Properties::PURE_VIRTUAL,
__void__setByInverseMatrix__C5_osg_Matrixd_R1,
"set the position of the matrix manipulator using a 4x4 Matrix. ",
"");
I_Method0(osg::Matrixd, getMatrix,
Properties::PURE_VIRTUAL,
__osg_Matrixd__getMatrix,
"get the position of the manipulator as 4x4 Matrix. ",
"");
I_Method0(osg::Matrixd, getInverseMatrix,
Properties::PURE_VIRTUAL,
__osg_Matrixd__getInverseMatrix,
"get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix. ",
"");
I_Method0(osgUtil::SceneView::FusionDistanceMode, getFusionDistanceMode,
Properties::VIRTUAL,
__osgUtil_SceneView_FusionDistanceMode__getFusionDistanceMode,
"Get the FusionDistanceMode. ",
"Used by SceneView for setting up stereo convergence. ");
I_Method0(float, getFusionDistanceValue,
Properties::VIRTUAL,
__float__getFusionDistanceValue,
"Get the FusionDistanceValue. ",
"Used by SceneView for setting up stereo convergence. ");
I_Method1(void, setIntersectTraversalMask, IN, unsigned int, mask,
Properties::NON_VIRTUAL,
__void__setIntersectTraversalMask__unsigned_int,
"Set the mask to use when set up intersection traversal such as used in manipulators that follow terrain or have collision detection. ",
"The intersection traversal mask is useful for controlling what parts of the scene graph should be used for intersection purposes. ");
I_Method0(unsigned int, getIntersectTraversalMask,
Properties::NON_VIRTUAL,
__unsigned_int__getIntersectTraversalMask,
"Get the mask to use when set up intersection traversal such as used in manipulators that follow terrain or have collision detection. ",
"");
I_Method1(void, setNode, IN, osg::Node *, x,
Properties::VIRTUAL,
__void__setNode__osg_Node_P1,
"Attach a node to the manipulator, automatically detaching any previously attached node. ",
"setNode(NULL) detaches previous nodes. May be ignored by manipulators which do not require a reference model. ");
I_Method0(const osg::Node *, getNode,
Properties::VIRTUAL,
__C5_osg_Node_P1__getNode,
"Return const node if attached. ",
"");
I_Method0(osg::Node *, getNode,
Properties::VIRTUAL,
__osg_Node_P1__getNode,
"Return node if attached. ",
"");
I_MethodWithDefaults4(void, setHomePosition, IN, const osg::Vec3d &, eye, , IN, const osg::Vec3d &, center, , IN, const osg::Vec3d &, up, , IN, bool, autoComputeHomePosition, false,
Properties::VIRTUAL,
__void__setHomePosition__C5_osg_Vec3d_R1__C5_osg_Vec3d_R1__C5_osg_Vec3d_R1__bool,
"Manually set the home position, and set the automatic compute of home position. ",
"");
I_Method3(void, getHomePosition, IN, osg::Vec3d &, eye, IN, osg::Vec3d &, center, IN, osg::Vec3d &, up,
Properties::VIRTUAL,
__void__getHomePosition__osg_Vec3d_R1__osg_Vec3d_R1__osg_Vec3d_R1,
"Get the manually set home position. ",
"");
I_Method1(void, setAutoComputeHomePosition, IN, bool, flag,
Properties::VIRTUAL,
__void__setAutoComputeHomePosition__bool,
"Set whether the automatic compute of the home position is enabled. ",
"");
I_Method0(bool, getAutoComputeHomePosition,
Properties::NON_VIRTUAL,
__bool__getAutoComputeHomePosition,
"Get whether the automatic compute of the home position is enabled. ",
"");
I_Method0(void, computeHomePosition,
Properties::VIRTUAL,
__void__computeHomePosition,
"Compute the home position. ",
"");
I_Method2(void, home, IN, const osgGA::GUIEventAdapter &, x, IN, osgGA::GUIActionAdapter &, x,
Properties::VIRTUAL,
__void__home__C5_GUIEventAdapter_R1__GUIActionAdapter_R1,
"Move the camera to the default position. ",
"May be ignored by manipulators if home functionality is not appropriate. ");
I_Method1(void, home, IN, double, x,
Properties::VIRTUAL,
__void__home__double,
"Move the camera to the default position. ",
"This version does not require GUIEventAdapter and GUIActionAdapter so may be called from somewhere other than a handle() method in GUIEventHandler. Application must be aware of implications. ");
I_Method2(void, init, IN, const osgGA::GUIEventAdapter &, x, IN, osgGA::GUIActionAdapter &, x,
Properties::VIRTUAL,
__void__init__C5_GUIEventAdapter_R1__GUIActionAdapter_R1,
"Start/restart the manipulator. ",
"FIXME: what does this actually mean? Provide examples. ");
I_Method2(bool, handle, IN, const osgGA::GUIEventAdapter &, ea, IN, osgGA::GUIActionAdapter &, us,
Properties::VIRTUAL,
__bool__handle__C5_GUIEventAdapter_R1__GUIActionAdapter_R1,
"Handle events, return true if handled, false otherwise. ",
"");
I_ProtectedConstructor0(____MatrixManipulator,
"",
"");
I_SimpleProperty(bool, AutoComputeHomePosition,
__bool__getAutoComputeHomePosition,
__void__setAutoComputeHomePosition__bool);
I_SimpleProperty(const osg::Matrixd &, ByInverseMatrix,
0,
__void__setByInverseMatrix__C5_osg_Matrixd_R1);
I_SimpleProperty(const osg::Matrixd &, ByMatrix,
0,
__void__setByMatrix__C5_osg_Matrixd_R1);
I_SimpleProperty(osgGA::MatrixManipulator::CoordinateFrameCallback *, CoordinateFrameCallback,
__CoordinateFrameCallback_P1__getCoordinateFrameCallback,
__void__setCoordinateFrameCallback__CoordinateFrameCallback_P1);
I_SimpleProperty(osgUtil::SceneView::FusionDistanceMode, FusionDistanceMode,
__osgUtil_SceneView_FusionDistanceMode__getFusionDistanceMode,
0);
I_SimpleProperty(float, FusionDistanceValue,
__float__getFusionDistanceValue,
0);
I_SimpleProperty(unsigned int, IntersectTraversalMask,
__unsigned_int__getIntersectTraversalMask,
__void__setIntersectTraversalMask__unsigned_int);
I_SimpleProperty(osg::Matrixd, InverseMatrix,
__osg_Matrixd__getInverseMatrix,
0);
I_SimpleProperty(osg::Matrixd, Matrix,
__osg_Matrixd__getMatrix,
0);
I_SimpleProperty(float, MinimumDistance,
__float__getMinimumDistance,
__void__setMinimumDistance__float);
I_SimpleProperty(osg::Node *, Node,
__osg_Node_P1__getNode,
__void__setNode__osg_Node_P1);
END_REFLECTOR
BEGIN_ABSTRACT_OBJECT_REFLECTOR(osgGA::MatrixManipulator::CoordinateFrameCallback)
I_DeclaringFile("osgGA/MatrixManipulator");
I_BaseType(osg::Referenced);
I_Constructor0(____CoordinateFrameCallback,
"",
"");
I_Method1(osg::CoordinateFrame, getCoordinateFrame, IN, const osg::Vec3d &, position,
Properties::PURE_VIRTUAL,
__osg_CoordinateFrame__getCoordinateFrame__C5_osg_Vec3d_R1,
"",
"");
END_REFLECTOR
|
#include "TefnoutPCH.hpp"
#include "SortingKey.hpp"
namespace Tefnout
{
namespace Rendering
{
namespace Command
{
SortingKey BuildSortingKey(std::uint32_t materialId, std::uint32_t depth, DrawCall drawType,
std::uint8_t viewportLayerId, std::uint8_t viewportId,
std::uint8_t targetId)
{
using namespace Utility;
SortingKey key = 0;
key |= Bits::Set(key, materialId, SortingKeyLayout::Material.Offset);
key |= Bits::Set(key, depth, SortingKeyLayout::Depth.Offset);
key |= Bits::Set(key, static_cast<std::uint8_t>(drawType), SortingKeyLayout::DrawCall.Offset);
key |= Bits::Set(key, viewportLayerId, SortingKeyLayout::ViewportLayer.Offset);
key |= Bits::Set(key, viewportId, SortingKeyLayout::Viewport.Offset);
key |= Bits::Set(key, targetId, SortingKeyLayout::Target.Offset);
return key;
}
} // namespace Command
} // namespace Rendering
} // namespace Tefnout
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LiICENSE file.
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h"
#include "skia/ext/image_operations.h"
#include "third_party/blink/public/platform/web_size.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/loader/threadable_loader.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h"
#include "third_party/blink/renderer/modules/background_fetch/icon_definition.h"
#include "third_party/blink/renderer/platform/graphics/color_behavior.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/image_frame.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_impl.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
namespace blink {
namespace {
const unsigned long kIconFetchTimeoutInMs = 30000;
const int kMinimumIconSizeInPx = 16;
const double kAnySizeScore = 0.8;
const double kUnspecifiedSizeScore = 0.4;
} // namespace
BackgroundFetchIconLoader::BackgroundFetchIconLoader() = default;
BackgroundFetchIconLoader::~BackgroundFetchIconLoader() {
// We should've called Stop() before the destructor is invoked.
DCHECK(stopped_ || icon_callback_.is_null());
}
void BackgroundFetchIconLoader::Start(BackgroundFetchBridge* bridge,
ExecutionContext* execution_context,
HeapVector<IconDefinition> icons,
IconCallback icon_callback) {
DCHECK(!stopped_);
DCHECK_GE(icons.size(), 1u);
DCHECK(bridge);
icons_ = std::move(icons);
bridge->GetIconDisplaySize(
WTF::Bind(&BackgroundFetchIconLoader::DidGetIconDisplaySizeIfSoLoadIcon,
WrapWeakPersistent(this), WrapWeakPersistent(execution_context),
std::move(icon_callback)));
}
void BackgroundFetchIconLoader::DidGetIconDisplaySizeIfSoLoadIcon(
ExecutionContext* execution_context,
IconCallback icon_callback,
const WebSize& icon_display_size_pixels) {
if (icon_display_size_pixels.IsEmpty()) {
std::move(icon_callback).Run(SkBitmap());
return;
}
int best_icon_index =
PickBestIconForDisplay(execution_context, icon_display_size_pixels);
if (best_icon_index < 0) {
// None of the icons provided was suitable.
std::move(icon_callback).Run(SkBitmap());
return;
}
KURL best_icon_url =
execution_context->CompleteURL(icons_[best_icon_index].src());
icon_callback_ = std::move(icon_callback);
ThreadableLoaderOptions threadable_loader_options;
threadable_loader_options.timeout_milliseconds = kIconFetchTimeoutInMs;
ResourceLoaderOptions resource_loader_options;
if (execution_context->IsWorkerGlobalScope())
resource_loader_options.request_initiator_context = kWorkerContext;
ResourceRequest resource_request(best_icon_url);
resource_request.SetRequestContext(WebURLRequest::kRequestContextImage);
resource_request.SetPriority(ResourceLoadPriority::kMedium);
resource_request.SetRequestorOrigin(execution_context->GetSecurityOrigin());
threadable_loader_ = ThreadableLoader::Create(*execution_context, this,
threadable_loader_options,
resource_loader_options);
threadable_loader_->Start(resource_request);
}
int BackgroundFetchIconLoader::PickBestIconForDisplay(
ExecutionContext* execution_context,
const WebSize& icon_display_size_pixels) {
int best_index = -1;
double best_score = 0.0;
for (size_t i = 0; i < icons_.size(); ++i) {
// If the icon has no or invalid src, move on.
if (!icons_[i].hasSrc())
continue;
KURL icon_url = execution_context->CompleteURL(icons_[i].src());
if (!icon_url.IsValid() || icon_url.IsEmpty())
continue;
double score = GetIconScore(icons_[i], icon_display_size_pixels.width);
if (!score)
continue;
// According to the spec, if two icons get the same score, we must use the
// one that's declared last. (https://w3c.github.io/manifest/#icons-member).
if (score >= best_score) {
best_score = score;
best_index = i;
}
}
return best_index;
}
// The scoring works as follows:
// When the size is "any", the icon size score is kAnySizeScore.
// If unspecified, use the unspecified size score, kUnspecifiedSizeScore as
// icon score.
// For other sizes, the icon score lies in [0,1] and is computed by multiplying
// the dominant size score and aspect ratio score.
//
// The dominant size score lies in [0, 1] and is computed using
// dominant size and and |ideal_size|:
// - If dominant_size < kMinimumIconSizeInPx, the size score is 0.0.
// - For all other sizes, the score is calculated as
// 1/(1 + abs(dominant_size-ideal_size))
// - If dominant_size < ideal_size, there is an upscaling penalty, which is
// dominant_size/ideal_size.
//
// The aspect ratio score lies in [0, 1] and is computed by dividing the short
// edge length by the long edge. (Bias towards square icons assumed).
//
// Note: If this is an ico file containing multiple sizes, return the best
// score.
double BackgroundFetchIconLoader::GetIconScore(IconDefinition icon,
const int ideal_size) {
// Extract sizes from the icon definition, expressed as "<width>x<height>
// <width>x<height> ...."
if (!icon.hasSizes() || icon.sizes().IsEmpty())
return kUnspecifiedSizeScore;
String sizes = icon.sizes();
// if any size is set to "any" return kAnySizeScore;
if (sizes.LowerASCII() == "any")
return kAnySizeScore;
Vector<String> sizes_str;
sizes.Split(" ", false /* allow_empty_entries*/, sizes_str);
// Pick the first size.
// TODO(nator): Add support for multiple sizes (.ico files).
Vector<String> width_and_height_str;
sizes_str[0].Split("x", false /* allow_empty_entries */,
width_and_height_str);
// If sizes isn't in this format, consider it as 'unspecified'.
if (width_and_height_str.size() != 2)
return kUnspecifiedSizeScore;
double width = width_and_height_str[0].ToDouble();
double height = width_and_height_str[1].ToDouble();
// Compute dominant size score
int dominant_size = std::max(width, height);
int short_size = std::min(width, height);
if (dominant_size < kMinimumIconSizeInPx)
return 0.0;
double dominant_size_score = 1.0 / (1.0 + abs(dominant_size - ideal_size));
if (dominant_size < ideal_size)
dominant_size_score = dominant_size_score * dominant_size / ideal_size;
// Compute aspect ratio score. If dominant_size is zero, we'd have returned
// by now.
double aspect_ratio_score = short_size / dominant_size;
// Compute icon score.
return aspect_ratio_score * dominant_size_score;
}
void BackgroundFetchIconLoader::Stop() {
if (stopped_)
return;
stopped_ = true;
if (threadable_loader_) {
threadable_loader_->Cancel();
threadable_loader_ = nullptr;
}
}
void BackgroundFetchIconLoader::DidReceiveData(const char* data,
unsigned length) {
if (!data_)
data_ = SharedBuffer::Create();
data_->Append(data, length);
}
void BackgroundFetchIconLoader::DidFinishLoading(
unsigned long resource_identifier) {
if (stopped_)
return;
if (data_) {
// Decode data.
std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create(
data_, true /* data_complete*/, ImageDecoder::kAlphaPremultiplied,
ColorBehavior::TransformToSRGB());
if (decoder) {
// the |ImageFrame*| is owned by the decoder.
ImageFrame* image_frame = decoder->DecodeFrameBufferAtIndex(0);
if (image_frame) {
std::move(icon_callback_).Run(image_frame->Bitmap());
return;
}
}
}
RunCallbackWithEmptyBitmap();
}
void BackgroundFetchIconLoader::DidFail(const ResourceError& error) {
RunCallbackWithEmptyBitmap();
}
void BackgroundFetchIconLoader::DidFailRedirectCheck() {
RunCallbackWithEmptyBitmap();
}
void BackgroundFetchIconLoader::RunCallbackWithEmptyBitmap() {
// If this has been stopped it is not desirable to trigger further work,
// there is a shutdown of some sort in progress.
if (stopped_)
return;
std::move(icon_callback_).Run(SkBitmap());
}
} // namespace blink
|
#include "alert.h"
#include "clientversion.h"
#include "chainparams.h"
#include "init.h"
#include "net.h"
#include "utilstrencodings.h"
#include "utiltime.h"
/*
If you need to broadcast an alert, here's what to do:
1. Modify alert parameters below, see alert.* and comments in the code
for what does what.
2. run futurocoind with -printalert or -sendalert like this:
/path/to/futurocoind -printalert
One minute after starting up the alert will be broadcast. It is then
flooded through the network until the nRelayUntil time, and will be
active until nExpiration OR the alert is cancelled.
If you screw up something, send another alert with nCancel set to cancel
the bad alert.
*/
void ThreadSendAlert(CConnman& connman)
{
if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert"))
return;
// Wait one minute so we get well connected. If we only need to print
// but not to broadcast - do this right away.
if (mapArgs.count("-sendalert"))
MilliSleep(60*1000);
//
// Alerts are relayed around the network until nRelayUntil, flood
// filling to every node.
// After the relay time is past, new nodes are told about alerts
// when they connect to peers, until either nExpiration or
// the alert is cancelled by a newer alert.
// Nodes never save alerts to disk, they are in-memory-only.
//
CAlert alert;
alert.nRelayUntil = GetAdjustedTime() + 15 * 60;
alert.nExpiration = GetAdjustedTime() + 30 * 60 * 60;
alert.nID = 1; // keep track of alert IDs somewhere
alert.nCancel = 0; // cancels previous messages up to this ID number
// These versions are protocol versions
alert.nMinVer = 70000;
alert.nMaxVer = 70103;
//
// 1000 for Misc warnings like out of disk space and clock is wrong
// 2000 for longer invalid proof-of-work chain
// Higher numbers mean higher priority
alert.nPriority = 5000;
alert.strComment = "";
alert.strStatusBar = "URGENT: Upgrade required: see https://www.futurocoin.org";
// Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done:
// alert.setSubVer.insert(std::string("/FuturoCoin Core:0.12.0.58/"));
// Sign
if(!alert.Sign())
{
LogPrintf("ThreadSendAlert() : could not sign alert\n");
return;
}
// Test
CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION);
sBuffer << alert;
CAlert alert2;
sBuffer >> alert2;
if (!alert2.CheckSignature(Params().AlertKey()))
{
printf("ThreadSendAlert() : CheckSignature failed\n");
return;
}
assert(alert2.vchMsg == alert.vchMsg);
assert(alert2.vchSig == alert.vchSig);
alert.SetNull();
printf("\nThreadSendAlert:\n");
printf("hash=%s\n", alert2.GetHash().ToString().c_str());
printf("%s", alert2.ToString().c_str());
printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str());
printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str());
// Confirm
if (!mapArgs.count("-sendalert"))
return;
while (connman.GetNodeCount(CConnman::CONNECTIONS_ALL) == 0 && !ShutdownRequested())
MilliSleep(500);
if (ShutdownRequested())
return;
// Send
printf("ThreadSendAlert() : Sending alert\n");
int nSent = 0;
{
connman.ForEachNode([&alert2, &connman, &nSent](CNode* pnode) {
if (alert2.RelayTo(pnode, connman))
{
printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str());
nSent++;
}
});
}
printf("ThreadSendAlert() : Alert sent to %d nodes\n", nSent);
}
|
#pragma once
#include <mbgl/programs/circle_program.hpp>
#include <mbgl/programs/extrusion_texture_program.hpp>
#include <mbgl/programs/fill_program.hpp>
#include <mbgl/programs/fill_extrusion_program.hpp>
#include <mbgl/programs/line_program.hpp>
#include <mbgl/programs/raster_program.hpp>
#include <mbgl/programs/symbol_program.hpp>
#include <mbgl/programs/debug_program.hpp>
#include <mbgl/programs/collision_box_program.hpp>
#include <mbgl/programs/program_parameters.hpp>
namespace mbgl {
class Programs {
public:
Programs(gl::Context& context, const ProgramParameters& programParameters)
: circle(context, programParameters),
extrusionTexture(context, programParameters),
fill(context, programParameters),
fillExtrusion(context, programParameters),
fillExtrusionPattern(context, programParameters),
fillPattern(context, programParameters),
fillOutline(context, programParameters),
fillOutlinePattern(context, programParameters),
line(context, programParameters),
lineSDF(context, programParameters),
linePattern(context, programParameters),
raster(context, programParameters),
symbolIcon(context, programParameters),
symbolIconSDF(context, programParameters),
symbolGlyph(context, programParameters),
debug(context, ProgramParameters(programParameters.pixelRatio, false, programParameters.cacheDir)),
collisionBox(context, ProgramParameters(programParameters.pixelRatio, false, programParameters.cacheDir)) {
}
CircleProgram circle;
ExtrusionTextureProgram extrusionTexture;
FillProgram fill;
FillExtrusionProgram fillExtrusion;
FillExtrusionPatternProgram fillExtrusionPattern;
FillPatternProgram fillPattern;
FillOutlineProgram fillOutline;
FillOutlinePatternProgram fillOutlinePattern;
LineProgram line;
LineSDFProgram lineSDF;
LinePatternProgram linePattern;
RasterProgram raster;
SymbolIconProgram symbolIcon;
SymbolSDFIconProgram symbolIconSDF;
SymbolSDFTextProgram symbolGlyph;
DebugProgram debug;
CollisionBoxProgram collisionBox;
};
} // namespace mbgl
|
#pragma once
#include <string>
#include <sstream>
#include "defines.hpp"
#include "registers.hpp"
#include "cpu_state.hpp"
namespace M68K{
namespace DISASSEMBLER{
std::string reg(RegisterType reg);
std::string sizeSuffix(DataSize size);
std::string effectiveAddress(AddressingMode mode, RegisterType reg, DataSize size, CPUState& cpu_state);
std::string conditionSuffix(Condition cond);
}
}
|
// 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 __PROCESS_ID_HPP__
#define __PROCESS_ID_HPP__
/** @file */
#include <string>
namespace process {
namespace ID {
/**
* Returns 'prefix(N)' where N represents the number of instances
* where the same prefix (wrt. string value equality) has been used
* to generate an ID.
*
* @param prefix The prefix to base the result.
* @return An "ID" in the shape 'prefix(N)'.
*/
std::string generate(const std::string& prefix = "");
} // namespace ID {
} // namespace process {
#endif // __PROCESS_ID_HPP__
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "AdaptiveExecuteAction.h"
using namespace Microsoft::WRL;
using namespace ABI::AdaptiveCards::ObjectModel::Uwp;
using namespace ABI::Windows::Data::Json;
namespace AdaptiveCards::ObjectModel::Uwp
{
HRESULT AdaptiveExecuteAction::RuntimeClassInitialize() noexcept
try
{
std::shared_ptr<AdaptiveCards::ExecuteAction> executeAction = std::make_shared<AdaptiveCards::ExecuteAction>();
return RuntimeClassInitialize(executeAction);
}
CATCH_RETURN;
HRESULT AdaptiveExecuteAction::RuntimeClassInitialize(const std::shared_ptr<AdaptiveCards::ExecuteAction>& sharedExecuteAction)
try
{
auto sharedJson = sharedExecuteAction->GetDataJson();
if (!sharedJson.empty())
{
RETURN_IF_FAILED(StringToJsonValue(sharedExecuteAction->GetDataJson(), &m_dataJson));
}
m_associatedInputs =
static_cast<ABI::AdaptiveCards::ObjectModel::Uwp::AssociatedInputs>(sharedExecuteAction->GetAssociatedInputs());
RETURN_IF_FAILED(UTF8ToHString(sharedExecuteAction->GetVerb(), m_verb.GetAddressOf()));
InitializeBaseElement(std::static_pointer_cast<AdaptiveCards::BaseActionElement>(sharedExecuteAction));
return S_OK;
}
CATCH_RETURN;
HRESULT AdaptiveExecuteAction::get_ActionType(_Out_ ABI::AdaptiveCards::ObjectModel::Uwp::ActionType* actionType)
{
*actionType = ABI::AdaptiveCards::ObjectModel::Uwp::ActionType::Execute;
return S_OK;
}
HRESULT AdaptiveExecuteAction::get_DataJson(_COM_Outptr_ IJsonValue** data) { return m_dataJson.CopyTo(data); }
HRESULT AdaptiveExecuteAction::put_DataJson(_In_ IJsonValue* data)
{
m_dataJson = data;
return S_OK;
}
HRESULT AdaptiveExecuteAction::get_AssociatedInputs(_Out_ ABI::AdaptiveCards::ObjectModel::Uwp::AssociatedInputs* associatedInputs)
{
*associatedInputs = m_associatedInputs;
return S_OK;
}
HRESULT AdaptiveExecuteAction::put_AssociatedInputs(ABI::AdaptiveCards::ObjectModel::Uwp::AssociatedInputs associatedInputs)
{
m_associatedInputs = associatedInputs;
return S_OK;
}
HRESULT AdaptiveExecuteAction::get_Verb(_Outptr_ HSTRING* verb) { return m_verb.CopyTo(verb); }
HRESULT AdaptiveExecuteAction::put_Verb(_In_ HSTRING verb) { return m_verb.Set(verb); }
HRESULT AdaptiveExecuteAction::GetSharedModel(std::shared_ptr<AdaptiveCards::BaseActionElement>& sharedModel)
try
{
std::shared_ptr<AdaptiveCards::ExecuteAction> executeAction = std::make_shared<AdaptiveCards::ExecuteAction>();
RETURN_IF_FAILED(CopySharedElementProperties(*executeAction));
std::string jsonAsString;
if (m_dataJson != nullptr)
{
RETURN_IF_FAILED(JsonValueToString(m_dataJson.Get(), jsonAsString));
executeAction->SetDataJson(std::move(jsonAsString));
}
executeAction->SetAssociatedInputs(static_cast<AdaptiveCards::AssociatedInputs>(m_associatedInputs));
std::string verb;
RETURN_IF_FAILED(HStringToUTF8(m_verb.Get(), verb));
executeAction->SetVerb(verb);
sharedModel = std::move(executeAction);
return S_OK;
}
CATCH_RETURN;
}
|
/*
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 "seurat/geometry/raytracer.h"
#include "ion/math/vector.h"
#include "ion/math/vectorutils.h"
#include "gtest/gtest.h"
#include "seurat/geometry/mesh.h"
#include "seurat/geometry/mesh_util.h"
namespace seurat {
namespace geometry {
namespace {
using ion::math::Point3f;
using ion::math::Vector3f;
TEST(RaytracerTest, TestIntersectRayQuad) {
// A unit-sized square in the z=-1 plane.
const std::vector<Point3f> vertex_array = {
Point3f(0.0f, 0.0f, -1.0f),
Point3f(1.0f, 0.0f, -1.0f),
Point3f(1.0f, 1.0f, -1.0f),
Point3f(0.0f, 1.0f, -1.0f),
};
const std::vector<int> index_buffer = {0, 1, 2, 0, 2, 3};
std::unique_ptr<Raytracer> raytracer =
Raytracer::Build(vertex_array, index_buffer);
float t_hit;
int triangle_index;
bool hit = raytracer->FindFirstHit(Point3f(0.5f, 0.5f, 0.5f),
Vector3f(0.0f, 0.0f, -1.0f), &t_hit,
&triangle_index);
EXPECT_TRUE(hit);
EXPECT_GT(1.0e-5f, std::fabs(t_hit - 1.5f));
}
TEST(RaytracerTest, TestNoIntersection) {
// A unit-sized square in the z=-1 plane.
const std::vector<Point3f> vertex_array = {
Point3f(0.0f, 0.0f, -1.0f),
Point3f(1.0f, 0.0f, -1.0f),
Point3f(1.0f, 1.0f, -1.0f),
Point3f(0.0f, 1.0f, -1.0f),
};
const std::vector<int> index_buffer = {0, 1, 2, 0, 2, 3};
std::unique_ptr<Raytracer> raytracer =
Raytracer::Build(vertex_array, index_buffer);
float t_hit;
int triangle_index;
bool hit = raytracer->FindFirstHit(Point3f(0.5f, 0.5f, -3.0f),
Vector3f(0.0f, 0.0f, -1.0f), &t_hit,
&triangle_index);
EXPECT_FALSE(hit);
}
// Builds a scene consisting of 3 overlapping quads:
// 1. A square at z=0.
// 2. A rectangle at z=0.1 covering the right half (x > 0.5) of the square.
// 3. A rectangle at z=0.2 on the top half (y > 0.5).
//
// The following diagram indicates the number of layers of geometry at different
// locations.
//
// ^ +y
// |
//
// +----+----+
// | 2 | 3 |
// | | |
// +----+----+
// | 1 | 2 |
// | | |
// +---------+ ->
// +x
Mesh MakeTestScene() {
Mesh mesh(0);
// The unit-square in the XY plane.
AppendTriangleFan(
{
Point3f(0.0f, 0.0f, 0.0f), //
Point3f(0.0f, 1.0f, 0.0f), //
Point3f(1.0f, 1.0f, 0.0f), //
Point3f(1.0f, 0.0f, 0.0f) //
},
{}, &mesh);
// The unit-square, clipped to x > 0.5 and translated to z = 0.1.
AppendTriangleFan(
{
Point3f(0.5f, 0.0f, 0.1f), //
Point3f(0.5f, 1.0f, 0.1f), //
Point3f(1.0f, 1.0f, 0.1f), //
Point3f(1.0f, 0.0f, 0.1f) //
},
{}, &mesh);
// The unit-square, clipped to y > 0.5 and translated to z = 0.2.
AppendTriangleFan(
{
Point3f(0.0f, 0.5f, 0.2f), //
Point3f(0.0f, 1.0f, 0.2f), //
Point3f(1.0f, 1.0f, 0.2f), //
Point3f(1.0f, 0.5f, 0.2f) //
},
{}, &mesh);
return mesh;
}
TEST(RaytracerTest, TestFindFirstHit) {
std::unique_ptr<Raytracer> raytracer = Raytracer::Build(MakeTestScene());
float t_hit;
int triangle_index;
bool hit;
hit = raytracer->FindFirstHit(Point3f(0.30f, 0.25f, -10.0f),
Vector3f(0.0f, 0.0f, 2.0f), &t_hit,
&triangle_index);
// The first hit should be at the unit-square in the XY plane, at t = 5, since
// the ray has z=2.0 and is 10.0 units away from the plane.
EXPECT_TRUE(hit);
EXPECT_NEAR(5.0f, t_hit, 1e-5f);
hit = raytracer->FindFirstHit(Point3f(0.80f, 0.75f, 0.3f),
Vector3f(0.0f, 0.0f, -1.0f), &t_hit,
&triangle_index);
// The first hit should be at the rectangle at z=0.2f, at t = 0.1, since
// the ray has z=-1.0 and is 0.1 units away from the plane.
EXPECT_TRUE(hit);
EXPECT_NEAR(0.1, t_hit, 1e-5f);
}
TEST(RaytracerTest, TestCountIntersections) {
std::unique_ptr<Raytracer> raytracer = Raytracer::Build(MakeTestScene());
// Note that the query rays specifically do not fall on the diagonal of the
// quad, since that may result in the raytracer detecting two triangle
// intersections.
//
// Detecting such cases would be expensive, and is unnecessary.
// No intersections due to t_max.
EXPECT_EQ(0, raytracer->CountIntersections({0.3f, 0.25f, -2.0f},
{0.0f, 0.0f, 10.0f}, 0.01f, 100));
EXPECT_EQ(1, raytracer->CountIntersections({0.3f, 0.25f, -2.0f},
{0.0f, 0.0f, 10.0f}, 1.0f, 100));
EXPECT_EQ(2, raytracer->CountIntersections({0.75f, 0.30f, -2.0f},
{0.0f, 0.0f, 10.0f}, 1.0f, 100));
EXPECT_EQ(3, raytracer->CountIntersections({0.75f, 0.80f, -2.0f},
{0.0f, 0.0f, 10.0f}, 10.0f, 3));
// Limited to 1 intersection by max_intersection_count.
EXPECT_EQ(1, raytracer->CountIntersections({0.75f, 0.81f, -2.0f},
{0.0f, 0.0f, 10.0f}, 1.0f, 1));
EXPECT_EQ(3, raytracer->CountIntersections(
{0.75f, 0.80f, -2.0f}, {0.0f, 0.0f, 10.0f},
std::numeric_limits<float>::infinity(),
std::numeric_limits<int>::max()));
EXPECT_EQ(3, raytracer->CountIntersections(
{0.75f, 0.80f, -2.0f}, {0.0f, 0.0f, 10.0f},
std::numeric_limits<float>::infinity(), 3));
}
TEST(RaytracerTest, TestFindAllIntersections) {
std::unique_ptr<Raytracer> raytracer = Raytracer::Build(MakeTestScene());
// No intersections, since the query ray originates far to the left of the
// scene, with x = -10.
{
std::vector<Raytracer::Intersection> intersections;
raytracer->FindAllIntersections({-10.0f, 0.25f, -2.0f}, {0.0f, 0.0f, 10.0f},
&intersections);
EXPECT_TRUE(intersections.empty());
}
{
std::vector<Raytracer::Intersection> intersections;
raytracer->FindAllIntersections({0.3f, 0.25f, -2.0f}, {0.0f, 0.0f, 10.0f},
&intersections);
EXPECT_EQ(1, intersections.size());
EXPECT_NEAR(0.2f, intersections[0].t_hit, 1e-5f);
// This is the second triangle.
EXPECT_EQ(1, intersections[0].triangle_index);
}
{
std::vector<Raytracer::Intersection> intersections;
raytracer->FindAllIntersections({0.8f, 0.75f, -2.0f}, {0.0f, 0.0f, 0.1f},
&intersections);
EXPECT_EQ(3, intersections.size());
}
}
} // namespace
} // namespace geometry
} // namespace seurat
|
// (c) Copyright Fernando Luis Cacciola Carballal 2000-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)
// See library home page at http://www.boost.org/libs/numeric/conversion
//
// Contact the author at: fernando_cacciola@hotmail.com
//
#ifndef AUTOBOOST_NUMERIC_CONVERSION_CONVERTER_POLICIES_FLC_12NOV2002_HPP
#define AUTOBOOST_NUMERIC_CONVERSION_CONVERTER_POLICIES_FLC_12NOV2002_HPP
#include <typeinfo> // for std::bad_cast
#include <autoboost/config/no_tr1/cmath.hpp> // for std::floor and std::ceil
#include <autoboost/throw_exception.hpp>
#include <functional>
#include "autoboost/type_traits/is_arithmetic.hpp"
#include "autoboost/mpl/if.hpp"
#include "autoboost/mpl/integral_c.hpp"
namespace autoboost { namespace numeric
{
template<class S>
struct Trunc
{
typedef S source_type ;
typedef typename mpl::if_< is_arithmetic<S>,S,S const&>::type argument_type ;
static source_type nearbyint ( argument_type s )
{
#if !defined(AUTOBOOST_NO_STDC_NAMESPACE)
using std::floor ;
using std::ceil ;
#endif
return s < static_cast<S>(0) ? ceil(s) : floor(s) ;
}
typedef mpl::integral_c< std::float_round_style, std::round_toward_zero> round_style ;
} ;
template<class S>
struct Floor
{
typedef S source_type ;
typedef typename mpl::if_< is_arithmetic<S>,S,S const&>::type argument_type ;
static source_type nearbyint ( argument_type s )
{
#if !defined(AUTOBOOST_NO_STDC_NAMESPACE)
using std::floor ;
#endif
return floor(s) ;
}
typedef mpl::integral_c< std::float_round_style, std::round_toward_neg_infinity> round_style ;
} ;
template<class S>
struct Ceil
{
typedef S source_type ;
typedef typename mpl::if_< is_arithmetic<S>,S,S const&>::type argument_type ;
static source_type nearbyint ( argument_type s )
{
#if !defined(AUTOBOOST_NO_STDC_NAMESPACE)
using std::ceil ;
#endif
return ceil(s) ;
}
typedef mpl::integral_c< std::float_round_style, std::round_toward_infinity> round_style ;
} ;
template<class S>
struct RoundEven
{
typedef S source_type ;
typedef typename mpl::if_< is_arithmetic<S>,S,S const&>::type argument_type ;
static source_type nearbyint ( argument_type s )
{
// Algorithm contributed by Guillaume Melquiond
#if !defined(AUTOBOOST_NO_STDC_NAMESPACE)
using std::floor ;
using std::ceil ;
#endif
// only works inside the range not at the boundaries
S prev = floor(s);
S next = ceil(s);
S rt = (s - prev) - (next - s); // remainder type
S const zero(0.0);
S const two(2.0);
if ( rt < zero )
return prev;
else if ( rt > zero )
return next;
else
{
bool is_prev_even = two * floor(prev / two) == prev ;
return ( is_prev_even ? prev : next ) ;
}
}
typedef mpl::integral_c< std::float_round_style, std::round_to_nearest> round_style ;
} ;
enum range_check_result
{
cInRange = 0 ,
cNegOverflow = 1 ,
cPosOverflow = 2
} ;
class bad_numeric_cast : public std::bad_cast
{
public:
virtual const char * what() const throw()
{ return "bad numeric conversion: overflow"; }
};
class negative_overflow : public bad_numeric_cast
{
public:
virtual const char * what() const throw()
{ return "bad numeric conversion: negative overflow"; }
};
class positive_overflow : public bad_numeric_cast
{
public:
virtual const char * what() const throw()
{ return "bad numeric conversion: positive overflow"; }
};
struct def_overflow_handler
{
void operator() ( range_check_result r ) // throw(negative_overflow,positive_overflow)
{
#ifndef AUTOBOOST_NO_EXCEPTIONS
if ( r == cNegOverflow )
throw negative_overflow() ;
else if ( r == cPosOverflow )
throw positive_overflow() ;
#else
if ( r == cNegOverflow )
::autoboost::throw_exception(negative_overflow()) ;
else if ( r == cPosOverflow )
::autoboost::throw_exception(positive_overflow()) ;
#endif
}
} ;
struct silent_overflow_handler
{
void operator() ( range_check_result ) {} // throw()
} ;
template<class Traits>
struct raw_converter
{
typedef typename Traits::result_type result_type ;
typedef typename Traits::argument_type argument_type ;
static result_type low_level_convert ( argument_type s ) { return static_cast<result_type>(s) ; }
} ;
struct UseInternalRangeChecker {} ;
} } // namespace autoboost::numeric
#endif
|
/*/////////////////////////////////////////////////////////////////////////////////
/// An
/// ___ ____ ___ _____ ___ ____
/// / _ \ / ___|_ _|_ _/ _ \| _ \
/// | | | | | _ | | | || | | | |_) |
/// | |_| | |_| || | | || |_| | _ <
/// \___/ \____|___| |_| \___/|_| \_\
/// File
///
/// Copyright (c) 2008-2016 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team
///
/// The MIT License
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////*/
#include "mainwindow.hxx"
#include "ofstreewidget.hxx"
#include "projectfilesview.hxx"
#include "OgitorsPrerequisites.h"
#include "OgitorsRoot.h"
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtGui/QDragEnterEvent>
#include <QtGui/QDropEvent>
#include <QtCore/QMimeData>
#include <QtCore/QDirIterator>
#define MAX_BUFFER_SIZE 0xFFFFFF
//----------------------------------------------------------------------------------------
OfsTreeWidget::OfsTreeWidget(QWidget *parent, unsigned int capabilities, QStringList initialSelection) : QTreeWidget(parent), mCapabilities(capabilities)
{
mSelectedItems = initialSelection;
mRecycleBinParent = NULL;
setColumnCount(1);
setHeaderHidden(true);
setSelectionMode(QAbstractItemView::ExtendedSelection);
setSelectionBehavior(QAbstractItemView::SelectItems);
setContextMenuPolicy(Qt::CustomContextMenu);
setDragDropOverwriteMode(false);
setAutoScroll(true);
if(capabilities & CAP_ALLOW_DROPS)
setDragDropMode(QAbstractItemView::DragDrop);
mUnknownFileIcon = mOgitorMainWindow->mIconProvider.icon(QFileIconProvider::File);
mFile = Ogitors::OgitorsRoot::getSingletonPtr()->GetProjectFile();
mFile->addTrigger(this, OFS::_OfsBase::CLBK_CREATE, &triggerCallback);
mFile->addTrigger(this, OFS::_OfsBase::CLBK_DELETE, &triggerCallback);
refreshWidget();
mAddFilesThread = new AddFilesThread();
mExtractorThread = new ExtractorThread();
connect(mAddFilesThread, SIGNAL(finished()), this, SLOT(threadFinished()));
connect(mExtractorThread, SIGNAL(finished()), this, SLOT(threadFinished()));
}
//----------------------------------------------------------------------------------------
OfsTreeWidget::~OfsTreeWidget()
{
delete mAddFilesThread;
mAddFilesThread = 0;
delete mExtractorThread;
mExtractorThread = 0;
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::fillTree(QTreeWidgetItem *pItem, std::string path)
{
OFS::FileList list = mFile->listFiles(path.c_str(), OFS::OFS_DIR);
std::sort(list.begin(), list.end(), OFS::FileEntry::Compare);
for(unsigned int i = 0;i < list.size();i++)
{
Ogre::String name = list[i].name;
QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(name.c_str())));
item->setIcon(0, mOgitorMainWindow->mIconProvider.icon(QFileIconProvider::Folder));
item->setTextColor(0, Qt::blue);
std::string fullpath = path + name + "/";
item->setWhatsThis(0, QString(fullpath.c_str()));
if(mCapabilities & CAP_SHOW_COLORS)
{
bool isReadOnly = (list[i].flags & OFS::OFS_READONLY) > 0;
bool isHidden = (list[i].flags & OFS::OFS_HIDDEN) > 0;
QColor textColor = Qt::black;
if(isReadOnly && isHidden)
textColor = QColor(255, 210, 210);
else if(isReadOnly)
textColor = QColor(255, 0, 0);
else if(isHidden)
textColor = QColor(210, 210, 210);
if(list[i].flags & OFS::OFS_LINK)
textColor.setBlue(255);
item->setTextColor(0, textColor);
}
pItem->addChild(item);
mItemMap.insert(NameTreeWidgetMap::value_type(fullpath, item));
fillTree(item, fullpath);
}
if(path != "/" && list.size() == 0)
{
QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(".")));
item->setTextColor(0, Qt::black);
item->setWhatsThis(0, QString(path.c_str()));
pItem->addChild(item);
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::fillTreeFiles(QTreeWidgetItem *pItem, std::string path)
{
OFS::FileList list = mFile->listFiles(path.c_str(), OFS::OFS_FILE);
std::sort(list.begin(), list.end(), OFS::FileEntry::Compare);
for(unsigned int i = 0;i < list.size();i++)
{
Ogre::String name = list[i].name;
Ogre::String ext_name = name;
QIcon icon = mUnknownFileIcon;
int ext_pos = ext_name.find_last_of(".");
if(ext_pos > 0)
{
ext_name.erase(0, ext_pos);
FileIconMap::iterator it = mOgitorMainWindow->mFileIconMap.find(ext_name);
if(it == mOgitorMainWindow->mFileIconMap.end())
{
std::string filename = "./qtOgitor_icontest";
filename += ext_name;
std::fstream stream;
stream.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::trunc);
stream.close();
QFileInfo info(QString(filename.c_str()));
icon = mOgitorMainWindow->mIconProvider.icon(info);
if(icon.isNull())
icon = mUnknownFileIcon;
mOgitorMainWindow->mFileIconMap.insert(FileIconMap::value_type(ext_name, icon));
QFile::remove(QString(filename.c_str()));
}
else
icon = it->second;
}
QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(name.c_str())));
item->setIcon(0, icon);
item->setTextColor(0, Qt::black);
std::string fullpath = path + name;
item->setWhatsThis(0, QString(fullpath.c_str()));
if(mCapabilities & CAP_SHOW_COLORS)
{
bool isReadOnly = (list[i].flags & OFS::OFS_READONLY) > 0;
bool isHidden = (list[i].flags & OFS::OFS_HIDDEN) > 0;
QColor textColor = Qt::black;
if(isReadOnly && isHidden)
textColor = QColor(255, 210, 210);
else if(isReadOnly)
textColor = QColor(255, 0, 0);
else if(isHidden)
textColor = QColor(210, 210, 210);
if(list[i].flags & OFS::OFS_LINK)
textColor.setBlue(255);
item->setTextColor(0, textColor);
}
pItem->addChild(item);
mItemMap.insert(NameTreeWidgetMap::value_type(fullpath, item));
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::fillRecycleBin(QTreeWidgetItem *pItem)
{
OFS::FileList list = mFile->listRecycleBinFiles();
if( list.size() > 0 )
pItem->setIcon(0, QIcon(":/icons/recyclebin_full.svg"));
else
pItem->setIcon(0, QIcon(":/icons/recyclebin_empty.svg"));
std::sort(list.begin(), list.end(), OFS::FileEntry::Compare);
for(unsigned int i = 0;i < list.size();i++)
{
Ogre::String name = list[i].name;
Ogre::String ext_name = name;
QIcon icon = mUnknownFileIcon;
if( list[i].flags & OFS::OFS_DIR )
icon = mOgitorMainWindow->mIconProvider.icon(QFileIconProvider::Folder);
else
{
int ext_pos = ext_name.find_last_of(".");
if(ext_pos > 0)
{
ext_name.erase(0, ext_pos);
FileIconMap::iterator it = mOgitorMainWindow->mFileIconMap.find(ext_name);
if(it == mOgitorMainWindow->mFileIconMap.end())
{
std::string filename = "./qtOgitor_icontest";
filename += ext_name;
std::fstream stream;
stream.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::trunc);
stream.close();
QFileInfo info(QString(filename.c_str()));
icon = mOgitorMainWindow->mIconProvider.icon(info);
if(icon.isNull())
icon = mUnknownFileIcon;
mOgitorMainWindow->mFileIconMap.insert(FileIconMap::value_type(ext_name, icon));
QFile::remove(QString(filename.c_str()));
}
else
icon = it->second;
}
}
QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(name.c_str())));
item->setIcon(0, icon);
item->setTextColor(0, Qt::black);
item->setWhatsThis(0, QString("%1").arg(list[i].id));
item->setToolTip(0, QString(name.c_str()) + QString(" (%1)").arg(list[i].id));
pItem->addChild(item);
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::refreshWidget()
{
disconnect(this, SIGNAL(itemSelectionChanged()), this, SLOT(onSelectionChanged()));
if(mCapabilities & CAP_SHOW_FILES)
{
disconnect(this, SIGNAL(itemCollapsed( QTreeWidgetItem * )), this, SLOT(onItemCollapsed( QTreeWidgetItem * )));
disconnect(this, SIGNAL(itemExpanded( QTreeWidgetItem * )), this, SLOT(onItemExpanded( QTreeWidgetItem * )));
}
// Save current expansion state
QStringList list;
NameTreeWidgetMap::iterator it = mItemMap.begin();
while(it != mItemMap.end())
{
if(it->second->isExpanded())
list << it->second->whatsThis(0);
it++;
}
clear();
mItemMap.clear();
QTreeWidgetItem* item = 0;
QTreeWidgetItem* pItem = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Project")));
pItem->setIcon(0, mOgitorMainWindow->mIconProvider.icon(QFileIconProvider::Folder));
pItem->setTextColor(0, Qt::black);
QFont fnt = pItem->font(0);
fnt.setBold(true);
pItem->setFont(0, fnt);
pItem->setWhatsThis(0, QString("/"));
addTopLevelItem(pItem);
fillTree(pItem, "/");
if(mCapabilities & CAP_SHOW_FILES)
fillTreeFiles(pItem, "/");
if(mCapabilities & CAP_SHOW_RECYCLEBIN)
{
QTreeWidgetItem* rItem = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("<Recycle Bin>")));
rItem->setIcon(0, QIcon(":/icons/recyclebin_empty.svg"));
rItem->setTextColor(0, Qt::black);
rItem->setFont(0, fnt);
rItem->setWhatsThis(0, QString("/"));
addTopLevelItem(rItem);
fillRecycleBin(rItem);
}
expandItem(pItem);
for(int i = 0; i < mSelectedItems.size(); i++)
{
if(mSelectedItems.at(i) == "/")
setItemSelected(pItem, true);
else
{
NameTreeWidgetMap::iterator it = mItemMap.find(mSelectedItems.at(i).toStdString());
if(it != mItemMap.end())
{
clearSelection();
scrollToItem(it->second);
setItemSelected(it->second, true);
}
}
}
if(mCapabilities & CAP_SHOW_FILES)
{
connect(this, SIGNAL(itemCollapsed( QTreeWidgetItem * )), this, SLOT(onItemCollapsed( QTreeWidgetItem * )));
connect(this, SIGNAL(itemExpanded( QTreeWidgetItem * )), this, SLOT(onItemExpanded( QTreeWidgetItem * )));
}
// Restore expansion state
foreach(QString string, list)
{
it = mItemMap.find(string.toStdString());
if(it != mItemMap.end())
{
it->second->setExpanded(true);
}
}
connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(onSelectionChanged()));
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::onSelectionChanged()
{
mSelectedItems.clear();
QList<QTreeWidgetItem*> selectionList = selectedItems();
for(int i = 0; i < selectionList.size(); i++)
{
mSelectedItems.push_back(selectionList[i]->whatsThis(0));
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::onItemCollapsed(QTreeWidgetItem* item)
{
std::vector<QTreeWidgetItem*> deleteList;
if(item != NULL && item != topLevelItem(0) && item != mRecycleBinParent && item->parent() != mRecycleBinParent)
{
int total = item->childCount();
for(int i = 0;i < total;i++)
{
if(!item->child(i)->whatsThis(0).endsWith("/"))
deleteList.push_back(item->child(i));
}
NameTreeWidgetMap::iterator it;
for(unsigned int i = 0;i < deleteList.size();i++)
{
QTreeWidgetItem *chItem = deleteList[i];
QString value = chItem->whatsThis(0);
it = mItemMap.find(value.toStdString());
mItemMap.erase(it);
item->removeChild(chItem);
}
if(total > 0 && item->childCount() == 0)
{
QTreeWidgetItem* chItem = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(".")));
chItem->setTextColor(0, Qt::black);
chItem->setWhatsThis(0, item->whatsThis(0));
item->addChild(chItem);
}
}
clearSelection();
setItemSelected(item, true);
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::onItemExpanded(QTreeWidgetItem* item)
{
if(item != NULL && item != topLevelItem(0) && item != mRecycleBinParent && item->parent() != mRecycleBinParent)
{
int total = item->childCount();
for(int i = 0;i < total;i++)
{
if(item->child(i)->whatsThis(0) == item->whatsThis(0))
{
item->removeChild(item->child(i));
break;
}
}
fillTreeFiles(item, item->whatsThis(0).toStdString());
}
clearSelection();
setItemSelected(item, true);
}
//----------------------------------------------------------------------------------------
QStringList OfsTreeWidget::getFilenames(const QMimeData* data)
{
QStringList result;
result = data->formats();
QList<QUrl> urls = data->urls();
for(int i = 0; i < urls.size(); ++i)
result.push_back(urls.at(i).toLocalFile());
return result;
}
//----------------------------------------------------------------------------------
void OfsTreeWidget::dragEnterEvent(QDragEnterEvent *evt)
{
if(mCapabilities & CAP_ALLOW_DROPS)
{
// Get the filenames
QStringList filenames = getFilenames(evt->mimeData());
// Don't accept empty drags
if(!filenames.empty())
{
evt->accept();
return;
}
}
evt->ignore();
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::dragMoveEvent(QDragMoveEvent *evt)
{
if(mCapabilities & CAP_ALLOW_DROPS)
{
QTreeWidgetItem *item = itemAt(evt->pos());
if(item != NULL && item->whatsThis(0).endsWith("/"))
{
evt->accept();
return;
}
}
evt->ignore();
QTreeWidget::dragMoveEvent(evt);
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::dropEvent(QDropEvent *evt)
{
if(mCapabilities & CAP_ALLOW_DROPS)
{
QTreeWidgetItem *item = itemAt(evt->pos());
if(item != NULL && item->whatsThis(0).endsWith("/"))
{
QByteArray itemData = evt->mimeData()->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&itemData, QIODevice::ReadOnly);
int r, c;
QMap<int, QVariant> variant;
stream >> r >> c >> variant;
QString source = variant[5].toString();
QString target = item->whatsThis(0).append(variant[0].toString());
if(source != target)
{
if(!source.endsWith(".OGSCENE", Qt::CaseInsensitive))
{
mFile->moveFile(source.toUtf8(), target.toUtf8());
refreshWidget();
evt->accept();
return;
}
else
{
QMessageBox::information(QApplication::activeWindow(), "Ogitor", tr("The Ogitor scene file cannot be moved!"));
evt->ignore();
return;
}
}
}
}
evt->ignore();
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::addFiles(QString rootDir, QStringList list)
{
if(!mAddFilesThread->isRunning())
{
emit busyState(true);
mAddFilesThread->addFiles(mFile, rootDir.toStdString(), list);
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::extractFiles()
{
if(!mFile.valid())
return;
QString path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "", QApplication::applicationDirPath()
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
);
#else
, QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly);
#endif
if(!path.isEmpty())
{
OFS::FileList theList;
QList<QTreeWidgetItem*> selItems = selectedItems();
std::string baseDir = "";
if(selItems.size() == 0)
{
theList = mFile->listFiles("/");
baseDir = "/";
}
else
{
for(int i = 0;i < selItems.size();i++)
{
OFS::FileEntry entry;
QString name = selItems[i]->whatsThis(0);
if(name.endsWith("/"))
mFile->getDirEntry(name.toStdString().c_str(), entry);
else
mFile->getFileEntry(name.toStdString().c_str(), entry);
entry.name = name.toStdString();
theList.push_back(entry);
}
}
if(!mExtractorThread->isRunning())
{
emit busyState(true);
mExtractorThread->extract(mFile, baseDir, path, theList);
}
}
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::threadFinished()
{
refreshWidget();
emit busyState(false);
}
//----------------------------------------------------------------------------------------
void OfsTreeWidget::triggerCallback(void* userData, OFS::_OfsBase::OfsEntryDesc* arg1, const char* arg2)
{
emit mOgitorMainWindow->getProjectFilesViewWidget()->triggerRefresh();
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
void ExtractorThread::extract(const OFS::OfsPtr& _ofsFile, const std::string& _currentDir, const QString& _path, const OFS::FileList& _list)
{
path = _path;
mlist = _list;
currentDir = _currentDir;
ofsFileName = _ofsFile->getFileSystemName();
start();
}
//------------------------------------------------------------------------------------
void ExtractorThread::extractFiles(QString path, const OFS::FileList& list)
{
std::ofstream out_handle;
OFS::OFSHANDLE in_handle;
unsigned int output_amount = 0;
mutex.lock();
currentPos = 0.0f;
msgProgress = "";
mutex.unlock();
for(unsigned int i = 0;i < list.size();i++)
{
if(list[i].flags & OFS::OFS_DIR)
{
QString dir_path = path + QString("/") + QString(list[i].name.c_str());
QDir directory(dir_path);
directory.mkpath(dir_path);
}
else
{
std::string file_path = path.toStdString() + std::string("/") + list[i].name;
std::string file_ofs_path = list[i].name;
QFileInfo info(QString(file_path.c_str()));
QDir directory(info.absolutePath());
directory.mkpath(info.absolutePath());
mutex.lock();
msgProgress = file_ofs_path.c_str();
mutex.unlock();
out_handle.open(file_path.c_str(), std::ofstream::out | std::ofstream::binary);
if(out_handle.is_open())
{
try
{
OFS::OfsResult ret = ofsFile->openFile(in_handle, file_ofs_path.c_str());
if(ret != OFS::OFS_OK)
{
out_handle.close();
continue;
}
unsigned int total = list[i].file_size;
while(total > 0)
{
if(total < MAX_BUFFER_SIZE)
{
ofsFile->read(in_handle, tmp_buffer, total);
out_handle.write(tmp_buffer, total);
output_amount += total;
total = 0;
}
else
{
ofsFile->read(in_handle, tmp_buffer, MAX_BUFFER_SIZE);
out_handle.write(tmp_buffer, MAX_BUFFER_SIZE);
total -= MAX_BUFFER_SIZE;
output_amount += MAX_BUFFER_SIZE;
}
if(mTotalFileSize > 0)
{
mutex.lock();
currentPos = (float)output_amount / (float)mTotalFileSize;
mutex.unlock();
}
}
}
catch(OFS::Exception& e)
{
QMessageBox::information(QApplication::activeWindow(),"Ofs Exception:", tr("Error Extracting File : ") + QString(file_ofs_path.c_str()) + QString("\n") + QString(e.getDescription().c_str()), QMessageBox::Ok);
}
out_handle.close();
ofsFile->closeFile(in_handle);
}
}
}
mutex.lock();
currentPos = 1.0f;
msgProgress = tr("Finished Extracting");
mutex.unlock();
}
//------------------------------------------------------------------------------------
unsigned int ExtractorThread::generateList(OFS::FileList& list)
{
unsigned int list_max = list.size();
unsigned int file_size = 0;
std::string tmpSaveCurrentDir;
OFS::FileList subList;
for(unsigned int i = 0;i < list_max;i++)
{
list[i].name = currentDir + list[i].name;
file_size += list[i].file_size;
if(list[i].flags & OFS::OFS_DIR)
{
tmpSaveCurrentDir = currentDir;
currentDir = list[i].name + "/";
subList = ofsFile->listFiles(currentDir.c_str());
file_size += generateList(subList);
for(unsigned int z = 0;z < subList.size();z++)
list.push_back(subList[z]);
currentDir = tmpSaveCurrentDir;
}
}
return file_size;
}
//------------------------------------------------------------------------------------
void ExtractorThread::run()
{
try
{
ofsFile.mount(ofsFileName.c_str());
}
catch(...)
{
return;
}
mTotalFileSize = generateList(mlist);
std::sort(mlist.begin(), mlist.end(), OFS::FileEntry::Compare);
tmp_buffer = new char[MAX_BUFFER_SIZE];
extractFiles(path, mlist);
delete [] tmp_buffer;
ofsFile.unmount();
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
bool AddFilesListCompare ( AddFilesData elem1, AddFilesData elem2 )
{
return (strcmp(elem1.ofsName.toStdString().c_str(), elem2.ofsName.toStdString().c_str()) < 0);
}
//------------------------------------------------------------------------------------
void AddFilesThread::addFiles(const OFS::OfsPtr& _ofsFile, const std::string& _currentDir, const QStringList& _list)
{
mlist.clear();
AddFilesData data;
for(int i = 0;i < _list.size();i++)
{
data.fileName = _list.at(i);
data.onFS = true;
data.isDir = false;
mlist.push_back(data);
}
currentDir = _currentDir;
ofsFileName = _ofsFile->getFileSystemName();
start();
}
//------------------------------------------------------------------------------------
void AddFilesThread::addFiles(const AddFilesList& list)
{
OFS::OFSHANDLE fhandle;
unsigned int output_amount = 0;
mutex.lock();
currentPos = 0.0f;
msgProgress = "";
mutex.unlock();
// Handle the items
for(unsigned int i = 0; i < list.size(); ++i)
{
if(!list[i].isDir)
{
QString path = list[i].fileName;
std::string file_ofs_path = list[i].ofsName.toStdString();
mutex.lock();
msgProgress = file_ofs_path.c_str();
mutex.unlock();
std::ifstream stream;
stream.open(path.toStdString().c_str(), std::fstream::in | std::fstream::binary);
if(stream.is_open())
{
stream.seekg(0, std::fstream::end);
unsigned int stream_size = stream.tellg();
stream.seekg(0, std::fstream::beg);
if(stream_size >= MAX_BUFFER_SIZE)
{
//createFile accepts initial data to be written during allocation
//its an optimization, thats why we don't have to call Ofs::write after createFile
stream.read(tmp_buffer, MAX_BUFFER_SIZE);
try
{
if(ofsFile->createFile(fhandle, file_ofs_path.c_str(), MAX_BUFFER_SIZE, MAX_BUFFER_SIZE, tmp_buffer) != OFS::OFS_OK)
{
stream.close();
continue;
}
stream_size -= MAX_BUFFER_SIZE;
output_amount += MAX_BUFFER_SIZE;
}
catch(OFS::Exception& e)
{
QMessageBox::information(QApplication::activeWindow(),"Ofs Exception:", QString(e.getDescription().c_str()), QMessageBox::Ok);
stream.close();
continue;
}
if(mTotalFileSize > 0)
{
mutex.lock();
currentPos = (float)output_amount / (float)mTotalFileSize;
mutex.unlock();
}
try
{
while(stream_size > 0)
{
if(stream_size >= MAX_BUFFER_SIZE)
{
stream.read(tmp_buffer, MAX_BUFFER_SIZE);
ofsFile->write(fhandle, tmp_buffer, MAX_BUFFER_SIZE);
stream_size -= MAX_BUFFER_SIZE;
output_amount += MAX_BUFFER_SIZE;
}
else
{
stream.read(tmp_buffer, stream_size);
ofsFile->write(fhandle, tmp_buffer, stream_size);
output_amount += stream_size;
stream_size = 0;
}
if(mTotalFileSize > 0)
{
mutex.lock();
currentPos = (float)output_amount / (float)mTotalFileSize;
mutex.unlock();
}
}
}
catch(OFS::Exception& e)
{
QMessageBox::information(QApplication::activeWindow(), "Ofs Exception:", QString(e.getDescription().c_str()), QMessageBox::Ok);
}
stream.close();
ofsFile->closeFile(fhandle);
}
else
{
stream.read(tmp_buffer, stream_size);
try
{
output_amount += stream_size;
if(mTotalFileSize > 0)
{
mutex.lock();
currentPos = (float)output_amount / (float)mTotalFileSize;
mutex.unlock();
}
// createFile() accepts initial data to be written during allocation.
// It's an optimization, thats why we don't have to call Ofs::write after createFile()
if(ofsFile->createFile(fhandle, file_ofs_path.c_str(), stream_size, stream_size, tmp_buffer) != OFS::OFS_OK)
{
QMessageBox::information(QApplication::activeWindow(),"File Copy Error", tr("File copy failed for : ")+ QString(file_ofs_path.c_str()), QMessageBox::Ok);
stream.close();
continue;
}
}
catch(OFS::Exception& e)
{
QMessageBox::information(QApplication::activeWindow(),"Ofs Exception:", QString(e.getDescription().c_str()), QMessageBox::Ok);
}
stream.close();
ofsFile->closeFile(fhandle);
}
}
}
else
{
std::string dir_ofs_path = list[i].ofsName.toStdString();
try
{
OFS::OfsResult ret = ofsFile->createDirectory(dir_ofs_path.c_str());
if(ret != OFS::OFS_OK)
{
QMessageBox::information(QApplication::activeWindow(), "Ofs Exception:", tr("Cannot create directory : ") + QString(dir_ofs_path.c_str()), QMessageBox::Ok);
continue;
}
}
catch(OFS::Exception& e)
{
QMessageBox::information(QApplication::activeWindow(), "Ofs Exception:", tr("Cannot create directory : ") + QString(dir_ofs_path.c_str()) + QString("\n") + QString(e.getDescription().c_str()), QMessageBox::Ok);
continue;
}
}
}
mutex.lock();
currentPos = 1.0f;
mutex.unlock();
}
//------------------------------------------------------------------------------------
unsigned int AddFilesThread::generateList(AddFilesList& list)
{
unsigned int list_max = list.size();
unsigned int file_size = 0;
AddFilesData data;
AddFilesList subList;
std::string tmpSaveCurrentDir;
for(unsigned int i = 0;i < list_max;i++)
{
QFileInfo file(list[i].fileName);
if(!file.isDir() && (list[i].onFS == true))
{
list[i].isDir = false;
list[i].ofsName = QString(currentDir.c_str()) + file.fileName();
file_size += file.size();
}
else if(file.isDir() || (list[i].onFS == false && list[i].isDir == true))
{
QString path = file.baseName();
list[i].isDir = true;
list[i].ofsName = QString(currentDir.c_str()) + path;
subList.clear();
QDirIterator it(file.absoluteFilePath());
while(it.hasNext())
{
QFileInfo file2(it.next());
if(file2.isDir())
{
QString path2 = file2.baseName();
if(path2.isEmpty() || path2 == QString("..") || path2 == QString("."))
continue;
}
data.fileName = file2.absoluteFilePath();
data.isDir = file2.isDir();
data.ofsName = list[i].ofsName + "/" + file2.fileName();
subList.push_back(data);
}
if(subList.size() > 0)
{
tmpSaveCurrentDir = currentDir;
currentDir = currentDir + path.toStdString() + "/";
file_size += generateList(subList);
for(unsigned int z = 0;z < subList.size();z++)
list.push_back(subList[z]);
currentDir = tmpSaveCurrentDir;
}
}
}
return file_size;
}
//------------------------------------------------------------------------------------
void AddFilesThread::run()
{
try
{
ofsFile.mount(ofsFileName.c_str());
}
catch(...)
{
return;
}
mTotalFileSize = generateList(mlist);
std::sort(mlist.begin(), mlist.end(), AddFilesListCompare);
tmp_buffer = new char[MAX_BUFFER_SIZE];
addFiles(mlist);
delete [] tmp_buffer;
tmp_buffer = 0;
ofsFile.unmount();
}
//------------------------------------------------------------------------------------
|
// Copyright 2016 The Fuchsia 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/media/audio/audio_core/audio_device_manager.h"
#include <lib/fit/promise.h>
#include <lib/fit/single_threaded_executor.h>
#include <string>
#include <trace/event.h>
#include "src/media/audio/audio_core/audio_core_impl.h"
#include "src/media/audio/audio_core/base_capturer.h"
#include "src/media/audio/audio_core/base_renderer.h"
#include "src/media/audio/audio_core/driver_output.h"
#include "src/media/audio/audio_core/plug_detector.h"
#include "src/media/audio/audio_core/reporter.h"
#include "src/media/audio/lib/logging/logging.h"
namespace media::audio {
AudioDeviceManager::AudioDeviceManager(ThreadingModel* threading_model,
std::unique_ptr<PlugDetector> plug_detector,
RouteGraph* route_graph, LinkMatrix* link_matrix)
: threading_model_(*threading_model),
route_graph_(*route_graph),
plug_detector_(std::move(plug_detector)),
link_matrix_(*link_matrix) {
FX_DCHECK(route_graph);
FX_DCHECK(threading_model);
FX_DCHECK(link_matrix);
}
AudioDeviceManager::~AudioDeviceManager() {
Shutdown();
FX_DCHECK(devices_.empty());
}
// Configure this admin singleton object to manage audio device instances.
zx_status_t AudioDeviceManager::Init() {
TRACE_DURATION("audio", "AudioDeviceManager::Init");
// Start monitoring for plug/unplug events of pluggable audio output devices.
zx_status_t res =
plug_detector_->Start(fit::bind_member(this, &AudioDeviceManager::AddDeviceByChannel));
if (res != ZX_OK) {
FX_PLOGS(ERROR, res) << "AudioDeviceManager failed to start plug detector";
return res;
}
return ZX_OK;
}
// We are no longer managing audio devices, unwind everything.
void AudioDeviceManager::Shutdown() {
TRACE_DURATION("audio", "AudioDeviceManager::Shutdown");
plug_detector_->Stop();
std::vector<fit::promise<void>> device_promises;
for (auto& [_, device] : devices_pending_init_) {
device_promises.push_back(device->Shutdown());
}
devices_pending_init_.clear();
for (auto& [_, device] : devices_) {
device_promises.push_back(device->Shutdown());
}
devices_.clear();
fit::run_single_threaded(fit::join_promise_vector(std::move(device_promises)));
}
void AudioDeviceManager::AddDeviceEnumeratorClient(
fidl::InterfaceRequest<fuchsia::media::AudioDeviceEnumerator> request) {
bindings_.AddBinding(this, std::move(request));
}
void AudioDeviceManager::SetEffectConfig(const std::string& instance_name,
const std::string& config) {
for (auto& [_, device] : devices_) {
device->SetEffectConfig(instance_name, config);
}
}
void AudioDeviceManager::AddDevice(const std::shared_ptr<AudioDevice>& device) {
TRACE_DURATION("audio", "AudioDeviceManager::AddDevice");
FX_DCHECK(device != nullptr);
threading_model_.FidlDomain().executor()->schedule_task(
device->Startup()
.and_then([this, device]() mutable {
devices_pending_init_.insert({device->token(), std::move(device)});
})
.or_else([device](zx_status_t& error) {
FX_PLOGS(ERROR, error) << "AddDevice failed";
REPORT(DeviceStartupFailed(*device));
device->Shutdown();
}));
}
void AudioDeviceManager::ActivateDevice(const std::shared_ptr<AudioDevice>& device) {
TRACE_DURATION("audio", "AudioDeviceManager::ActivateDevice");
FX_DCHECK(device != nullptr);
// Have we already been removed from the pending list? If so, the device is
// already shutting down and there is nothing to be done.
if (devices_pending_init_.find(device->token()) == devices_pending_init_.end()) {
return;
}
// If this device is still waiting for initialization, move it over to the set of active devices.
// Otherwise (if not waiting for initialization), we've been removed.
auto dev = devices_pending_init_.extract(device->token());
if (!dev) {
return;
}
devices_.insert(std::move(dev));
REPORT(ActivatingDevice(*device));
device->SetActivated();
// Notify interested users of the new device. If it will become the new default, set 'is_default'
// properly in the notification ("default" device is currently defined simply as last-plugged).
fuchsia::media::AudioDeviceInfo info;
device->GetDeviceInfo(&info);
auto last_plugged = FindLastPlugged(device->type());
info.is_default = (last_plugged && (last_plugged->token() == device->token()));
for (auto& client : bindings_.bindings()) {
client->events().OnDeviceAdded(info);
}
OnPlugStateChanged(device, device->plugged(), device->plug_time());
UpdateDefaultDevice(device->is_input());
}
void AudioDeviceManager::RemoveDevice(const std::shared_ptr<AudioDevice>& device) {
TRACE_DURATION("audio", "AudioDeviceManager::RemoveDevice");
FX_DCHECK(device != nullptr);
REPORT(RemovingDevice(*device));
// If device was active: reset the default (based on most-recently-plugged).
if (device->activated()) {
OnDeviceUnplugged(device, device->plug_time());
}
device->Shutdown();
auto& device_set = device->activated() ? devices_ : devices_pending_init_;
device_set.erase(device->token());
// If device was active: notify clients of the removal.
if (device->activated()) {
for (auto& client : bindings_.bindings()) {
client->events().OnDeviceRemoved(device->token());
}
}
}
void AudioDeviceManager::OnPlugStateChanged(const std::shared_ptr<AudioDevice>& device,
bool plugged, zx::time plug_time) {
TRACE_DURATION("audio", "AudioDeviceManager::OnPlugStateChanged");
FX_DCHECK(device != nullptr);
// Update our bookkeeping for device's plug state. If no change, we're done.
if (!device->UpdatePlugState(plugged, plug_time)) {
return;
}
if (plugged) {
OnDevicePlugged(device, plug_time);
} else {
OnDeviceUnplugged(device, plug_time);
}
}
void AudioDeviceManager::GetDevices(GetDevicesCallback cbk) {
TRACE_DURATION("audio", "AudioDeviceManager::GetDevices");
std::vector<fuchsia::media::AudioDeviceInfo> ret;
for (const auto& [_, dev] : devices_) {
if (dev->token() != ZX_KOID_INVALID) {
fuchsia::media::AudioDeviceInfo info;
dev->GetDeviceInfo(&info);
info.is_default =
(dev->token() == (dev->is_input() ? default_input_token_ : default_output_token_));
ret.push_back(std::move(info));
}
}
cbk(std::move(ret));
}
void AudioDeviceManager::GetDeviceGain(uint64_t device_token, GetDeviceGainCallback cbk) {
TRACE_DURATION("audio", "AudioDeviceManager::GetDeviceGain");
fuchsia::media::AudioGainInfo info = {0};
auto it = devices_.find(device_token);
if (it == devices_.end()) {
cbk(ZX_KOID_INVALID, info);
return;
}
auto [_, dev] = *it;
FX_DCHECK(dev->device_settings() != nullptr);
dev->device_settings()->GetGainInfo(&info);
cbk(device_token, info);
}
void AudioDeviceManager::SetDeviceGain(uint64_t device_token,
fuchsia::media::AudioGainInfo gain_info,
uint32_t set_flags) {
TRACE_DURATION("audio", "AudioDeviceManager::SetDeviceGain");
auto it = devices_.find(device_token);
if (it == devices_.end()) {
return;
}
auto [_, dev] = *it;
// SetGainInfo clamps out-of-range values (e.g. +infinity) into the device-
// allowed gain range. NAN is undefined (signless); handle it here and exit.
if ((set_flags & fuchsia::media::SetAudioGainFlag_GainValid) && isnan(gain_info.gain_db)) {
FX_LOGS(WARNING) << "Invalid device gain " << gain_info.gain_db << " dB -- making no change";
return;
}
dev->system_gain_dirty = true;
// Change the gain and then report the new settings to our clients.
REPORT(SettingDeviceGainInfo(*dev, gain_info, set_flags));
dev->SetGainInfo(gain_info, set_flags);
NotifyDeviceGainChanged(*dev);
}
void AudioDeviceManager::GetDefaultInputDevice(GetDefaultInputDeviceCallback cbk) {
cbk(default_input_token_);
}
void AudioDeviceManager::GetDefaultOutputDevice(GetDefaultOutputDeviceCallback cbk) {
cbk(default_output_token_);
}
std::shared_ptr<AudioDevice> AudioDeviceManager::FindLastPlugged(AudioObject::Type type,
bool allow_unplugged) {
TRACE_DURATION("audio", "AudioDeviceManager::FindLastPlugged");
FX_DCHECK((type == AudioObject::Type::Output) || (type == AudioObject::Type::Input));
std::shared_ptr<AudioDevice> best = nullptr;
// TODO(johngro): Consider tracking last-plugged times in a fbl::WAVLTree, so
// this operation becomes O(1). N is pretty low right now, so the benefits do
// not currently outweigh the complexity of maintaining this index.
for (auto& [_, device] : devices_) {
if (device->type() != type) {
continue;
}
if ((best == nullptr) || (!best->plugged() && device->plugged()) ||
((best->plugged() == device->plugged()) && (best->plug_time() < device->plug_time()))) {
best = device;
}
}
FX_DCHECK((best == nullptr) || (best->type() == type));
if (!allow_unplugged && best && !best->plugged()) {
return nullptr;
}
return best;
}
void AudioDeviceManager::OnDeviceUnplugged(const std::shared_ptr<AudioDevice>& device,
zx::time plug_time) {
TRACE_DURATION("audio", "AudioDeviceManager::OnDeviceUnplugged");
FX_DCHECK(device);
device->UpdatePlugState(/*plugged=*/false, plug_time);
route_graph_.RemoveDevice(device.get());
UpdateDefaultDevice(device->is_input());
}
void AudioDeviceManager::OnDevicePlugged(const std::shared_ptr<AudioDevice>& device,
zx::time plug_time) {
TRACE_DURATION("audio", "AudioDeviceManager::OnDevicePlugged");
FX_DCHECK(device);
device->UpdatePlugState(/*plugged=*/true, plug_time);
route_graph_.AddDevice(device.get());
UpdateDefaultDevice(device->is_input());
}
void AudioDeviceManager::NotifyDeviceGainChanged(const AudioDevice& device) {
TRACE_DURATION("audio", "AudioDeviceManager::NotifyDeviceGainChanged");
fuchsia::media::AudioGainInfo info;
FX_DCHECK(device.device_settings() != nullptr);
device.device_settings()->GetGainInfo(&info);
for (auto& client : bindings_.bindings()) {
client->events().OnDeviceGainChanged(device.token(), info);
}
}
void AudioDeviceManager::UpdateDefaultDevice(bool input) {
TRACE_DURATION("audio", "AudioDeviceManager::UpdateDefaultDevice");
const auto new_dev =
FindLastPlugged(input ? AudioObject::Type::Input : AudioObject::Type::Output);
uint64_t new_id = new_dev ? new_dev->token() : ZX_KOID_INVALID;
uint64_t& old_id = input ? default_input_token_ : default_output_token_;
if (old_id != new_id) {
for (auto& client : bindings_.bindings()) {
client->events().OnDefaultDeviceChanged(old_id, new_id);
}
old_id = new_id;
}
}
void AudioDeviceManager::AddDeviceByChannel(zx::channel device_channel, std::string device_name,
bool is_input) {
TRACE_DURATION("audio", "AudioDeviceManager::AddDeviceByChannel");
AUD_VLOG(TRACE) << " adding " << (is_input ? "input" : "output") << " '" << device_name << "'";
// Hand the stream off to the proper type of class to manage.
std::shared_ptr<AudioDevice> new_device;
if (is_input) {
new_device =
AudioInput::Create(std::move(device_channel), &threading_model(), this, &link_matrix_);
} else {
new_device =
DriverOutput::Create(std::move(device_channel), &threading_model(), this, &link_matrix_);
}
if (new_device == nullptr) {
FX_LOGS(ERROR) << "Failed to instantiate audio " << (is_input ? "input" : "output") << " for '"
<< device_name << "'";
}
REPORT(AddingDevice(device_name, *new_device));
AddDevice(std::move(new_device));
}
} // namespace media::audio
|
#include<iostream>
using namespace std;
#define N 9
bool check(int grid[N][N], int &row , int &col) {
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
if(grid[i][j] == 0 ) {
row = i;
col = j;
return true;
}
}
}
return false;
}
bool rowSafe(int grid[N][N], int row , int x) {
for(int i=0;i<N;i++) {
if(grid[row][i] == x) {
return false;
}
}
return true;
}
bool colSafe(int grid[N][N], int col , int x) {
for(int i=0;i<N;i++) {
if(grid[i][col] == x) {
return false;
}
}
return true;
}
bool boxSafe(int grid[N][N], int row ,int col ,int x) {
int rowFactor = row - (row%3);
int colFactor = col - (col%3);
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(grid[i+rowFactor][j+colFactor] == x) {
return false;
}
}
}
return true;
}
bool isSafe(int grid[N][N], int row,int col,int i) {
if( rowSafe(grid,row,i) && colSafe(grid,col,i) && boxSafe(grid,row,col,i) ) {
return true;
}
return false;
}
bool sudokuSolver(int grid[][9]){
int row,col;
if(!check(grid,row,col)) {
return true;
}
for(int i=1;i<=N;i++) {
if(isSafe(grid,row,col,i)) {
grid[row][col]=i;
if(sudokuSolver(grid)) {
return true;
}
grid[row][col] = 0;
}
}
return false;
}
int main()
{
int n = 9;
int board[9][9];
for(int i = 0; i < n ;i++){
for(int j = 0; j < n; j++){
cin >> board[i][j];
}
}
if(sudokuSolver(board)){
cout << "true";
}
else{
cout << "false";
}
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "QueryProfile.h"
#include "Aql/Query.h"
#include "Aql/QueryList.h"
#include "Aql/Timing.h"
#include "Basics/EnumIterator.h"
#include "Basics/debugging.h"
#include "VocBase/vocbase.h"
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::aql;
/// @brief create a profile
QueryProfile::QueryProfile(Query* query)
: _query(query),
_lastStamp(query->startTime()),
_tracked(false) {
for (auto& it : _timers) {
it = 0.0; // reset timers
}
}
/// @brief destroy a profile
QueryProfile::~QueryProfile() {
unregisterFromQueryList();
}
void QueryProfile::registerInQueryList() {
TRI_ASSERT(!_tracked);
auto queryList = _query->vocbase().queryList();
_tracked = queryList->insert(_query);
}
void QueryProfile::unregisterFromQueryList() noexcept {
// only remove from list when the query was inserted into it...
if (_tracked) {
auto queryList = _query->vocbase().queryList();
try {
queryList->remove(_query);
} catch (...) {
}
_tracked = false;
}
}
/// @brief sets a state to done
double QueryProfile::setStateDone(QueryExecutionState::ValueType state) {
double const now = arangodb::aql::currentSteadyClockValue();
if (state != QueryExecutionState::ValueType::INVALID_STATE &&
state != QueryExecutionState::ValueType::KILLED) {
// record duration of state
_timers[static_cast<int>(state)] = now - _lastStamp;
}
// set timestamp
_lastStamp = now;
return now;
}
/// @brief sets the absolute end time for an execution state
void QueryProfile::setStateEnd(QueryExecutionState::ValueType state, double time) {
_timers[static_cast<int>(state)] = time - _lastStamp;
}
/// @brief convert the profile to VelocyPack
void QueryProfile::toVelocyPack(VPackBuilder& builder) const {
VPackObjectBuilder guard(&builder, "profile", true);
for (auto state : ENUM_ITERATOR(QueryExecutionState::ValueType, INITIALIZATION, FINALIZATION)) {
double const value = _timers[static_cast<size_t>(state)];
if (value >= 0.0) {
builder.add(QueryExecutionState::toString(state), VPackValue(value));
}
}
}
|
#include <kernels_rpp.h>
#include <vx_ext_rpp.h>
#include <stdio.h>
#include <iostream>
#include "internal_rpp.h"
#include "internal_publishKernels.h"
#include </opt/rocm/rpp/include/rpp.h>
#include </opt/rocm/rpp/include/rppdefs.h>
#include </opt/rocm/rpp/include/rppi.h>
struct RainbatchPDROIDLocalData {
RPPCommonHandle handle;
rppHandle_t rppHandle;
Rpp32u device_type;
Rpp32u nbatchSize;
RppiROI *roiPoints;
RppiSize *srcDimensions;
RppiSize maxSrcDimensions;
RppPtr_t pSrc;
RppPtr_t pDst;
vx_float32 *rainValue;
vx_uint32 *rainWidth;
vx_uint32 *rainHeight;
vx_float32 *rainTransperancy;
#if ENABLE_OPENCL
cl_mem cl_pSrc;
cl_mem cl_pDst;
#endif
};
static vx_status VX_CALLBACK refreshRainbatchPDROID(vx_node node, const vx_reference *parameters, vx_uint32 num, RainbatchPDROIDLocalData *data)
{
vx_status status = VX_SUCCESS;
size_t arr_size;
vx_status copy_status;
STATUS_ERROR_CHECK(vxQueryArray((vx_array)parameters[4], VX_ARRAY_ATTRIBUTE_NUMITEMS, &arr_size, sizeof(arr_size)));
data->rainValue = (vx_float32 *)malloc(sizeof(vx_float32) * arr_size);
copy_status = vxCopyArrayRange((vx_array)parameters[4], 0, arr_size, sizeof(vx_float32),data->rainValue, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
STATUS_ERROR_CHECK(vxQueryArray((vx_array)parameters[5], VX_ARRAY_ATTRIBUTE_NUMITEMS, &arr_size, sizeof(arr_size)));
data->rainWidth = (vx_uint32 *)malloc(sizeof(vx_uint32) * arr_size);
copy_status = vxCopyArrayRange((vx_array)parameters[5], 0, arr_size, sizeof(vx_uint32),data->rainWidth, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
STATUS_ERROR_CHECK(vxQueryArray((vx_array)parameters[6], VX_ARRAY_ATTRIBUTE_NUMITEMS, &arr_size, sizeof(arr_size)));
data->rainHeight = (vx_uint32 *)malloc(sizeof(vx_uint32) * arr_size);
copy_status = vxCopyArrayRange((vx_array)parameters[6], 0, arr_size, sizeof(vx_uint32),data->rainHeight, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
STATUS_ERROR_CHECK(vxQueryArray((vx_array)parameters[7], VX_ARRAY_ATTRIBUTE_NUMITEMS, &arr_size, sizeof(arr_size)));
data->rainTransperancy = (vx_float32 *)malloc(sizeof(vx_float32) * arr_size);
copy_status = vxCopyArrayRange((vx_array)parameters[7], 0, arr_size, sizeof(vx_float32),data->rainTransperancy, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
STATUS_ERROR_CHECK(vxReadScalarValue((vx_scalar)parameters[12], &data->nbatchSize));
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[0], VX_IMAGE_HEIGHT, &data->maxSrcDimensions.height, sizeof(data->maxSrcDimensions.height)));
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[0], VX_IMAGE_WIDTH, &data->maxSrcDimensions.width, sizeof(data->maxSrcDimensions.width)));
data->maxSrcDimensions.height = data->maxSrcDimensions.height / data->nbatchSize;
data->srcDimensions = (RppiSize *)malloc(sizeof(RppiSize) * data->nbatchSize);
Rpp32u *srcBatch_width = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
Rpp32u *srcBatch_height = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
copy_status = vxCopyArrayRange((vx_array)parameters[1], 0, data->nbatchSize, sizeof(Rpp32u),srcBatch_width, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
copy_status = vxCopyArrayRange((vx_array)parameters[2], 0, data->nbatchSize, sizeof(Rpp32u),srcBatch_height, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
for(int i = 0; i < data->nbatchSize; i++){
data->srcDimensions[i].width = srcBatch_width[i];
data->srcDimensions[i].height = srcBatch_height[i];
}
data->roiPoints = (RppiROI *)malloc(sizeof(RppiROI) * data->nbatchSize);
Rpp32u *batch_roiX = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
Rpp32u *batch_roiY = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
Rpp32u *batch_roiWidth = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
Rpp32u *batch_roiHeight = (Rpp32u *)malloc(sizeof(Rpp32u) * data->nbatchSize);
copy_status = vxCopyArrayRange((vx_array)parameters[8], 0, data->nbatchSize, sizeof(Rpp32u),batch_roiX, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
copy_status = vxCopyArrayRange((vx_array)parameters[9], 0, data->nbatchSize, sizeof(Rpp32u),batch_roiY, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
copy_status = vxCopyArrayRange((vx_array)parameters[10], 0, data->nbatchSize, sizeof(Rpp32u),batch_roiWidth, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
copy_status = vxCopyArrayRange((vx_array)parameters[11], 0, data->nbatchSize, sizeof(Rpp32u),batch_roiHeight, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
for(int i = 0; i < data->nbatchSize; i++){
data->roiPoints[i].x = batch_roiX[i];
data->roiPoints[i].y = batch_roiY[i];
data->roiPoints[i].roiWidth = batch_roiWidth[i];
data->roiPoints[i].roiHeight = batch_roiHeight[i];
}
if(data->device_type == AGO_TARGET_AFFINITY_GPU) {
#if ENABLE_OPENCL
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[0], VX_IMAGE_ATTRIBUTE_AMD_OPENCL_BUFFER, &data->cl_pSrc, sizeof(data->cl_pSrc)));
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[3], VX_IMAGE_ATTRIBUTE_AMD_OPENCL_BUFFER, &data->cl_pDst, sizeof(data->cl_pDst)));
#endif
}
if(data->device_type == AGO_TARGET_AFFINITY_CPU) {
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[0], VX_IMAGE_ATTRIBUTE_AMD_HOST_BUFFER, &data->pSrc, sizeof(vx_uint8)));
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[3], VX_IMAGE_ATTRIBUTE_AMD_HOST_BUFFER, &data->pDst, sizeof(vx_uint8)));
}
return status;
}
static vx_status VX_CALLBACK validateRainbatchPDROID(vx_node node, const vx_reference parameters[], vx_uint32 num, vx_meta_format metas[])
{
vx_status status = VX_SUCCESS;
vx_enum scalar_type;
STATUS_ERROR_CHECK(vxQueryScalar((vx_scalar)parameters[12], VX_SCALAR_TYPE, &scalar_type, sizeof(scalar_type)));
if(scalar_type != VX_TYPE_UINT32) return ERRMSG(VX_ERROR_INVALID_TYPE, "validate: Paramter: #12 type=%d (must be size)\n", scalar_type);
STATUS_ERROR_CHECK(vxQueryScalar((vx_scalar)parameters[13], VX_SCALAR_TYPE, &scalar_type, sizeof(scalar_type)));
if(scalar_type != VX_TYPE_UINT32) return ERRMSG(VX_ERROR_INVALID_TYPE, "validate: Paramter: #13 type=%d (must be size)\n", scalar_type);
// Check for input parameters
vx_parameter input_param;
vx_image input;
vx_df_image df_image;
input_param = vxGetParameterByIndex(node,0);
STATUS_ERROR_CHECK(vxQueryParameter(input_param, VX_PARAMETER_ATTRIBUTE_REF, &input, sizeof(vx_image)));
STATUS_ERROR_CHECK(vxQueryImage(input, VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));
if(df_image != VX_DF_IMAGE_U8 && df_image != VX_DF_IMAGE_RGB)
{
return ERRMSG(VX_ERROR_INVALID_FORMAT, "validate: RainbatchPDROID: image: #0 format=%4.4s (must be RGB2 or U008)\n", (char *)&df_image);
}
// Check for output parameters
vx_image output;
vx_df_image format;
vx_parameter output_param;
vx_uint32 height, width;
output_param = vxGetParameterByIndex(node,3);
STATUS_ERROR_CHECK(vxQueryParameter(output_param, VX_PARAMETER_ATTRIBUTE_REF, &output, sizeof(vx_image)));
STATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));
STATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(metas[3], VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(metas[3], VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(metas[3], VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));
vxReleaseImage(&input);
vxReleaseImage(&output);
vxReleaseParameter(&output_param);
vxReleaseParameter(&input_param);
return status;
}
static vx_status VX_CALLBACK processRainbatchPDROID(vx_node node, const vx_reference * parameters, vx_uint32 num)
{
RppStatus status = RPP_SUCCESS;
RainbatchPDROIDLocalData * data = NULL;
STATUS_ERROR_CHECK(vxQueryNode(node, VX_NODE_LOCAL_DATA_PTR, &data, sizeof(data)));
vx_df_image df_image = VX_DF_IMAGE_VIRT;
STATUS_ERROR_CHECK(vxQueryImage((vx_image)parameters[0], VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));
if(data->device_type == AGO_TARGET_AFFINITY_GPU) {
#if ENABLE_OPENCL
cl_command_queue handle = data->handle.cmdq;
refreshRainbatchPDROID(node, parameters, num, data);
if (df_image == VX_DF_IMAGE_U8 ){
// status = rppi_rain_u8_pln1_batchPD_ROID_gpu((void *)data->cl_pSrc,data->srcDimensions,data->maxSrcDimensions,(void *)data->cl_pDst,data->rainValue,data->rainWidth,data->rainHeight,data->rainTransperancy,data->roiPoints,data->nbatchSize,data->rppHandle);
}
else if(df_image == VX_DF_IMAGE_RGB) {
// status = rppi_rain_u8_pkd3_batchPD_ROID_gpu((void *)data->cl_pSrc,data->srcDimensions,data->maxSrcDimensions,(void *)data->cl_pDst,data->rainValue,data->rainWidth,data->rainHeight,data->rainTransperancy,data->roiPoints,data->nbatchSize,data->rppHandle);
}
return status;
#endif
}
if(data->device_type == AGO_TARGET_AFFINITY_CPU) {
refreshRainbatchPDROID(node, parameters, num, data);
if (df_image == VX_DF_IMAGE_U8 ){
// status = rppi_rain_u8_pln1_batchPD_ROID_host(data->pSrc,data->srcDimensions,data->maxSrcDimensions,data->pDst,data->rainValue,data->rainWidth,data->rainHeight,data->rainTransperancy,data->roiPoints,data->nbatchSize,data->rppHandle);
}
else if(df_image == VX_DF_IMAGE_RGB) {
// status = rppi_rain_u8_pkd3_batchPD_ROID_host(data->pSrc,data->srcDimensions,data->maxSrcDimensions,data->pDst,data->rainValue,data->rainWidth,data->rainHeight,data->rainTransperancy,data->roiPoints,data->nbatchSize,data->rppHandle);
}
return status;
}
}
static vx_status VX_CALLBACK initializeRainbatchPDROID(vx_node node, const vx_reference *parameters, vx_uint32 num)
{
RainbatchPDROIDLocalData * data = new RainbatchPDROIDLocalData;
memset(data, 0, sizeof(*data));
#if ENABLE_OPENCL
STATUS_ERROR_CHECK(vxQueryNode(node, VX_NODE_ATTRIBUTE_AMD_OPENCL_COMMAND_QUEUE, &data->handle.cmdq, sizeof(data->handle.cmdq)));
#endif
STATUS_ERROR_CHECK(vxCopyScalar((vx_scalar)parameters[13], &data->device_type, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
refreshRainbatchPDROID(node, parameters, num, data);
#if ENABLE_OPENCL
if(data->device_type == AGO_TARGET_AFFINITY_GPU)
rppCreateWithStreamAndBatchSize(&data->rppHandle, data->handle.cmdq, data->nbatchSize);
#endif
if(data->device_type == AGO_TARGET_AFFINITY_CPU)
rppCreateWithBatchSize(&data->rppHandle, data->nbatchSize);
STATUS_ERROR_CHECK(vxSetNodeAttribute(node, VX_NODE_LOCAL_DATA_PTR, &data, sizeof(data)));
return VX_SUCCESS;
}
static vx_status VX_CALLBACK uninitializeRainbatchPDROID(vx_node node, const vx_reference *parameters, vx_uint32 num)
{
RainbatchPDROIDLocalData * data;
STATUS_ERROR_CHECK(vxQueryNode(node, VX_NODE_LOCAL_DATA_PTR, &data, sizeof(data)));
#if ENABLE_OPENCL
if(data->device_type == AGO_TARGET_AFFINITY_GPU)
rppDestroyGPU(data->rppHandle);
#endif
if(data->device_type == AGO_TARGET_AFFINITY_CPU)
rppDestroyHost(data->rppHandle);
delete(data);
return VX_SUCCESS;
}
vx_status RainbatchPDROID_Register(vx_context context)
{
vx_status status = VX_SUCCESS;
// Add kernel to the context with callbacks
vx_kernel kernel = vxAddUserKernel(context, "org.rpp.RainbatchPDROID",
VX_KERNEL_RPP_RAINBATCHPDROID,
processRainbatchPDROID,
14,
validateRainbatchPDROID,
initializeRainbatchPDROID,
uninitializeRainbatchPDROID);
ERROR_CHECK_OBJECT(kernel);
AgoTargetAffinityInfo affinity;
vxQueryContext(context, VX_CONTEXT_ATTRIBUTE_AMD_AFFINITY,&affinity, sizeof(affinity));
#if ENABLE_OPENCL
// enable OpenCL buffer access since the kernel_f callback uses OpenCL buffers instead of host accessible buffers
vx_bool enableBufferAccess = vx_true_e;
if(affinity.device_type == AGO_TARGET_AFFINITY_GPU)
STATUS_ERROR_CHECK(vxSetKernelAttribute(kernel, VX_KERNEL_ATTRIBUTE_AMD_OPENCL_BUFFER_ACCESS_ENABLE, &enableBufferAccess, sizeof(enableBufferAccess)));
#else
vx_bool enableBufferAccess = vx_false_e;
#endif
if (kernel)
{
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 1, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 3, VX_OUTPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 4, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 5, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 6, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 7, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 8, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 9, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 10, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 11, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 12, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 13, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxFinalizeKernel(kernel));
}
if (status != VX_SUCCESS)
{
exit: vxRemoveKernel(kernel); return VX_FAILURE;
}
return status;
}
|
// Copyright Samuel Stark 2017
#pragma once
#include "instruction_sources.h"
namespace GB::Instructions::ALU{
// Adds
template<typename T, typename AddToSource, typename AddFromSource, bool WithCarry>
class AddInstruction{};
template<typename AddToSource, typename AddValueSource, bool WithCarry>
class AddInstruction<uint8_t, AddToSource, AddValueSource, WithCarry> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(AddToSource, uint8_t, SourceUsage::ReadAndWrite);
//STATIC_ASSERT_IS_SOURCE_INTERFACE(AddValueSource, uint8_t, SourceUsage::ReadOnly);
static_assert(AddValueSource::load);
public:
uint8_t execute(CPU& cpu) override{
bool should_carry = WithCarry && cpu.is_flag_set(CPUFlag::Carry);
uint8_t add_from = AddValueSource::load(cpu);
uint8_t add_to = AddToSource::load(cpu);
int addition_result = add_from + add_to + (should_carry ? 1 : 0);
uint8_t wrapped_result = addition_result & 0xff;
cpu.set_flag(CPUFlag::Zero, wrapped_result == 0);
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::Carry, (addition_result >> 8) & 1);
// The "& 0xf" zeroes out the top 4 bits.
// A Half Carry occurs if the result of the bottom 4 bits added together
// has the 5th bit set. "& 0x10" makes the number 0 if the 5th bit isn't set,
// or 0x10 if it is.
cpu.set_flag(CPUFlag::HalfCarry, (((add_from & 0xf) + (add_to & 0xf) + (should_carry ? 1 : 0)) >> 4) & 1);
AddToSource::store(cpu, wrapped_result);
return 4 + AddValueSource::cycles + AddToSource::cycles;
}
};
template<typename AddToSource, typename AddValueSource>
class AddInstruction<uint16_t, AddToSource, AddValueSource, false> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(AddToSource, uint16_t, SourceUsage::ReadAndWrite);
//STATIC_ASSERT_IS_SOURCE_INTERFACE(AddValueSource, uint16_t, SourceUsage::ReadOnly);
static_assert(AddValueSource::load);
public:
uint8_t execute(CPU& cpu) override{
uint16_t add_from = AddValueSource::load(cpu);
uint16_t add_to = AddToSource::load(cpu);
int addition_result = add_from + add_to;
uint16_t wrapped_result = addition_result & 0xffff;
// Ignore Zero flag
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::Carry, (addition_result >> 16) & 1);
// The "& 0xff" zeroes out the top 8 bits.
// A Half Carry occurs if the result of the bottom 8 bits added together
// has the 5th bit set. "& 0x100" makes the number 0 if the 9th bit isn't set,
// or 0x100 if it is.
cpu.set_flag(CPUFlag::HalfCarry, (((add_from & 0xfff) + (add_to & 0xfff)) & 0x1000) == 0x1000);
AddToSource::store(cpu, wrapped_result);
return 4 + AddValueSource::cycles + AddToSource::cycles;
}
};
// Subtracts
template<typename SubFromSource, typename SubValueSource, bool WithCarry>
class SubInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(SubFromSource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(SubValueSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
bool should_carry = WithCarry && cpu.is_flag_set(CPUFlag::Carry);
uint8_t sub_from = SubFromSource::load(cpu);
uint8_t sub_value = SubValueSource::load(cpu);
int subtraction_result = sub_from - sub_value - (should_carry ? 1 : 0);
uint8_t wrapped_result = static_cast<uint8_t>(subtraction_result);
if (CPU::extended_debug_data){
fprintf(stdout, "sub_from = %d, sub_value = %d, result = %d (wrapped %d)\n", sub_from, sub_value, subtraction_result, wrapped_result);
}
cpu.set_flag(CPUFlag::Zero, wrapped_result == 0);
cpu.set_flag(CPUFlag::Negative, true);
cpu.set_flag(CPUFlag::Carry, subtraction_result < 0);
// The "& 0xf" zeroes out the top 4 bits.
// A Half Carry occurs if the result of the bottom 4 bits subtracted is < 0,
// i.e. if the bottom 4 bits of sub_value > the bottom 4 bits of sub_from
cpu.set_flag(CPUFlag::HalfCarry, ((sub_value & 0xf) + (should_carry ? 1 : 0)) > (sub_from & 0xf));
SubFromSource::store(cpu, wrapped_result);
return 4 + SubFromSource::cycles + SubValueSource::cycles;
}
};
// Logical Ops
template<typename IntoSource, typename ValueSource>
class AndInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(IntoSource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(ValueSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
auto result = IntoSource::load(cpu) & ValueSource::load(cpu);
cpu.set_flag(CPUFlag::Zero, result == 0);
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::Carry, false);
cpu.set_flag(CPUFlag::HalfCarry, true);
IntoSource::store(cpu, result);
return 4 + IntoSource::cycles + ValueSource::cycles;
}
};
template<typename IntoSource, typename ValueSource>
class OrInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(IntoSource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(ValueSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
auto result = IntoSource::load(cpu) | ValueSource::load(cpu);
cpu.set_flag(CPUFlag::Zero, result == 0);
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::Carry, false);
cpu.set_flag(CPUFlag::HalfCarry, false);
IntoSource::store(cpu, result);
return 4 + IntoSource::cycles + ValueSource::cycles;
}
};
template<typename IntoSource, typename ValueSource>
class XorInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(IntoSource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(ValueSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
auto result = IntoSource::load(cpu) ^ ValueSource::load(cpu);
cpu.set_flag(CPUFlag::Zero, result == 0);
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::Carry, false);
cpu.set_flag(CPUFlag::HalfCarry, false);
IntoSource::store(cpu, result);
return 4 + IntoSource::cycles + ValueSource::cycles;
}
};
template<typename ASource, typename BSource>
class CompareInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(ASource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(BSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
uint8_t a = ASource::load(cpu);
uint8_t b = BSource::load(cpu);
if (CPU::extended_debug_data){
fprintf(stdout, "Comparing 0x%02x (%d dec) to 0x%02x (%d dec)\n", a, a, b, b);
}
cpu.set_flag(CPUFlag::Zero, a == b);
cpu.set_flag(CPUFlag::Negative, true);
cpu.set_flag(CPUFlag::Carry, b > a);
cpu.set_flag(CPUFlag::HalfCarry, (b & 0xf) > (a & 0xf));
return 4 + ASource::cycles + BSource::cycles;
}
};
template<typename FromSource, typename IntoSource>
class NotInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(FromSource, uint8_t, SourceUsage::ReadAndWrite);
STATIC_ASSERT_IS_SOURCE_INTERFACE(IntoSource, uint8_t, SourceUsage::ReadOnly);
uint8_t execute(CPU& cpu) override{
auto result = ~FromSource::load(cpu);
cpu.set_flag(CPUFlag::Negative, true);
cpu.set_flag(CPUFlag::HalfCarry, true);
IntoSource::store(cpu, result);
return IntoSource::cycles + FromSource::cycles;
}
};
template<typename ValueType, typename InSource>
class IncrementInstruction{};
template<typename InSource>
class IncrementInstruction<uint8_t, InSource> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(InSource, uint8_t, SourceUsage::ReadAndWrite);
uint8_t execute(CPU& cpu) override{
uint8_t value = InSource::load(cpu);
uint8_t new_value = value + 1;
InSource::store(cpu, new_value);
cpu.set_flag(CPUFlag::Zero, new_value == 0);
cpu.set_flag(CPUFlag::Negative, false);
// Ignore Carry flag
// If the last 4 bits are all set then the increment resulted in a half-carry
cpu.set_flag(CPUFlag::HalfCarry, (value & 0xf) == 0xf);
return InSource::cycles;
};
};
template<typename InSource>
class IncrementInstruction<uint16_t, InSource> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(InSource, uint16_t, SourceUsage::ReadAndWrite);
uint8_t execute(CPU& cpu) override{
uint16_t value = InSource::load(cpu);
uint16_t new_value = value + 1;
InSource::store(cpu, new_value);
return InSource::cycles;
};
};
template<typename ValueType, typename InSource>
class DecrementInstruction{};
template<typename InSource>
class DecrementInstruction<uint8_t, InSource> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(InSource, uint8_t, SourceUsage::ReadAndWrite);
uint8_t execute(CPU& cpu) override{
uint8_t value = InSource::load(cpu);
uint8_t new_value = value - 1;
InSource::store(cpu, new_value);
cpu.set_flag(CPUFlag::Zero, new_value == 0);
cpu.set_flag(CPUFlag::Negative, true);
// Ignore Carry flag
// If the last 4 bits are all zero then the decrement resulted in a half-carry?
cpu.set_flag(CPUFlag::HalfCarry, (value & 0xf) == 0x0);
return InSource::cycles;
};
};
template<typename InSource>
class DecrementInstruction<uint16_t, InSource> : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(InSource, uint16_t, SourceUsage::ReadAndWrite);
uint8_t execute(CPU& cpu) override{
uint16_t value = InSource::load(cpu);
uint16_t new_value = value - 1;
InSource::store(cpu, new_value);
return InSource::cycles;
};
};
template<typename InSource, bool RotateLeft, bool IncludeCarry, bool IsCB = false>
class RotateInstruction : public Instruction{
using Instruction::Instruction;
STATIC_ASSERT_IS_SOURCE_INTERFACE(InSource, uint8_t, SourceUsage::ReadAndWrite);
uint8_t execute(CPU& cpu) override{
uint8_t value = InSource::load(cpu);
uint8_t rotated = rotate_value(cpu, value);
InSource::store(cpu, rotated);
// This is a special case, Rotates always take at least 4 cycles even though they only use one register
if (IsCB){
return (4 + InSource::cycles) * 2; // TODO: This seems tenuous at best.
}
return 4;
};
static inline uint8_t rotate_value(CPU& cpu, uint8_t value){
uint8_t result;
if (RotateLeft){
result = (value << 1);
if (IncludeCarry){
result = result | (cpu.is_flag_set(CPUFlag::Carry) ? 0b1 : 0b0);
}else{
result = result | ((value & 0b10000000) ? 0b1 : 0b0);
}
cpu.set_flag(CPUFlag::Carry, value & 0b10000000);
}else{
result = (value >> 1);
if (IncludeCarry){
result = result | (cpu.is_flag_set(CPUFlag::Carry) ? 0b10000000 : 0b0);
}else{
result = result | ((value & 0b1) ? 0b10000000 : 0b0);
}
cpu.set_flag(CPUFlag::Carry, value & 0b1);
}
cpu.set_flag(CPUFlag::Zero, IsCB ? (result == 0) : false);
cpu.set_flag(CPUFlag::Negative, false);
cpu.set_flag(CPUFlag::HalfCarry, false);
return result;
}
};
}
|
#include "Iop_Vblank.h"
#include "IopBios.h"
#include "Iop_Intc.h"
#include "../Log.h"
using namespace Iop;
#define LOG_NAME "iop_vblank"
#define FUNCTION_WAITVBLANKSTART "WaitVblankStart"
#define FUNCTION_WAITVBLANKEND "WaitVblankEnd"
#define FUNCTION_WAITVBLANK "WaitVblank"
#define FUNCTION_REGISTERVBLANKHANDLER "RegisterVblankHandler"
CVblank::CVblank(CIopBios& bios)
: m_bios(bios)
{
}
std::string CVblank::GetId() const
{
return "vblank";
}
std::string CVblank::GetFunctionName(unsigned int functionId) const
{
switch(functionId)
{
case 4:
return FUNCTION_WAITVBLANKSTART;
break;
case 5:
return FUNCTION_WAITVBLANKEND;
break;
case 6:
return FUNCTION_WAITVBLANK;
break;
case 8:
return FUNCTION_REGISTERVBLANKHANDLER;
break;
default:
return "unknown";
break;
}
}
void CVblank::Invoke(CMIPS& context, unsigned int functionId)
{
switch(functionId)
{
case 4:
context.m_State.nGPR[CMIPS::V0].nD0 = WaitVblankStart();
break;
case 5:
context.m_State.nGPR[CMIPS::V0].nD0 = WaitVblankEnd();
break;
case 6:
context.m_State.nGPR[CMIPS::V0].nD0 = WaitVblank();
break;
case 8:
context.m_State.nGPR[CMIPS::V0].nD0 = RegisterVblankHandler(
context,
context.m_State.nGPR[CMIPS::A0].nV0,
context.m_State.nGPR[CMIPS::A1].nV0,
context.m_State.nGPR[CMIPS::A2].nV0,
context.m_State.nGPR[CMIPS::A3].nV0);
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Unknown function called (%d).\r\n", functionId);
break;
}
}
int32 CVblank::WaitVblankStart()
{
#ifdef _DEBUG
CLog::GetInstance().Print(LOG_NAME, FUNCTION_WAITVBLANKSTART "();\r\n");
#endif
m_bios.SleepThreadTillVBlankStart();
return 0;
}
int32 CVblank::WaitVblankEnd()
{
#ifdef _DEBUG
CLog::GetInstance().Print(LOG_NAME, FUNCTION_WAITVBLANKEND "();\r\n");
#endif
m_bios.SleepThreadTillVBlankEnd();
return 0;
}
int32 CVblank::WaitVblank()
{
#ifdef _DEBUG
CLog::GetInstance().Print(LOG_NAME, FUNCTION_WAITVBLANK "();\r\n");
#endif
//TODO: Skip waiting if we're already in Vblank
m_bios.SleepThreadTillVBlankStart();
return 0;
}
int32 CVblank::RegisterVblankHandler(CMIPS& context, uint32 startEnd, uint32 priority, uint32 handlerPtr, uint32 handlerParam)
{
#ifdef _DEBUG
CLog::GetInstance().Print(LOG_NAME, FUNCTION_REGISTERVBLANKHANDLER "(startEnd = %d, priority = %d, handler = 0x%08X, arg = 0x%08X).\r\n",
startEnd, priority, handlerPtr, handlerParam);
#endif
uint32 intrLine = startEnd ? CIntc::LINE_EVBLANK : CIntc::LINE_VBLANK;
m_bios.RegisterIntrHandler(intrLine, 0, handlerPtr, handlerParam);
uint32 mask = context.m_pMemoryMap->GetWord(CIntc::MASK0);
mask |= (1 << intrLine);
context.m_pMemoryMap->SetWord(CIntc::MASK0, mask);
return 0;
}
|
// Copyright 2020 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/heap/paged-spaces.h"
#include "src/base/optional.h"
#include "src/base/platform/mutex.h"
#include "src/execution/isolate.h"
#include "src/execution/vm-state-inl.h"
#include "src/heap/array-buffer-sweeper.h"
#include "src/heap/heap.h"
#include "src/heap/incremental-marking.h"
#include "src/heap/memory-allocator.h"
#include "src/heap/memory-chunk-inl.h"
#include "src/heap/paged-spaces-inl.h"
#include "src/heap/read-only-heap.h"
#include "src/logging/counters.h"
#include "src/objects/string.h"
#include "src/utils/utils.h"
namespace v8 {
namespace internal {
// ----------------------------------------------------------------------------
// PagedSpaceObjectIterator
PagedSpaceObjectIterator::PagedSpaceObjectIterator(Heap* heap,
PagedSpace* space)
: cur_addr_(kNullAddress),
cur_end_(kNullAddress),
space_(space),
page_range_(space->first_page(), nullptr),
current_page_(page_range_.begin()) {
space_->MakeLinearAllocationAreaIterable();
heap->mark_compact_collector()->EnsureSweepingCompleted();
}
PagedSpaceObjectIterator::PagedSpaceObjectIterator(Heap* heap,
PagedSpace* space,
Page* page)
: cur_addr_(kNullAddress),
cur_end_(kNullAddress),
space_(space),
page_range_(page),
current_page_(page_range_.begin()) {
space_->MakeLinearAllocationAreaIterable();
heap->mark_compact_collector()->EnsureSweepingCompleted();
#ifdef DEBUG
AllocationSpace owner = page->owner_identity();
DCHECK(owner == OLD_SPACE || owner == MAP_SPACE || owner == CODE_SPACE);
#endif // DEBUG
}
// We have hit the end of the page and should advance to the next block of
// objects. This happens at the end of the page.
bool PagedSpaceObjectIterator::AdvanceToNextPage() {
DCHECK_EQ(cur_addr_, cur_end_);
if (current_page_ == page_range_.end()) return false;
Page* cur_page = *(current_page_++);
cur_addr_ = cur_page->area_start();
cur_end_ = cur_page->area_end();
DCHECK(cur_page->SweepingDone());
return true;
}
Page* PagedSpace::InitializePage(MemoryChunk* chunk) {
Page* page = static_cast<Page*>(chunk);
DCHECK_EQ(
MemoryChunkLayout::AllocatableMemoryInMemoryChunk(page->owner_identity()),
page->area_size());
// Make sure that categories are initialized before freeing the area.
page->ResetAllocationStatistics();
page->SetOldGenerationPageFlags(heap()->incremental_marking()->IsMarking());
page->AllocateFreeListCategories();
page->InitializeFreeListCategories();
page->list_node().Initialize();
page->InitializationMemoryFence();
return page;
}
PagedSpace::PagedSpace(Heap* heap, AllocationSpace space,
Executability executable, FreeList* free_list,
LocalSpaceKind local_space_kind)
: SpaceWithLinearArea(heap, space, free_list),
executable_(executable),
local_space_kind_(local_space_kind) {
area_size_ = MemoryChunkLayout::AllocatableMemoryInMemoryChunk(space);
accounting_stats_.Clear();
}
void PagedSpace::TearDown() {
while (!memory_chunk_list_.Empty()) {
MemoryChunk* chunk = memory_chunk_list_.front();
memory_chunk_list_.Remove(chunk);
heap()->memory_allocator()->Free<MemoryAllocator::kFull>(chunk);
}
accounting_stats_.Clear();
}
void PagedSpace::RefillFreeList() {
// Any PagedSpace might invoke RefillFreeList. We filter all but our old
// generation spaces out.
if (identity() != OLD_SPACE && identity() != CODE_SPACE &&
identity() != MAP_SPACE) {
return;
}
DCHECK_IMPLIES(is_local_space(), is_compaction_space());
MarkCompactCollector* collector = heap()->mark_compact_collector();
size_t added = 0;
{
Page* p = nullptr;
while ((p = collector->sweeper()->GetSweptPageSafe(this)) != nullptr) {
// We regularly sweep NEVER_ALLOCATE_ON_PAGE pages. We drop the freelist
// entries here to make them unavailable for allocations.
if (p->IsFlagSet(Page::NEVER_ALLOCATE_ON_PAGE)) {
p->ForAllFreeListCategories([this](FreeListCategory* category) {
category->Reset(free_list());
});
}
// Also merge old-to-new remembered sets if not scavenging because of
// data races: One thread might iterate remembered set, while another
// thread merges them.
if (local_space_kind() != LocalSpaceKind::kCompactionSpaceForScavenge) {
p->MergeOldToNewRememberedSets();
}
// Only during compaction pages can actually change ownership. This is
// safe because there exists no other competing action on the page links
// during compaction.
if (is_compaction_space()) {
DCHECK_NE(this, p->owner());
PagedSpace* owner = reinterpret_cast<PagedSpace*>(p->owner());
base::MutexGuard guard(owner->mutex());
owner->RefineAllocatedBytesAfterSweeping(p);
owner->RemovePage(p);
added += AddPage(p);
added += p->wasted_memory();
} else {
base::MutexGuard guard(mutex());
DCHECK_EQ(this, p->owner());
RefineAllocatedBytesAfterSweeping(p);
added += RelinkFreeListCategories(p);
added += p->wasted_memory();
}
if (is_compaction_space() && (added > kCompactionMemoryWanted)) break;
}
}
}
void PagedSpace::MergeLocalSpace(LocalSpace* other) {
base::MutexGuard guard(mutex());
DCHECK(identity() == other->identity());
// Unmerged fields:
// area_size_
other->FreeLinearAllocationArea();
for (int i = static_cast<int>(AllocationOrigin::kFirstAllocationOrigin);
i <= static_cast<int>(AllocationOrigin::kLastAllocationOrigin); i++) {
allocations_origins_[i] += other->allocations_origins_[i];
}
// The linear allocation area of {other} should be destroyed now.
DCHECK_EQ(kNullAddress, other->top());
DCHECK_EQ(kNullAddress, other->limit());
// Move over pages.
for (auto it = other->begin(); it != other->end();) {
Page* p = *(it++);
p->MergeOldToNewRememberedSets();
// Ensure that pages are initialized before objects on it are discovered by
// concurrent markers.
p->InitializationMemoryFence();
// Relinking requires the category to be unlinked.
other->RemovePage(p);
AddPage(p);
DCHECK_IMPLIES(
!p->IsFlagSet(Page::NEVER_ALLOCATE_ON_PAGE),
p->AvailableInFreeList() == p->AvailableInFreeListFromAllocatedBytes());
// TODO(leszeks): Here we should allocation step, but:
// 1. Allocation groups are currently not handled properly by the sampling
// allocation profiler, and
// 2. Observers might try to take the space lock, which isn't reentrant.
// We'll have to come up with a better solution for allocation stepping
// before shipping, which will likely be using LocalHeap.
}
for (auto p : other->GetNewPages()) {
heap()->NotifyOldGenerationExpansion(identity(), p);
}
DCHECK_EQ(0u, other->Size());
DCHECK_EQ(0u, other->Capacity());
}
size_t PagedSpace::CommittedPhysicalMemory() {
if (!base::OS::HasLazyCommits()) return CommittedMemory();
BasicMemoryChunk::UpdateHighWaterMark(allocation_info_.top());
base::MutexGuard guard(mutex());
size_t size = 0;
for (Page* page : *this) {
size += page->CommittedPhysicalMemory();
}
return size;
}
bool PagedSpace::ContainsSlow(Address addr) const {
Page* p = Page::FromAddress(addr);
for (const Page* page : *this) {
if (page == p) return true;
}
return false;
}
void PagedSpace::RefineAllocatedBytesAfterSweeping(Page* page) {
CHECK(page->SweepingDone());
auto marking_state =
heap()->incremental_marking()->non_atomic_marking_state();
// The live_byte on the page was accounted in the space allocated
// bytes counter. After sweeping allocated_bytes() contains the
// accurate live byte count on the page.
size_t old_counter = marking_state->live_bytes(page);
size_t new_counter = page->allocated_bytes();
DCHECK_GE(old_counter, new_counter);
if (old_counter > new_counter) {
DecreaseAllocatedBytes(old_counter - new_counter, page);
}
marking_state->SetLiveBytes(page, 0);
}
Page* PagedSpace::RemovePageSafe(int size_in_bytes) {
base::MutexGuard guard(mutex());
Page* page = free_list()->GetPageForSize(size_in_bytes);
if (!page) return nullptr;
RemovePage(page);
return page;
}
size_t PagedSpace::AddPage(Page* page) {
CHECK(page->SweepingDone());
page->set_owner(this);
memory_chunk_list_.PushBack(page);
AccountCommitted(page->size());
IncreaseCapacity(page->area_size());
IncreaseAllocatedBytes(page->allocated_bytes(), page);
for (size_t i = 0; i < ExternalBackingStoreType::kNumTypes; i++) {
ExternalBackingStoreType t = static_cast<ExternalBackingStoreType>(i);
IncrementExternalBackingStoreBytes(t, page->ExternalBackingStoreBytes(t));
}
return RelinkFreeListCategories(page);
}
void PagedSpace::RemovePage(Page* page) {
CHECK(page->SweepingDone());
memory_chunk_list_.Remove(page);
UnlinkFreeListCategories(page);
DecreaseAllocatedBytes(page->allocated_bytes(), page);
DecreaseCapacity(page->area_size());
AccountUncommitted(page->size());
for (size_t i = 0; i < ExternalBackingStoreType::kNumTypes; i++) {
ExternalBackingStoreType t = static_cast<ExternalBackingStoreType>(i);
DecrementExternalBackingStoreBytes(t, page->ExternalBackingStoreBytes(t));
}
}
void PagedSpace::SetTopAndLimit(Address top, Address limit) {
DCHECK(top == limit ||
Page::FromAddress(top) == Page::FromAddress(limit - 1));
BasicMemoryChunk::UpdateHighWaterMark(allocation_info_.top());
allocation_info_.Reset(top, limit);
}
size_t PagedSpace::ShrinkPageToHighWaterMark(Page* page) {
size_t unused = page->ShrinkToHighWaterMark();
accounting_stats_.DecreaseCapacity(static_cast<intptr_t>(unused));
AccountUncommitted(unused);
return unused;
}
void PagedSpace::ResetFreeList() {
for (Page* page : *this) {
free_list_->EvictFreeListItems(page);
}
DCHECK(free_list_->IsEmpty());
}
void PagedSpace::ShrinkImmortalImmovablePages() {
DCHECK(!heap()->deserialization_complete());
BasicMemoryChunk::UpdateHighWaterMark(allocation_info_.top());
FreeLinearAllocationArea();
ResetFreeList();
for (Page* page : *this) {
DCHECK(page->IsFlagSet(Page::NEVER_EVACUATE));
ShrinkPageToHighWaterMark(page);
}
}
Page* PagedSpace::AllocatePage() {
return heap()->memory_allocator()->AllocatePage(AreaSize(), this,
executable());
}
Page* PagedSpace::Expand() {
Page* page = AllocatePage();
if (page == nullptr) return nullptr;
ConcurrentAllocationMutex guard(this);
AddPage(page);
Free(page->area_start(), page->area_size(),
SpaceAccountingMode::kSpaceAccounted);
return page;
}
Page* PagedSpace::ExpandBackground(LocalHeap* local_heap) {
Page* page = AllocatePage();
if (page == nullptr) return nullptr;
base::MutexGuard lock(&space_mutex_);
AddPage(page);
Free(page->area_start(), page->area_size(),
SpaceAccountingMode::kSpaceAccounted);
return page;
}
int PagedSpace::CountTotalPages() {
int count = 0;
for (Page* page : *this) {
count++;
USE(page);
}
return count;
}
void PagedSpace::SetLinearAllocationArea(Address top, Address limit) {
SetTopAndLimit(top, limit);
if (top != kNullAddress && top != limit &&
heap()->incremental_marking()->black_allocation()) {
Page::FromAllocationAreaAddress(top)->CreateBlackArea(top, limit);
}
}
void PagedSpace::DecreaseLimit(Address new_limit) {
Address old_limit = limit();
DCHECK_LE(top(), new_limit);
DCHECK_GE(old_limit, new_limit);
if (new_limit != old_limit) {
base::Optional<CodePageMemoryModificationScope> optional_scope;
if (identity() == CODE_SPACE) {
MemoryChunk* chunk = MemoryChunk::FromAddress(new_limit);
optional_scope.emplace(chunk);
}
SetTopAndLimit(top(), new_limit);
Free(new_limit, old_limit - new_limit,
SpaceAccountingMode::kSpaceAccounted);
if (heap()->incremental_marking()->black_allocation()) {
Page::FromAllocationAreaAddress(new_limit)->DestroyBlackArea(new_limit,
old_limit);
}
}
}
void PagedSpace::MarkLinearAllocationAreaBlack() {
DCHECK(heap()->incremental_marking()->black_allocation());
Address current_top = top();
Address current_limit = limit();
if (current_top != kNullAddress && current_top != current_limit) {
Page::FromAllocationAreaAddress(current_top)
->CreateBlackArea(current_top, current_limit);
}
}
void PagedSpace::UnmarkLinearAllocationArea() {
Address current_top = top();
Address current_limit = limit();
if (current_top != kNullAddress && current_top != current_limit) {
Page::FromAllocationAreaAddress(current_top)
->DestroyBlackArea(current_top, current_limit);
}
}
void PagedSpace::MakeLinearAllocationAreaIterable() {
Address current_top = top();
Address current_limit = limit();
if (current_top != kNullAddress && current_top != current_limit) {
base::Optional<CodePageMemoryModificationScope> optional_scope;
if (identity() == CODE_SPACE) {
MemoryChunk* chunk = MemoryChunk::FromAddress(current_top);
optional_scope.emplace(chunk);
}
heap_->CreateFillerObjectAt(current_top,
static_cast<int>(current_limit - current_top),
ClearRecordedSlots::kNo);
}
}
size_t PagedSpace::Available() {
ConcurrentAllocationMutex guard(this);
return free_list_->Available();
}
void PagedSpace::FreeLinearAllocationArea() {
// Mark the old linear allocation area with a free space map so it can be
// skipped when scanning the heap.
Address current_top = top();
Address current_limit = limit();
if (current_top == kNullAddress) {
DCHECK_EQ(kNullAddress, current_limit);
return;
}
AdvanceAllocationObservers();
if (current_top != current_limit &&
heap()->incremental_marking()->black_allocation()) {
Page::FromAddress(current_top)
->DestroyBlackArea(current_top, current_limit);
}
SetTopAndLimit(kNullAddress, kNullAddress);
DCHECK_GE(current_limit, current_top);
// The code page of the linear allocation area needs to be unprotected
// because we are going to write a filler into that memory area below.
if (identity() == CODE_SPACE) {
heap()->UnprotectAndRegisterMemoryChunk(
MemoryChunk::FromAddress(current_top));
}
DCHECK_IMPLIES(current_limit - current_top >= 2 * kTaggedSize,
heap()->incremental_marking()->marking_state()->IsWhite(
HeapObject::FromAddress(current_top)));
Free(current_top, current_limit - current_top,
SpaceAccountingMode::kSpaceAccounted);
}
void PagedSpace::ReleasePage(Page* page) {
DCHECK_EQ(
0, heap()->incremental_marking()->non_atomic_marking_state()->live_bytes(
page));
DCHECK_EQ(page->owner(), this);
free_list_->EvictFreeListItems(page);
if (Page::FromAllocationAreaAddress(allocation_info_.top()) == page) {
SetTopAndLimit(kNullAddress, kNullAddress);
}
if (identity() == CODE_SPACE) {
heap()->isolate()->RemoveCodeMemoryChunk(page);
}
AccountUncommitted(page->size());
accounting_stats_.DecreaseCapacity(page->area_size());
heap()->memory_allocator()->Free<MemoryAllocator::kPreFreeAndQueue>(page);
}
void PagedSpace::SetReadable() {
DCHECK(identity() == CODE_SPACE);
for (Page* page : *this) {
CHECK(heap()->memory_allocator()->IsMemoryChunkExecutable(page));
page->SetReadable();
}
}
void PagedSpace::SetReadAndExecutable() {
DCHECK(identity() == CODE_SPACE);
for (Page* page : *this) {
CHECK(heap()->memory_allocator()->IsMemoryChunkExecutable(page));
page->SetReadAndExecutable();
}
}
void PagedSpace::SetReadAndWritable() {
DCHECK(identity() == CODE_SPACE);
for (Page* page : *this) {
CHECK(heap()->memory_allocator()->IsMemoryChunkExecutable(page));
page->SetReadAndWritable();
}
}
std::unique_ptr<ObjectIterator> PagedSpace::GetObjectIterator(Heap* heap) {
return std::unique_ptr<ObjectIterator>(
new PagedSpaceObjectIterator(heap, this));
}
bool PagedSpace::TryAllocationFromFreeListMain(size_t size_in_bytes,
AllocationOrigin origin) {
ConcurrentAllocationMutex guard(this);
DCHECK(IsAligned(size_in_bytes, kTaggedSize));
DCHECK_LE(top(), limit());
#ifdef DEBUG
if (top() != limit()) {
DCHECK_EQ(Page::FromAddress(top()), Page::FromAddress(limit() - 1));
}
#endif
// Don't free list allocate if there is linear space available.
DCHECK_LT(static_cast<size_t>(limit() - top()), size_in_bytes);
// Mark the old linear allocation area with a free space map so it can be
// skipped when scanning the heap. This also puts it back in the free list
// if it is big enough.
FreeLinearAllocationArea();
size_t new_node_size = 0;
FreeSpace new_node =
free_list_->Allocate(size_in_bytes, &new_node_size, origin);
if (new_node.is_null()) return false;
DCHECK_GE(new_node_size, size_in_bytes);
// The old-space-step might have finished sweeping and restarted marking.
// Verify that it did not turn the page of the new node into an evacuation
// candidate.
DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(new_node));
// Memory in the linear allocation area is counted as allocated. We may free
// a little of this again immediately - see below.
Page* page = Page::FromHeapObject(new_node);
IncreaseAllocatedBytes(new_node_size, page);
DCHECK_EQ(allocation_info_.start(), allocation_info_.top());
Address start = new_node.address();
Address end = new_node.address() + new_node_size;
Address limit = ComputeLimit(start, end, size_in_bytes);
DCHECK_LE(limit, end);
DCHECK_LE(size_in_bytes, limit - start);
if (limit != end) {
if (identity() == CODE_SPACE) {
heap()->UnprotectAndRegisterMemoryChunk(page);
}
Free(limit, end - limit, SpaceAccountingMode::kSpaceAccounted);
}
SetLinearAllocationArea(start, limit);
return true;
}
base::Optional<std::pair<Address, size_t>> PagedSpace::RawRefillLabBackground(
LocalHeap* local_heap, size_t min_size_in_bytes, size_t max_size_in_bytes,
AllocationAlignment alignment, AllocationOrigin origin) {
DCHECK(!is_local_space() && identity() == OLD_SPACE);
DCHECK_EQ(origin, AllocationOrigin::kRuntime);
auto result = TryAllocationFromFreeListBackground(
local_heap, min_size_in_bytes, max_size_in_bytes, alignment, origin);
if (result) return result;
MarkCompactCollector* collector = heap()->mark_compact_collector();
// Sweeping is still in progress.
if (collector->sweeping_in_progress()) {
// First try to refill the free-list, concurrent sweeper threads
// may have freed some objects in the meantime.
RefillFreeList();
// Retry the free list allocation.
auto result = TryAllocationFromFreeListBackground(
local_heap, min_size_in_bytes, max_size_in_bytes, alignment, origin);
if (result) return result;
// Now contribute to sweeping from background thread and then try to
// reallocate.
Sweeper::FreeSpaceMayContainInvalidatedSlots
invalidated_slots_in_free_space =
Sweeper::FreeSpaceMayContainInvalidatedSlots::kNo;
const int kMaxPagesToSweep = 1;
int max_freed = collector->sweeper()->ParallelSweepSpace(
identity(), static_cast<int>(min_size_in_bytes), kMaxPagesToSweep,
invalidated_slots_in_free_space);
RefillFreeList();
if (static_cast<size_t>(max_freed) >= min_size_in_bytes) {
auto result = TryAllocationFromFreeListBackground(
local_heap, min_size_in_bytes, max_size_in_bytes, alignment, origin);
if (result) return result;
}
}
if (heap()->ShouldExpandOldGenerationOnSlowAllocation(local_heap) &&
heap()->CanExpandOldGenerationBackground(AreaSize()) &&
ExpandBackground(local_heap)) {
DCHECK((CountTotalPages() > 1) ||
(min_size_in_bytes <= free_list_->Available()));
auto result = TryAllocationFromFreeListBackground(
local_heap, min_size_in_bytes, max_size_in_bytes, alignment, origin);
if (result) return result;
}
if (collector->sweeping_in_progress()) {
// Complete sweeping for this space.
collector->DrainSweepingWorklistForSpace(identity());
RefillFreeList();
// Last try to acquire memory from free list.
return TryAllocationFromFreeListBackground(
local_heap, min_size_in_bytes, max_size_in_bytes, alignment, origin);
}
return {};
}
base::Optional<std::pair<Address, size_t>>
PagedSpace::TryAllocationFromFreeListBackground(LocalHeap* local_heap,
size_t min_size_in_bytes,
size_t max_size_in_bytes,
AllocationAlignment alignment,
AllocationOrigin origin) {
base::MutexGuard lock(&space_mutex_);
DCHECK_LE(min_size_in_bytes, max_size_in_bytes);
DCHECK_EQ(identity(), OLD_SPACE);
size_t new_node_size = 0;
FreeSpace new_node =
free_list_->Allocate(min_size_in_bytes, &new_node_size, origin);
if (new_node.is_null()) return {};
DCHECK_GE(new_node_size, min_size_in_bytes);
// The old-space-step might have finished sweeping and restarted marking.
// Verify that it did not turn the page of the new node into an evacuation
// candidate.
DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(new_node));
// Memory in the linear allocation area is counted as allocated. We may free
// a little of this again immediately - see below.
Page* page = Page::FromHeapObject(new_node);
IncreaseAllocatedBytes(new_node_size, page);
heap()->StartIncrementalMarkingIfAllocationLimitIsReachedBackground();
size_t used_size_in_bytes = Min(new_node_size, max_size_in_bytes);
Address start = new_node.address();
Address end = new_node.address() + new_node_size;
Address limit = new_node.address() + used_size_in_bytes;
DCHECK_LE(limit, end);
DCHECK_LE(min_size_in_bytes, limit - start);
if (limit != end) {
Free(limit, end - limit, SpaceAccountingMode::kSpaceAccounted);
}
return std::make_pair(start, used_size_in_bytes);
}
#ifdef DEBUG
void PagedSpace::Print() {}
#endif
#ifdef VERIFY_HEAP
void PagedSpace::Verify(Isolate* isolate, ObjectVisitor* visitor) {
bool allocation_pointer_found_in_space =
(allocation_info_.top() == allocation_info_.limit());
size_t external_space_bytes[kNumTypes];
size_t external_page_bytes[kNumTypes];
for (int i = 0; i < kNumTypes; i++) {
external_space_bytes[static_cast<ExternalBackingStoreType>(i)] = 0;
}
for (Page* page : *this) {
CHECK_EQ(page->owner(), this);
for (int i = 0; i < kNumTypes; i++) {
external_page_bytes[static_cast<ExternalBackingStoreType>(i)] = 0;
}
if (page == Page::FromAllocationAreaAddress(allocation_info_.top())) {
allocation_pointer_found_in_space = true;
}
CHECK(page->SweepingDone());
PagedSpaceObjectIterator it(isolate->heap(), this, page);
Address end_of_previous_object = page->area_start();
Address top = page->area_end();
for (HeapObject object = it.Next(); !object.is_null(); object = it.Next()) {
CHECK(end_of_previous_object <= object.address());
// The first word should be a map, and we expect all map pointers to
// be in map space.
Map map = object.map();
CHECK(map.IsMap());
CHECK(ReadOnlyHeap::Contains(map) ||
isolate->heap()->map_space()->Contains(map));
// Perform space-specific object verification.
VerifyObject(object);
// The object itself should look OK.
object.ObjectVerify(isolate);
if (identity() != RO_SPACE && !FLAG_verify_heap_skip_remembered_set) {
isolate->heap()->VerifyRememberedSetFor(object);
}
// All the interior pointers should be contained in the heap.
int size = object.Size();
object.IterateBody(map, size, visitor);
CHECK(object.address() + size <= top);
end_of_previous_object = object.address() + size;
if (object.IsExternalString()) {
ExternalString external_string = ExternalString::cast(object);
size_t size = external_string.ExternalPayloadSize();
external_page_bytes[ExternalBackingStoreType::kExternalString] += size;
}
}
for (int i = 0; i < kNumTypes; i++) {
ExternalBackingStoreType t = static_cast<ExternalBackingStoreType>(i);
CHECK_EQ(external_page_bytes[t], page->ExternalBackingStoreBytes(t));
external_space_bytes[t] += external_page_bytes[t];
}
}
for (int i = 0; i < kNumTypes; i++) {
if (i == ExternalBackingStoreType::kArrayBuffer) continue;
ExternalBackingStoreType t = static_cast<ExternalBackingStoreType>(i);
CHECK_EQ(external_space_bytes[t], ExternalBackingStoreBytes(t));
}
CHECK(allocation_pointer_found_in_space);
if (identity() == OLD_SPACE) {
size_t bytes = heap()->array_buffer_sweeper()->old().BytesSlow();
CHECK_EQ(bytes,
ExternalBackingStoreBytes(ExternalBackingStoreType::kArrayBuffer));
}
#ifdef DEBUG
VerifyCountersAfterSweeping(isolate->heap());
#endif
}
void PagedSpace::VerifyLiveBytes() {
IncrementalMarking::MarkingState* marking_state =
heap()->incremental_marking()->marking_state();
for (Page* page : *this) {
CHECK(page->SweepingDone());
PagedSpaceObjectIterator it(heap(), this, page);
int black_size = 0;
for (HeapObject object = it.Next(); !object.is_null(); object = it.Next()) {
// All the interior pointers should be contained in the heap.
if (marking_state->IsBlack(object)) {
black_size += object.Size();
}
}
CHECK_LE(black_size, marking_state->live_bytes(page));
}
}
#endif // VERIFY_HEAP
#ifdef DEBUG
void PagedSpace::VerifyCountersAfterSweeping(Heap* heap) {
size_t total_capacity = 0;
size_t total_allocated = 0;
for (Page* page : *this) {
DCHECK(page->SweepingDone());
total_capacity += page->area_size();
PagedSpaceObjectIterator it(heap, this, page);
size_t real_allocated = 0;
for (HeapObject object = it.Next(); !object.is_null(); object = it.Next()) {
if (!object.IsFreeSpaceOrFiller()) {
real_allocated += object.Size();
}
}
total_allocated += page->allocated_bytes();
// The real size can be smaller than the accounted size if array trimming,
// object slack tracking happened after sweeping.
DCHECK_LE(real_allocated, accounting_stats_.AllocatedOnPage(page));
DCHECK_EQ(page->allocated_bytes(), accounting_stats_.AllocatedOnPage(page));
}
DCHECK_EQ(total_capacity, accounting_stats_.Capacity());
DCHECK_EQ(total_allocated, accounting_stats_.Size());
}
void PagedSpace::VerifyCountersBeforeConcurrentSweeping() {
// We need to refine the counters on pages that are already swept and have
// not been moved over to the actual space. Otherwise, the AccountingStats
// are just an over approximation.
RefillFreeList();
size_t total_capacity = 0;
size_t total_allocated = 0;
auto marking_state =
heap()->incremental_marking()->non_atomic_marking_state();
for (Page* page : *this) {
size_t page_allocated =
page->SweepingDone()
? page->allocated_bytes()
: static_cast<size_t>(marking_state->live_bytes(page));
total_capacity += page->area_size();
total_allocated += page_allocated;
DCHECK_EQ(page_allocated, accounting_stats_.AllocatedOnPage(page));
}
DCHECK_EQ(total_capacity, accounting_stats_.Capacity());
DCHECK_EQ(total_allocated, accounting_stats_.Size());
}
#endif
void PagedSpace::UpdateInlineAllocationLimit(size_t min_size) {
// Ensure there are no unaccounted allocations.
DCHECK_EQ(allocation_info_.start(), allocation_info_.top());
Address new_limit = ComputeLimit(top(), limit(), min_size);
DCHECK_LE(top(), new_limit);
DCHECK_LE(new_limit, limit());
DecreaseLimit(new_limit);
}
// -----------------------------------------------------------------------------
// OldSpace implementation
void PagedSpace::PrepareForMarkCompact() {
// We don't have a linear allocation area while sweeping. It will be restored
// on the first allocation after the sweep.
FreeLinearAllocationArea();
// Clear the free list before a full GC---it will be rebuilt afterward.
free_list_->Reset();
}
bool PagedSpace::RefillLabMain(int size_in_bytes, AllocationOrigin origin) {
VMState<GC> state(heap()->isolate());
RuntimeCallTimerScope runtime_timer(
heap()->isolate(), RuntimeCallCounterId::kGC_Custom_SlowAllocateRaw);
return RawRefillLabMain(size_in_bytes, origin);
}
Page* LocalSpace::Expand() {
Page* page = PagedSpace::Expand();
new_pages_.push_back(page);
return page;
}
bool CompactionSpace::RefillLabMain(int size_in_bytes,
AllocationOrigin origin) {
return RawRefillLabMain(size_in_bytes, origin);
}
bool PagedSpace::TryExpand(int size_in_bytes, AllocationOrigin origin) {
Page* page = Expand();
if (!page) return false;
if (!is_compaction_space()) {
heap()->NotifyOldGenerationExpansion(identity(), page);
}
DCHECK((CountTotalPages() > 1) ||
(static_cast<size_t>(size_in_bytes) <= free_list_->Available()));
return TryAllocationFromFreeListMain(static_cast<size_t>(size_in_bytes),
origin);
}
bool PagedSpace::RawRefillLabMain(int size_in_bytes, AllocationOrigin origin) {
// Non-compaction local spaces are not supported.
DCHECK_IMPLIES(is_local_space(), is_compaction_space());
// Allocation in this space has failed.
DCHECK_GE(size_in_bytes, 0);
const int kMaxPagesToSweep = 1;
if (TryAllocationFromFreeListMain(size_in_bytes, origin)) return true;
MarkCompactCollector* collector = heap()->mark_compact_collector();
// Sweeping is still in progress.
if (collector->sweeping_in_progress()) {
// First try to refill the free-list, concurrent sweeper threads
// may have freed some objects in the meantime.
RefillFreeList();
// Retry the free list allocation.
if (TryAllocationFromFreeListMain(static_cast<size_t>(size_in_bytes),
origin))
return true;
if (ContributeToSweepingMain(size_in_bytes, kMaxPagesToSweep, size_in_bytes,
origin))
return true;
}
if (is_compaction_space()) {
// The main thread may have acquired all swept pages. Try to steal from
// it. This can only happen during young generation evacuation.
PagedSpace* main_space = heap()->paged_space(identity());
Page* page = main_space->RemovePageSafe(size_in_bytes);
if (page != nullptr) {
AddPage(page);
if (TryAllocationFromFreeListMain(static_cast<size_t>(size_in_bytes),
origin))
return true;
}
}
if (heap()->ShouldExpandOldGenerationOnSlowAllocation() &&
heap()->CanExpandOldGeneration(AreaSize())) {
if (TryExpand(size_in_bytes, origin)) {
return true;
}
}
// Try sweeping all pages.
if (ContributeToSweepingMain(0, 0, size_in_bytes, origin)) {
return true;
}
if (heap()->gc_state() != Heap::NOT_IN_GC && !heap()->force_oom()) {
// Avoid OOM crash in the GC in order to invoke NearHeapLimitCallback after
// GC and give it a chance to increase the heap limit.
return TryExpand(size_in_bytes, origin);
}
return false;
}
bool PagedSpace::ContributeToSweepingMain(int required_freed_bytes,
int max_pages, int size_in_bytes,
AllocationOrigin origin) {
// Cleanup invalidated old-to-new refs for compaction space in the
// final atomic pause.
Sweeper::FreeSpaceMayContainInvalidatedSlots invalidated_slots_in_free_space =
is_compaction_space() ? Sweeper::FreeSpaceMayContainInvalidatedSlots::kYes
: Sweeper::FreeSpaceMayContainInvalidatedSlots::kNo;
MarkCompactCollector* collector = heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->sweeper()->ParallelSweepSpace(identity(), required_freed_bytes,
max_pages,
invalidated_slots_in_free_space);
RefillFreeList();
return TryAllocationFromFreeListMain(size_in_bytes, origin);
}
return false;
}
AllocationResult PagedSpace::AllocateRawSlow(int size_in_bytes,
AllocationAlignment alignment,
AllocationOrigin origin) {
if (!is_local_space()) {
// Start incremental marking before the actual allocation, this allows the
// allocation function to mark the object black when incremental marking is
// running.
heap()->StartIncrementalMarkingIfAllocationLimitIsReached(
heap()->GCFlagsForIncrementalMarking(),
kGCCallbackScheduleIdleGarbageCollection);
}
#ifdef V8_HOST_ARCH_32_BIT
AllocationResult result =
alignment != kWordAligned
? AllocateRawAligned(size_in_bytes, alignment, origin)
: AllocateRawUnaligned(size_in_bytes, origin);
#else
AllocationResult result = AllocateRawUnaligned(size_in_bytes, origin);
#endif
return result;
}
// -----------------------------------------------------------------------------
// MapSpace implementation
// TODO(dmercadier): use a heap instead of sorting like that.
// Using a heap will have multiple benefits:
// - for now, SortFreeList is only called after sweeping, which is somewhat
// late. Using a heap, sorting could be done online: FreeListCategories would
// be inserted in a heap (ie, in a sorted manner).
// - SortFreeList is a bit fragile: any change to FreeListMap (or to
// MapSpace::free_list_) could break it.
void MapSpace::SortFreeList() {
using LiveBytesPagePair = std::pair<size_t, Page*>;
std::vector<LiveBytesPagePair> pages;
pages.reserve(CountTotalPages());
for (Page* p : *this) {
free_list()->RemoveCategory(p->free_list_category(kFirstCategory));
pages.push_back(std::make_pair(p->allocated_bytes(), p));
}
// Sorting by least-allocated-bytes first.
std::sort(pages.begin(), pages.end(),
[](const LiveBytesPagePair& a, const LiveBytesPagePair& b) {
return a.first < b.first;
});
for (LiveBytesPagePair const& p : pages) {
// Since AddCategory inserts in head position, it reverts the order produced
// by the sort above: least-allocated-bytes will be Added first, and will
// therefore be the last element (and the first one will be
// most-allocated-bytes).
free_list()->AddCategory(p.second->free_list_category(kFirstCategory));
}
}
#ifdef VERIFY_HEAP
void MapSpace::VerifyObject(HeapObject object) { CHECK(object.IsMap()); }
#endif
} // namespace internal
} // namespace v8
|
#ifndef __EVIAS_CORE_TEST_NETWORKOBJECTS_NS_IRCCLIENT__
#define __EVIAS_CORE_TEST_NETWORKOBJECTS_NS_IRCCLIENT__
/**
* Package : eVias unitary test suite
*
* Copyright (c) 2010 - 2011 Grégory Saive
*
* For more informations about the licensing of this product, please refer
* to the LICENCE file in the root application directory.
*
* Version: 1.0
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "../../application/irc.hpp"
#include "../../core/unit_test_abstract.hpp"
namespace evias {
namespace core {
namespace test {
namespace networkObjects {
// client hooks
using evias::application::__ircReplyData;
using evias::application::Irc;
class ircClient : public unitTest
{
public :
ircClient () : unitTest () { };
~ircClient () {};
inline void prepare ()
{
_host = "irc.freenode.net";
_port = 6667;
_nick1 = "eViasBot";;
_user = "GregSaive";
_name = "eVias Open Development";
_pass = "";
_client = new Irc;
_client->setQuietMode(true);
setReturnCode((int) RETURN_SUCCESS);
}
inline int execute ()
{
assertable<bool>::assertEqual((bool) _returnCode, true);
_client->start(
(char*)(_host.c_str()), _port,
(char*)(_nick1.c_str()),
(char*)(_user.c_str()),
(char*)(_name.c_str()),
(char*)(_pass.c_str())
);
assertable<bool>::assertEqual(_client->isConnected(), true);
// catch until endofmotd (connected status fulfilled)
_client->catchIt(Irc::MSG_ENDMOTD);
// Channel JOIN
string codes = string(Irc::MSG_INVALIDCHAN).append("|").append(Irc::MSG_ENDLIST);
// test channel join
_client->channelJoin((char*) "#gregchan");
_client->catchIt(codes);
assertable<string>::assertEqual(_client->getLastTreatedCommand(), Irc::MSG_ENDLIST);
// Channel PART
codes = string(Irc::MSG_CHANPART).append("|")
.append(Irc::MSG_NOTONCHAN).append("|")
.append(Irc::MSG_INVALIDCHAN);
// test valid channel part
_client->channelPart((char*) "#gregchan");
_client->catchIt(codes);
assertable<string>::assertEqual(_client->getLastTreatedCommand(), Irc::MSG_CHANPART);
// test "notonchan" channel part
_client->channelPart((char*) "#whocares");
_client->catchIt(codes);
assertable<string>::assertEqual(_client->getLastTreatedCommand(), Irc::MSG_NOTONCHAN);
return setReturnCode((int) RETURN_SUCCESS);
}
inline int shutdown ()
{
if (_client != NULL)
delete _client;
if (_client2 != NULL)
delete _client2;
return _returnCode;
}
private :
Irc* _client;
Irc* _client2;
string _host;
int _port;
string _nick1;
string _nick2;
string _user;
string _user2;
string _name;
string _name2;
string _pass;
};
}; // end namespace networkObjects
}; // end namespace test
}; // end namespace core
}; // end namespace evias
#endif
|
#include "EnemyAnimation.h"
#include "ScopeFrame.h"
#include "Frame.h"
EnemyAnimation::EnemyAnimation()
:AimedAnimation(), m_scope(nullptr)
{
}
EnemyAnimation::EnemyAnimation(ALLEGRO_BITMAP* sheet, int x, int y, int w, int h, int nb)
:AimedAnimation(sheet, x, y, w, h, nb), m_scope(nullptr)
{
}
EnemyAnimation::~EnemyAnimation()
{
}
void EnemyAnimation::createScope(ALLEGRO_BITMAP *img, double angleOffset)
{
if (m_scope != nullptr)
delete m_scope;
m_scope = new ScopeFrame(img, angleOffset, 0, 0);
}
void EnemyAnimation::createScope(ALLEGRO_BITMAP *img, int x, int y, int w, int h, double angleOffset)
{
if (m_scope != nullptr)
delete m_scope;
m_scope = new ScopeFrame(img, x, y, w, h, angleOffset, 0, 0);
}
void EnemyAnimation::draw(double destx, double desty, unsigned frameNumber)
{
Frame *currFrame = this->getFrame(frameNumber);
m_scope->draw(destx + (currFrame->width() / 2),
desty + (currFrame->height() / 2), m_aimedDir);
currFrame->draw(destx, desty, m_aimedDir);
}
|
#include "Offline/Print/inc/MCTrajectoryPrinter.hh"
#include "art/Framework/Principal/Provenance.h"
#include <string>
#include <iomanip>
void
mu2e::MCTrajectoryPrinter::Print(art::Event const& event,
std::ostream& os) {
if(verbose()<1) return;
if(tags().empty()) {
// if a list of instances not specified, print all instances
std::vector< art::Handle<MCTrajectoryCollection> > vah = event.getMany<MCTrajectoryCollection>();
for (auto const & ah : vah) Print(ah);
} else {
// print requested instances
for(const auto& tag : tags() ) {
auto ih = event.getValidHandle<MCTrajectoryCollection>(tag);
Print(ih);
}
}
}
void
mu2e::MCTrajectoryPrinter::Print(const art::Handle<MCTrajectoryCollection>& handle,
std::ostream& os) {
if(verbose()<1) return;
// the product tags with all four fields, with underscores
std::string tag = handle.provenance()->productDescription().branchName();
tag.pop_back(); // remove trailing dot
PrintHeader(tag,os);
Print(*handle);
}
void
mu2e::MCTrajectoryPrinter::Print(const art::ValidHandle<MCTrajectoryCollection>& handle,
std::ostream& os) {
if(verbose()<1) return;
// the product tags with all four fields, with underscores
std::string tag = handle.provenance()->productDescription().branchName();
tag.pop_back(); // remove trailing dot
PrintHeader(tag,os);
Print(*handle);
}
void
mu2e::MCTrajectoryPrinter::Print(const MCTrajectoryCollection& coll, std::ostream& os) {
if(verbose()<1) return;
os << "MCTrajectoryCollection has " << coll.size() << " trajectories\n";
if(verbose()==1) PrintListHeader();
int i = 0;
for(const auto& obj: coll) Print(obj.second, i++);
}
void
mu2e::MCTrajectoryPrinter::Print(const art::Ptr<MCTrajectory>& obj, int ind, std::ostream& os) {
if(verbose()<1) return;
Print(*obj,ind);
}
void
mu2e::MCTrajectoryPrinter::Print(const mu2e::MCTrajectory& obj, int ind, std::ostream& os) {
if(verbose()<1) return;
int pkey = obj.simid();
const auto& points = obj.points();
os << std::setiosflags(std::ios::fixed | std::ios::right);
if(ind>=0) os << std::setw(4) << ind;
if(verbose()==1) {
const auto& v0 = points.front();
const auto& v1 = points.back();
os
<< " " << std::setw(8) << pkey
<< " " << std::setw(4) << points.size()
<< " "
<< " " << std::setw(8) << std::setprecision(1) << v0.x()
<< " " << std::setw(8) << std::setprecision(1) << v0.y()
<< " " << std::setw(8) << std::setprecision(1) << v0.z()
<< " " << std::setw(9) << std::setprecision(1) << v0.t()
<< " " << std::setw(9) << std::setprecision(1) << v0.kineticEnergy()
<< " "
<< " " << std::setw(8) << std::setprecision(1) << v1.x()
<< " " << std::setw(8) << std::setprecision(1) << v1.y()
<< " " << std::setw(8) << std::setprecision(1) << v1.z()
<< " " << std::setw(9) << std::setprecision(1) << v1.t()
<< " " << std::setw(9) << std::setprecision(1) << v1.kineticEnergy()
<< std::endl;
} else {
os
<< " parentKey: " << std::setw(8) << pkey
<< " npoint: " << std::setw(4) << points.size() << "\n";
os << " Sim start: " << obj.sim()->startPosition() << "\n"
<< " Sim end : " << obj.sim()->endPosition() << "\n";
int i=0;
for(auto const& pp : points ) {
os
<< " " << std::setw(4) << i++
<< " " << std::setw(8) << std::setprecision(1) << pp.x()
<< " " << std::setw(8) << std::setprecision(1) << pp.y()
<< " " << std::setw(8) << std::setprecision(1) << pp.z()
<< " " << std::setw(9) << std::setprecision(1) << pp.t()
<< " " << std::setw(9) << std::setprecision(1) << pp.kineticEnergy()
<< std::endl;
}
} // end if verbose
}
void
mu2e::MCTrajectoryPrinter::PrintHeader(const std::string& tag, std::ostream& os) {
if(verbose()<1) return;
os << "\nProductPrint " << tag << "\n";
}
void
mu2e::MCTrajectoryPrinter::PrintListHeader(std::ostream& os) {
if(verbose()<1) return;
os << "ind parent npoint first Point firstT firstEk last Point lastT lastEk\n";
}
|
#include "CollisionInfo.h"
#include <bsp/BSPPolygon.h>
#include "config.h"
//-----------------------------------------------------------------------------
using namespace math;
//-----------------------------------------------------------------------------
CollisionInfo::CollisionInfo() :
m_collisionMask( COLLIDE_NONE ),
m_pos( 0,0,0 ),
m_positionCell( 0 ),
m_collisionCell( 0 ),
m_poly( 0 ),
m_normal( 0,0,0 ),
m_point( 0,0,0 ),
m_obj( 0 )
{
}
CollisionInfo::CollisionInfo( const Vector3& pos, GameCell* cell ) :
m_collisionMask( COLLIDE_NONE ),
m_pos( pos ),
m_positionCell( cell ),
m_collisionCell( 0 ),
m_poly( 0 ),
m_normal( 0,0,0 ),
m_point( 0,0,0 ),
m_obj( 0 )
{
}
CollisionInfo::CollisionInfo( const Vector3& pos,
GameCell* positionCell, GameCell* collisionCell,
const bsp::BSPPolygon* poly, const math::Vector3& normal, const math::Vector3& point,
GameObject* obj, GameBSPTree* bsptree ) :
m_collisionMask( COLLIDE_NONE ),
m_pos( pos ),
m_positionCell( positionCell ),
m_collisionCell( collisionCell ),
m_poly( poly ),
m_normal( normal ),
m_point( point ),
m_obj( obj ),
m_bsptree( bsptree )
{
if ( obj )
m_collisionMask |= COLLIDE_OBJECT;
if ( poly )
m_collisionMask |= poly->collisionMask();
if ( bsptree )
m_collisionMask |= COLLIDE_BSP;
assert( !(m_collisionMask & COLLIDE_OBJECT) || m_obj );
}
const Vector3& CollisionInfo::position() const
{
return m_pos;
}
GameCell* CollisionInfo::positionCell() const
{
return m_positionCell;
}
GameCell* CollisionInfo::collisionCell() const
{
assert( m_collisionMask != COLLIDE_NONE );
return m_collisionCell;
}
const Vector3& CollisionInfo::normal() const
{
assert( m_collisionMask != COLLIDE_NONE );
return m_normal;
}
const Vector3& CollisionInfo::point() const
{
assert( m_collisionMask != COLLIDE_NONE );
return m_point;
}
const bsp::BSPPolygon* CollisionInfo::polygon() const
{
assert( (m_collisionMask & COLLIDE_GEOMETRY_SEETHROUGH) || (m_collisionMask & COLLIDE_GEOMETRY_SOLID) );
assert( m_poly );
return m_poly;
}
GameObject* CollisionInfo::object() const
{
assert( m_collisionMask & COLLIDE_OBJECT );
assert( m_obj );
return m_obj;
}
bool CollisionInfo::isCollision( CollisionType type ) const
{
return 0 != (type & m_collisionMask);
}
GameBSPTree* CollisionInfo::bspTree() const
{
return m_bsptree;
}
|
#ifndef MCDataProducts_CrvSiPMCharges_hh
#define MCDataProducts_CrvSiPMCharges_hh
//
//
// Contact person Ralf Ehrlich
//
#include "MCDataProducts/inc/StepPointMCCollection.hh"
#include <vector>
#include <cmath>
namespace mu2e
{
class CrvSiPMCharges
{
public:
CrvSiPMCharges() {}
struct CrvSingleCharge
{
double _time;
double _charge;
double _chargeInPEs;
art::Ptr<StepPointMC> _step;
CrvSingleCharge(double time, double charge, double chargeInPEs, art::Ptr<StepPointMC> step) :
_time(time), _charge(charge), _chargeInPEs(chargeInPEs), _step(step) {}
CrvSingleCharge(double time, double charge, double chargeInPEs) : //that's for dark noise (i.e. no StepPointMCs)
_time(time), _charge(charge), _chargeInPEs(chargeInPEs) {}
CrvSingleCharge() : _time(NAN), _charge(NAN), _chargeInPEs(NAN) {} //to make ROOT happy
};
std::vector<CrvSingleCharge> &GetSiPMCharges(int fiberNumber, int side);
std::vector<CrvSingleCharge> &GetSiPMCharges(int SiPMNumber);
const std::vector<CrvSingleCharge> &GetSiPMCharges(int fiberNumber, int side) const;
const std::vector<CrvSingleCharge> &GetSiPMCharges(int SiPMNumber) const;
size_t GetNumberOfSiPMCharges(int fiberNumber, int side) const;
size_t GetNumberOfSiPMCharges(int SiPMNumber) const;
bool IsEmpty() const;
double GetFirstSiPMChargeTime(int fiberNumber, int side) const;
double GetFirstSiPMChargeTime(int SiPMNumber) const;
private:
static int FindSiPMNumber(int fiberNumber, int side);
static void CheckSiPMNumber(int SiPMNumber);
std::vector<CrvSingleCharge> _crvSiPMCharges[4];
};
}
#endif /* MCDataProducts_CrvSiPMCharges_hh */
|
/**
* Stateful metaprogramming
* ========================
*
* This is arcane and almost the darkest corner of C++.
*
* Note: Compile with -std=c++17.
*/
#include <type_traits>
template <int N>
struct flag {
// Argument-dependent lookup.
// warning: friend declaration ‘...’ declares a non-template function
// [-Wnon-template-friend]
friend constexpr int adl_flag(flag<N>);
constexpr operator int() { return N; }
};
template <int N>
struct write {
friend constexpr int adl_flag(flag<N>) { return N; }
static constexpr int value = N;
};
template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
return R;
}
template <int N = 0>
constexpr int read(double, flag<N>)
{
return N;
}
template <int N = 0>
constexpr int counter(int R = write<read(0, flag<0>{}) + N>::value)
{
return R;
}
template <int = counter()>
struct S {};
int main()
{
static_assert(counter() != counter(), "well done holy compiler");
static_assert(!std::is_same_v<S<>, S<>>, "good boy");
return 0;
}
|
/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef MATH_UTILS_HPP
#define MATH_UTILS_HPP
#include <stdint.h>
#include <math.h>
#include "utils.hpp"
#include "nstl.hpp"
#include "mkldnn_traits.hpp"
namespace mkldnn {
namespace impl {
namespace math {
template <typename data_t, typename acc_t>
inline typename utils::enable_if<!nstl::is_integral<data_t>::value,
typename utils::remove_reference<data_t>::type>::type
saturate(const acc_t &x) {
return (typename utils::remove_reference<data_t>::type)x;
}
template <typename data_t, typename acc_t>
inline typename utils::enable_if<nstl::is_integral<data_t>::value,
typename utils::remove_reference<data_t>::type>::type
saturate(const acc_t &x) {
acc_t v = x;
if (v < (acc_t)nstl::numeric_limits<data_t>::lowest())
v = (acc_t)nstl::numeric_limits<data_t>::lowest();
if (v > (acc_t)nstl::numeric_limits<data_t>::max())
v = (acc_t)nstl::numeric_limits<data_t>::max();
return (typename utils::remove_reference<data_t>::type)v;
}
template <typename data_t>
double saturate(const double &x) {
double v = x;
if (v < (double)nstl::numeric_limits<data_t>::lowest())
v = (double)nstl::numeric_limits<data_t>::lowest();
if (v > (double)nstl::numeric_limits<data_t>::max())
v = (double)nstl::numeric_limits<data_t>::max();
return v;
}
template <> inline int8_t saturate<int8_t, uint8_t>(const uint8_t &x) {
return x <= 127u ? x : 127;
}
template <> inline uint8_t saturate<uint8_t, int8_t>(const int8_t &x) {
return x >= 0 ? x : 0;
}
template <typename out_t>
inline typename utils::enable_if<nstl::is_integral<out_t>::value, out_t>::type
out_round(float v, round_mode_t rmode = round_mode::nearest)
{ return (out_t)(rmode == round_mode::down ? floorf(v) : nearbyintf(v)); }
template <typename out_t>
inline typename utils::enable_if<nstl::is_integral<out_t>::value, out_t>::type
out_round(double v, round_mode_t rmode = round_mode::nearest)
{ return (out_t)(rmode == round_mode::down ? floor(v) : nearbyint(v)); }
template <typename out_t>
inline typename utils::enable_if<!nstl::is_integral<out_t>::value, out_t>::type
out_round(float v, round_mode_t rmode = round_mode::nearest)
{ UNUSED(rmode); return v; }
inline int gcd(int a, int b) {
a = impl::nstl::abs(a);
b = impl::nstl::abs(b);
if (a < b) { int x = a; a = b; b = x; }
if (b == 0) return a;
int r;
while ((r = a % b) != 0) { a = b; b = r; }
return b;
}
template <typename T>
inline bool is_pow2(const T& v) { return (v & (v - 1)) == 0; }
/** returns floor(log2(v)), aka the position of the leftmost non-0 bit */
inline int ilog2q(size_t v) {
if (v == 0)
return -1;
int p = 0;
# define CP(pw) do { if (v >= (1ull << pw)) { v >>= pw; p += pw; } } while(0)
CP(32); CP(16); CP(8); CP(4); CP(2); CP(1);
# undef CP
return p;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U one_m_square(T x) {
return (U)(1 - x) * (1 + x);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U x_m_square(T x) {
return (U)(1 - x) * x;
}
/* activation */
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U relu_fwd(T s, A alpha) {
return s > 0 ? s : (U)(s * alpha);
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U relu_bwd(T dd, T s, A alpha) {
return s > 0 ? dd : (U)(dd * alpha);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U tanh_fwd(T s) {
const float e = tanhf((float) s);
return (U)e;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U tanh_bwd(T dd, T s) {
const float e = tanh_fwd<float>((float) s);
return (U)(dd * (1 - e) * (1 + e));
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U elu_fwd(T s, A alpha) {
return s > 0 ? s : (U)(alpha * (::expm1f((float)s)));
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U elu_bwd(T dd, T s, A alpha) {
return (U)(dd * (s > 0 ? 1 : alpha * ::expf((float)s)));
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U square_fwd(T s) {
return s * s;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U square_bwd(T dd, T s) {
return dd * 2 * s;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U abs_fwd(T s) {
return s > 0 ? s : -s;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U abs_bwd(T dd, T s) {
return s > 0 ? dd : s < 0 ? -dd : 0;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U sqrt_fwd(T s) {
return s > 0 ? (U)(::sqrtf((float)(s))) : 0;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U sqrt_bwd(T dd, T s) {
return s > 0
? (U)(dd / (2 * ::sqrtf((float)(s))))
: 0;
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U linear_fwd(T s, A alpha, A beta) {
return (U)(alpha * s + beta);
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U linear_bwd(T dd, T s, A alpha, A beta) {
(void) s;
(void) beta;
return (U)(dd * alpha);
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U bounded_relu_fwd(T s, A alpha) {
s = s > 0 ? s : 0;
return s > alpha ? (U)(alpha) : s;
}
template <typename T, typename A,
typename U = typename utils::remove_reference<T>::type>
inline U bounded_relu_bwd(T dd, T s, A alpha) {
return dd * (0 < s && s < alpha ? 1 : 0);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U soft_relu_fwd(T s) {
float max_logf = 8.872284e+01; //::logf(FLT_MAX)
return s < max_logf ? (U)(::log1pf(::expf((float)s))) : s;
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U soft_relu_bwd(T dd, T s) {
return (U)(dd / (1 + ::expf((float)(-s))));
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U logistic_fwd(T s) {
U v = (U)(::expf((float) -s));
return 1 / (1 + v);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U logistic_bwd(T dd, T s) {
U v = logistic_fwd<T, U>(s);
return dd * v * (1 - v);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U exp_fwd(T s) {
return (U)(::expf((float)s));
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U exp_bwd(T dd, T s) {
return dd * exp_fwd<T, U>(s);
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U gelu_fwd(T s) {
const float sqrt_2_over_pi = 0.797884;
const float fitting_const = 0.044715;
float v = tanh_fwd(sqrt_2_over_pi * s * (1 + fitting_const * s * s));
return (U)(0.5 * s * (1. + v));
}
template <typename T, typename U = typename utils::remove_reference<T>::type>
inline U gelu_bwd(T dd, T s) {
const float sqrt_2_over_pi = 0.797884;
const float fitting_const = 0.044715;
float g = s * sqrt_2_over_pi * (1 + fitting_const * s * s);
float dg = sqrt_2_over_pi * (1 + 3 * fitting_const * s * s);
float v = tanh_fwd(g);
return (U)(dd * 0.5 * (1. + v) * (1. + s * (1 - v) * dg));
}
inline bool eltwise_fwd_preserves_zero(alg_kind_t alg, bool jit_impl = false) {
using namespace alg_kind;
using namespace utils;
const bool preserves_zero = true
&& !one_of(alg, eltwise_linear, eltwise_soft_relu, eltwise_logistic,
eltwise_exp)
&& IMPLICATION(jit_impl, !one_of(alg, eltwise_elu, eltwise_tanh));
return preserves_zero;
}
inline float get_bias(const char *bias, size_t offset, data_type_t data_type)
{
if (!bias)
return 0.0f;
#define CASE(dt) \
case dt: return (float)((const prec_traits<dt>::type *)bias)[offset]
switch (data_type) {
CASE(data_type::s8);
CASE(data_type::u8);
CASE(data_type::s32);
CASE(data_type::f32);
default: assert(!"unimplemented");
}
return 0; // never happens (should probably be a NaN)
#undef CASE
}
}
}
}
#endif
|
#ifndef CY_NNQS_JASTROW_SAMPLES_HPP
#define CY_NNQS_JASTROW_SAMPLES_HPP
#include "Machines/Jastrow.hpp"
#include "Utilities/type_traits.hpp"
namespace yannq
{
template<typename T>
class JastrowState;
template<typename T>
class MachineStateTypes<Jastrow<T> >
{
public:
using StateValue = JastrowState<T>;
using StateRef = JastrowState<T>;
};
template<typename ScalarT>
class JastrowState
{
private:
Jastrow<ScalarT>& qs_;
Eigen::VectorXi sigma_;
ScalarT theta_;
public:
using T = ScalarT;
JastrowState(Jastrow<T>& qs, const Eigen::VectorXi& sigma)
: qs_(qs), sigma_(sigma)
{
theta_ = qs.calcTheta(sigma_);
}
JastrowState(Jastrow<T>& qs, const Eigen::VectorXi& sigma, T theta)
: qs_(qs), sigma_(sigma), theta_(theta)
{
}
JastrowState(const JastrowState<T>& rhs)
: qs_(rhs.qs_), sigma_(rhs.sigma_), theta_(rhs.theta_)
{
}
JastrowState<T> operator=(const JastrowState<T>& rhs)
{
assert(&rhs.qs_ == &qs_);
sigma_ = rhs.sigma_;
theta_ = rhs.theta_;
}
T logRatio(int k) const
{
T res = -2.0*qs_.A(k)*T(sigma_(k));
for(int j = k+1; j < qs_.getN(); j++)
{
res -= 2.0*qs_.J(k,j)*T(sigma_(k)*sigma_(j));
}
for(int i = 0; i < k; i++)
{
res -= 2.0*qs_.J(i,k)*T(sigma_(k)*sigma_(i));
}
return res;
}
T logRatio(int k, int l) const
{
T res = logRatio(k);
res += logRatio(l);
res += 4.0*(qs_.J(k,l)+qs_.J(l,k))*T(sigma_(k)*sigma_(l));
return res;
}
T ratio(int k) const
{
return std::exp(logRatio(k));
}
T ratio(int k, int l) const
{
return std::exp(logRatio(k, l));
}
void flip(int k)
{
theta_ += logRatio(k);
sigma_(k) *= -1;
}
void flip(int k, int l)
{
theta_ += logRatio(k,l);
sigma_(k) *= -1;
sigma_(l) *= -1;
}
template<std::size_t N>
void flip(const std::array<int, N>& v)
{
for(auto a : v)
{
sigma_(a) *= -1;
}
theta_ = qs_.calcTheta(sigma_);
}
template<std::size_t N>
T logRatio(const std::array<int, N>& v) const
{
Eigen::VectorXi toSigma = sigma_;
for(auto a : v)
{
toSigma(a) *= -1;
}
return logRatio(toSigma);
}
T logRatio(const Eigen::VectorXi& to) const
{
T thetaTo = qs_.calcTheta(to);
return thetaTo - theta_;
}
T logRatio(const JastrowState<T>& rhs) const
{
return rhs.theta_ - theta_;
}
std::tuple<Eigen::VectorXi, T> data() const
{
return std::make_tuple(sigma_, theta_);
}
inline int sigmaAt(int i) const
{
return sigma_(i);
}
inline T getTheta() const
{
return theta_;
}
};
} //namespace yannq
#endif//CY_NNQS_JASTROW_SAMPLES_HPP
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2016 by Contributors
* \file storage_flatten.cc
*/
// Flattens storage from multi-dimensional array to 1D
// buffer access as in Halide pipeline.
#include <tvm/ir.h>
#include <tvm/expr.h>
#include <tvm/operation.h>
#include <tvm/ir_mutator.h>
#include <tvm/expr_operator.h>
#include <tvm/ir_pass.h>
#include <tvm/buffer.h>
#include <tvm/target_info.h>
#include <tvm/runtime/device_api.h>
#include <unordered_map>
#include "ir_util.h"
#include "arg_binder.h"
#include "../arithmetic/compute_expr.h"
#include "../runtime/thread_storage_scope.h"
namespace tvm {
namespace ir {
using HalideIR::Internal::Region;
using runtime::StorageRank;
using runtime::StorageScope;
using runtime::ThreadScope;
using intrinsic::tvm_address_of;
class StorageFlattener : public IRMutator {
public:
explicit StorageFlattener(Map<Tensor, Buffer> extern_buffer,
int cache_line_size, bool create_bound_attributes)
: create_bound_attributes_(create_bound_attributes) {
for (auto kv : extern_buffer) {
BufferEntry e;
e.buffer = kv.second;
e.external = true;
buf_map_[TensorKey{kv.first->op, kv.first->value_index}] = e;
}
cache_line_size_ = cache_line_size;
}
Stmt Mutate_(const Store* op, const Stmt& s) final {
Stmt stmt = IRMutator::Mutate_(op, s);
op = stmt.as<Store>();
auto it = var_remap_.find(op->buffer_var.get());
if (it != var_remap_.end() &&
!it->second.same_as(op->buffer_var)) {
CHECK(it->second.as<Variable>());
VarExpr buf_var(it->second.node_);
return Store::make(buf_var, op->value, op->index, op->predicate);
} else {
return stmt;
}
}
Stmt Mutate_(const AttrStmt* op, const Stmt& s) final {
if (op->attr_key == attr::realize_scope) {
storage_scope_[op->node.get()] = op->value.as<StringImm>()->value;
return this->Mutate(op->body);
} else if (op->attr_key == attr::double_buffer_scope &&
op->node.node_->derived_from<OperationNode>()) {
Operation func(op->node.node_);
Stmt body = Mutate(op->body);
for (int i = 0; i < func->num_outputs(); ++i) {
TensorKey key{func, i};
auto it = buf_map_.find(key);
CHECK(it != buf_map_.end())
<< "Cannot find allocated buffer for " << key.f;
body = AttrStmt::make(
it->second.buffer->data, op->attr_key, op->value, body);
}
return body;
} else if (op->attr_key == attr::thread_extent) {
IterVar iv(op->node.node_);
ThreadScope ts = ThreadScope::make(iv->thread_tag);
curr_thread_scope_.push_back(ts);
Stmt stmt = IRMutator::Mutate_(op, s);
curr_thread_scope_.pop_back();
return stmt;
} else if (op->attr_key == attr::buffer_bind_scope) {
return HandleBufferBindScope(op);
} else if (op->attr_key == attr::buffer_dim_align) {
Tensor tensor(op->node.node_);
const Call* tuple = op->value.as<Call>();
CHECK(tuple && tuple->is_intrinsic(intrinsic::tvm_tuple));
TensorKey key{tensor->op, tensor->value_index};
auto& vinfo = dim_align_[key];
int dim = tuple->args[0].as<IntImm>()->value;
if (static_cast<size_t>(dim) >= vinfo.size()) {
vinfo.resize(dim + 1);
}
vinfo[dim].align_factor = tuple->args[1].as<IntImm>()->value;
vinfo[dim].align_offset = tuple->args[2].as<IntImm>()->value;
return this->Mutate(op->body);
} else if (op->attr_key == attr::opengl_stage_scope) {
is_opengl_ = true;
}
return IRMutator::Mutate_(op, s);
}
Stmt Mutate_(const Provide* op, const Stmt& s) final {
if (create_bound_attributes_)
shape_collector_.clear();
Stmt stmt = IRMutator::Mutate_(op, s);
op = stmt.as<Provide>();
TensorKey key{op->func, op->value_index};
auto it = buf_map_.find(key);
CHECK(it != buf_map_.end())
<< "Cannot find allocated buffer for " << key.f;
const BufferEntry& e = it->second;
CHECK(!e.released)
<< "Read a buffer that is already out of scope";
if (is_opengl_) {
return Evaluate::make(Call::make(
Type(),
Call::glsl_texture_store,
{e.buffer->data, op->value},
Call::Intrinsic));
} else {
Stmt body = e.buffer.vstore(e.RelIndex(op->args), op->value);
if (create_bound_attributes_ && ShapeIsValid(e.buffer->shape)) {
shape_collector_.push_back(
std::make_pair(e.buffer->data, e.buffer->shape));
}
// To create bound attribute collector should has at least one item.
if (create_bound_attributes_ && shape_collector_.size()) {
for (size_t i = 0; i < shape_collector_.size(); ++i) {
body = AttrStmt::make(
shape_collector_[i].first, ir::attr::buffer_bound,
MakeBound(e.buffer->dtype, shape_collector_[i].second), body);
}
}
return body;
}
}
Stmt Mutate_(const Realize* op, const Stmt& s) final {
TensorKey key{op->func, op->value_index};
if (buf_map_.count(key)) {
CHECK(buf_map_.at(key).external);
return this->Mutate(op->body);
} else {
// create a buffer entry
BufferEntry e;
e.bounds = op->bounds;
Array<Expr> shape;
for (auto r : e.bounds) {
shape.push_back(r->extent);
}
// deduce current storage scope.
auto it = storage_scope_.find(op->func.get());
CHECK(it != storage_scope_.end())
<< "Cannot find storage scope of " << op->func
<< " value_index=" << op->value_index;
StorageScope skey;
const std::string& strkey = it->second;
if (strkey.length() == 0) {
if (curr_thread_scope_.size() != 0) {
skey.rank = runtime::DefaultStorageRank(
curr_thread_scope_.back().rank);
}
} else {
skey = StorageScope::make(strkey);
}
// use small alignment for small arrays
int32_t const_size = Allocate::constant_allocation_size(shape, key.GetName());
int align = GetTempAllocaAlignment(op->type, const_size);
if (skey.tag.length() != 0) {
MemoryInfo info = GetMemoryInfo(skey.to_string());
if (info.defined()) {
align = (info->max_simd_bits + op->type.bits() - 1) / op->type.bits();
CHECK_LE(const_size * op->type.bits(), info->max_num_bits)
<< "Allocation exceed bound of memory tag " << skey.to_string();
}
}
Array<Expr> strides;
if (dim_align_.count(key) != 0 && shape.size() != 0) {
std::vector<Expr> rstrides;
const std::vector<DimAlignInfo>& avec = dim_align_[key];
int first_dim = 0;
Expr stride = make_const(shape[first_dim].type(), 1);
for (size_t i = shape.size(); i != 0; --i) {
size_t dim = i - 1;
if (dim < avec.size() && avec[dim].align_factor != 0) {
Expr factor = make_const(stride.type(), avec[dim].align_factor);
Expr offset = make_const(stride.type(), avec[dim].align_offset);
stride = stride + (factor + offset - stride % factor) % factor;
stride = ir::Simplify(stride);
}
rstrides.push_back(stride);
stride = arith::ComputeExpr<Mul>(stride, shape[dim]);
}
strides = Array<Expr>(rstrides.rbegin(), rstrides.rend());
}
e.buffer = BufferNode::make(
Var(key.GetName(), Handle()),
op->type, shape, strides, Expr(),
key.GetName(), skey.to_string(),
align, 0, kDefault);
buf_map_[key] = e;
Stmt body = this->Mutate(op->body);
buf_map_[key].released = true;
Stmt ret;
Type storage_type = e.buffer->dtype;
// specially handle bool, lower its storage
// type to be Int(8)(byte)
if (storage_type == Bool()) {
storage_type = Int(8);
}
if (strides.size() != 0) {
int first_dim = 0;
ret = Allocate::make(
e.buffer->data, storage_type,
{arith::ComputeExpr<Mul>(e.buffer->strides[first_dim], e.buffer->shape[first_dim])},
make_const(Bool(e.buffer->dtype.lanes()), true), body);
} else {
shape = e.buffer->shape;
if (shape.size() == 0) {
shape.push_back(make_const(Int(32), 1));
}
ret = Allocate::make(
e.buffer->data, storage_type, shape,
make_const(Bool(e.buffer->dtype.lanes()), true), body);
}
ret = AttrStmt::make(
e.buffer->data, attr::storage_scope,
StringImm::make(e.buffer->scope), ret);
if (create_bound_attributes_ && ShapeIsValid(e.buffer->shape)) {
ret = AttrStmt::make(e.buffer->data, ir::attr::buffer_bound,
MakeBound(e.buffer->dtype, e.buffer->shape), ret);
}
return ret;
}
}
Expr Mutate_(const Load* op, const Expr& e) final {
Expr expr = IRMutator::Mutate_(op, e);
op = expr.as<Load>();
auto it = var_remap_.find(op->buffer_var.get());
if (it != var_remap_.end() &&
!it->second.same_as(op->buffer_var)) {
CHECK(it->second.as<Variable>());
VarExpr buf_var(it->second.node_);
return Load::make(op->type, buf_var, op->index, op->predicate);
} else {
return expr;
}
}
Expr Mutate_(const Variable* op, const Expr& e) final {
auto it = var_remap_.find(op);
if (it != var_remap_.end()) {
return it->second;
} else {
return e;
}
}
Expr Mutate_(const Call* op, const Expr& olde) final {
Expr expr = IRMutator::Mutate_(op, olde);
op = expr.as<Call>();
if (op != nullptr && op->call_type == Call::Halide) {
TensorKey key{op->func, op->value_index};
auto it = buf_map_.find(key);
CHECK(it != buf_map_.end())
<< "Cannot find allocated buffer for " << key.f;
const BufferEntry& e = it->second;
CHECK(!e.released)
<< "Read a buffer that is already out of scope";
if (create_bound_attributes_ && ShapeIsValid(e.buffer->shape)) {
shape_collector_.push_back(
std::make_pair(e.buffer->data, e.buffer->shape));
}
return e.buffer.vload(e.RelIndex(op->args), e.buffer->dtype);
} else {
return expr;
}
}
Stmt Mutate_(const Prefetch *op, const Stmt &s) final {
Stmt stmt = IRMutator::Mutate_(op, s);
op = stmt.as<Prefetch>();
CHECK(op != nullptr);
TensorKey key{op->func, op->value_index};
auto it = buf_map_.find(key);
CHECK(it != buf_map_.end())
<< "Cannot find allocated buffer for " << key.f;
const BufferEntry& e = it->second;
CHECK(!e.released)
<< "Read a buffer that is already out of scope";
CHECK_EQ(e.buffer->shape.size(), op->bounds.size())
<< "Prefetch dim should be the same as buffer dim";
int block_size = 1,
elem_cnt = cache_line_size_ / e.buffer->dtype.bytes(),
shape = 0;
int starts = op->bounds.size() - 1;
while (starts > 0 && arith::GetConstInt(e.buffer->shape[starts], &shape)
&& elem_cnt >= block_size * shape) {
block_size *= shape;
starts--;
}
Expr stride(elem_cnt / block_size);
Array<Expr> args;
std::vector<VarExpr> vars;
for (int i = op->bounds.size() - 1; i > starts; --i) {
args.push_back(op->bounds[i]->min);
}
auto &func_name = op->func->func_name();
vars.push_back(VarExpr("prefetch." + func_name + "." + std::to_string(starts), Int(32)));
args.push_back(op->bounds[starts]->min + stride * vars.back());
for (int i = starts - 1; i >= 0; --i) {
vars.push_back(VarExpr("prefetch." + func_name + "." + std::to_string(i), Int(32)));
args.push_back(vars.back() + op->bounds[i]->min);
}
for (int i = starts; i >= 0; --i) {
if (i < starts) {
stmt = For::make(
vars[i], 0, op->bounds[i]->extent, ForType::Serial, DeviceAPI::Host, stmt);
} else {
Expr load = e.buffer.vload(e.RelIndex(args), e.buffer->dtype);
Expr address = Call::make(Handle(), tvm_address_of, {load}, Call::PureIntrinsic);
Expr prefetch = Call::make(op->type, Call::prefetch, {address, 0, 3, 1}, Call::Intrinsic);
stmt = Evaluate::make(prefetch);
Expr extent = (op->bounds[i]->extent - 1) / stride + 1;
stmt = For::make(vars[i], 0, extent, ForType::Serial, DeviceAPI::Host, stmt);
}
}
return stmt;
}
private:
// The specific tensor data layout is not determined before
// StorageFlatten pass. We use buffer_bind_scope
// to specify before hand we want to bind a subregion
// of tensor to a symbolic buffer, which get used in extern.
//
// Example:
//
// realize A in range [i*4, extent=10) {
// bind Ab to A in [i*4+1, extent=4) {
// call_func(Ab.ptr, Ab.shape[0])
// }
// }
//
// After StorageFlatten
//
// alloc A[10]
// call(A + 1, 4)
//
// Buffer is a protocol to declare specific
// data layout and shape we expect.
// So this function need to check:
// - If the bind range is within the realize range
// - If we can match the requirement of buffer
// - Remap variables such as Ab.ptr to the actual value.
//
// Here are a few possible failure cases:
// - Buffer is declared to have constant shape,
// but we try to bind it to a different one.
// - Buffer is declared to be compact(no strides)
// but this binded region is a subregion of
// a matrix(tensor), which means it requires strides.
//
// We do support a few relaxed case, such as bindingx
// region with shape [1, 1, n, m] to buffer with shape [n, m]
Stmt HandleBufferBindScope(const AttrStmt* op) {
Array<NodeRef> arr(op->node.node_);
CHECK_EQ(arr.size(), 2U);
const BufferNode* buffer = arr[0].as<BufferNode>();
const TensorNode* tensor = arr[1].as<TensorNode>();
const Call* tuple = op->value.as<Call>();
CHECK(buffer && tensor);
CHECK(tuple && tuple->is_intrinsic(intrinsic::tvm_tuple));
TensorKey key{tensor->op, tensor->value_index};
CHECK(buf_map_.count(key))
<< "Cannot find buffer of " << tensor->op << " value=" << tensor->value_index;
const BufferEntry& be = buf_map_.at(key);
CHECK(!be.released);
CHECK_EQ(tuple->args.size(), be.buffer->shape.size() * 2);
Array<Expr> begins, extents;
if (be.bounds.size() != 0) {
CHECK_EQ(tuple->args.size(), be.bounds.size() * 2);
for (size_t i = 0; i < be.buffer->shape.size(); ++i) {
begins.push_back(
arith::ComputeExpr<Sub>(tuple->args[2 * i], be.bounds[i]->min));
extents.push_back(tuple->args[2 * i + 1]);
}
} else {
for (size_t i = 0; i < tuple->args.size(); i += 2) {
begins.push_back(tuple->args[i]);
extents.push_back(tuple->args[i + 1]);
}
}
Buffer slice = be.buffer.MakeSlice(begins, extents);
if (buffer->strides.size() == 0) {
CHECK_EQ(slice->strides.size(), 0U)
<< "Trying to bind compact buffer to strided one strides="
<< slice->strides;
} else {
slice = slice.MakeStrideView();
}
// start binding
ArgBinder binder(&var_remap_);
binder.BindBuffer(Buffer(arr[0].node_), slice, buffer->name, true);
// Apply the remaps
Stmt body = MergeNest(binder.asserts(), op->body);
body = MergeNest(binder.init_nest(), body);
body = this->Mutate(body);
// remove the binds
for (const Var& v : binder.defs()) {
var_remap_.erase(v.get());
}
return body;
}
// The buffer entry in the flatten map
struct DimAlignInfo {
int align_factor{0};
int align_offset{0};
};
// The buffer entry in the flatten map
struct BufferEntry {
// the buffer of storage
Buffer buffer;
// the bounds of realization, can be null, means everything
Region bounds;
// Whether the buffer is external
bool external{false};
// Whether we are out of allocation bounds and buffer get released.
bool released{false};
// relative index
inline Array<Expr> RelIndex(Array<Expr> args) const {
if (bounds.size() != 0) {
Array<Expr> index;
CHECK_EQ(bounds.size(), args.size());
for (size_t i = 0; i < bounds.size(); ++i) {
index.push_back(args[i] - bounds[i]->min);
}
return index;
} else {
return args;
}
}
};
bool ShapeIsValid(const Array<Expr> &shape) {
// Zero-dimensional tensor does not need boundary check.
if (!shape.size())
return false;
for (size_t i = 0; i < shape.size(); ++i) {
if (!shape[i].defined() || !shape[i].type().is_scalar() ||
is_negative_const(shape[i])) {
return false;
}
}
return true;
}
Expr MakeBound(const Type &type, const Array<Expr> &shape) {
// We have already checked the shape size to be greater then 0.
Expr bound = Mul::make(make_const(shape[0].type(), type.lanes()), shape[0]);
for (size_t i = 1; i < shape.size(); ++i) {
bound = Mul::make(
bound, Mul::make(make_const(bound.type(), type.lanes()), shape[i]));
}
return bound;
}
// The buffer assignment map
// Variable remap
std::unordered_map<const Variable*, Expr> var_remap_;
// Buffer map
std::unordered_map<TensorKey, BufferEntry> buf_map_;
// Dimension alignment
std::unordered_map<TensorKey, std::vector<DimAlignInfo> > dim_align_;
// Storage scope
std::unordered_map<const Node*, std::string> storage_scope_;
// The current thread scope.
std::vector<ThreadScope> curr_thread_scope_;
// Collects shapes.
std::vector<std::pair<VarExpr, Array<Expr>>> shape_collector_;
// The size of cacheline
int cache_line_size_;
// The current stage is an OpenGL shader.
bool is_opengl_{false};
// Whether to mark load/store with theirs bounds.
bool create_bound_attributes_{false};
};
Stmt StorageFlatten(Stmt stmt, Map<Tensor, Buffer> extern_buffer,
int cache_line_size, bool create_bound_attributes) {
stmt =
StorageFlattener(extern_buffer, cache_line_size, create_bound_attributes)
.Mutate(stmt);
return stmt;
}
} // namespace ir
} // namespace tvm
|
auto PPU::serialize(serializer& s) -> void {
ppubase.Thread::serialize(s);
PPUcounter::serialize(s);
latch.serialize(s);
io.serialize(s);
s.array(vram);
s.array(cgram);
for(auto& object : objects) object.serialize(s);
Line::start = 0;
Line::count = 0;
}
auto PPU::Latch::serialize(serializer& s) -> void {
s.integer(interlace);
s.integer(overscan);
s.integer(hires);
s.integer(hd);
s.integer(ss);
s.integer(vram);
s.integer(oam);
s.integer(cgram);
s.integer(oamAddress);
s.integer(cgramAddress);
s.integer(mode7);
s.integer(counters);
s.integer(hcounter);
s.integer(vcounter);
ppu1.serialize(s);
ppu2.serialize(s);
}
auto PPU::Latch::PPUstate::serialize(serializer& s) -> void {
s.integer(mdr);
s.integer(bgofs);
}
auto PPU::IO::serialize(serializer& s) -> void {
s.integer(displayDisable);
s.integer(displayBrightness);
s.integer(oamBaseAddress);
s.integer(oamAddress);
s.integer(oamPriority);
s.integer(bgPriority);
s.integer(bgMode);
s.integer(vramIncrementMode);
s.integer(vramMapping);
s.integer(vramIncrementSize);
s.integer(vramAddress);
s.integer(cgramAddress);
s.integer(cgramAddressLatch);
s.integer(hcounter);
s.integer(vcounter);
s.integer(interlace);
s.integer(overscan);
s.integer(pseudoHires);
s.integer(extbg);
mosaic.serialize(s);
mode7.serialize(s);
window.serialize(s);
bg1.serialize(s);
bg2.serialize(s);
bg3.serialize(s);
bg4.serialize(s);
obj.serialize(s);
col.serialize(s);
}
auto PPU::IO::Mosaic::serialize(serializer& s) -> void {
s.integer(size);
s.integer(counter);
}
auto PPU::IO::Mode7::serialize(serializer& s) -> void {
s.integer(hflip);
s.integer(vflip);
s.integer(repeat);
s.integer(a);
s.integer(b);
s.integer(c);
s.integer(d);
s.integer(x);
s.integer(y);
s.integer(hoffset);
s.integer(voffset);
}
auto PPU::IO::Window::serialize(serializer& s) -> void {
s.integer(oneLeft);
s.integer(oneRight);
s.integer(twoLeft);
s.integer(twoRight);
}
auto PPU::IO::WindowLayer::serialize(serializer& s) -> void {
s.integer(oneEnable);
s.integer(oneInvert);
s.integer(twoEnable);
s.integer(twoInvert);
s.integer(mask);
s.integer(aboveEnable);
s.integer(belowEnable);
}
auto PPU::IO::WindowColor::serialize(serializer& s) -> void {
s.integer(oneEnable);
s.integer(oneInvert);
s.integer(twoEnable);
s.integer(twoInvert);
s.integer(mask);
s.integer(aboveMask);
s.integer(belowMask);
}
auto PPU::IO::Background::serialize(serializer& s) -> void {
window.serialize(s);
s.integer(aboveEnable);
s.integer(belowEnable);
s.integer(mosaicEnable);
s.integer(tiledataAddress);
s.integer(screenAddress);
s.integer(screenSize);
s.integer(tileSize);
s.integer(hoffset);
s.integer(voffset);
s.integer(tileMode);
s.array(priority);
}
auto PPU::IO::Object::serialize(serializer& s) -> void {
window.serialize(s);
s.integer(aboveEnable);
s.integer(belowEnable);
s.integer(interlace);
s.integer(baseSize);
s.integer(nameselect);
s.integer(tiledataAddress);
s.integer(first);
s.integer(rangeOver);
s.integer(timeOver);
s.array(priority);
}
auto PPU::IO::Color::serialize(serializer& s) -> void {
window.serialize(s);
s.array(enable);
s.integer(directColor);
s.integer(blendMode);
s.integer(halve);
s.integer(mathMode);
s.integer(fixedColor);
}
auto PPU::Object::serialize(serializer& s) -> void {
s.integer(x);
s.integer(y);
s.integer(character);
s.integer(nameselect);
s.integer(vflip);
s.integer(hflip);
s.integer(priority);
s.integer(palette);
s.integer(size);
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. 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 of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "AvailabilityManagerHighTemperatureTurnOn.hpp"
#include "AvailabilityManagerHighTemperatureTurnOn_Impl.hpp"
#include "Model.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_AvailabilityManager_HighTemperatureTurnOn_FieldEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
AvailabilityManagerHighTemperatureTurnOn_Impl::AvailabilityManagerHighTemperatureTurnOn_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == AvailabilityManagerHighTemperatureTurnOn::iddObjectType());
}
AvailabilityManagerHighTemperatureTurnOn_Impl::AvailabilityManagerHighTemperatureTurnOn_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == AvailabilityManagerHighTemperatureTurnOn::iddObjectType());
}
AvailabilityManagerHighTemperatureTurnOn_Impl::AvailabilityManagerHighTemperatureTurnOn_Impl(const AvailabilityManagerHighTemperatureTurnOn_Impl& other,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& AvailabilityManagerHighTemperatureTurnOn_Impl::outputVariableNames() const
{
static std::vector<std::string> result{
"Availability Manager High Temperature Turn On Control Status"
};
return result;
}
IddObjectType AvailabilityManagerHighTemperatureTurnOn_Impl::iddObjectType() const {
return AvailabilityManagerHighTemperatureTurnOn::iddObjectType();
}
boost::optional<Node> AvailabilityManagerHighTemperatureTurnOn_Impl::sensorNode() const {
return getObject<ModelObject>().getModelObjectTarget<Node>(OS_AvailabilityManager_HighTemperatureTurnOnFields::SensorNodeName);
}
double AvailabilityManagerHighTemperatureTurnOn_Impl::temperature() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_HighTemperatureTurnOnFields::Temperature,true);
OS_ASSERT(value);
return value.get();
}
bool AvailabilityManagerHighTemperatureTurnOn_Impl::setSensorNode(const Node& node) {
bool result = setPointer(OS_AvailabilityManager_HighTemperatureTurnOnFields::SensorNodeName, node.handle());
return result;
}
void AvailabilityManagerHighTemperatureTurnOn_Impl::resetSensorNode() {
bool result = setString(OS_AvailabilityManager_HighTemperatureTurnOnFields::SensorNodeName, "");
OS_ASSERT(result);
}
bool AvailabilityManagerHighTemperatureTurnOn_Impl::setTemperature(double temperature) {
bool result = setDouble(OS_AvailabilityManager_HighTemperatureTurnOnFields::Temperature, temperature);
OS_ASSERT(result);
return result;
}
} // detail
AvailabilityManagerHighTemperatureTurnOn::AvailabilityManagerHighTemperatureTurnOn(const Model& model)
: AvailabilityManager(AvailabilityManagerHighTemperatureTurnOn::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>());
setTemperature(30);
}
IddObjectType AvailabilityManagerHighTemperatureTurnOn::iddObjectType() {
return IddObjectType(IddObjectType::OS_AvailabilityManager_HighTemperatureTurnOn);
}
boost::optional<Node> AvailabilityManagerHighTemperatureTurnOn::sensorNode() const {
return getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>()->sensorNode();
}
double AvailabilityManagerHighTemperatureTurnOn::temperature() const {
return getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>()->temperature();
}
bool AvailabilityManagerHighTemperatureTurnOn::setSensorNode(const Node& node) {
return getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>()->setSensorNode(node);
}
void AvailabilityManagerHighTemperatureTurnOn::resetSensorNode() {
getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>()->resetSensorNode();
}
bool AvailabilityManagerHighTemperatureTurnOn::setTemperature(double temperature) {
return getImpl<detail::AvailabilityManagerHighTemperatureTurnOn_Impl>()->setTemperature(temperature);
}
/// @cond
AvailabilityManagerHighTemperatureTurnOn::AvailabilityManagerHighTemperatureTurnOn(std::shared_ptr<detail::AvailabilityManagerHighTemperatureTurnOn_Impl> impl)
: AvailabilityManager(impl)
{}
/// @endcond
} // model
} // openstudio
|
/* Copyright 2017 Kyle McDonald */
#include "NoteScheduler.h"
|
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef TR_MEMORYREFERENCE_INCL
#define TR_MEMORYREFERENCE_INCL
#include "codegen/OMRMemoryReference.hpp"
#include <stddef.h>
#include <stdint.h>
#include "env/jittypes.h"
namespace TR { class X86DataSnippet; }
class TR_ScratchRegisterManager;
namespace TR { class CodeGenerator; }
namespace TR { class LabelSymbol; }
namespace TR { class Node; }
namespace TR { class Register; }
namespace TR { class SymbolReference; }
namespace TR
{
class OMR_EXTENSIBLE MemoryReference : public OMR::MemoryReferenceConnector
{
public:
MemoryReference(TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(cg) {}
MemoryReference(TR::Register *br,
TR::SymbolReference *sr,
TR::Register *ir,
uint8_t s,
TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(br, sr, ir, s, cg) {}
MemoryReference(TR::Register *br,
TR::Register *ir,
uint8_t s,
TR::CodeGenerator*cg) :
OMR::MemoryReferenceConnector(br, ir, s, cg) {}
MemoryReference(TR::Register *br,
intptrj_t disp,
TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(br, disp, cg) {}
MemoryReference(intptrj_t disp,
TR::CodeGenerator *cg,
TR_ScratchRegisterManager *srm = NULL) :
OMR::MemoryReferenceConnector(disp, cg, srm) {}
MemoryReference(TR::Register *br,
TR::Register *ir,
uint8_t s,
intptrj_t disp,
TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(br, ir, s, disp, cg) {}
MemoryReference(TR::X86DataSnippet *cds,
TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(cds, cg) {}
MemoryReference(TR::LabelSymbol *label,
TR::CodeGenerator *cg) :
OMR::MemoryReferenceConnector(label, cg) {}
MemoryReference(TR::Node *rootLoadOrStore,
TR::CodeGenerator *cg,
bool canRematerializeAddressAdds,
TR_ScratchRegisterManager *srm = NULL) :
OMR::MemoryReferenceConnector(rootLoadOrStore, cg, canRematerializeAddressAdds, srm) {}
MemoryReference(TR::SymbolReference *symRef,
TR::CodeGenerator *cg,
TR_ScratchRegisterManager *srm = NULL) :
OMR::MemoryReferenceConnector(symRef, cg, srm) {}
MemoryReference(TR::SymbolReference *symRef,
intptrj_t displacement,
TR::CodeGenerator *cg,
TR_ScratchRegisterManager *srm = NULL) :
OMR::MemoryReferenceConnector(symRef, displacement, cg, srm) {}
MemoryReference(MemoryReference& mr,
intptrj_t n,
TR::CodeGenerator *cg,
TR_ScratchRegisterManager *srm = NULL) :
OMR::MemoryReferenceConnector(mr, n, cg, srm) {}
};
}
#endif
|
//=========================================================================
// Copyright (C) 2012 The Elastos 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 "CObjectFactory.h"
namespace Elastos {
namespace Droid {
namespace DialerBind {
CAR_INTERFACE_IMPL(CObjectFactory, Singleton, IObjectFactory);
CAR_SINGLETON_IMPL(CObjectFactory);
ECode CObjectFactory::NewCachedNumberLookupService(
/* [out] */ ICachedNumberLookupService** service)
{
VALIDATE_NOT_NULL(service);
AutoPtr<ICachedNumberLookupService> temp = NewCachedNumberLookupService();
*service = temp;
if (*service) {
REFCOUNT_ADD(*service);
}
return NOERROR;
}
ECode CObjectFactory::NewCallLogAdapter(
/* [in] */ IContext* context,
/* [in] */ ICallFetcher* callFetcher,
/* [in] */ IContactInfoHelper* contactInfoHelper,
/* [in] */ ICallLogAdapterCallItemExpandedListener* callItemExpandedListener,
/* [in] */ ICallLogAdapterOnReportButtonClickListener* onReportButtonClickListener,
/* [in] */ Boolean isCallLog,
/* [out] */ ICallLogAdapter** adapter)
{
VALIDATE_NOT_NULL(adapter);
AutoPtr<ICallLogAdapter> temp = NewCallLogAdapter(context, callFetcher,
contactInfoHelper, callItemExpandedListener,
onReportButtonClickListener, isCallLog);
*adapter = temp;
REFCOUNT_ADD(*adapter);
return NOERROR;
}
ECode CObjectFactory::GetReportDialogFragment(
/* [in] */ const String& name,
/* [out] */ IDialogFragment** fragment)
{
VALIDATE_NOT_NULL(fragment);
AutoPtr<IDialogFragment> temp = GetReportDialogFragment(name);
*fragment = temp;
if (*fragment) {
REFCOUNT_ADD(*fragment);
}
return NOERROR;
}
AutoPtr<ICachedNumberLookupService> CObjectFactory::NewCachedNumberLookupService()
{
// no-op
return NULL;
}
AutoPtr<ICallLogAdapter> CObjectFactory::NewCallLogAdapter(
/* [in] */ IContext* context,
/* [in] */ ICallFetcher* callFetcher,
/* [in] */ IContactInfoHelper* contactInfoHelper,
/* [in] */ ICallLogAdapterCallItemExpandedListener* callItemExpandedListener,
/* [in] */ ICallLogAdapterOnReportButtonClickListener* onReportButtonClickListener,
/* [in] */ Boolean isCallLog)
{
AutoPtr<ICallLogAdapter> adapter;
CCallLogAdapter::New(context, callFetcher, contactInfoHelper,
callItemExpandedListener, onReportButtonClickListener,
isCallLog, (ICallLogAdapter**)&adapter);
return adapter;
}
AutoPtr<IDialogFragment> CObjectFactory::GetReportDialogFragment(
/* [in] */ const String& name)
{
return NULL;
}
} // DialerBind
} // Droid
} // Elastos
|
// Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2014-2020 The Vuicoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/networkstyle.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <chainparams.h>
#include <tinyformat.h>
#include <util.h>
#include <QApplication>
static const struct {
const char *networkId;
const char *appName;
const int iconColorHueShift;
const int iconColorSaturationReduction;
const std::string titleAddText;
} network_styles[] = {
{"main", QAPP_APP_NAME_DEFAULT, 0, 0, ""},
{"test", QAPP_APP_NAME_TESTNET, 190, 20, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")},
{"devnet", QAPP_APP_NAME_DEVNET, 190, 20, "[devnet: %s]"},
{"regtest", QAPP_APP_NAME_REGTEST, 160, 30, "[regtest]"}
};
static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles);
void NetworkStyle::rotateColor(QColor& col, const int iconColorHueShift, const int iconColorSaturationReduction)
{
int h, s, l, a;
col.getHsl(&h, &s, &l, &a);
// rotate color on RGB color circle
h += iconColorHueShift;
// change saturation value
s -= iconColorSaturationReduction;
s = std::max(s, 0);
col.setHsl(h,s,l,a);
}
void NetworkStyle::rotateColors(QImage& img, const int iconColorHueShift, const int iconColorSaturationReduction) {
int h,s,l,a;
// traverse though lines
for(int y=0;y<img.height();y++)
{
QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) );
// loop through pixels
for(int x=0;x<img.width();x++)
{
QColor col;
col.setRgba(scL[x]);
rotateColor(col, iconColorHueShift, iconColorSaturationReduction);
scL[x] = col.rgba();
}
}
}
// titleAddText needs to be const char* for tr()
NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText):
appName(_appName),
titleAddText(qApp->translate("SplashScreen", _titleAddText)),
badgeColor(QColor(0, 141, 228)) // default badge color is the original Vuicoin's blue, regardless of the current theme
{
// Allow for separate UI settings for testnets
QApplication::setApplicationName(appName);
// Make sure settings migrated properly
GUIUtil::migrateQtSettings();
// load pixmap
QPixmap appIconPixmap(":/icons/bitcoin");
if(iconColorHueShift != 0 && iconColorSaturationReduction != 0)
{
// generate QImage from QPixmap
QImage appIconImg = appIconPixmap.toImage();
rotateColors(appIconImg, iconColorHueShift, iconColorSaturationReduction);
//convert back to QPixmap
#if QT_VERSION >= 0x040700
appIconPixmap.convertFromImage(appIconImg);
#else
appIconPixmap = QPixmap::fromImage(appIconImg);
#endif
// tweak badge color
rotateColor(badgeColor, iconColorHueShift, iconColorSaturationReduction);
}
appIcon = QIcon(appIconPixmap);
trayAndWindowIcon = QIcon(appIconPixmap.scaled(QSize(256,256)));
splashImage = QPixmap(":/images/splash");
}
const NetworkStyle *NetworkStyle::instantiate(const QString &networkId)
{
for (unsigned x=0; x<network_styles_count; ++x)
{
if (networkId == network_styles[x].networkId)
{
std::string appName = network_styles[x].appName;
std::string titleAddText = network_styles[x].titleAddText;
if (networkId == QString(CBaseChainParams::DEVNET.c_str())) {
appName = strprintf(appName, gArgs.GetDevNetName());
titleAddText = strprintf(titleAddText, gArgs.GetDevNetName());
}
return new NetworkStyle(
appName.c_str(),
network_styles[x].iconColorHueShift,
network_styles[x].iconColorSaturationReduction,
titleAddText.c_str());
}
}
return 0;
}
|
//===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- 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
//
//===----------------------------------------------------------------------===//
#include "obj2yaml.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/Minidump.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/InitLLVM.h"
using namespace llvm;
using namespace llvm::object;
static Error dumpObject(const ObjectFile &Obj) {
if (Obj.isCOFF())
return errorCodeToError(coff2yaml(outs(), cast<COFFObjectFile>(Obj)));
if (Obj.isXCOFF())
return errorCodeToError(xcoff2yaml(outs(), cast<XCOFFObjectFile>(Obj)));
if (Obj.isELF())
return elf2yaml(outs(), Obj);
if (Obj.isWasm())
return errorCodeToError(wasm2yaml(outs(), cast<WasmObjectFile>(Obj)));
llvm_unreachable("unexpected object file format");
}
static Error dumpInput(StringRef File) {
ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false,
/*RequiresNullTerminator=*/false);
if (std::error_code EC = FileOrErr.getError())
return errorCodeToError(EC);
std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
MemoryBufferRef MemBuf = Buffer->getMemBufferRef();
if (file_magic::archive == identify_magic(MemBuf.getBuffer()))
return archive2yaml(outs(), MemBuf);
Expected<std::unique_ptr<Binary>> BinOrErr =
createBinary(MemBuf, /*Context=*/nullptr);
if (!BinOrErr)
return BinOrErr.takeError();
Binary &Binary = *BinOrErr->get();
// Universal MachO is not a subclass of ObjectFile, so it needs to be handled
// here with the other binary types.
if (Binary.isMachO() || Binary.isMachOUniversalBinary())
return macho2yaml(outs(), Binary);
if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
return dumpObject(*Obj);
if (MinidumpFile *Minidump = dyn_cast<MinidumpFile>(&Binary))
return minidump2yaml(outs(), *Minidump);
return Error::success();
}
static void reportError(StringRef Input, Error Err) {
if (Input == "-")
Input = "<stdin>";
std::string ErrMsg;
raw_string_ostream OS(ErrMsg);
logAllUnhandledErrors(std::move(Err), OS);
OS.flush();
errs() << "Error reading file: " << Input << ": " << ErrMsg;
errs().flush();
}
cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"),
cl::init("-"));
int main(int argc, char *argv[]) {
InitLLVM X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
if (Error Err = dumpInput(InputFilename)) {
reportError(InputFilename, std::move(Err));
return 1;
}
return 0;
}
|
#include <memory>
#include <jni.h>
#include "Log.h"
#include "JNIAutoLocalStr.h"
#include "AndroidLuaLibTapjoy.h"
#include "TapjoyLuaExtraLib.h"
#include "ae_sdl2.h"
using namespace std;
using namespace ae;
using namespace ae::jni;
using namespace ae::tapjoy;
/// The log cat.
static const char *logTag = "AE/Tapjoy";
/// The Android implementation of the Lua library.
static AndroidLuaLibTapjoy *luaLibTapjoy;
/** */
extern "C" {
/** */
void Java_com_andcreations_tapjoy_AETapjoy_loadLuaLib(
JNIEnv *env,jclass clazz);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_connectionSucceeded(
JNIEnv *env,jclass clazz);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_connectionFailed(
JNIEnv *env,jclass clazz);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_requestSucceeded(
JNIEnv *env,jclass clazz,jstring jPlacement);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_requestFailed(
JNIEnv *env,jclass clazz,jstring jPlacement,jstring jError);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentIsReady(
JNIEnv *env,jclass clazz,jstring jPlacement);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentShown(
JNIEnv *env,jclass clazz,jstring jPlacement);
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentDismissed(
JNIEnv *env,jclass clazz,jstring jPlacement);
};
/** */
void Java_com_andcreations_tapjoy_AETapjoy_loadLuaLib(JNIEnv *env,jclass clazz) {
if (luaLibTapjoy != (AndroidLuaLibTapjoy *)0) {
Log::warning(logTag,"Tapjoy Lua library already loaded. "
"Skipping loading again.");
return;
}
luaLibTapjoy = new (nothrow) AndroidLuaLibTapjoy();
if (luaLibTapjoy == (AndroidLuaLibTapjoy *)0) {
Log::error(logTag,"Failed to load Tapjoy library. No memory.");
return;
}
TapjoyLuaExtraLib *lib = new (nothrow) TapjoyLuaExtraLib(luaLibTapjoy);
if (lib == (TapjoyLuaExtraLib *)0) {
Log::error(logTag,"Failed to load Tapjoy library. No memory.");
return;
}
aeAddLuaExtraLib(lib);
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_connectionSucceeded(
JNIEnv *env,jclass clazz) {
//
luaLibTapjoy->connectionSucceeded();
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_connectionFailed(
JNIEnv *env,jclass clazz) {
//
luaLibTapjoy->connectionFailed();
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_requestSucceeded(
JNIEnv *env,jclass clazz,jstring jPlacement) {
//
const char *placement = env->GetStringUTFChars(jPlacement,(jboolean *)0);
JNIAutoLocalStr placementLocalStr(env,jPlacement,placement);
luaLibTapjoy->requestSucceeded(string(placement));
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_requestFailed(
JNIEnv *env,jclass clazz,jstring jPlacement,jstring jError) {
//
const char *placement = env->GetStringUTFChars(jPlacement,(jboolean *)0);
JNIAutoLocalStr placementLocalStr(env,jPlacement,placement);
const char *error = env->GetStringUTFChars(jError,(jboolean *)0);
JNIAutoLocalStr errorLocalStr(env,jError,error);
luaLibTapjoy->requestFailed(string(placement),string(error));
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentIsReady(
JNIEnv *env,jclass clazz,jstring jPlacement) {
//
const char *placement = env->GetStringUTFChars(jPlacement,(jboolean *)0);
JNIAutoLocalStr placementLocalStr(env,jPlacement,placement);
luaLibTapjoy->contentIsReady(string(placement));
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentShown(
JNIEnv *env,jclass clazz,jstring jPlacement) {
//
const char *placement = env->GetStringUTFChars(jPlacement,(jboolean *)0);
JNIAutoLocalStr placementLocalStr(env,jPlacement,placement);
luaLibTapjoy->contentShown(string(placement));
}
/** */
void Java_com_andcreations_tapjoy_AETapjoy_contentDismissed(
JNIEnv *env,jclass clazz,jstring jPlacement) {
//
const char *placement = env->GetStringUTFChars(jPlacement,(jboolean *)0);
JNIAutoLocalStr placementLocalStr(env,jPlacement,placement);
luaLibTapjoy->contentDismissed(string(placement));
}
|
/*******************************************************************************
* Copyright 2018-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <float.h>
#include <math.h>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <type_traits>
#include "oneapi/dnnl/dnnl.h"
#if DNNL_CPU_RUNTIME != DNNL_RUNTIME_NONE
#include "tests/test_isa_common.hpp"
#endif
#include "utils/parallel.hpp"
#include "dnnl_common.hpp"
#include "dnnl_memory.hpp"
#include "rnn/rnn.hpp"
#include "rnn/rnn_aux.hpp"
// Using hidden attr API for testing RNN
dnnl_status_t dnnl_primitive_attr_set_rnn_tparams(dnnl_primitive_attr_t attr,
bool mode, dnnl_dim_t ngates, const float *scales, float cscale);
namespace {
// In order to have consistent filling across compilers and operating systems,
// we implement the equivalent of std::normal_distribution using the so-called
// Marsaglia polar method.
template <typename T>
class normal_distribution_t {
public:
normal_distribution_t(T mean, T stddev)
: gen(-1.f, 1.f)
, is_odd_(false)
, odd_(1.f)
, mean_(mean)
, stddev_(stddev) {
static_assert(std::is_floating_point<T>::value,
"T must be a floating point type.");
}
template <typename URNG>
T operator()(URNG &g) {
T r, r2, x, y;
if (is_odd_) {
is_odd_ = false;
return odd_;
}
is_odd_ = true;
do {
x = gen(g); // x E [-1, 1)
y = gen(g); // y E [-1, 1)
r2 = x * x + y * y;
} while (0.f == r2 || 1.f < r2); // r2 E (0, 1]
r = stddev_ * std::sqrt(-2.f * std::log(r2) / r2);
x = mean_ + x * r;
y = mean_ + y * r;
odd_ = x;
return y;
}
private:
std::uniform_real_distribution<T> gen;
bool is_odd_;
T odd_;
const T mean_;
const T stddev_;
};
} // namespace
namespace rnn {
dnnl_primitive_attr_t create_dnnl_rnn_attr(const prb_t &prb) {
dnnl_primitive_attr_t dnnl_attr = nullptr;
DNN_SAFE_V(dnnl_primitive_attr_create(&dnnl_attr));
if (prb.skip_nonlinear)
DNN_SAFE_V(dnnl_primitive_attr_set_rnn_tparams(dnnl_attr, true,
prb.n_gates(), prb.linear_scales, prb.linear_cscale));
DNN_SAFE_V(dnnl_primitive_attr_set_rnn_weights_qparams(
dnnl_attr, prb.wei_nscales, prb.wei_scales_mask, prb.wei_scales));
if (prb.is_lstm_projection() && prb.is_int8())
DNN_SAFE_V(dnnl_primitive_attr_set_rnn_weights_projection_qparams(
dnnl_attr, prb.wei_proj_nscales, prb.wei_proj_scales_mask,
prb.wei_proj_scales));
if (prb.data_scale != 1.0 || prb.data_shift != 0.0)
DNN_SAFE_V(dnnl_primitive_attr_set_rnn_data_qparams(
dnnl_attr, prb.data_scale, prb.data_shift));
DNN_SAFE_V(dnnl_primitive_attr_set_scratchpad_mode(
dnnl_attr, prb.attr.scratchpad_mode));
DNN_SAFE_V(dnnl_primitive_attr_set_fpmath_mode(
dnnl_attr, prb.attr.fpmath_mode));
return dnnl_attr;
}
int check_ldoi_s8_reorder(const prb_t &prb, rnn_data_kind_t kind,
const dnn_mem_t &mem_dt, const dnn_mem_t &mem_fp,
const_dnnl_primitive_attr_t attr = nullptr) {
// TODO: enable for all cpu_kind when supported
if (is_gpu()) return OK;
// we compare ldio_f32 -> ldio_s8 to ldio_f32 -> ldoi_f32 -> ldio_s8
// f32 is in ldio
dnn_mem_t mem_ldoi_f32(mem_fp.md_, dnnl_f32, "ldoi", get_cpu_engine());
dnn_mem_t mem_s8_src(mem_dt.md_, dnnl_s8, get_test_engine());
mem_ldoi_f32.reorder(mem_fp);
mem_s8_src.reorder(mem_ldoi_f32, attr);
dnn_mem_t mem_s8_dst(mem_dt.md_, dnnl_s8, get_test_engine());
mem_s8_dst.reorder(mem_fp, attr);
// we check that the two are identical
auto sz = mem_dt.size();
uint8_t *s8_src_handle = (uint8_t *)mem_s8_src;
uint8_t *s8_dst_handle = (uint8_t *)mem_s8_dst;
// check that both have the same size
assert(mem_s8_src.size() == mem_s8_dst.size());
// check that both have the same alignment modulo align_data in
// gemm_pack_storage.hpp
assert((uint64_t)s8_src_handle % 0x1000
== (uint64_t)s8_dst_handle % 0x1000);
for (size_t i = 0; i < sz; ++i) {
if (s8_src_handle[i] != s8_dst_handle[i]) { return FAIL; }
}
return OK;
}
int check_s8s8_reorder(const prb_t &prb, rnn_data_kind_t kind,
const dnn_mem_t &mem_dt, const dnn_mem_t &mem_fp) {
// TODO: enable for all cpu_kind when supported
if (is_gpu()) return OK;
#if DNNL_CPU_RUNTIME == DNNL_RUNTIME_DPCPP
// DPC++ does not provide a simple way to access the underlying
// buffer alignment.
return OK;
#endif
// In the main test, we fill buffers with f32 and reorder to s8
// with quantization.
// The endgoal is to check that the reorder
// f32_plain_nonquantized --reorder--> s8_packed_quantized
// gives the same output as the sequence
// f32_plain --quant--> s8_plain_quantized --reorder--> s8_packed_quantized
// Here,
// 1. we quantize the f32 plain memory to s8 plain memory,
// 2. we reorder the s8 plain to s8 packed (queried from rnn primitive desc)
// 3. we check that the two memory are bitwise identical.
// Note: the two s8 packed memories need to have the same
// alignment as packed buffer is aligned internally and the offset
// is kept in the metadata.
// Works fine with dnn_mem_t as it is align to 2MB large page boundary
dnn_mem_t mem_s8_src(mem_fp.md_, dnnl_s8, get_cpu_engine());
dnn_mem_t mem_s8_dst(mem_dt.md_, dnnl_s8, get_test_engine());
/* 1. compute f32_plain --quant--> s8_plain_quantized */
/* Do fixed partitioning to have same filling for any number of threads */
auto nelems = mem_fp.nelems();
const int64_t n_chunks = 16;
const int64_t chunk_size = div_up(nelems, n_chunks);
const auto quantize = [&](const float *scales, int nscales, float shift,
int idx_chunk) {
int64_t idx_start = idx_chunk * chunk_size;
int64_t idx_end = MIN2(idx_start + chunk_size, nelems);
for (int64_t idx = idx_start; idx < idx_end; ++idx) {
const float current_scale = scales[idx % nscales];
float val_f32 = mem_fp.get_elem(idx);
int8_t val_s8 = saturate_and_round<dnnl_s8>(
val_f32 * current_scale + shift);
mem_s8_src.set_elem(idx, val_s8);
}
};
switch (kind) {
case WEIGHTS_LAYER:
case WEIGHTS_ITER:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
quantize(prb.wei_scales, prb.wei_nscales, 0, idx);
});
break;
case WEIGHTS_PROJECTION:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
quantize(prb.wei_proj_scales, prb.wei_proj_nscales, 0, idx);
});
break;
case SRC_LAYER:
case SRC_ITER:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
quantize(&(prb.data_scale), 1, prb.data_shift, idx);
});
break;
default: assert(!"unsupported kind");
}
/* 2. compute s8_plain_quantized --reorder--> s8_packed_quantized */
mem_s8_dst.reorder(mem_s8_src);
/* 3. we check that the two memory are bitwise identical. */
auto sz = mem_dt.size();
uint8_t *s8_dst_handle = (uint8_t *)mem_s8_dst;
uint8_t *mem_dt_handle = (uint8_t *)mem_dt;
// check that both have the same size
assert(mem_dt.size() == mem_s8_dst.size());
// check that both have the same alignment modulo align_data in gemm_pack_storage.hpp
assert((uint64_t)s8_dst_handle % 0x1000
== (uint64_t)mem_dt_handle % 0x1000);
for (size_t i = 0; i < sz; ++i) {
if (s8_dst_handle[i] != mem_dt_handle[i]) { return FAIL; }
}
return OK;
}
int fill_memory(const prb_t &prb, rnn_data_kind_t kind, dnn_mem_t &mem_dt,
dnn_mem_t &mem_fp, dnnl_data_type_t dt, float mean, float stddev,
float min, float max, const_dnnl_primitive_attr_t attr = nullptr,
bool flip_sign = false) {
const auto nelems = mem_dt.nelems();
if (nelems == 0) return OK;
assert(mem_dt.nelems() == mem_fp.nelems());
// For non-int8 RNN the data is filled according to cfg directly.
// However, for int8 RNN we have slightly obscure logic, at least for now:
// 1. cfg describes the quantized data;
// 2. We fill first f32 de-quantized data, by inverse-applying the scale
// and shift to the data generated by cfg distribution;
// 3. We reorder the data for the oneDNN RNN primitive
// 4. Q10n of the data for reference benchdnn RNN:
// 4.a. If the tensor is weights -- q10n it here;
// 4.b. If the tensor is data -- reference benchdnn RNN will quantize it.
// pass rnn attributes to f32 -> int8 reorders only
const_dnnl_primitive_attr_t reorder_attr = nullptr;
if (prb.is_int8() && (dt != dnnl_f32)) reorder_attr = attr;
float default_scales[1] = {1.0f};
float default_shift = 0.0f;
/* Do fixed partitioning to have same filling for any number of threads */
const int64_t n_chunks = 16;
const int64_t chunk_size = div_up(nelems, n_chunks);
// 2. We fill first f32 de-quantized data, by inverse-applying the scale
// and shift to the data generated by cfg distribution;
auto fill_chunk = [&](const float *scales, int nscales, float shift,
int idx_chunk) {
int64_t idx_start = idx_chunk * chunk_size;
int64_t idx_end = MIN2(idx_start + chunk_size, nelems);
std::minstd_rand msr;
msr.seed(idx_start + kind);
normal_distribution_t<float> gen(mean, stddev);
for (int64_t idx = idx_start; idx < idx_end; ++idx) {
float val = round_to_nearest_representable(dt, gen(msr));
val = MAX2(MIN2(val, max), min);
val = (val - shift)
/ scales[idx % nscales]; // change only int8-case
// Vanilla RNN with RELU testing related only: flip the sign of
// inputs for `mb` == 0 to test RELU part
if (flip_sign) {
assert(kind == SRC_LAYER || kind == SRC_ITER);
auto ld = kind == SRC_LAYER ? prb.slc : prb.sic;
if (idx % (prb.mb * ld) < ld) val *= -1;
}
mem_fp.set_elem(idx, val);
}
};
switch (kind) {
case WEIGHTS_PROJECTION:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
fill_chunk(
prb.wei_proj_scales, prb.wei_proj_nscales, 0.0f, idx);
});
break;
case WEIGHTS_LAYER:
case WEIGHTS_ITER:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
fill_chunk(prb.wei_scales, prb.wei_nscales, 0.0f, idx);
});
break;
case SRC_LAYER:
case SRC_ITER:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
fill_chunk(&(prb.data_scale), 1, prb.data_shift, idx);
});
break;
default: // we do no scale/shift
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
fill_chunk(default_scales, 1, default_shift, idx);
});
}
// 3. We reorder the data for the DNNL RNN primitive
mem_dt.reorder(mem_fp, reorder_attr);
if ((reorder_attr != nullptr) && (dt == dnnl_s8))
if (check_s8s8_reorder(prb, kind, mem_dt, mem_fp) != OK) return FAIL;
if ((kind == WEIGHTS_PROJECTION) && (dt == dnnl_s8))
if (check_ldoi_s8_reorder(prb, kind, mem_dt, mem_fp, reorder_attr)
!= OK)
return FAIL;
// Bullet 4.a holds: quantize weights for int8 benchdnn reference RNN
if (prb.is_int8()) {
auto quantize_chunk
= [&](const float *scales, int nscales, int idx_chunk) {
int64_t idx_start = idx_chunk * chunk_size;
int64_t idx_end = MIN2(idx_start + chunk_size, nelems);
for (int64_t idx = idx_start; idx < idx_end; ++idx) {
float current_scale = scales[idx % nscales];
float val = ((float *)mem_fp)[idx];
val = round(current_scale * val);
mem_fp.set_elem(idx, MAX2(MIN2(val, max), min));
}
};
switch (kind) {
case WEIGHTS_LAYER:
case WEIGHTS_ITER:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
quantize_chunk(prb.wei_scales, prb.wei_nscales, idx);
});
break;
case WEIGHTS_PROJECTION:
benchdnn_parallel_nd(n_chunks, [&](int64_t idx) {
quantize_chunk(
prb.wei_proj_scales, prb.wei_proj_nscales, idx);
});
break;
default: // Nothing to do
break;
}
}
return OK;
}
int fill_memory(const prb_t &prb, rnn_data_kind_t kind, dnn_mem_t &mem_dt,
dnn_mem_t &mem_fp, const_dnnl_primitive_attr_t attr = nullptr,
bool flip_sign = false) {
const dt_conf_t::entry_t &c = prb.cfg[kind];
return fill_memory(prb, kind, mem_dt, mem_fp, c.dt, c.f_mean, c.f_stddev,
c.f_min, c.f_max, attr, flip_sign);
}
int fill_activation(const prb_t &prb, rnn_data_kind_t kind, dnn_mem_t &mem_dt,
dnn_mem_t &mem_fp, const_dnnl_primitive_attr_t attr = nullptr) {
// In general, we mostly want to use positive values to avoid
// cancellation from happening during computation. The only case
// where we actually want negative values to appear is for 1 layer
// 1 iteration tests using vanilla_rnn and non-zero alpha. In that
// case, we want to check that alpha is applied accordingly. Here
// skip_nonlinear is checked as we want to test relu with non-zero
// alpha, and not the linear function that would replace it under
// skip_nonlinear=true.
bool flip_sign = prb.skip_nonlinear == false && prb.alg == VANILLA_RNN
&& prb.activation == RELU
&& (kind == SRC_LAYER || kind == SRC_ITER);
return fill_memory(prb, kind, mem_dt, mem_fp, attr, flip_sign);
}
int fill_src_iter_c(const prb_t &prb, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp,
const_dnnl_primitive_attr_t attr = nullptr) {
const bool special_case = prb.prop == dnnl_backward && prb.skip_nonlinear;
if (!special_case)
return fill_memory(prb, SRC_ITER_C, mem_dt, mem_fp, attr);
// The scaling factors in tparams when testing backward are common for
// for forward and backward passes, and computed as 1 over maximum of
// the accumulation chain:
// - ~n_gates on FWD
// - ~dhc * n_gates on BWD_D
// - ~mb * n_gates on BWD_W
//
// This makes tparam relatively small for the forward pass (compare to
// the forward pass when we test forward only). This in turn, makes
// src_iter_c converge relatively fast to the value ~ i_gate * c_gate,
// which is (typically) way smaller than the original distribution for
// src_iter_c.
//
// TODO: use different tparams for forward and
// backward passes when testing BWD_DW.
//
// The problem appears on backward pass. Consider diff_f_gate that
// contributes to backward weights when batch or number of iterations
// is big:
// diff_f_gate[iter] = src_iter_c[iter] * diff_dst[iter].
// diff_weights += ~diff_f_gate[iter].
//
// Assume, that diff_dst[iter] is always about the same for every iter.
// Since src_iter_c[0] >> src_iter_c[iter] for iter > 0, this makes the
// diff_weight be highly dependent on the order of accumulating the
// diff_f_gate[iter].
//
// Originally we had something like:
// diff_weights = v + v * 10^-5 + ... + v * 10^-5 (n_iter * MB summands).
// Depending on the order of summation the difference might exceed the
// typical bound approximation: coefficient * log(number_of_summands).
//
// Anyways, the algorithm below tries to put the first src_iter_c[iter = 0]
// in the same ballpark as all the subsequent src_iter_c[iter > 0].
//
// The estimation is based on the following rough assumptions:
// src_iter_c[iter+1] = f_gate * src_iter_c[iter] + i_gate * c_gate
// ~= f_gate * small_value + i_gate * c_gate
// ~= i_gate * c_gate.
// i_gate ~= tparams[i_gate] * (
// 1 / ngates * mean_src_layer +
// 1 / ngates * mean_src_iter +
// mean_bias);
//
// Same for c_gate.
// The (1 / ngates) factor is taken from fill_weights().
float expect_gemm_output = (1.f / prb.n_gates()) * prb.cfg[SRC_LAYER].f_mean
+ (1.f / prb.n_gates()) * prb.cfg[SRC_ITER].f_mean
+ prb.cfg[BIAS].f_mean;
float expect_i_gate = (float)prb.linear_scales[LSTM_I] * expect_gemm_output;
float expect_c_gate = (float)prb.linear_scales[LSTM_C] * expect_gemm_output;
float expect_src_iter_c_mean = expect_i_gate * expect_c_gate;
float adjust_factor = 1;
const bool need_adjust = expect_src_iter_c_mean < prb.cfg[SRC_ITER_C].f_mean
&& prb.cfg[SRC_ITER_C].f_mean != 0;
if (need_adjust)
adjust_factor = expect_src_iter_c_mean / prb.cfg[SRC_ITER_C].f_mean;
const dt_conf_t::entry_t &c = prb.cfg[SRC_ITER_C];
return fill_memory(prb, SRC_ITER_C, mem_dt, mem_fp, c.dt,
c.f_mean * adjust_factor, c.f_stddev * adjust_factor,
c.f_min * adjust_factor, c.f_max * adjust_factor, attr);
}
int fill_weights(const prb_t &prb, rnn_data_kind_t kind, dnn_mem_t &mem_dt,
dnn_mem_t &mem_fp, const_dnnl_primitive_attr_t attr = nullptr) {
const auto nelems = mem_dt.nelems();
if (nelems == 0) return OK;
const dt_conf_t::entry_t &c = prb.cfg[kind];
assert(kind == WEIGHTS_PROJECTION ? mem_fp.ndims() == 4
: mem_fp.ndims() == 5);
const auto &dims = mem_fp.md_.dims;
const int64_t L = dims[0];
const int64_t D = dims[1];
const int64_t I = dims[2];
const int64_t G = (kind == WEIGHTS_PROJECTION) ? 1 : dims[3];
const int64_t O = (kind == WEIGHTS_PROJECTION) ? dims[3] : dims[4];
float gate_factor
= (kind == WEIGHTS_PROJECTION) ? 1.f : 1.f / prb.n_gates();
const auto tag = tag::abx;
dnn_mem_t mem_pure_fp(mem_dt.md_, dnnl_f32, tag, get_cpu_engine());
for (int64_t i = 0; i < mem_fp.nelems(); i++) {
mem_fp.set_elem(i, 0);
mem_pure_fp.set_elem(i, 0);
}
auto scales = (kind == WEIGHTS_PROJECTION) ? prb.wei_proj_scales
: prb.wei_scales;
auto n_scales = (kind == WEIGHTS_PROJECTION) ? prb.wei_proj_nscales
: prb.wei_nscales;
// Fill weights sparsely to avoid accumulation errors. Using two memories:
// one is quantized for reference, another is for a reorder.
for_(int64_t l = 0; l < L; l++)
for_(int64_t d = 0; d < D; d++)
for_(int64_t g = 0; g < G; g++)
for (int64_t o = 0; o < O; o++) {
int64_t i_off = ((19 * o + 7 * g + 11 * d + 13 * l) % I);
int64_t off = (((l * D + d) * I + i_off) * G + g) * O + o;
float val = gate_factor;
mem_pure_fp.set_elem(off, val);
if (prb.is_int8()) val *= scales[off % n_scales];
mem_fp.set_elem(off, round_to_nearest_representable(c.dt, val));
}
// Pass rnn attributes to f32 -> s8 reorders only
const_dnnl_primitive_attr_t reorder_attr = nullptr;
if (prb.is_int8()) reorder_attr = attr;
mem_dt.reorder(mem_pure_fp, reorder_attr);
// Test that s8 -> s8 reorder works correctly
if ((reorder_attr != nullptr) && (c.dt == dnnl_s8))
return check_s8s8_reorder(prb, kind, mem_dt, mem_pure_fp);
return OK;
}
int fill_bias(const prb_t &prb, rnn_data_kind_t kind, dnn_mem_t &mem_dt,
dnn_mem_t &mem_fp) {
// To reduce likelihood of cancellation happening in bwd by bias,
// (especially for GRU), we want diff_bias to be sparse
auto dims = mem_fp.md_.dims;
auto L = dims[0];
auto D = dims[1];
auto G = dims[2];
auto O = dims[3];
std::minstd_rand msr;
normal_distribution_t<float> gen(
prb.cfg[kind].f_mean, prb.cfg[kind].f_stddev);
msr.seed(kind);
for_(int64_t l = 0; l < L; l++)
for_(int64_t d = 0; d < D; d++)
for_(int64_t g = 0; g < G; g++)
for (int64_t o = 0; o < O; o++) {
auto idx = l * D * G * O + d * G * O + g * O + o;
auto val = round_to_nearest_representable(
prb.cfg[kind].dt, gen(msr) * flip_coin(idx, 0.05f));
mem_fp.set_elem(idx, val);
}
mem_dt.reorder(mem_fp);
return OK;
}
void compute_ref(
const prb_t *prb, const args_t &args, dnnl_primitive_t prim_ref) {
const prb_t &prb_ = *prb;
if (prb_.prop != dnnl_backward)
compute_ref_fwd(prb_, args);
else
compute_ref_bwd(prb_, args);
}
dnnl_status_t init_pd(dnnl_engine_t engine, const prb_t *p_ptr,
dnnl_primitive_desc_t &rpd, res_t *res, dir_t dir,
const_dnnl_primitive_desc_t hint) {
const auto &prb = *p_ptr;
dnnl_rnn_desc_t rd;
dnnl_prop_kind_t fwd_prop = dnnl_prop_kind_undef;
switch (prb.prop) {
case dnnl_forward_training: fwd_prop = dnnl_forward_training; break;
case dnnl_forward_inference: fwd_prop = dnnl_forward_inference; break;
// If we are testing backward, we have to run forward training first
// in order to generate a valid workspace.
case dnnl_backward: fwd_prop = dnnl_forward_training; break;
default: DNN_SAFE_STATUS(dnnl_invalid_arguments);
}
const bool is_gru_lbr = prb.alg == LBR_GRU || prb.alg == LBR_AUGRU;
// Enable testing with non trivial strides
int the_stride = prb.trivial_strides ? 0 : 1;
// bidirectional = 2, s for lstm = 2, for all other = 1
dnnl_dims_t weights_layer_dims
= {prb.n_layer, prb.n_dir(), prb.slc, prb.n_gates(), prb.dhc};
dnnl_dims_t weights_iter_dims
= {prb.n_layer, prb.n_dir(), prb.sic, prb.n_gates(), prb.dhc};
dnnl_dims_t attention_dims = {prb.n_iter, prb.mb, 1};
dnnl_dims_t weights_peephole_dims = {prb.n_layer, prb.n_dir(), 3, prb.dhc};
dnnl_dims_t weights_projection_dims
= {prb.n_layer, prb.n_dir(), prb.dhc, prb.dic};
dnnl_dims_t bias_dims
= {prb.n_layer, prb.n_dir(), prb.n_gates() + is_gru_lbr, prb.dhc};
// dnnl_tnc
dnnl_dims_t dst_layer_dims = {prb.n_iter, prb.mb, prb.dlc(PRIMITIVE)};
dnnl_dims_t src_layer_dims = {prb.n_iter, prb.mb, prb.slc};
auto src_layer_d = dnn_mem_t::init_md(
3, src_layer_dims, prb.cfg[SRC_LAYER].dt, tag::abx /* dnnl_tnc */);
src_layer_d.format_desc.blocking.strides[0] += the_stride;
dnnl_dims_t src_iter_dims = {prb.n_layer, prb.n_dir(), prb.mb, prb.sic};
auto src_iter_d = dnn_mem_t::init_md(
4, src_iter_dims, prb.cfg[SRC_ITER].dt, tag::abx /* dnnl_ldnc */);
src_iter_d.format_desc.blocking.strides[2] = prb.sic + the_stride;
for (int d = 1; d >= 0; --d)
src_iter_d.format_desc.blocking.strides[d]
= src_iter_d.format_desc.blocking.strides[d + 1]
* src_iter_d.dims[d + 1];
dnnl_dims_t src_iter_c_dims = {prb.n_layer, prb.n_dir(), prb.mb, prb.dhc};
auto src_iter_c_d = dnn_mem_t::init_md(4, src_iter_c_dims,
prb.cfg[SRC_ITER_C].dt, tag::abx /* dnnl_ldnc */);
src_iter_c_d.format_desc.blocking.strides[2] = prb.dhc + the_stride;
for (int d = 1; d >= 0; --d)
src_iter_c_d.format_desc.blocking.strides[d]
= src_iter_c_d.format_desc.blocking.strides[d + 1]
* src_iter_c_d.dims[d + 1];
auto weights_layer_d = dnn_mem_t::init_md(
5, weights_layer_dims, prb.cfg[WEIGHTS_LAYER].dt, tag::any);
auto weights_iter_d = dnn_mem_t::init_md(
5, weights_iter_dims, prb.cfg[WEIGHTS_ITER].dt, tag::any);
dnnl_memory_desc_t attention_d {};
if (prb.is_augru())
attention_d = dnn_mem_t::init_md(3, attention_dims,
prb.cfg[AUGRU_ATTENTION].dt, tag::abx /* dnnl_tnc */);
dnnl_memory_desc_t weights_peephole_d {};
if (prb.is_lstm_peephole())
weights_peephole_d = dnn_mem_t::init_md(4, weights_peephole_dims,
prb.cfg[WEIGHTS_PEEPHOLE].dt, tag::abx /* dnnl_ldgo */);
dnnl_memory_desc_t weights_projection_d {};
if (prb.is_lstm_projection())
weights_projection_d = dnn_mem_t::init_md(4, weights_projection_dims,
prb.cfg[WEIGHTS_PROJECTION].dt, tag::any);
auto bias_d = dnn_mem_t::init_md(4, bias_dims, prb.cfg[BIAS].dt, tag::any);
auto dst_layer_d = dnn_mem_t::init_md(
3, dst_layer_dims, prb.cfg[DST_LAYER].dt, tag::abx /* dnnl_tnc */);
dst_layer_d.format_desc.blocking.strides[0] += the_stride;
dnnl_dims_t dst_iter_dims = {prb.n_layer, prb.n_dir(), prb.mb, prb.dic};
auto dst_iter_d = dnn_mem_t::init_md(
4, dst_iter_dims, prb.cfg[DST_ITER].dt, tag::abx /* dnnl_ldnc */);
dst_iter_d.format_desc.blocking.strides[2] = prb.dic + the_stride;
for (int d = 1; d >= 0; --d)
dst_iter_d.format_desc.blocking.strides[d]
= dst_iter_d.format_desc.blocking.strides[d + 1]
* dst_iter_d.dims[d + 1];
dnnl_dims_t dst_iter_c_dims = {prb.n_layer, prb.n_dir(), prb.mb, prb.dhc};
auto dst_iter_c_d = dnn_mem_t::init_md(4, dst_iter_c_dims,
prb.cfg[DST_ITER_C].dt, tag::abx /* dnnl_ldnc */);
dst_iter_c_d.format_desc.blocking.strides[2] = prb.dhc + the_stride;
for (int d = 1; d >= 0; --d)
dst_iter_c_d.format_desc.blocking.strides[d]
= dst_iter_c_d.format_desc.blocking.strides[d + 1]
* dst_iter_c_d.dims[d + 1];
// Initializing the forward pass
// When inference, we use forward_inference
// When training, we use forward_training
if (dir & FLAG_FWD) {
DNN_SAFE_STATUS(init_rnn_fwd_desc(&rd, prb, fwd_prop, &src_layer_d,
&src_iter_d, &src_iter_c_d, &attention_d, &weights_layer_d,
&weights_iter_d, &weights_peephole_d, &weights_projection_d,
&bias_d, &dst_layer_d, &dst_iter_d, &dst_iter_c_d));
} else {
// TODO: add stride support for diff_* tensors
auto diff_src_layer_d = dnn_mem_t::init_md(
3, src_layer_dims, prb.cfg[DIFF_SRC_LAYER].dt, tag::any);
auto diff_src_iter_d = dnn_mem_t::init_md(
4, src_iter_dims, prb.cfg[DIFF_SRC_ITER].dt, tag::any);
auto diff_src_iter_c_d = dnn_mem_t::init_md(
4, src_iter_c_dims, prb.cfg[DIFF_SRC_ITER_C].dt, tag::any);
auto diff_weights_layer_d = dnn_mem_t::init_md(5, weights_layer_dims,
prb.cfg[DIFF_WEIGHTS_LAYER].dt, tag::any);
auto diff_weights_iter_d = dnn_mem_t::init_md(
5, weights_iter_dims, prb.cfg[DIFF_WEIGHTS_ITER].dt, tag::any);
dnnl_memory_desc_t diff_attention_d {};
if (prb.is_augru())
diff_attention_d = dnn_mem_t::init_md(3, attention_dims,
prb.cfg[DIFF_AUGRU_ATTENTION].dt, tag::abx /* dnnl_tnc */);
dnnl_memory_desc_t diff_weights_peephole_d {};
if (prb.is_lstm_peephole())
diff_weights_peephole_d = dnn_mem_t::init_md(4,
weights_peephole_dims, prb.cfg[DIFF_WEIGHTS_PEEPHOLE].dt,
tag::abx /* dnnl_ldgo */);
dnnl_memory_desc_t diff_weights_projection_d {};
if (prb.is_lstm_projection())
diff_weights_projection_d
= dnn_mem_t::init_md(4, weights_projection_dims,
prb.cfg[DIFF_WEIGHTS_PROJECTION].dt, tag::any);
auto diff_bias_d = dnn_mem_t::init_md(
4, bias_dims, prb.cfg[DIFF_BIAS].dt, tag::any);
auto diff_dst_layer_d = dnn_mem_t::init_md(
3, dst_layer_dims, prb.cfg[DIFF_DST_LAYER].dt, tag::any);
auto diff_dst_iter_d = dnn_mem_t::init_md(
4, dst_iter_dims, prb.cfg[DIFF_DST_ITER].dt, tag::any);
auto diff_dst_iter_c_d = dnn_mem_t::init_md(
4, dst_iter_c_dims, prb.cfg[DIFF_DST_ITER_C].dt, tag::any);
DNN_SAFE_STATUS(init_rnn_bwd_desc(&rd, prb, prb.prop, &src_layer_d,
&src_iter_d, &src_iter_c_d, &attention_d, &weights_layer_d,
&weights_iter_d, &weights_peephole_d, &weights_projection_d,
&bias_d, &dst_layer_d, &dst_iter_d, &dst_iter_c_d,
&diff_src_layer_d, &diff_src_iter_d, &diff_src_iter_c_d,
&diff_attention_d, &diff_weights_layer_d, &diff_weights_iter_d,
&diff_weights_peephole_d, &diff_weights_projection_d,
&diff_bias_d, &diff_dst_layer_d, &diff_dst_iter_d,
&diff_dst_iter_c_d));
}
auto dnnl_attr = make_benchdnn_dnnl_wrapper(create_dnnl_rnn_attr(prb));
return dnnl_primitive_desc_create(&rpd, &rd, dnnl_attr, engine, nullptr);
}
void skip_unimplemented_prb(const prb_t *prb_, res_t *res) {
const prb_t &prb = *prb_;
dir_t dir = str2dir(prop2str(prb.prop));
skip_unimplemented_data_type({prb.cfg[SRC_LAYER].dt}, dir, res);
skip_unimplemented_sum_po(prb.attr, res);
#if !defined(DNNL_X64) || DNNL_X64 == 0 \
|| DNNL_CPU_RUNTIME == DNNL_RUNTIME_THREADPOOL
// int8 is not supported altogether since RNN relies on packed IGEMM
// FIXME: this will disable int8 RNN testing if the library is built with
// Intel MKL that does have packed IGEMM
if (prb.is_int8()) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
#endif
// int8 weights reorder does not support non trivial strides;
// only LSTM and GRU cell kinds support int8 so far;
if (prb.is_int8()) {
if (!prb.trivial_strides) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
if (prb.alg != VANILLA_LSTM && prb.alg != VANILLA_GRU) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
}
// LSTM w/ projection is not supported for bf16
if (prb.is_lstm_projection() && prb.cfg[SRC_LAYER].dt == dnnl_bf16) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
// GPU limitations for RNN
if (is_gpu()) {
bool is_AUGRU = prb.alg == VANILLA_AUGRU || prb.alg == LBR_AUGRU;
if (is_AUGRU) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
if (prb.is_lstm_projection() || prb.is_lstm_peephole()) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
if (prb.is_int8() && prb.alg != VANILLA_LSTM) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
// Implemented only for CPU
if (prb.cfg[BIAS].dt == dnnl_bf16 || prb.cfg[SRC_ITER_C].dt == dnnl_bf16
|| prb.cfg[DST_ITER_C].dt == dnnl_bf16) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
}
}
void skip_invalid_prb(const prb_t *prb_, res_t *res) {
const prb_t &prb = *prb_;
#if DNNL_CPU_RUNTIME != DNNL_RUNTIME_NONE
// only AMX LSTM cell kinds support signed int8 so far;
if (prb.is_s8()) {
static auto isa = dnnl_get_effective_cpu_isa();
if (prb.alg != VANILLA_LSTM
|| !dnnl::is_superset(isa, dnnl_cpu_isa_avx512_core_amx)) {
res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED;
return;
}
}
#endif
// Consistency validation.
bool consistent_proj
= IMPLICATION(!prb.with_projection, prb.dhc == prb.dic);
bool consistent_L = IMPLICATION(prb.n_layer > 1, prb.slc == prb.dic);
bool consistent_T = IMPLICATION(prb.n_iter > 1, prb.sic == prb.dic);
bool is_GRU = prb.alg == VANILLA_GRU || prb.alg == LBR_GRU;
bool consistent_GRU = IMPLICATION(is_GRU, prb.sic == prb.dic);
bool is_AUGRU = prb.alg == VANILLA_AUGRU || prb.alg == LBR_AUGRU;
bool consistent_AUGRU = IMPLICATION(is_AUGRU,
prb.sic == prb.dic && prb.n_layer == 1
&& prb.direction == dnnl_unidirectional_left2right);
if (!consistent_proj || !consistent_L || !consistent_T || !consistent_GRU
|| !consistent_AUGRU) {
res->state = SKIPPED, res->reason = INVALID_CASE;
return;
}
// Only LSTM supports peephole and projection layer.
bool is_lstm_peephole
= IMPLICATION(prb.with_peephole, prb.alg == VANILLA_LSTM);
bool is_lstm_projection
= IMPLICATION(prb.with_projection, prb.alg == VANILLA_LSTM);
if (!is_lstm_peephole || !is_lstm_projection) {
res->state = SKIPPED, res->reason = INVALID_CASE;
return;
}
}
void setup_cmp(compare::compare_t &cmp, const prb_t *prb, data_kind_t kind,
const args_t &ref_args) {
const auto rnn_kind = data_kind2rnn_data_kind(kind);
const auto &cfg = prb->cfg[rnn_kind];
// factor 2 is because of the sum of 2 GEMMs
int64_t fwd_acc_dim = 2 * prb->n_gates() + 1;
if (prb->alg == VANILLA_GRU || prb->alg == VANILLA_AUGRU)
fwd_acc_dim *= prb->sic;
int64_t bwdd_acc_dim = prb->n_gates() * prb->dhc;
int64_t bwdw_acc_dim = prb->mb;
int64_t acc_dim = fwd_acc_dim;
if (prb->prop == dnnl_backward) acc_dim *= MAX2(bwdd_acc_dim, bwdw_acc_dim);
// Here the factor 4 just gives some wiggle room for fp32 testing
float trh = 4
* (1 + (prb->prop == dnnl_backward)) // double wiggle room for bwd
* ((prb->direction == dnnl_bidirectional_sum)
+ 1) // double trh if bidir_sum
* ceilf(log2f(acc_dim * prb->n_iter)) * cfg.eps;
// expect exact value for int8
if (cfg.dt == dnnl_u8 || cfg.dt == dnnl_s8) trh = 0.f;
cmp.set_threshold(trh);
// Note: we do an eltwise comparison only when:
// - we use skip_nonlinear;
// - we do not use skip_nonlinear and we test only one cell execution;
// - for int8 computations the tensor is not DST_ITER_C;
// If the above conditions are not met, we check only L1, L2 and L8.
// Rough rationale for the `DST_ITER_C` exception in int8 case:
// - The formula for one-step c-state is:
// c_t = f_t * c_{t−1} + i_t * c~_t.
// Here all computations happen in f32 (f_t, i_t, and c~_t are dequantized
// right before the computations + the corresponding bias added).
// - In int8 case we don't have much control over these components and
// cannot surmount potential cancellations, if any.
// In practice, I observed that the relative element-wise error of values
// in `DST_ITER_C` was bigger (up-to 8e-5) whenever the values
// themselves were smaller (which indirectly means the problem is exactly
// in the cancellation). Unfortunately, this even happened with only one
// layer and one time stamp.
// - So, for now the solution is to use l1- l2- and l_inf-norms to validate
// `DST_ITER_C`. When we switch testing on using precise
// integer arithmetic based on modulo operation in rnn_tparams (instead of
// current unreliable re-scaling), this testing weakness should go away.
// - Just an obvious side note: `DST_LAYER` and `DST_ITER`
// are immediate dequantization of the corresponding u8 tensors. Hence,
// as long as we get precise u8 intermediate results (and so far we do),
// the f32 result should be pretty accurate -- the dequantization is just
// two simple ops: f32 = scale * u8 + shift.
bool check_p2p = (prb->skip_nonlinear
|| ((prb->n_layer == 1) && (prb->n_iter == 1)));
if (prb->is_int8() && rnn_kind == DST_ITER_C) check_p2p = false;
cmp.set_norm_validation_mode(!check_p2p);
const auto rnn_add_check =
[&, prb](const compare::compare_t::driver_check_func_args_t &args) {
// Limitation from current filling.
// TODO: find a better filling to get rid of this...
if ((prb->alg == LBR_GRU || prb->alg == LBR_AUGRU
|| prb->alg == VANILLA_RNN)
&& prb->prop == dnnl_backward) {
return args.diff < args.trh;
}
return false;
};
cmp.set_driver_check_function(rnn_add_check);
}
int doit(const prb_t &prb, res_t *res) {
if (bench_mode == LIST) return res->state = LISTED, OK;
benchdnn_dnnl_wrapper_t<dnnl_primitive_t> prim;
SAFE(init_prim(prim, init_pd, &prb, res), WARN);
if (res->state == SKIPPED || res->state == UNIMPLEMENTED) return OK;
auto const_fpd = query_pd(prim);
if (check_mem_size(const_fpd) != OK) {
return res->state = SKIPPED, res->reason = NOT_ENOUGH_RAM, OK;
}
const auto &src_layer_md = query_md(const_fpd, DNNL_ARG_SRC_LAYER);
const auto &src_layer_attention_md
= query_md(const_fpd, DNNL_ARG_AUGRU_ATTENTION);
const auto &src_iter_md = query_md(const_fpd, DNNL_ARG_SRC_ITER);
const auto &src_iter_c_md = query_md(const_fpd, DNNL_ARG_SRC_ITER_C);
const auto &weights_layer_md = query_md(const_fpd, DNNL_ARG_WEIGHTS_LAYER);
const auto &weights_iter_md = query_md(const_fpd, DNNL_ARG_WEIGHTS_ITER);
const auto &weights_peephole_md
= query_md(const_fpd, DNNL_ARG_WEIGHTS_PEEPHOLE);
const auto &weights_projection_md
= query_md(const_fpd, DNNL_ARG_WEIGHTS_PROJECTION);
const auto &bias_md = query_md(const_fpd, DNNL_ARG_BIAS);
const auto &dst_layer_md = query_md(const_fpd, DNNL_ARG_DST_LAYER);
const auto &dst_iter_md = query_md(const_fpd, DNNL_ARG_DST_ITER);
const auto &dst_iter_c_md = query_md(const_fpd, DNNL_ARG_DST_ITER_C);
const auto &workspace_md = query_md(const_fpd, DNNL_ARG_WORKSPACE);
const auto &scratchpad_md = query_md(const_fpd, DNNL_ARG_SCRATCHPAD);
const auto &test_engine = get_test_engine();
const auto &ref_engine = get_cpu_engine();
dnn_mem_t src_layer_dt(src_layer_md, test_engine);
dnn_mem_t src_layer_attention_dt(src_layer_attention_md, test_engine);
dnn_mem_t src_iter_dt(src_iter_md, test_engine);
dnn_mem_t src_iter_c_dt(src_iter_c_md, test_engine);
dnn_mem_t weights_layer_dt(weights_layer_md, test_engine);
dnn_mem_t weights_iter_dt(weights_iter_md, test_engine);
dnn_mem_t weights_peephole_dt(weights_peephole_md, test_engine);
dnn_mem_t weights_projection_dt(weights_projection_md, test_engine);
dnn_mem_t bias_dt(bias_md, test_engine);
dnn_mem_t dst_layer_dt(dst_layer_md, test_engine);
dnn_mem_t dst_iter_dt(dst_iter_md, test_engine);
dnn_mem_t dst_iter_c_dt(dst_iter_c_md, test_engine);
dnn_mem_t workspace_dt(workspace_md, test_engine);
dnn_mem_t scratchpad_dt(scratchpad_md, test_engine);
dnn_mem_t src_layer_fp(
src_layer_md, dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t src_layer_attention_fp(
src_layer_attention_md, dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t src_iter_fp(src_iter_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t src_iter_c_fp(
src_iter_c_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t weights_layer_fp(
weights_layer_md, dnnl_f32, tag::abx /*ldigo*/, ref_engine);
dnn_mem_t weights_iter_fp(
weights_iter_md, dnnl_f32, tag::abx /*ldigo*/, ref_engine);
dnn_mem_t weights_peephole_fp(
weights_peephole_md, dnnl_f32, tag::abx /*ldgo*/, ref_engine);
dnn_mem_t weights_projection_fp(
weights_projection_md, dnnl_f32, tag::abx /*ldio*/, ref_engine);
dnn_mem_t bias_fp(bias_md, dnnl_f32, tag::abx /*ldgo*/, ref_engine);
dnn_mem_t dst_layer_fp(
dst_layer_md, dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t dst_iter_fp(dst_iter_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t dst_iter_c_fp(
dst_iter_c_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t bwd_weights_layer_dt;
dnn_mem_t bwd_weights_iter_dt;
dnn_mem_t bwd_weights_projection_dt;
dnn_mem_t diff_src_layer_dt;
dnn_mem_t diff_src_layer_attention_dt;
dnn_mem_t diff_src_iter_dt;
dnn_mem_t diff_src_iter_c_dt;
dnn_mem_t diff_weights_layer_dt;
dnn_mem_t diff_weights_iter_dt;
dnn_mem_t diff_weights_peephole_dt;
dnn_mem_t diff_weights_projection_dt;
dnn_mem_t diff_bias_dt;
dnn_mem_t diff_dst_layer_dt;
dnn_mem_t diff_dst_iter_dt;
dnn_mem_t diff_dst_iter_c_dt;
// for int8 RNN we need pass attributes for data q10n
auto rnn_attr = query_attr(const_fpd);
SAFE(fill_activation(prb, SRC_LAYER, src_layer_dt, src_layer_fp, rnn_attr),
WARN);
if (prb.alg == VANILLA_AUGRU || prb.alg == LBR_AUGRU)
SAFE(fill_activation(prb, AUGRU_ATTENTION, src_layer_attention_dt,
src_layer_attention_fp, rnn_attr),
WARN);
SAFE(fill_activation(prb, SRC_ITER, src_iter_dt, src_iter_fp, rnn_attr),
WARN);
if (prb.alg == VANILLA_LSTM)
SAFE(fill_src_iter_c(prb, src_iter_c_dt, src_iter_c_fp, rnn_attr),
WARN);
SAFE(fill_weights(prb, WEIGHTS_LAYER, weights_layer_dt, weights_layer_fp,
rnn_attr),
WARN);
SAFE(fill_weights(
prb, WEIGHTS_ITER, weights_iter_dt, weights_iter_fp, rnn_attr),
WARN);
SAFE(fill_memory(prb, WEIGHTS_PEEPHOLE, weights_peephole_dt,
weights_peephole_fp),
WARN);
SAFE(fill_weights(prb, WEIGHTS_PROJECTION, weights_projection_dt,
weights_projection_fp, rnn_attr),
WARN);
SAFE(fill_memory(prb, BIAS, bias_dt, bias_fp), WARN);
SAFE(fill_activation(prb, DST_LAYER, dst_layer_dt, dst_layer_fp), WARN);
SAFE(fill_activation(prb, DST_ITER, dst_iter_dt, dst_iter_fp), WARN);
if (prb.alg == VANILLA_LSTM)
SAFE(fill_memory(prb, DST_ITER_C, dst_iter_c_dt, dst_iter_c_fp), WARN);
args_t args, ref_args;
// Running the forward pass
args.set(DNNL_ARG_SRC_LAYER, src_layer_dt);
args.set(DNNL_ARG_AUGRU_ATTENTION, src_layer_attention_dt);
args.set(DNNL_ARG_SRC_ITER, src_iter_dt);
args.set(DNNL_ARG_SRC_ITER_C, src_iter_c_dt);
args.set(DNNL_ARG_WEIGHTS_LAYER, weights_layer_dt);
args.set(DNNL_ARG_WEIGHTS_ITER, weights_iter_dt);
args.set(DNNL_ARG_WEIGHTS_PEEPHOLE, weights_peephole_dt);
args.set(DNNL_ARG_WEIGHTS_PROJECTION, weights_projection_dt);
args.set(DNNL_ARG_BIAS, bias_dt);
args.set(DNNL_ARG_DST_LAYER, dst_layer_dt);
args.set(DNNL_ARG_DST_ITER, dst_iter_dt);
args.set(DNNL_ARG_DST_ITER_C, dst_iter_c_dt);
args.set(DNNL_ARG_WORKSPACE, workspace_dt);
args.set(DNNL_ARG_SCRATCHPAD, scratchpad_dt);
SAFE(execute_and_wait(prim, args, res), WARN);
if (prb.prop != dnnl_backward) {
if (is_bench_mode(CORR)) {
ref_args.set(DNNL_ARG_SRC_LAYER, src_layer_fp);
ref_args.set(DNNL_ARG_AUGRU_ATTENTION, src_layer_attention_fp);
ref_args.set(DNNL_ARG_SRC_ITER, src_iter_fp);
ref_args.set(DNNL_ARG_SRC_ITER_C, src_iter_c_fp);
ref_args.set(DNNL_ARG_WEIGHTS_LAYER, weights_layer_fp);
ref_args.set(DNNL_ARG_WEIGHTS_ITER, weights_iter_fp);
ref_args.set(DNNL_ARG_WEIGHTS_PEEPHOLE, weights_peephole_fp);
ref_args.set(DNNL_ARG_WEIGHTS_PROJECTION, weights_projection_fp);
ref_args.set(DNNL_ARG_BIAS, bias_fp);
ref_args.set(DNNL_ARG_DST_LAYER, dst_layer_fp);
ref_args.set(DNNL_ARG_DST_ITER, dst_iter_fp);
ref_args.set(DNNL_ARG_DST_ITER_C, dst_iter_c_fp);
std::vector<data_kind_t> kinds {
data_kind_t::DST, data_kind_t::DST_ITER};
if (prb.alg == VANILLA_LSTM) {
kinds.push_back(data_kind_t::DST_ITER_C);
}
check_correctness(&prb, kinds, args, ref_args, setup_cmp, res);
}
} else {
benchdnn_dnnl_wrapper_t<dnnl_primitive_t> tmp_prim;
SAFE(init_prim(tmp_prim, init_pd, &prb, res, FLAG_BWD), WARN);
if (res->state == SKIPPED || res->state == UNIMPLEMENTED) return OK;
prim.reset(tmp_prim.release());
auto const_bpd = query_pd(prim);
if (check_mem_size(const_bpd) != OK) {
return res->state = SKIPPED, res->reason = NOT_ENOUGH_RAM, OK;
}
const auto &bwd_weights_layer_md
= query_md(const_bpd, DNNL_ARG_WEIGHTS_LAYER);
const auto &bwd_weights_iter_md
= query_md(const_bpd, DNNL_ARG_WEIGHTS_ITER);
const auto &bwd_weights_projection_md
= query_md(const_bpd, DNNL_ARG_WEIGHTS_PROJECTION);
const auto &diff_src_layer_md
= query_md(const_bpd, DNNL_ARG_DIFF_SRC_LAYER);
const auto &diff_src_layer_attention_md
= query_md(const_bpd, DNNL_ARG_DIFF_AUGRU_ATTENTION);
const auto &diff_src_iter_md
= query_md(const_bpd, DNNL_ARG_DIFF_SRC_ITER);
const auto &diff_src_iter_c_md
= query_md(const_bpd, DNNL_ARG_DIFF_SRC_ITER_C);
const auto &diff_weights_layer_md
= query_md(const_bpd, DNNL_ARG_DIFF_WEIGHTS_LAYER);
const auto &diff_weights_iter_md
= query_md(const_bpd, DNNL_ARG_DIFF_WEIGHTS_ITER);
const auto &diff_weights_peephole_md
= query_md(const_bpd, DNNL_ARG_DIFF_WEIGHTS_PEEPHOLE);
const auto &diff_weights_projection_md
= query_md(const_bpd, DNNL_ARG_DIFF_WEIGHTS_PROJECTION);
const auto &diff_bias_md = query_md(const_bpd, DNNL_ARG_DIFF_BIAS);
const auto &diff_dst_layer_md
= query_md(const_bpd, DNNL_ARG_DIFF_DST_LAYER);
const auto &diff_dst_iter_md
= query_md(const_bpd, DNNL_ARG_DIFF_DST_ITER);
const auto &diff_dst_iter_c_md
= query_md(const_bpd, DNNL_ARG_DIFF_DST_ITER_C);
const auto &bwd_scratchpad_md
= query_md(const_bpd, DNNL_ARG_SCRATCHPAD);
bwd_weights_layer_dt = dnn_mem_t(bwd_weights_layer_md, test_engine);
bwd_weights_iter_dt = dnn_mem_t(bwd_weights_iter_md, test_engine);
bwd_weights_projection_dt
= dnn_mem_t(bwd_weights_projection_md, test_engine);
diff_src_layer_dt = dnn_mem_t(diff_src_layer_md, test_engine);
diff_src_layer_attention_dt
= dnn_mem_t(diff_src_layer_attention_md, test_engine);
diff_src_iter_dt = dnn_mem_t(diff_src_iter_md, test_engine);
diff_src_iter_c_dt = dnn_mem_t(diff_src_iter_c_md, test_engine);
diff_weights_layer_dt = dnn_mem_t(diff_weights_layer_md, test_engine);
diff_weights_iter_dt = dnn_mem_t(diff_weights_iter_md, test_engine);
diff_weights_peephole_dt
= dnn_mem_t(diff_weights_peephole_md, test_engine);
diff_weights_projection_dt
= dnn_mem_t(diff_weights_projection_md, test_engine);
diff_bias_dt = dnn_mem_t(diff_bias_md, test_engine);
diff_dst_layer_dt = dnn_mem_t(diff_dst_layer_md, test_engine);
diff_dst_iter_dt = dnn_mem_t(diff_dst_iter_md, test_engine);
diff_dst_iter_c_dt = dnn_mem_t(diff_dst_iter_c_md, test_engine);
scratchpad_dt = dnn_mem_t(bwd_scratchpad_md, test_engine);
dnn_mem_t diff_src_layer_fp(
diff_src_layer_md, dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t diff_src_layer_attention_fp(diff_src_layer_attention_md,
dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t diff_src_iter_fp(
diff_src_iter_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t diff_src_iter_c_fp(
diff_src_iter_c_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t diff_weights_layer_fp(diff_weights_layer_md, dnnl_f32,
tag::abx /*ldigo*/, ref_engine);
dnn_mem_t diff_weights_iter_fp(
diff_weights_iter_md, dnnl_f32, tag::abx /*ldigo*/, ref_engine);
dnn_mem_t diff_weights_peephole_fp(diff_weights_peephole_md, dnnl_f32,
tag::abx /*ldgo*/, ref_engine);
dnn_mem_t diff_weights_projection_fp(diff_weights_projection_md,
dnnl_f32, tag::abx /*ldio*/, ref_engine);
dnn_mem_t diff_bias_fp(
diff_bias_md, dnnl_f32, tag::abx /*ldgo*/, ref_engine);
dnn_mem_t diff_dst_layer_fp(
diff_dst_layer_md, dnnl_f32, tag::abx /*tnc*/, ref_engine);
dnn_mem_t diff_dst_iter_fp(
diff_dst_iter_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
dnn_mem_t diff_dst_iter_c_fp(
diff_dst_iter_c_md, dnnl_f32, tag::abx /*ldnc*/, ref_engine);
SAFE(bwd_weights_iter_dt.reorder(weights_iter_dt), WARN);
SAFE(bwd_weights_layer_dt.reorder(weights_layer_dt), WARN);
if (prb.is_lstm_projection())
SAFE(bwd_weights_projection_dt.reorder(weights_projection_dt),
WARN);
SAFE(fill_activation(
prb, DIFF_SRC_LAYER, diff_src_layer_dt, diff_src_layer_fp),
WARN);
if (prb.alg == VANILLA_AUGRU || prb.alg == LBR_AUGRU)
SAFE(fill_activation(prb, DIFF_AUGRU_ATTENTION,
diff_src_layer_attention_dt,
diff_src_layer_attention_fp),
WARN);
SAFE(fill_activation(
prb, DIFF_SRC_ITER, diff_src_iter_dt, diff_src_iter_fp),
WARN);
if (prb.alg == VANILLA_LSTM)
SAFE(fill_memory(prb, DIFF_SRC_ITER_C, diff_src_iter_c_dt,
diff_src_iter_c_fp),
WARN);
SAFE(fill_weights(prb, DIFF_WEIGHTS_LAYER, diff_weights_layer_dt,
diff_weights_layer_fp),
WARN);
SAFE(fill_weights(prb, DIFF_WEIGHTS_ITER, diff_weights_iter_dt,
diff_weights_iter_fp),
WARN);
SAFE(fill_memory(prb, DIFF_WEIGHTS_PEEPHOLE, diff_weights_peephole_dt,
diff_weights_peephole_fp),
WARN);
SAFE(fill_memory(prb, DIFF_WEIGHTS_PROJECTION,
diff_weights_projection_dt, diff_weights_projection_fp),
WARN);
SAFE(fill_bias(prb, DIFF_BIAS, diff_bias_dt, diff_bias_fp), WARN);
SAFE(fill_activation(
prb, DIFF_DST_LAYER, diff_dst_layer_dt, diff_dst_layer_fp),
WARN);
SAFE(fill_activation(
prb, DIFF_DST_ITER, diff_dst_iter_dt, diff_dst_iter_fp),
WARN);
if (prb.alg == VANILLA_LSTM)
SAFE(fill_memory(prb, DIFF_DST_ITER_C, diff_dst_iter_c_dt,
diff_dst_iter_c_fp),
WARN);
args.clear();
args.set(DNNL_ARG_SRC_LAYER, src_layer_dt);
args.set(DNNL_ARG_AUGRU_ATTENTION, src_layer_attention_dt);
args.set(DNNL_ARG_SRC_ITER, src_iter_dt);
args.set(DNNL_ARG_SRC_ITER_C, src_iter_c_dt);
args.set(DNNL_ARG_WEIGHTS_LAYER, bwd_weights_layer_dt);
args.set(DNNL_ARG_WEIGHTS_ITER, bwd_weights_iter_dt);
args.set(DNNL_ARG_WEIGHTS_PEEPHOLE, weights_peephole_dt);
args.set(DNNL_ARG_WEIGHTS_PROJECTION, bwd_weights_projection_dt);
args.set(DNNL_ARG_BIAS, bias_dt);
args.set(DNNL_ARG_DST_LAYER, dst_layer_dt);
args.set(DNNL_ARG_DST_ITER, dst_iter_dt);
args.set(DNNL_ARG_DST_ITER_C, dst_iter_c_dt);
args.set(DNNL_ARG_DIFF_DST_LAYER, diff_dst_layer_dt);
args.set(DNNL_ARG_DIFF_DST_ITER, diff_dst_iter_dt);
args.set(DNNL_ARG_DIFF_DST_ITER_C, diff_dst_iter_c_dt);
args.set(DNNL_ARG_WORKSPACE, workspace_dt);
args.set(DNNL_ARG_DIFF_SRC_LAYER, diff_src_layer_dt);
args.set(DNNL_ARG_DIFF_AUGRU_ATTENTION, diff_src_layer_attention_dt);
args.set(DNNL_ARG_DIFF_SRC_ITER, diff_src_iter_dt);
args.set(DNNL_ARG_DIFF_SRC_ITER_C, diff_src_iter_c_dt);
args.set(DNNL_ARG_DIFF_WEIGHTS_LAYER, diff_weights_layer_dt);
args.set(DNNL_ARG_DIFF_WEIGHTS_ITER, diff_weights_iter_dt);
args.set(DNNL_ARG_DIFF_WEIGHTS_PEEPHOLE, diff_weights_peephole_dt);
args.set(DNNL_ARG_DIFF_WEIGHTS_PROJECTION, diff_weights_projection_dt);
args.set(DNNL_ARG_DIFF_BIAS, diff_bias_dt);
args.set(DNNL_ARG_SCRATCHPAD, scratchpad_dt);
SAFE(execute_and_wait(prim, args, res), WARN);
if (is_bench_mode(CORR)) {
ref_args.set(DNNL_ARG_SRC_LAYER, src_layer_fp);
ref_args.set(DNNL_ARG_AUGRU_ATTENTION, src_layer_attention_fp);
ref_args.set(DNNL_ARG_SRC_ITER, src_iter_fp);
ref_args.set(DNNL_ARG_SRC_ITER_C, src_iter_c_fp);
ref_args.set(DNNL_ARG_WEIGHTS_LAYER, weights_layer_fp);
ref_args.set(DNNL_ARG_WEIGHTS_ITER, weights_iter_fp);
ref_args.set(DNNL_ARG_WEIGHTS_PEEPHOLE, weights_peephole_fp);
ref_args.set(DNNL_ARG_WEIGHTS_PROJECTION, weights_projection_fp);
ref_args.set(DNNL_ARG_BIAS, bias_fp);
ref_args.set(DNNL_ARG_DST_LAYER, dst_layer_fp);
ref_args.set(DNNL_ARG_DST_ITER, dst_iter_fp);
ref_args.set(DNNL_ARG_DST_ITER_C, dst_iter_c_fp);
ref_args.set(DNNL_ARG_DIFF_DST_LAYER, diff_dst_layer_fp);
ref_args.set(DNNL_ARG_DIFF_DST_ITER, diff_dst_iter_fp);
ref_args.set(DNNL_ARG_DIFF_DST_ITER_C, diff_dst_iter_c_fp);
ref_args.set(DNNL_ARG_DIFF_SRC_LAYER, diff_src_layer_fp);
ref_args.set(
DNNL_ARG_DIFF_AUGRU_ATTENTION, diff_src_layer_attention_fp);
ref_args.set(DNNL_ARG_DIFF_SRC_ITER, diff_src_iter_fp);
ref_args.set(DNNL_ARG_DIFF_SRC_ITER_C, diff_src_iter_c_fp);
ref_args.set(DNNL_ARG_DIFF_WEIGHTS_LAYER, diff_weights_layer_fp);
ref_args.set(DNNL_ARG_DIFF_WEIGHTS_ITER, diff_weights_iter_fp);
ref_args.set(
DNNL_ARG_DIFF_WEIGHTS_PEEPHOLE, diff_weights_peephole_fp);
ref_args.set(DNNL_ARG_DIFF_WEIGHTS_PROJECTION,
diff_weights_projection_fp);
ref_args.set(DNNL_ARG_DIFF_BIAS, diff_bias_fp);
std::vector<data_kind_t> kinds {data_kind_t::DST,
data_kind_t::DST_ITER, data_kind_t::SRC,
data_kind_t::SRC_ITER, data_kind_t::WEI,
data_kind_t::WEI_ITER, data_kind_t::BIA};
if (prb.alg == VANILLA_LSTM) {
kinds.push_back(data_kind_t::DST_ITER_C);
kinds.push_back(data_kind_t::SRC_ITER_C);
}
if (prb.alg == VANILLA_AUGRU || prb.alg == LBR_AUGRU)
kinds.push_back(data_kind_t::AUGRU_ATTENTION);
if (prb.is_lstm_peephole())
kinds.push_back(data_kind_t::WEI_PEEPHOLE);
if (prb.is_lstm_projection())
kinds.push_back(data_kind_t::WEI_PROJECTION);
check_correctness(&prb, kinds, args, ref_args, setup_cmp, res);
}
}
return measure_perf(res, prim, args);
}
} // namespace rnn
|
/**
* DeepDetect
* Copyright (c) 2018 Jolibrain
* Author: Corentin Barreau <corentin.barreau@epitech.eu>
*
* This file is part of deepdetect.
*
* deepdetect 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.
*
* deepdetect 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 deepdetect. If not, see <http://www.gnu.org/licenses/>.
*/
#include "outputconnectorstrategy.h"
#include <thread>
#include <algorithm>
#include "utils/utils.hpp"
// NCNN
#include "ncnnlib.h"
#include "ncnninputconns.h"
#include "cpu.h"
#include "net.h"
#include <iostream>
namespace dd
{
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
ncnn::UnlockedPoolAllocator
NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::_blob_pool_allocator
= ncnn::UnlockedPoolAllocator();
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
ncnn::PoolAllocator
NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::_workspace_pool_allocator
= ncnn::PoolAllocator();
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::NCNNLib(const NCNNModel &cmodel)
: MLLib<TInputConnectorStrategy, TOutputConnectorStrategy, NCNNModel>(
cmodel)
{
this->_libname = "ncnn";
_net = new ncnn::Net();
_net->opt.lightmode = true;
_net->opt.num_threads = _threads;
_net->opt.blob_allocator = &_blob_pool_allocator;
_net->opt.workspace_allocator = &_workspace_pool_allocator;
_net->opt.lightmode = _lightmode;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::NCNNLib(NCNNLib &&tl) noexcept
: MLLib<TInputConnectorStrategy, TOutputConnectorStrategy, NCNNModel>(
std::move(tl))
{
this->_libname = "ncnn";
_net = tl._net;
tl._net = nullptr;
_nclasses = tl._nclasses;
_threads = tl._threads;
_timeserie = tl._timeserie;
_old_height = tl._old_height;
_inputBlob = tl._inputBlob;
_outputBlob = tl._outputBlob;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::~NCNNLib()
{
delete _net;
_net = nullptr;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
void NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::init_mllib(const APIData &ad)
{
int res = _net->load_param(this->_mlmodel._params.c_str());
if (res != 0)
{
this->_logger->error(
"problem while loading ncnn params {} from repo {}",
this->_mlmodel._params, this->_mlmodel._repo);
throw MLLibBadParamException("could not load ncnn params ["
+ this->_mlmodel._params + "] from repo ["
+ this->_mlmodel._repo + "]");
}
res = _net->load_model(this->_mlmodel._weights.c_str());
if (res != 0)
{
this->_logger->error(
"problem while loading ncnn weigths {} from repo {}",
this->_mlmodel._weights, this->_mlmodel._repo);
throw MLLibBadParamException(
"could not load ncnn weights [" + this->_mlmodel._weights
+ "] from repo [" + this->_mlmodel._repo + "]");
}
_old_height = this->_inputc.height();
_net->set_input_h(_old_height);
if (ad.has("nclasses"))
_nclasses = ad.get("nclasses").get<int>();
if (ad.has("threads"))
_threads = ad.get("threads").get<int>();
else
_threads = dd_utils::my_hardware_concurrency();
_timeserie = this->_inputc._timeserie;
if (_timeserie)
this->_mltype = "timeserie";
if (ad.has("lightmode"))
{
_lightmode = ad.get("lightmode").get<bool>();
_net->opt.lightmode = _lightmode;
}
// setting the value of Input Layer
if (ad.has("inputblob"))
{
_inputBlob = ad.get("inputblob").get<std::string>();
}
// setting the final Output Layer
if (ad.has("outputblob"))
{
_outputBlob = ad.get("outputblob").get<std::string>();
}
_blob_pool_allocator.set_size_compare_ratio(0.0f);
_workspace_pool_allocator.set_size_compare_ratio(0.5f);
model_type(this->_mlmodel._params, this->_mltype);
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
void NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::clear_mllib(const APIData &ad)
{
(void)ad;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
int NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::train(const APIData &ad, APIData &out)
{
(void)ad;
(void)out;
return 0;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
int NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::predict(const APIData &ad, APIData &out)
{
TInputConnectorStrategy inputc(this->_inputc);
TOutputConnectorStrategy tout(this->_outputc);
this->_stats.transform_start();
try
{
inputc.transform(ad);
}
catch (...)
{
throw;
}
this->_stats.transform_end();
this->_stats.inc_inference_count(inputc._ids.size());
// if height (timestep) changes we need to clear net before recreating an
// extractor with new height, and to reload params and models after clear()
if (_old_height != -1 && _old_height != inputc.height())
{
// in case of new prediction with different timesteps value, clear old
// net
_net->clear();
_net->load_param(this->_mlmodel._params.c_str());
_net->load_model(this->_mlmodel._weights.c_str());
_old_height = inputc.height();
_net->set_input_h(_old_height);
}
ncnn::Extractor ex = _net->create_extractor();
ex.set_num_threads(_threads);
ex.input(_inputBlob.c_str(), inputc._in);
APIData ad_output = ad.getobj("parameters").getobj("output");
// Get bbox
bool bbox = false;
if (ad_output.has("bbox"))
bbox = ad_output.get("bbox").get<bool>();
// Ctc model
bool ctc = false;
int blank_label = -1;
if (ad_output.has("ctc"))
{
ctc = ad_output.get("ctc").get<bool>();
if (ctc)
{
if (ad_output.has("blank_label"))
blank_label = ad_output.get("blank_label").get<int>();
}
}
// Extract detection or classification
int ret = 0;
std::string out_blob = _outputBlob;
if (out_blob.empty())
{
if (bbox == true)
out_blob = "detection_out";
else if (ctc == true)
out_blob = "probs";
else if (_timeserie)
out_blob = "rnn_pred";
else
out_blob = "prob";
}
ret = ex.extract(out_blob.c_str(), inputc._out);
if (ret == -1)
{
throw MLLibInternalException("NCNN internal error");
}
std::vector<APIData> vrad;
std::vector<double> probs;
std::vector<std::string> cats;
std::vector<APIData> bboxes;
std::vector<APIData> series;
APIData rad;
// Get confidence_threshold
float confidence_threshold = 0.0;
if (ad_output.has("confidence_threshold"))
{
apitools::get_float(ad_output, "confidence_threshold",
confidence_threshold);
}
// Get best
int best = 1;
if (ad_output.has("best"))
{
best = ad_output.get("best").get<int>();
}
if (bbox == true)
{
for (int i = 0; i < inputc._out.h; i++)
{
const float *values = inputc._out.row(i);
if (values[1] < confidence_threshold)
continue;
cats.push_back(this->_mlmodel.get_hcorresp(values[0]));
probs.push_back(values[1]);
APIData ad_bbox;
ad_bbox.add("xmin",
static_cast<double>(values[2] * inputc.width()));
ad_bbox.add("ymin",
static_cast<double>(values[3] * inputc.height()));
ad_bbox.add("xmax",
static_cast<double>(values[4] * inputc.width()));
ad_bbox.add("ymax",
static_cast<double>(values[5] * inputc.height()));
bboxes.push_back(ad_bbox);
}
}
else if (ctc == true)
{
int alphabet = inputc._out.w;
int time_step = inputc._out.h;
std::vector<int> pred_label_seq_with_blank(time_step);
for (int t = 0; t < time_step; ++t)
{
const float *values = inputc._out.row(t);
pred_label_seq_with_blank[t] = std::distance(
values, std::max_element(values, values + alphabet));
}
std::vector<int> pred_label_seq;
int prev = blank_label;
for (int t = 0; t < time_step; ++t)
{
int cur = pred_label_seq_with_blank[t];
if (cur != prev && cur != blank_label)
pred_label_seq.push_back(cur);
prev = cur;
}
std::string outstr;
std::ostringstream oss;
for (auto l : pred_label_seq)
outstr += char(std::atoi(this->_mlmodel.get_hcorresp(l).c_str()));
cats.push_back(outstr);
probs.push_back(1.0);
}
else if (_timeserie)
{
std::vector<int> tsl = inputc._timeseries_lengths;
for (unsigned int tsi = 0; tsi < tsl.size(); ++tsi)
{
for (int ti = 0; ti < tsl[tsi]; ++ti)
{
std::vector<double> predictions;
for (int k = 0; k < inputc._ntargets; ++k)
{
double res = inputc._out.row(ti)[k];
predictions.push_back(inputc.unscale_res(res, k));
}
APIData ts;
ts.add("out", predictions);
series.push_back(ts);
}
}
}
else
{
std::vector<float> cls_scores;
cls_scores.resize(inputc._out.w);
for (int j = 0; j < inputc._out.w; j++)
{
cls_scores[j] = inputc._out[j];
}
int size = cls_scores.size();
std::vector<std::pair<float, int>> vec;
vec.resize(size);
for (int i = 0; i < size; i++)
{
vec[i] = std::make_pair(cls_scores[i], i);
}
std::partial_sort(vec.begin(), vec.begin() + best, vec.end(),
std::greater<std::pair<float, int>>());
for (int i = 0; i < best; i++)
{
if (vec[i].first < confidence_threshold)
continue;
cats.push_back(this->_mlmodel.get_hcorresp(vec[i].second));
probs.push_back(vec[i].first);
}
}
rad.add("uri", inputc._ids.at(0));
rad.add("loss", 0.0);
rad.add("cats", cats);
if (bbox == true)
rad.add("bboxes", bboxes);
if (_timeserie)
{
rad.add("series", series);
rad.add("probs", std::vector<double>(series.size(), 1.0));
}
else
rad.add("probs", probs);
if (_timeserie)
out.add("timeseries", true);
vrad.push_back(rad);
tout.add_results(vrad);
out.add("nclasses", this->_nclasses);
if (bbox == true)
out.add("bbox", true);
out.add("roi", false);
out.add("multibox_rois", false);
tout.finalize(ad.getobj("parameters").getobj("output"), out,
static_cast<MLModel *>(&this->_mlmodel));
out.add("status", 0);
return 0;
}
template <class TInputConnectorStrategy, class TOutputConnectorStrategy,
class TMLModel>
void NCNNLib<TInputConnectorStrategy, TOutputConnectorStrategy,
TMLModel>::model_type(const std::string ¶m_file,
std::string &mltype)
{
std::ifstream paramf(param_file);
std::stringstream content;
content << paramf.rdbuf();
std::size_t found_detection = content.str().find("DetectionOutput");
if (found_detection != std::string::npos)
{
mltype = "detection";
return;
}
std::size_t found_ocr = content.str().find("ContinuationIndicator");
if (found_ocr != std::string::npos)
{
mltype = "ctc";
return;
}
mltype = "classification";
}
template class NCNNLib<ImgNCNNInputFileConn, SupervisedOutput, NCNNModel>;
template class NCNNLib<CSVTSNCNNInputFileConn, SupervisedOutput, NCNNModel>;
}
|
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "Foundational/iwbits/iwbits.h"
#include "Foundational/iwstring/iwstring.h"
#define FIXED_SIZE_COUNTED_FINGERPRINT_IMPLEMENTATION
#include "fixed_size_counted_fingerprint.h"
/*
The fingerprint may or may not have a value for nset in it
*/
int
Fixed_Size_Counted_Fingerprint_uchar::construct_from_tdt_record (const const_IWSubstring & buffer)
{
assert (buffer.ends_with ('>'));
int open_angle_bracket = buffer.index ('<');
if (open_angle_bracket < 0)
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::construct_from_tdt_record:no < in TDT record, impossible\n";
return 0;
}
const_IWSubstring mybuffer (buffer);
mybuffer.remove_leading_chars (open_angle_bracket + 1);
mybuffer.chop ();
const_IWSubstring fp, other_info;
if (! mybuffer.split (fp, ';', other_info)) // just the fingerprint present, no info about nset or nbits
{
if (! _construct_from_tdt_record (mybuffer))
return 0;
_nbits = _n;
compute_nset ();
return 1;
}
if (! _construct_from_tdt_record (fp))
return 0;
// There is at least nset and maybe also nbits
const_IWSubstring token;
int i = 0;
other_info.nextword (token, i, ';');
if (! token.numeric_value (_nset) || _nset < 0)
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::construct_from_tdt_record:invalid nset value '" << token << "'\n";
return 0;
}
else
compute_nset ();
if (other_info.nextword (token, i, ';')) // info on nbits present
{
if (! token.numeric_value (_nbits) || _nbits < 0)
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::construct_from_tdt_record:invalid nbits value '" << token << "'\n";
return 0;
}
}
return _n;
}
int
Fixed_Size_Counted_Fingerprint_uchar::_construct_from_tdt_record (const const_IWSubstring & fp)
{
IW_Bits_Base b;
if (! b.construct_from_daylight_ascii_bit_rep (fp.rawchars (), fp.length ()))
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::_construct_from_tdt_record:invalid fingerprint data\n";
cerr << "'" << fp << "'\n";
return 0;
}
if (0 != b.nbits () % IW_BITS_PER_BYTE)
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::_construct_from_tdt_record:fingerprint representation contains " << b.nbits () << " bits, impossible\n";
return 0;
}
if (! resize (b.nbits () / IW_BITS_PER_BYTE)) // each count stored as an 8 bit byte
return 0;
memcpy (_count, b.bits (), _n);
return _n;
}
int
Fixed_Size_Counted_Fingerprint_uchar::write_daylight_ascii_representation (std::ostream & output,
const const_IWSubstring & tag,
int include_nset)
{
if (NULL == _count)
return 0;
if (include_nset && _nset <= 0)
compute_nset ();
IW_Bits_Base b;
if (! b.construct_from_array_of_bits (_count, _n))
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::write_daylight_ascii_representation:cannot allocate bits for n = " << _n << endl;
return 0;
}
IWString ascii;
b.daylight_ascii_representation (ascii);
output << tag << ascii;
if (include_nset)
output << ';' << _nset;
output << ">\n";
return output.good ();
}
int
Fixed_Size_Counted_Fingerprint_uchar::bits_in_common (const Fixed_Size_Counted_Fingerprint_uchar & rhs) const
{
int rc = 0;
for (int i = 0; i < _n; i++)
{
#ifdef DEBUG_FCBIC
int c = _count[i] * 256 + rhs._count[i];
cerr << " i = " << i << " lhs " << static_cast<int> (_count[i]) << " rhs " << static_cast<int> (rhs._count[i]) << " index " << c << endl;
cerr << " In common " << static_cast<int> (bic_table[c]) << endl;
#endif
// rc += bic_table[_count[i] * 256 + rhs._count[i]];
if (_count[i] < rhs._count[i])
rc += _count[i];
else
rc += rhs._count[i];
}
return rc;
}
/*static int
sum_vector_unsigned_char (const unsigned char * s,
int n)
{
int rc = 0;
for (int i = 0; i < n; i++)
{
rc += s[i];
}
return rc;
}*/
similarity_type_t
Fixed_Size_Counted_Fingerprint_uchar::tanimoto (const Fixed_Size_Counted_Fingerprint_uchar & rhs) const
{
int bic = bits_in_common (rhs);
//cerr << "Between fingerprints with " << _nset << " and " << rhs._nset << " bits set, bic " << bic << endl;
//assert (_n == rhs._n);
//assert (bic <= _nset);
//assert (bic <= rhs._nset);
if (0 == bic)
{
if (0 == _nset && 0 == rhs._nset)
return static_cast<similarity_type_t> (1.0);
return static_cast<similarity_type_t> (0.0);
}
return static_cast<float> (bic) / static_cast<float> (_nset + rhs._nset - bic);
}
int
Fixed_Size_Counted_Fingerprint_uchar::construct_from_array(unsigned char const* b, int nb)
{
if (! resize(nb))
{
cerr << "Fixed_Size_Counted_Fingerprint_uchar::construct_from_array:cannot size for " << nb << " bytes\n";
return 0;
}
_n = nb;
_nbits = nb;
_nset = 0;
for (int i = 0; i < _n; i++)
{
_count[i] = b[i];
if (_count[i])
_nset++;
}
return 1;
}
|
// --------------------------------------------------------------------------
// SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing
// --------------------------------------------------------------------------
// Copyright The SmartPeak Team -- Novo Nordisk Foundation
// Center for Biosustainability, Technical University of Denmark 2018-2021.
//
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Krzysztof Abram, Douglas McCloskey $
// $Authors: Douglas McCloskey $
// --------------------------------------------------------------------------
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <SmartPeak/test_config.h>
#include <algorithm>
#include <random>
#include <SmartPeak/cli/Parser.h>
#include <SmartPeak/cli/ApplicationSettings.h>
#include <SmartPeak/core/SampleType.h>
#include <SmartPeak/core/FeatureMetadata.h>
#include <SmartPeak/core/SharedProcessors.h>
#include <SmartPeak/core/Utilities.h>
struct ApplicationSettingsFixture : public ::testing::Test
{
/* ctor/dtor */
ApplicationSettingsFixture()
{
const auto argc = 27;
const char* argv[] = {
"ApplicationSettings_test",
"--report", "featureDB", "pivottable",
"--report-metadata", "PeAk_aRea", "Mz", "rt",
"--report-sample-types", "stanDard", "Unknown", "double blank",
"--load-session", "C:/SmartPeak/src/examples/data/GCMS_SIM_Unknowns/sequence.csv",
"--verbose",
"--allow-inconsistent",
"--workflow", "load_raw_data", "EXTRACT_SPECTRA_WINDOWS", "pick_ms1_features"
"SEARCH_ACCURATE_MASS", "LOAD_FeATURE_BACKGROUND_FILTERS",
"--log-dir", ".",
"--integrity", "SAMPLE", "is",
"--disable-colors"
};
m_parser_ptr = std::make_shared<SmartPeak::cli::Parser>(argc, argv);
m_application_settings_ptr = std::make_shared<SmartPeak::cli::ApplicationSettings>(*m_parser_ptr);
}
SmartPeak::cli::ApplicationSettings& get_application_settings() { return *m_application_settings_ptr; }
const SmartPeak::cli::ApplicationSettings& get_application_settings() const { return *m_application_settings_ptr; }
template<typename T>
bool option_exists(const std::string& option)
{
try
{
m_parser_ptr->get<T>(option);
}
catch (...)
{
return false;
}
return true;
}
public:
std::shared_ptr<SmartPeak::cli::Parser> m_parser_ptr;
std::shared_ptr<SmartPeak::cli::ApplicationSettings> m_application_settings_ptr;
};
/* ---------------------------------------------- */
TEST_F(ApplicationSettingsFixture, ApplicationSettings_define_options)
{
auto& application_settings = get_application_settings();
{
application_settings.define_options();
}
EXPECT_TRUE(option_exists<std::string>("l"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("r"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("rt"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("rm"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("w"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("t"));
EXPECT_TRUE(option_exists<std::string>("o"));
EXPECT_TRUE(option_exists<std::string>("i"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("p"));
EXPECT_TRUE(option_exists<std::vector<std::string>>("f"));
EXPECT_TRUE(option_exists<bool>("a"));
EXPECT_TRUE(option_exists<bool>("v"));
EXPECT_TRUE(option_exists<bool>("d"));
EXPECT_TRUE(option_exists<std::string>("ld"));
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_load_options)
{
auto& application_settings = get_application_settings();
{
application_settings.define_options();
application_settings.load_options();
}
EXPECT_EQ(application_settings.load_session,
"C:/SmartPeak/src/examples/data/GCMS_SIM_Unknowns/sequence.csv");
auto report = std::vector<std::string>{"featureDB", "pivottable"};
EXPECT_EQ(application_settings.report, report);
auto metadata = std::vector<std::string>{"PeAk_aRea", "Mz", "rt"};
EXPECT_EQ(application_settings.report_metadata, metadata);
auto samples = std::vector<std::string>{"stanDard", "Unknown", "double blank"};
EXPECT_EQ(application_settings.report_sample_types, samples);
EXPECT_TRUE(application_settings.verbose);
EXPECT_TRUE(application_settings.disable_colors);
EXPECT_TRUE(application_settings.allow_inconsistent);
auto workflow = std::vector<std::string>{
"load_raw_data", "EXTRACT_SPECTRA_WINDOWS", "pick_ms1_features"
"SEARCH_ACCURATE_MASS", "LOAD_FeATURE_BACKGROUND_FILTERS" };
EXPECT_EQ(application_settings.workflow, workflow);
EXPECT_EQ(application_settings.log_dir, ".");
auto integrity = std::vector<std::string>{"SAMPLE", "is"};
EXPECT_EQ(application_settings.integrity, integrity);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_process_options)
{
auto& application_settings = get_application_settings();
auto& parser = application_settings.get_parser();
{
application_settings.define_options();
application_settings.load_options();
application_settings.process_options();
}
auto report = std::vector<std::string>{"FEATUREDB", "PIVOTTABLE"};
EXPECT_EQ(application_settings.report, report);
auto metadata = std::vector<std::string>{"PEAK_AREA", "MZ", "RT"};
EXPECT_EQ(application_settings.report_metadata, metadata);
auto samples = std::vector<std::string>{"STANDARD", "UNKNOWN", "DOUBLE BLANK"};
EXPECT_EQ(application_settings.report_sample_types, samples);
auto workflow = std::vector<std::string>{
"LOAD_RAW_DATA", "EXTRACT_SPECTRA_WINDOWS", "PICK_MS1_FEATURES"
"SEARCH_ACCURATE_MASS", "LOAD_FEATURE_BACKGROUND_FILTERS" };
EXPECT_EQ(application_settings.workflow, workflow);
auto integrity = std::vector<std::string>{"SAMPLE", "IS"};
EXPECT_EQ(application_settings.integrity, integrity);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_contains_option)
{
using SmartPeak::cli::ApplicationSettings;
auto list = std::vector<std::string>{"string1", "string2", "string3"};
EXPECT_TRUE(ApplicationSettings::contains_option(list, "string1", "loginfo"));
EXPECT_TRUE(!ApplicationSettings::contains_option(list, "string4", "loginfo"));
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_validate_report)
{
auto& application_settings = get_application_settings();
application_settings.report = std::vector<std::string>{"FEATUREDB"};
EXPECT_NO_THROW(application_settings.validate_report());
application_settings.report = std::vector<std::string>{"PIVOTTABLE"};
EXPECT_NO_THROW(application_settings.validate_report());
application_settings.report = std::vector<std::string>{"FEATUREDB", "PIVOTTABLE"};
EXPECT_NO_THROW(application_settings.validate_report());
application_settings.report = std::vector<std::string>{"ALL"};
EXPECT_NO_THROW(application_settings.validate_report());
application_settings.report = std::vector<std::string>{"aksdng"};
EXPECT_THROW(application_settings.validate_report(), std::invalid_argument);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_validate_report_sample_types)
{
auto& application_settings = get_application_settings();
auto& available_types = SmartPeak::sampleTypeToString;
auto values = std::vector<std::string>{ "ALL" };
std::for_each(available_types.cbegin(), available_types.cend(),
[&values, &application_settings](const auto& t) {
auto str = SmartPeak::Utilities::str2upper(t.second);
values.push_back(str);
application_settings.report_sample_types = std::vector<std::string>{ str };
EXPECT_NO_THROW(application_settings.validate_report_sample_types());
application_settings.report_sample_types = values;
auto& rst = application_settings.report_sample_types;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(rst.begin(), rst.end(), g);
EXPECT_NO_THROW(application_settings.validate_report_sample_types());
});
application_settings.report_sample_types = std::vector<std::string>{"aksdng", "Standard"};
EXPECT_THROW(application_settings.validate_report_sample_types(), std::invalid_argument);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_validate_report_metadata)
{
auto& application_settings = get_application_settings();
auto& available = SmartPeak::metadataToString;
auto values = std::vector<std::string>{ "ALL" };
std::for_each(available.cbegin(), available.cend(),
[&values, &application_settings](const auto& t) {
auto str = SmartPeak::Utilities::str2upper(t.second);
values.push_back(str);
application_settings.report_metadata = std::vector<std::string>{ str };
EXPECT_NO_THROW(application_settings.validate_report_metadata());
application_settings.report_metadata = values;
auto& rm = application_settings.report_metadata;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(rm.begin(), rm.end(), g);
EXPECT_NO_THROW(application_settings.validate_report_metadata());
});
application_settings.report_metadata = std::vector<std::string>{"aksdng", "Standard"};
EXPECT_THROW(application_settings.validate_report_metadata(), std::invalid_argument);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_validate_workflow)
{
auto& application_settings = get_application_settings();
auto cmds_ = std::vector<std::string>{};
{
auto& cmds1 = SmartPeak::n_to_raw_data_method_;
auto& cmds2 = SmartPeak::n_to_seq_seg_method_;
auto& cmds3 = SmartPeak::n_to_sample_group_method_;
std::transform(cmds1.cbegin(), cmds1.cend(), std::back_inserter(cmds_), [](const auto& cmd) { return cmd.first; });
std::transform(cmds2.cbegin(), cmds2.cend(), std::back_inserter(cmds_), [](const auto& cmd) { return cmd.first; });
std::transform(cmds3.cbegin(), cmds3.cend(), std::back_inserter(cmds_), [](const auto& cmd) { return cmd.first; });
}
auto values = std::vector<std::string>{};
std::for_each(cmds_.cbegin(), cmds_.cend(),
[&values, &application_settings](const auto& t){
application_settings.workflow = std::vector<std::string>{ t };
EXPECT_NO_THROW(application_settings.validate_workflow());
values.push_back(t);
application_settings.workflow = values;
auto& w = application_settings.workflow;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(w.begin(), w.end(), g);
EXPECT_NO_THROW(application_settings.validate_workflow());
});
application_settings.workflow = std::vector<std::string>{"ASDFG", "LOAD_RAW_DATA"};
EXPECT_THROW(application_settings.validate_workflow(), std::invalid_argument);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_validate_integrity)
{
auto& application_settings = get_application_settings();
auto options = std::vector<std::string>{"SAMPLE", "COMP", "COMP_GROUP", "IS", "ALL", "NONE"};
auto values = std::vector<std::string>{};
std::for_each(options.cbegin(), options.cend(),
[&values, &application_settings](const auto& t) {
application_settings.integrity = std::vector<std::string>{ t };
EXPECT_NO_THROW(application_settings.validate_integrity());
values.push_back(t);
application_settings.integrity = values;
auto& i = application_settings.integrity;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(i.begin(), i.end(), g);
EXPECT_NO_THROW(application_settings.validate_integrity());
});
application_settings.integrity = std::vector<std::string>{"ASDFG", "COMP_GROUP"};
EXPECT_THROW(application_settings.validate_integrity(), std::invalid_argument);
}
TEST_F(ApplicationSettingsFixture, ApplicationSettings_get_key_value_from_option)
{
auto& application_settings = get_application_settings();
// one value
auto split_options_1 = application_settings.get_key_value_from_option("key1=value1");
std::pair<std::string, std::string> expected_split_options_1 = { std::string("key1"), std::string("value1") };
EXPECT_EQ(split_options_1, expected_split_options_1);
// empty
auto split_options_3 = application_settings.get_key_value_from_option("");
std::pair<std::string, std::string> expected_split_options_3 = { };
EXPECT_EQ(split_options_3, expected_split_options_3);
// surrounding quotes
auto split_options_4 = application_settings.get_key_value_from_option("key1=\"value1\"");
std::pair<std::string, std::string> expected_split_options_4 = { std::string("key1"), std::string("value1") };
EXPECT_EQ(split_options_4, expected_split_options_4);
}
|
//
// ulib - a collection of useful classes
// Copyright (C) 2006,2007,2008,2009,2012,2017,2020 Michael Fink
//
/// \file TestReaderWriterMutex.cpp tests for ReaderWriterMutex class
//
#include "stdafx.h"
#include "CppUnitTest.h"
#include <ulib/thread/ReaderWriterMutex.hpp>
#include <ulib/HighResolutionTimer.hpp>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest
{
const int DEFAULT_READERS = 1;
const int DEFAULT_WRITERS = 1;
const int DEFAULT_ITERATIONS = 2000000;
const int DEFAULT_READER_WORK_WHILE_HOLDING_LOCK = 0;
const int DEFAULT_WRITER_WORK_WHILE_HOLDING_LOCK = 0;
const int DEFAULT_READER_WORK_INBETWEEEN_LOCK_ACQUISTIONS = 0;
const int DEFAULT_WRITER_WORK_INBETWEEEN_LOCK_ACQUISTIONS = 0;
struct ProgramArgs
{
DWORD numReaderThreads;
DWORD numWriterThreads;
int numReaderIterations;
int numWriterIterations;
int readerWorkWhileHoldingLock;
int writerWorkWhileHoldingLock;
int readerWorkInBetweenLockAcquisitions;
int writerWorkInBetweenLockAcquisitions;
ProgramArgs()
: numReaderThreads(DEFAULT_READERS),
numWriterThreads(DEFAULT_WRITERS),
numReaderIterations(DEFAULT_ITERATIONS),
numWriterIterations(DEFAULT_ITERATIONS),
readerWorkWhileHoldingLock(DEFAULT_READER_WORK_WHILE_HOLDING_LOCK),
writerWorkWhileHoldingLock(DEFAULT_WRITER_WORK_WHILE_HOLDING_LOCK),
readerWorkInBetweenLockAcquisitions(DEFAULT_READER_WORK_INBETWEEEN_LOCK_ACQUISTIONS),
writerWorkInBetweenLockAcquisitions(DEFAULT_WRITER_WORK_INBETWEEEN_LOCK_ACQUISTIONS)
{
}
};
struct ThreadTimes
{
enum
{
Reader = 0,
Writer = 1
};
int type = Reader;
int updatesObserved = 0;
HighResolutionTimer timer;
};
struct ThreadArgs
{
int numReaderIterations;
int numWriterIterations;
int readerWorkWhileHoldingLock;
int writerWorkWhileHoldingLock;
int readerWorkInBetweenLockAcquisitions;
int writerWorkInBetweenLockAcquisitions;
int thdIndex;
void* valueHolder;
HANDLE hThreadWaitingEvent;
HANDLE hThreadWakeupEvent;
ThreadTimes* threadTimes;
};
class ValueHolder
{
public:
ValueHolder(ReaderWriterMutex& rwLock)
: rwLock_(rwLock),
value_(0),
workAccum_(0)
{
}
LONG getValue()
{
LONG result;
{
ReaderLock lock(rwLock_);
result = value_;
}
return result;
}
LONG getValue(int fakeWork)
{
LONG result;
{
ReaderLock lock(rwLock_);
for (int i = 0; i < fakeWork; ++i)
{
workAccum_ += i;
}
result = value_;
}
return result;
}
void setValue(LONG newValue)
{
WriterLock lock(rwLock_);
value_ = newValue;
}
void updateValue(int discardValue, int fakeWork)
{
WriterLock lock(rwLock_);
for (int i = 0; i < fakeWork; ++i)
{
workAccum_ += discardValue;
}
++value_;
}
private:
ReaderWriterMutex& rwLock_;
LONG value_;
// Dummy used to stall when doing fake work.
int workAccum_;
};
unsigned int __stdcall ReaderThreadFunc(void* args)
{
ThreadArgs* threadArgs = static_cast<ThreadArgs*>(args);
ThreadTimes* threadTimes = threadArgs->threadTimes + threadArgs->thdIndex;
ValueHolder* valueHolder = static_cast<ValueHolder*>(threadArgs->valueHolder);
int numIterations = threadArgs->numReaderIterations;
threadTimes->type = ThreadTimes::Reader;
SignalObjectAndWait(threadArgs->hThreadWaitingEvent, threadArgs->hThreadWakeupEvent, INFINITE, FALSE);
threadTimes->timer.Start();
LONG v = 0;
if ((threadArgs->readerWorkInBetweenLockAcquisitions == 0) || (threadArgs->readerWorkWhileHoldingLock == 0))
{
for (int i = 0; i < numIterations; ++i)
{
v = valueHolder->getValue();
}
}
else
{
int workWhileHoldingLock = threadArgs->readerWorkWhileHoldingLock;
int workBetweenAcquisitions = threadArgs->readerWorkInBetweenLockAcquisitions;
int updatesObserved = 0;
int oldValue = 0;
for (int i = 0; i < numIterations; ++i)
{
v = valueHolder->getValue(workWhileHoldingLock);
if (v != oldValue)
{
++updatesObserved;
oldValue = v;
}
for (int w = 0; w < workBetweenAcquisitions; ++w)
{
v = v + (w % 10);
}
}
threadTimes->updatesObserved = updatesObserved;
}
threadTimes->timer.Stop();
return v;
}
unsigned int __stdcall WriterThreadFunc(void* args)
{
ThreadArgs* threadArgs = static_cast<ThreadArgs*>(args);
ThreadTimes* threadTimes = threadArgs->threadTimes + threadArgs->thdIndex;
ValueHolder* valueHolder = static_cast<ValueHolder*>(threadArgs->valueHolder);
int numIterations = threadArgs->numWriterIterations;
threadTimes->type = ThreadTimes::Writer;
SignalObjectAndWait(threadArgs->hThreadWaitingEvent, threadArgs->hThreadWakeupEvent, INFINITE, FALSE);
threadTimes->timer.Start();
if ((threadArgs->writerWorkInBetweenLockAcquisitions == 0) && (threadArgs->writerWorkWhileHoldingLock == 0))
{
for (int i = 0; i < numIterations; ++i)
{
valueHolder->setValue(i);
}
}
else
{
int workWhileHoldingLock = threadArgs->writerWorkWhileHoldingLock;
int workBetweenAcquisitions = threadArgs->writerWorkInBetweenLockAcquisitions;
int newV = 0;
for (int i = 0; i < numIterations; ++i)
{
valueHolder->updateValue(newV, workWhileHoldingLock);
for (int w = 0; w < workBetweenAcquisitions; ++w)
{
newV = newV + (w % 10);
}
}
}
threadTimes->timer.Stop();
return numIterations;
}
/// tests reader/writer mutex
TEST_CLASS(TestReaderWriterMutex)
{
/// tests reader/writer
TEST_METHOD(TestReaderWriter)
{
// Must run on platform that supports QueryPerformanceFrequency.
LARGE_INTEGER perfFreq;
Assert::IsTrue(TRUE == QueryPerformanceFrequency(&perfFreq));
unsigned(__stdcall * readerStartAddress) (void*);
unsigned(__stdcall * writerStartAddress) (void*);
ProgramArgs programArgs;
programArgs.numReaderThreads = 1;
programArgs.numWriterThreads = 1;
DWORD totalThreads = programArgs.numReaderThreads + programArgs.numWriterThreads;
ThreadArgs threadArgs;
threadArgs.numReaderIterations = programArgs.numReaderIterations;
threadArgs.numWriterIterations = programArgs.numWriterIterations;
threadArgs.readerWorkWhileHoldingLock = programArgs.readerWorkWhileHoldingLock;
threadArgs.writerWorkWhileHoldingLock = programArgs.writerWorkWhileHoldingLock;
threadArgs.readerWorkInBetweenLockAcquisitions = programArgs.readerWorkInBetweenLockAcquisitions;
threadArgs.writerWorkInBetweenLockAcquisitions = programArgs.writerWorkInBetweenLockAcquisitions;
threadArgs.hThreadWaitingEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
threadArgs.hThreadWakeupEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
threadArgs.threadTimes = new ThreadTimes[totalThreads];
ReaderWriterMutex rwLock;
ValueHolder valHolder(rwLock);
readerStartAddress = ReaderThreadFunc;
writerStartAddress = WriterThreadFunc;
threadArgs.valueHolder = &valHolder;
HANDLE* threads = new HANDLE[totalThreads];
HANDLE* nextThread = threads;
int threadTimesIndex = 0;
// Create the readers
for (DWORD i = 0; i < programArgs.numReaderThreads; ++i, ++nextThread)
{
threadArgs.thdIndex = threadTimesIndex++;
*nextThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, readerStartAddress, &threadArgs, FALSE, NULL));
WaitForSingleObject(threadArgs.hThreadWaitingEvent, INFINITE);
}
// Create the writers
for (DWORD i = 0; i < programArgs.numWriterThreads; ++i, ++nextThread)
{
threadArgs.thdIndex = threadTimesIndex++;
*nextThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, writerStartAddress, &threadArgs, TRUE, NULL));
WaitForSingleObject(threadArgs.hThreadWaitingEvent, INFINITE);
}
HighResolutionTimer globalTimer;
globalTimer.Start();
SetEvent(threadArgs.hThreadWakeupEvent);
WaitForMultipleObjects(totalThreads, threads, TRUE, INFINITE);
globalTimer.Stop();
for (nextThread = threads; nextThread < (threads + totalThreads); ++nextThread)
{
CloseHandle(*nextThread);
}
delete[] threads;
CloseHandle(threadArgs.hThreadWaitingEvent);
CloseHandle(threadArgs.hThreadWakeupEvent);
double timeInSecs;
ATLTRACE(_T("Thread Timings:"));
// Calculate timings.
for (DWORD threadIndex = 0; threadIndex < totalThreads; ++threadIndex)
{
ThreadTimes* threadTimes = threadArgs.threadTimes + threadIndex;
timeInSecs = threadTimes->timer.Elapsed();
CString textUpdatesObserved;
if (threadTimes->type == ThreadTimes::Reader)
textUpdatesObserved.Format(_T(", updates observed: %i"), threadTimes->updatesObserved);
CString text;
text.Format(_T("\t%s %u duration %u.%03u secs.%s"),
(threadTimes->type == ThreadTimes::Reader) ? _T("Reader") : _T("Writer"),
threadIndex,
unsigned(timeInSecs), unsigned((timeInSecs - unsigned(timeInSecs)) * 1000.0),
textUpdatesObserved.GetString());
ATLTRACE(text);
}
delete[] threadArgs.threadTimes;
timeInSecs = globalTimer.Elapsed();
ATLTRACE(_T("Total execution time is %u.%03u seconds.\n"),
unsigned(timeInSecs), unsigned((timeInSecs - unsigned(timeInSecs)) * 1000.0));
}
};
} // namespace UnitTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.