hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
4e65589e56b357a5238f162e2b0cb858650eb374
3,126
cc
C++
content/browser/process_internals/process_internals_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/browser/process_internals/process_internals_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
content/browser/process_internals/process_internals_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversions.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "testing/gmock/include/gmock/gmock.h" namespace content { class ProcessInternalsWebUiBrowserTest : public ContentBrowserTest { protected: // Executing javascript in the WebUI requires using an isolated world in which // to execute the script because WebUI has a default CSP policy denying // "eval()", which is what EvalJs uses under the hood. bool ExecJsInWebUI(const std::string& script) { return ExecJs(shell()->web_contents()->GetMainFrame(), script, EXECUTE_SCRIPT_DEFAULT_OPTIONS, 1 /* world_id */); } }; // This test verifies that loading of the process-internals WebUI works // correctly and the process rendering it has no WebUI bindings. IN_PROC_BROWSER_TEST_F(ProcessInternalsWebUiBrowserTest, NoProcessBindings) { GURL url("chrome://process-internals/#web-contents"); EXPECT_TRUE(NavigateToURL(shell(), url)); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); // Execute script to ensure the page has loaded correctly and was successful // at retrieving data from the browser process. // Note: This requires using an isolated world in which to execute the // script because WebUI has a default CSP policy denying "eval()", which is // what EvalJs uses under the hood. std::string page_contents = EvalJs(shell()->web_contents()->GetMainFrame(), "document.body.innerHTML", EXECUTE_SCRIPT_DEFAULT_OPTIONS, 1 /* world_id */) .ExtractString(); // Crude verification that the page had the right content. EXPECT_THAT(page_contents, ::testing::HasSubstr("Process Internals")); } IN_PROC_BROWSER_TEST_F(ProcessInternalsWebUiBrowserTest, MojoJsBindingsCorrectlyScoped) { const std::u16string passed_title = u"passed"; GURL url("chrome://process-internals/#web-contents"); EXPECT_TRUE(NavigateToURL(shell(), url)); { TitleWatcher sent_title_watcher(shell()->web_contents(), passed_title); EXPECT_TRUE( ExecJsInWebUI("document.title = window.Mojo? 'passed' : 'failed';")); EXPECT_EQ(passed_title, sent_title_watcher.WaitAndGetTitle()); } EXPECT_TRUE(NavigateToURL(shell(), GURL("about:blank"))); { TitleWatcher sent_title_watcher(shell()->web_contents(), passed_title); EXPECT_TRUE( ExecJsInWebUI("document.title = window.Mojo? 'failed' : 'passed';")); EXPECT_EQ(passed_title, sent_title_watcher.WaitAndGetTitle()); } } } // namespace content
42.243243
80
0.742163
zealoussnow
4e6665fe6dbf02a5fb4af8c55d94b849798b8836
4,826
cpp
C++
src/Screens/MusicSelect/Drawables/ControlPanels.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
19
2020-02-28T20:34:12.000Z
2022-01-28T20:18:25.000Z
src/Screens/MusicSelect/Drawables/ControlPanels.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
7
2019-10-22T09:43:16.000Z
2022-03-12T00:15:13.000Z
src/Screens/MusicSelect/Drawables/ControlPanels.cpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
5
2019-10-22T08:14:57.000Z
2021-03-13T06:32:04.000Z
#include "ControlPanels.hpp" #include "../../../Toolkit/SFMLHelpers.hpp" namespace MusicSelect { void LeftButton::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); sf::CircleShape circle{get_panel_size()*0.4f}; circle.setFillColor(sf::Color::Black); circle.setOutlineThickness(0.02f*get_panel_size()); circle.setOutlineColor(sf::Color::White); Toolkit::set_origin_normalized(circle, 0.5f, 0.5f); circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(circle, states); sf::RectangleShape arrow_part{sf::Vector2f{0.1f,0.4f}*get_panel_size()}; arrow_part.setFillColor(sf::Color::White); Toolkit::set_origin_normalized(arrow_part, 2.f, 0.5f); arrow_part.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); arrow_part.move(0.05f*get_panel_size(), 0.f); arrow_part.rotate(45.f); target.draw(arrow_part, states); arrow_part.rotate(-90.f); target.draw(arrow_part, states); } void RightButton::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); sf::CircleShape circle{get_panel_size()*0.4f}; circle.setFillColor(sf::Color::Black); circle.setOutlineThickness(0.02f*get_panel_size()); circle.setOutlineColor(sf::Color::White); Toolkit::set_origin_normalized(circle, 0.5f, 0.5f); circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(circle, states); sf::RectangleShape arrow_part{sf::Vector2f{0.1f,0.4f}*get_panel_size()}; arrow_part.setFillColor(sf::Color::White); Toolkit::set_origin_normalized(arrow_part, -1.f, 0.5f); arrow_part.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); arrow_part.move(-0.05f*get_panel_size(), 0.f); arrow_part.rotate(45.f); target.draw(arrow_part, states); arrow_part.rotate(-90.f); target.draw(arrow_part, states); } void OptionsButton::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); sf::CircleShape circle{get_panel_size()*0.4f}; circle.setFillColor(sf::Color::Black); circle.setOutlineThickness(0.02f*get_panel_size()); circle.setOutlineColor(sf::Color::White); Toolkit::set_origin_normalized(circle, 0.5f, 0.5f); circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(circle, states); sf::Text label{ "OPTIONS", shared.fallback_font.black, static_cast<unsigned int>(0.2f*get_panel_size()) }; label.setFillColor(sf::Color::White); Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f); label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); label.setScale(0.8f, 1.0f); target.draw(label, states); } void StartButton::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); sf::CircleShape circle{get_panel_size()*0.4f}; circle.setFillColor(sf::Color::Black); circle.setOutlineThickness(0.02f*get_panel_size()); circle.setOutlineColor(shared.BSC_color); Toolkit::set_origin_normalized(circle, 0.5f, 0.5f); circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(circle, states); sf::Text label{ "START", shared.fallback_font.black, static_cast<unsigned int>(0.2f*get_panel_size()) }; label.setFillColor(shared.BSC_color); Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f); label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(label, states); } void BackButton::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); sf::CircleShape circle{get_panel_size()*0.4f}; circle.setFillColor(sf::Color::Black); circle.setOutlineThickness(0.02f*get_panel_size()); circle.setOutlineColor(shared.EXT_color); Toolkit::set_origin_normalized(circle, 0.5f, 0.5f); circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(circle, states); sf::Text label{ "BACK", shared.fallback_font.black, static_cast<unsigned int>(0.2f*get_panel_size()) }; label.setFillColor(shared.EXT_color); Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f); label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f); target.draw(label, states); } }
43.477477
87
0.648363
Subject38
4e6ae5947b7e3480f74525a74eceeda1ab1347ef
752
cpp
C++
lib/DBMS/DBMS.cpp
travisolbrich/315-P1-DBMS
84168bbb3f5fe7518cbb212baa01d54ca7e6815d
[ "MIT" ]
null
null
null
lib/DBMS/DBMS.cpp
travisolbrich/315-P1-DBMS
84168bbb3f5fe7518cbb212baa01d54ca7e6815d
[ "MIT" ]
null
null
null
lib/DBMS/DBMS.cpp
travisolbrich/315-P1-DBMS
84168bbb3f5fe7518cbb212baa01d54ca7e6815d
[ "MIT" ]
3
2016-02-15T22:32:31.000Z
2021-01-10T14:41:14.000Z
#include "../SqlTokenizer/SqlTokenizer.h" #include "../SqlTokenizer/Token.h" #include "../SqlParser/SqlParser.h" #include "../DBMSEngine/Relation.h" #include "../DBMSEngine/Engine.h" #include "DBMS.h" #include <string> #include <vector> /** Returns: 0: valid answer 1: Exception 2: Exit called **/ int DBMS::execute(string query) { try { SqlTokenizer* tokenizer = new SqlTokenizer(query); vector<Token> tokens = tokenizer->split(); if(tokens[0].getType() == Token::EXIT) return 2; SqlParser* parser = new SqlParser(tokens, engine); parser->parse(); } catch (exception& e) { cout << "!!! " << e.what() << "\n"; return 1; } return 0; } Relation DBMS::relation(string relation) { return *engine->getRelation(relation); }
18.341463
52
0.660904
travisolbrich
4e6af3670917df035958d0dbc1368177dd4e0669
157
cpp
C++
problem-2/main.cpp
ProgrammingLanguagesClass/Assignment-2
a65ff25decee4da401660a0c85bb3467f065e119
[ "MIT" ]
1
2019-12-10T11:03:59.000Z
2019-12-10T11:03:59.000Z
problem-2/main.cpp
ProgrammingLanguagesClass/Assignment-2
a65ff25decee4da401660a0c85bb3467f065e119
[ "MIT" ]
null
null
null
problem-2/main.cpp
ProgrammingLanguagesClass/Assignment-2
a65ff25decee4da401660a0c85bb3467f065e119
[ "MIT" ]
1
2019-01-03T11:00:30.000Z
2019-01-03T11:00:30.000Z
#include <iostream> #include "main.h" using namespace std; string getGrade(int score) { string grade; // Write your code here return grade; }
12.076923
27
0.66879
ProgrammingLanguagesClass
4e6c736bb84dcefe43dc1cdebe261f47dc437c97
6,678
cpp
C++
test/distribution/joint_distribution_iid_test.cpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
17
2015-07-03T06:53:05.000Z
2021-05-15T20:55:12.000Z
test/distribution/joint_distribution_iid_test.cpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
3
2015-02-20T12:48:17.000Z
2019-12-18T08:45:13.000Z
test/distribution/joint_distribution_iid_test.cpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
15
2015-02-20T11:34:14.000Z
2021-05-15T20:55:13.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac (jan.issac@gmail.com) * Manuel Wuthrich (manuel.wuthrich@gmail.com) * * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * \file joint_distribution_iid_test.cpp * \date Febuary 2015 * \author Jan Issac (jan.issac@gmail.com) */ #include <gtest/gtest.h> #include <Eigen/Dense> #include <fl/distribution/gaussian.hpp> #include <fl/distribution/joint_distribution_iid.hpp> TEST(JointDistribution_IID_Tests, fixed_fixed_single_gaussian) { constexpr int dim = 2; typedef Eigen::Matrix<double, dim, 1> FVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<FVariate>, 1> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<FVariate>()); typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE(fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE(fl::are_similar( joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); } TEST(JointDistribution_IID_Tests, fixed_dynamic_single_gaussian) { typedef Eigen::Matrix<double, -1, 1> DVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<DVariate>, 1> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<DVariate>(13)); constexpr int dim = 13; typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE( fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE( fl::are_similar(joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); } TEST(JointDistribution_IID_Tests, dynamic_dynamic_single_gaussian) { typedef Eigen::Matrix<double, -1, 1> DVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<DVariate>, -1> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<DVariate>(13), 1); constexpr int dim = 13; typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE( fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE( fl::are_similar(joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); } TEST(JointDistribution_IID_Tests, fixed_fixed_three_gaussian) { typedef Eigen::Matrix<double, 13, 1> FVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<FVariate>, 3> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<FVariate>()); constexpr int dim = 3 * 13; typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE( fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE( fl::are_similar(joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); } TEST(JointDistribution_IID_Tests, fixed_dynamic_three_gaussian) { typedef Eigen::Matrix<double, -1, 1> DVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<DVariate>, 3> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<DVariate>(13)); constexpr int dim = 3 * 13; typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE( fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE( fl::are_similar(joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); } TEST(JointDistribution_IID_Tests, dynamic_dynamic_three_gaussian) { typedef Eigen::Matrix<double, -1, 1> DVariate; typedef fl::JointDistribution< fl::MultipleOf<fl::Gaussian<DVariate>, -1> > FSingeDistribution; FSingeDistribution joint_distr = FSingeDistribution(fl::Gaussian<DVariate>(13), 3); constexpr int dim = 3 * 13; typedef Eigen::Matrix<double, dim, 1> ExpectedMean; typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance; EXPECT_EQ(joint_distr.dimension(), dim); EXPECT_TRUE( fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1))); EXPECT_TRUE( fl::are_similar(joint_distr.covariance(), ExpectedCovariance::Identity(dim, dim))); }
33.727273
81
0.686733
aeolusbot-tommyliu
4e6d1fa6994a4c3374ff41e672058f0baf99e5ab
576
cpp
C++
Opportunity.ChakraBridge.WinRT/Value/JsString.cpp
OpportunityLiu/ChakraBridge
38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3
[ "MIT" ]
null
null
null
Opportunity.ChakraBridge.WinRT/Value/JsString.cpp
OpportunityLiu/ChakraBridge
38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3
[ "MIT" ]
null
null
null
Opportunity.ChakraBridge.WinRT/Value/JsString.cpp
OpportunityLiu/ChakraBridge
38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3
[ "MIT" ]
null
null
null
#include "pch.h" #include "JsString.h" using namespace Opportunity::ChakraBridge::WinRT; JsStringImpl::~JsStringImpl() { // ignore error. JsRelease(Reference.Ref, nullptr); } JsStringImpl::JsStringImpl(RawValue ref) :JsValueImpl(std::move(ref)) { Reference.AddRef(); } uint32 JsStringImpl::Length::get() { return static_cast<uint32>(Reference.StrLength()); } string^ JsStringImpl::ToString() { return Reference.ToString(); } IJsString^ JsString::Create(string^ value) { return ref new JsStringImpl(RawValue(value->Data(),value->Length())); }
18
73
0.704861
OpportunityLiu
4e6f96ffeb0d0f1b8b3698debfd3b342ebda6277
25,032
cpp
C++
ExaHyPE/exahype/mappings/PredictionOrLocalRecomputation.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
null
null
null
ExaHyPE/exahype/mappings/PredictionOrLocalRecomputation.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
null
null
null
ExaHyPE/exahype/mappings/PredictionOrLocalRecomputation.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
1
2021-04-08T16:12:18.000Z
2021-04-08T16:12:18.000Z
/**os * 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/mappings/PredictionOrLocalRecomputation.h" #include <algorithm> #include "tarch/multicore/Loop.h" #include "peano/utils/Globals.h" #include "peano/utils/Loop.h" #include "peano/datatraversal/autotuning/Oracle.h" #include "peano/datatraversal/TaskSet.h" #include "exahype/mappings/LevelwiseAdjacencyBookkeeping.h" #include "exahype/solvers/LimitingADERDGSolver.h" #include "exahype/mappings/Prediction.h" tarch::logging::Log exahype::mappings::PredictionOrLocalRecomputation::_log( "exahype::mappings::PredictionOrLocalRecomputation"); peano::CommunicationSpecification exahype::mappings::PredictionOrLocalRecomputation::communicationSpecification() const { return peano::CommunicationSpecification( peano::CommunicationSpecification::ExchangeMasterWorkerData::MaskOutMasterWorkerDataAndStateExchange, peano::CommunicationSpecification::ExchangeWorkerMasterData::SendDataAndStateAfterLastTouchVertexLastTime,false); } peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::enterCellSpecification(int level) const { const int coarsestSolverLevel = solvers::Solver::getCoarsestMeshLevelOfAllSolvers(); if ( std::abs(level)>=coarsestSolverLevel ) { return peano::MappingSpecification( peano::MappingSpecification::WholeTree, peano::MappingSpecification::RunConcurrentlyOnFineGrid,true); // performs reduction } else { return peano::MappingSpecification( peano::MappingSpecification::Nop, peano::MappingSpecification::RunConcurrentlyOnFineGrid,false); } } peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::touchVertexFirstTimeSpecification(int level) const { return Vertex::getNeighbourMergeSpecification(level); } // Below specs are all nop peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::leaveCellSpecification(int level) const { return peano::MappingSpecification( peano::MappingSpecification::Nop, peano::MappingSpecification::RunConcurrentlyOnFineGrid,false); } peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::touchVertexLastTimeSpecification(int level) const { return peano::MappingSpecification( peano::MappingSpecification::Nop, peano::MappingSpecification::RunConcurrentlyOnFineGrid,true); } peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::ascendSpecification(int level) const { return peano::MappingSpecification( peano::MappingSpecification::Nop, peano::MappingSpecification::AvoidCoarseGridRaces,true); } peano::MappingSpecification exahype::mappings::PredictionOrLocalRecomputation::descendSpecification(int level) const { return peano::MappingSpecification( peano::MappingSpecification::Nop, peano::MappingSpecification::AvoidCoarseGridRaces,true); } void exahype::mappings::PredictionOrLocalRecomputation::beginIteration( exahype::State& solverState) { logTraceInWith1Argument("beginIteration(State)", solverState); #ifdef Parallel // enforce reductions from worker side in last step; turns off reductions in other iterations solverState.setReduceStateAndCell( exahype::State::isLastIterationOfBatchOrNoBatch() ); #endif if ( exahype::solvers::Solver::SpawnPredictionAsBackgroundJob && exahype::State::isLastIterationOfBatchOrNoBatch() ) { peano::datatraversal::TaskSet::startToProcessBackgroundJobs(); // TODO(Dominic): Still necessary? } logTraceOutWith1Argument("beginIteration(State)", solverState); } bool exahype::mappings::PredictionOrLocalRecomputation::performLocalRecomputation( exahype::solvers::Solver* solver) { return solver->getMeshUpdateEvent()==exahype::solvers::Solver::MeshUpdateEvent::IrregularLimiterDomainChange; } bool exahype::mappings::PredictionOrLocalRecomputation::performPrediction( exahype::solvers::Solver* solver) { return exahype::solvers::Solver::FuseAllADERDGPhases && solver->hasRequestedAnyMeshRefinement(); } void exahype::mappings::PredictionOrLocalRecomputation::endIteration( exahype::State& state) { logTraceInWith1Argument("endIteration(State)", state); if ( state.isLastIterationOfBatchOrNoBatch() ) { // background threads exahype::solvers::Solver::ensureAllJobsHaveTerminated(exahype::solvers::Solver::JobType::ReductionJob); } logTraceOutWith1Argument("endIteration(State)", state); } void exahype::mappings::PredictionOrLocalRecomputation::enterCell( exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { logTraceInWith4Arguments("enterCell(...)", fineGridCell, fineGridVerticesEnumerator.toString(), coarseGridCell, fineGridPositionOfCell); if ( fineGridCell.isInitialised() ) { solvers::Solver::CellInfo cellInfo = fineGridCell.createCellInfo(); const tarch::la::Vector<DIMENSIONS_TIMES_TWO,int> boundaryMarkers = exahype::Cell::collectBoundaryMarkers(fineGridVertices,fineGridVerticesEnumerator); const bool isAtRemoteBoundary = tarch::la::oneEquals(boundaryMarkers,LevelwiseAdjacencyBookkeeping::RemoteAdjacencyIndex); for (unsigned int solverNumber=0; solverNumber<exahype::solvers::RegisteredSolvers.size(); solverNumber++) { auto* solver = exahype::solvers::RegisteredSolvers[solverNumber]; if ( performLocalRecomputation( solver ) && exahype::State::isFirstIterationOfBatchOrNoBatch() ) { auto* limitingADERDG = static_cast<exahype::solvers::LimitingADERDGSolver*>(solver); limitingADERDG->localRecomputation(solverNumber,cellInfo,boundaryMarkers); } else if ( performPrediction(solver) && exahype::State::isFirstIterationOfBatchOrNoBatch() ) { switch ( solver->getType() ) { case solvers::Solver::Type::ADERDG: static_cast<solvers::ADERDGSolver*>(solver)->predictionAndVolumeIntegral(solverNumber,cellInfo,isAtRemoteBoundary); break; case solvers::Solver::Type::LimitingADERDG: static_cast<solvers::LimitingADERDGSolver*>(solver)->predictionAndVolumeIntegral(solverNumber,cellInfo,isAtRemoteBoundary); break; case solvers::Solver::Type::FiniteVolumes: // insert code here break; default: assertionMsg(false,"Unrecognised solver type: "<<solvers::Solver::toString(solver->getType())); logError("mergeWithBoundaryDataIfNotDoneYet(...)","Unrecognised solver type: "<<solvers::Solver::toString(solver->getType())); std::abort(); break; } } else if ( performPrediction(solver) && exahype::State::isLastIterationOfBatchOrNoBatch() ) { switch ( solver->getType() ) { case solvers::Solver::Type::ADERDG: static_cast<solvers::ADERDGSolver*>(solver)->prolongateFaceData(solverNumber,cellInfo,isAtRemoteBoundary); break; case solvers::Solver::Type::LimitingADERDG: static_cast<solvers::LimitingADERDGSolver*>(solver)->getSolver()->prolongateFaceData(solverNumber,cellInfo,isAtRemoteBoundary); break; case solvers::Solver::Type::FiniteVolumes: // insert code here break; default: assertionMsg(false,"Unrecognised solver type: "<<solvers::Solver::toString(solver->getType())); logError("mergeWithBoundaryDataIfNotDoneYet(...)","Unrecognised solver type: "<<solvers::Solver::toString(solver->getType())); std::abort(); break; } } } } logTraceOutWith1Argument("enterCell(...)", fineGridCell); } void exahype::mappings::PredictionOrLocalRecomputation::leaveCell( exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::mergeNeighboursDataDuringLocalRecomputationLoopBody( const int pos1Scalar, const int pos2Scalar, const exahype::Vertex& vertex, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h) { const auto pos1 = Vertex::delineariseIndex2(pos1Scalar); const auto pos2 = Vertex::delineariseIndex2(pos2Scalar); const int cellDescriptionsIndex1 = vertex.getCellDescriptionsIndex(pos1Scalar); const int cellDescriptionsIndex2 = vertex.getCellDescriptionsIndex(pos2Scalar); const bool validIndex1 = cellDescriptionsIndex1 >= 0; const bool validIndex2 = cellDescriptionsIndex2 >= 0; if ( validIndex1 && validIndex2 ) { solvers::Solver::CellInfo cellInfo1 = vertex.createCellInfo(pos1Scalar); solvers::Solver::CellInfo cellInfo2 = vertex.createCellInfo(pos2Scalar); solvers::Solver::InterfaceInfo face(pos1,pos2); for (int solverNumber=0; solverNumber<static_cast<int>(solvers::RegisteredSolvers.size()); solverNumber++) { auto* solver = exahype::solvers::RegisteredSolvers[solverNumber]; if ( performLocalRecomputation(solver) ) { static_cast<exahype::solvers::LimitingADERDGSolver*>(solver)-> mergeNeighboursDataDuringLocalRecomputation(solverNumber,cellInfo1,cellInfo2,pos1,pos2); } } } } void exahype::mappings::PredictionOrLocalRecomputation::touchVertexFirstTime( exahype::Vertex& vertex, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex ) { logTraceInWith6Arguments( "touchVertexFirstTime(...)", vertex, x, h, coarseGridVerticesEnumerator.toString(), coarseGridCell, fineGridPositionOfVertex ); if ( exahype::State::isFirstIterationOfBatchOrNoBatch() && State::hasOneSolverRequestedLocalRecomputation() ) { mergeNeighboursDataDuringLocalRecomputationLoopBody(0,1,vertex,x,h); mergeNeighboursDataDuringLocalRecomputationLoopBody(0,2,vertex,x,h); #if DIMENSIONS==3 mergeNeighboursDataDuringLocalRecomputationLoopBody(0,4,vertex,x,h); #endif } logTraceOutWith1Argument( "touchVertexFirstTime(...)", vertex ); } #ifdef Parallel /////////////////////////////////////// // NEIGHBOUR /////////////////////////////////////// void exahype::mappings::PredictionOrLocalRecomputation::mergeWithNeighbour( exahype::Vertex& vertex, const exahype::Vertex& neighbour, int fromRank, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, int level) { logTraceInWith6Arguments( "mergeWithNeighbour(...)", vertex, neighbour, fromRank, fineGridX, fineGridH, level ); if ( exahype::State::isFirstIterationOfBatchOrNoBatch() && State::hasOneSolverRequestedLocalRecomputation() && vertex.hasToCommunicate(level) ) { #if DIMENSIONS==3 receiveNeighbourDataLoopBody(fromRank,4,0,vertex,fineGridX,fineGridH,level); receiveNeighbourDataLoopBody(fromRank,0,4,vertex,fineGridX,fineGridH,level); #endif receiveNeighbourDataLoopBody(fromRank,2,0,vertex,fineGridX,fineGridH,level); receiveNeighbourDataLoopBody(fromRank,0,2,vertex,fineGridX,fineGridH,level); receiveNeighbourDataLoopBody(fromRank,1,0,vertex,fineGridX,fineGridH,level); receiveNeighbourDataLoopBody(fromRank,0,1,vertex,fineGridX,fineGridH,level); } logTraceOut( "mergeWithNeighbour(...)" ); } void exahype::mappings::PredictionOrLocalRecomputation::receiveNeighbourDataLoopBody( const int fromRank, const int srcScalar, const int destScalar, const exahype::Vertex& vertex, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, const int level) { const auto src = Vertex::delineariseIndex2(srcScalar); const auto dest = Vertex::delineariseIndex2(destScalar); if ( vertex.hasToReceiveMetadata(fromRank,srcScalar,destScalar,vertex.getAdjacentRanks()) ) { const int destCellDescriptionsIndex = vertex.getCellDescriptionsIndex(destScalar); const bool validIndex = destCellDescriptionsIndex >= 0; assertion( !validIndex || exahype::solvers::ADERDGSolver::Heap::getInstance().isValidIndex(destCellDescriptionsIndex)); if ( validIndex ) { solvers::Solver::CellInfo cellInfo = vertex.createCellInfo(destScalar); solvers::Solver::BoundaryFaceInfo face(dest,src); // dest and src are swapped const auto barycentre = Vertex::computeFaceBarycentre(x,h,face._direction,dest); for(unsigned int solverNumber = solvers::RegisteredSolvers.size(); solverNumber-- > 0;) { auto* solver = solvers::RegisteredSolvers[solverNumber]; if ( performLocalRecomputation( solver ) ) { assertion1( solver->getType()==solvers::Solver::Type::LimitingADERDG, solver->toString() ); static_cast<solvers::LimitingADERDGSolver*>(solver)-> mergeWithNeighbourDataDuringLocalRecomputation(fromRank,solverNumber,cellInfo,src,dest,barycentre,level); } } } } } void exahype::mappings::PredictionOrLocalRecomputation::prepareSendToNeighbour( exahype::Vertex& vertex, int toRank, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, int level) { logTraceInWith3Arguments( "prepareSendToNeighbour(...)", vertex, toRank, level ); if ( exahype::State::isLastIterationOfBatchOrNoBatch() && exahype::solvers::Solver::FuseAllADERDGPhases ) { vertex.sendToNeighbour(toRank,true,x,h,level); } logTraceOut( "prepareSendToNeighbour(...)" ); } bool exahype::mappings::PredictionOrLocalRecomputation::prepareSendToWorker( exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell, int worker) { return exahype::State::isLastIterationOfBatchOrNoBatch(); // notifies master this worker wants to perform reduction } void exahype::mappings::PredictionOrLocalRecomputation::prepareSendToMaster( exahype::Cell& localCell, exahype::Vertex* vertices, const peano::grid::VertexEnumerator& verticesEnumerator, const exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, const exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { if ( exahype::State::isLastIterationOfBatchOrNoBatch() ) { const int masterRank = tarch::parallel::NodePool::getInstance().getMasterRank(); for (auto* solver : exahype::solvers::RegisteredSolvers) { if ( solver->getMeshUpdateEvent()==exahype::solvers::Solver::MeshUpdateEvent::IrregularLimiterDomainChange ) { solver->sendDataToMaster(masterRank,0.0,0); } } } } void exahype::mappings::PredictionOrLocalRecomputation::mergeWithMaster( const exahype::Cell& workerGridCell, exahype::Vertex* const workerGridVertices, const peano::grid::VertexEnumerator& workerEnumerator, exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell, int workerRank, const exahype::State& workerState, exahype::State& masterState) { if ( exahype::State::isLastIterationOfBatchOrNoBatch() ) { for (auto* solver : exahype::solvers::RegisteredSolvers) { if ( solver->getMeshUpdateEvent()==exahype::solvers::Solver::MeshUpdateEvent::IrregularLimiterDomainChange ) { solver->mergeWithWorkerData(workerRank,0.0,0); } } } } // // Below all methods are nop. // //===================================== void exahype::mappings::PredictionOrLocalRecomputation::receiveDataFromMaster( exahype::Cell& receivedCell, exahype::Vertex* receivedVertices, const peano::grid::VertexEnumerator& receivedVerticesEnumerator, exahype::Vertex* const receivedCoarseGridVertices, const peano::grid::VertexEnumerator& receivedCoarseGridVerticesEnumerator, exahype::Cell& receivedCoarseGridCell, exahype::Vertex* const workersCoarseGridVertices, const peano::grid::VertexEnumerator& workersCoarseGridVerticesEnumerator, exahype::Cell& workersCoarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::prepareCopyToRemoteNode( exahype::Vertex& localVertex, int toRank, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, int level) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::prepareCopyToRemoteNode( exahype::Cell& localCell, int toRank, const tarch::la::Vector<DIMENSIONS, double>& cellCentre, const tarch::la::Vector<DIMENSIONS, double>& cellSize, int level) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::mergeWithRemoteDataDueToForkOrJoin( exahype::Vertex& localVertex, const exahype::Vertex& masterOrWorkerVertex, int fromRank, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, int level) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::mergeWithRemoteDataDueToForkOrJoin( exahype::Cell& localCell, const exahype::Cell& masterOrWorkerCell, int fromRank, const tarch::la::Vector<DIMENSIONS, double>& cellCentre, const tarch::la::Vector<DIMENSIONS, double>& cellSize, int level) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::mergeWithWorker( exahype::Cell& localCell, const exahype::Cell& receivedMasterCell, const tarch::la::Vector<DIMENSIONS, double>& cellCentre, const tarch::la::Vector<DIMENSIONS, double>& cellSize, int level) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::mergeWithWorker( exahype::Vertex& localVertex, const exahype::Vertex& receivedMasterVertex, const tarch::la::Vector<DIMENSIONS, double>& x, const tarch::la::Vector<DIMENSIONS, double>& h, int level) { // do nothing } #endif exahype::mappings::PredictionOrLocalRecomputation::PredictionOrLocalRecomputation() { // do nothing } exahype::mappings::PredictionOrLocalRecomputation::~PredictionOrLocalRecomputation() { // do nothing } #if defined(SharedMemoryParallelisation) exahype::mappings::PredictionOrLocalRecomputation::PredictionOrLocalRecomputation( const PredictionOrLocalRecomputation& masterThread) { // do nothing } // Merge over threads void exahype::mappings::PredictionOrLocalRecomputation::mergeWithWorkerThread( const PredictionOrLocalRecomputation& workerThread) { // do nothing } #endif void exahype::mappings::PredictionOrLocalRecomputation::createHangingVertex( exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::destroyHangingVertex( const exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::createInnerVertex( exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::createBoundaryVertex( exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::destroyVertex( const exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::createCell( exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::destroyCell( const exahype::Cell& fineGridCell, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfCell) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::touchVertexLastTime( exahype::Vertex& fineGridVertex, const tarch::la::Vector<DIMENSIONS, double>& fineGridX, const tarch::la::Vector<DIMENSIONS, double>& fineGridH, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell, const tarch::la::Vector<DIMENSIONS, int>& fineGridPositionOfVertex) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::descend( exahype::Cell* const fineGridCells, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell) { // do nothing } void exahype::mappings::PredictionOrLocalRecomputation::ascend( exahype::Cell* const fineGridCells, exahype::Vertex* const fineGridVertices, const peano::grid::VertexEnumerator& fineGridVerticesEnumerator, exahype::Vertex* const coarseGridVertices, const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator, exahype::Cell& coarseGridCell) { // do nothing }
44.148148
155
0.740932
linusseelinger
4e70497236b5f181b81da3ed17ebe1bd946a0c23
382
hpp
C++
src/geocode/protocol_mapquest.hpp
stephaneyfx/geocode-cpp
18ec8f62cbd71953f200c41887408028a03cd8a5
[ "MIT" ]
null
null
null
src/geocode/protocol_mapquest.hpp
stephaneyfx/geocode-cpp
18ec8f62cbd71953f200c41887408028a03cd8a5
[ "MIT" ]
null
null
null
src/geocode/protocol_mapquest.hpp
stephaneyfx/geocode-cpp
18ec8f62cbd71953f200c41887408028a03cd8a5
[ "MIT" ]
null
null
null
// Copyright (C) 2018 Stephane Raux. Distributed under the MIT license. #pragma once #include "protocol.hpp" #include <string> class ProtocolMapQuest { public: explicit ProtocolMapQuest(std::string key); std::string host() const; Coordinates parse(const Response& resp) const; Request request(const std::string& location) const; private: std::string key; };
21.222222
71
0.719895
stephaneyfx
4e70e45f0c11f881a50d7ea5189126a2233439bd
4,475
cc
C++
ui/ozone/platform/drm/gpu/drm_gpu_util.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
ui/ozone/platform/drm/gpu/drm_gpu_util.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ui/ozone/platform/drm/gpu/drm_gpu_util.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// 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 LICENSE file. #include "ui/ozone/platform/drm/gpu/drm_gpu_util.h" #include <fcntl.h> #include <xf86drm.h> #include <xf86drmMode.h> #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "ui/display/types/gamma_ramp_rgb_entry.h" #include "ui/ozone/platform/drm/gpu/drm_device.h" namespace ui { bool GetDrmPropertyForName(DrmDevice* drm, drmModeObjectProperties* properties, const std::string& name, DrmDevice::Property* property) { for (uint32_t i = 0; i < properties->count_props; ++i) { ScopedDrmPropertyPtr drm_property(drm->GetProperty(properties->props[i])); if (name != drm_property->name) continue; property->id = drm_property->prop_id; property->value = properties->prop_values[i]; if (property->id) return true; } return false; } bool AddPropertyIfValid(drmModeAtomicReq* property_set, uint32_t object_id, const DrmDevice::Property& property) { if (!property.id) return true; int ret = drmModeAtomicAddProperty(property_set, object_id, property.id, property.value); if (ret < 0) { LOG(ERROR) << "Failed to set property object_id=" << object_id << " property_id=" << property.id << " property_value=" << property.value << " error=" << -ret; return false; } return true; } ScopedDrmColorLutPtr CreateLutBlob( const std::vector<display::GammaRampRGBEntry>& source) { TRACE_EVENT0("drm", "CreateLutBlob"); if (source.empty()) return nullptr; ScopedDrmColorLutPtr lut(static_cast<drm_color_lut*>( malloc(sizeof(drm_color_lut) * source.size()))); drm_color_lut* p = lut.get(); for (size_t i = 0; i < source.size(); ++i) { p[i].red = source[i].r; p[i].green = source[i].g; p[i].blue = source[i].b; } return lut; } ScopedDrmColorCtmPtr CreateCTMBlob(const std::vector<float>& color_matrix) { if (color_matrix.empty()) return nullptr; ScopedDrmColorCtmPtr ctm( static_cast<drm_color_ctm*>(malloc(sizeof(drm_color_ctm)))); DCHECK_EQ(color_matrix.size(), base::size(ctm->matrix)); for (size_t i = 0; i < base::size(ctm->matrix); ++i) { if (color_matrix[i] < 0) { ctm->matrix[i] = static_cast<uint64_t>(-color_matrix[i] * (1ull << 32)); ctm->matrix[i] |= static_cast<uint64_t>(1) << 63; } else { ctm->matrix[i] = static_cast<uint64_t>(color_matrix[i] * (1ull << 32)); } } return ctm; } std::vector<display::GammaRampRGBEntry> ResampleLut( const std::vector<display::GammaRampRGBEntry>& lut_in, size_t desired_size) { TRACE_EVENT1("drm", "ResampleLut", "desired_size", desired_size); if (lut_in.empty()) return std::vector<display::GammaRampRGBEntry>(); if (lut_in.size() == desired_size) return lut_in; std::vector<display::GammaRampRGBEntry> result; result.resize(desired_size); for (size_t i = 0; i < desired_size; ++i) { size_t base_index = lut_in.size() * i / desired_size; size_t remaining = lut_in.size() * i % desired_size; if (base_index < lut_in.size() - 1) { result[i].r = lut_in[base_index].r + (lut_in[base_index + 1].r - lut_in[base_index].r) * remaining / desired_size; result[i].g = lut_in[base_index].g + (lut_in[base_index + 1].g - lut_in[base_index].g) * remaining / desired_size; result[i].b = lut_in[base_index].b + (lut_in[base_index + 1].b - lut_in[base_index].b) * remaining / desired_size; } else { result[i] = lut_in.back(); } } return result; } bool IsDriverName(const char* device_file_name, const char* driver) { base::ScopedFD fd(open(device_file_name, O_RDWR)); if (!fd.is_valid()) { LOG(ERROR) << "Failed to open DRM device " << device_file_name; return false; } ScopedDrmVersionPtr version(drmGetVersion(fd.get())); if (!version) { LOG(ERROR) << "Failed to query DRM version " << device_file_name; return false; } if (strncmp(driver, version->name, version->name_len) == 0) return true; return false; } } // namespace ui
31.076389
78
0.627039
mghgroup
4e73d28eaf35e20955ff67c5a9a70c97c9781d65
1,318
cpp
C++
raizes_equacao.cpp
Institutionoffoz/Teste1
cfb5c67b8b93daf0a777caed15f8fcefa1fce51d
[ "MIT" ]
null
null
null
raizes_equacao.cpp
Institutionoffoz/Teste1
cfb5c67b8b93daf0a777caed15f8fcefa1fce51d
[ "MIT" ]
null
null
null
raizes_equacao.cpp
Institutionoffoz/Teste1
cfb5c67b8b93daf0a777caed15f8fcefa1fce51d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> int raizes(double a, double b, double c, double *px1, double *px2) { double delta; if(a == 0.0) { *px1 = *px2 = -c/b; } else { delta = b * b - 4 * a * c; if(delta < 0) { *px1 = *px2 = -3.14159265359; } else { if(delta == 0.0) { *px1 = *px2 = -b/(2*a); } else { delta = sqrt(delta); *px1 = (-b+delta)/(2*a); *px2 = (-b-delta)/(2*a); } } } } int main() { double a, b, c; double x1, x2; printf("programa que calcula as raizes de uma equacao do segundo grau\n"); printf("informe os coeficientes (a b c)\n"); printf("informe a\n"); scanf("%lf", &a); printf("informe b\n"); scanf("%lf", &b); printf("informe c\n"); scanf("%lf", &c); raizes(a,b,c,&x1,&x2); if(x1 == -3.14159265359) { printf("raizes reais inexistentes\n"); } else { if(x1==x2) { printf("uma raiz real %.2lf\n", x1); } else { printf("duas raizes reais: %.2lf , %.2lf\n", x1, x2); } } return 0; }
19.671642
78
0.403642
Institutionoffoz
4e75707d7d71c63a8b0376c10824ee39930c8b04
80,177
cxx
C++
com/oleutest/stgbvt/ctolestg/tests/stgbase/irootstg.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/oleutest/stgbvt/ctolestg/tests/stgbase/irootstg.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/oleutest/stgbvt/ctolestg/tests/stgbase/irootstg.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//------------------------------------------------------------------------- // // Microsoft OLE // Copyright (C) Microsoft Corporation, 1994 - 1995. // // File: irootstg.cxx // // Contents: storage base tests basically pertaining to IRootStorage // interface. // // Functions: // // History: 25-July-1996 NarindK Created. // 27-Mar-97 SCousens Conversionified // //-------------------------------------------------------------------------- #include <dfheader.hxx> #pragma hdrstop #include "init.hxx" //Local Functions - Actual test functions. HRESULT IROOTSTGTEST_100a(int argc, char *argv[], LPTSTR ptAlt); HRESULT IROOTSTGTEST_101a(int argc, char *argv[], LPTSTR ptAlt); HRESULT IROOTSTGTEST_102a(int argc, char *argv[], LPTSTR ptAlt); HRESULT IROOTSTGTEST_103a(int argc, char *argv[], LPTSTR ptAlt); // These stubs call a processor function for common processing // before going on to call the actual tests. HRESULT IROOTSTGTEST_100(int argc, char *argv[]) { return RunTestAltPath(argc, argv, IROOTSTGTEST_100a); } HRESULT IROOTSTGTEST_101(int argc, char *argv[]) { return RunTestAltPath(argc, argv, IROOTSTGTEST_101a); } HRESULT IROOTSTGTEST_102(int argc, char *argv[]) { return RunTestAltPath(argc, argv, IROOTSTGTEST_102a); } HRESULT IROOTSTGTEST_103(int argc, char *argv[]) { return RunTestAltPath(argc, argv, IROOTSTGTEST_103a); } //---------------------------------------------------------------------------- // // Test: IROOTSTGTEST_100a // // Synopsis: A random docfile with random number of storages/streams is // created/committed/closed. The root docfile is instantiated // and CRC'd. QueryInterface for an IRootStorage is called and then // SwitchToFile with a new file name is called. The orignal file is // released. We then modify the switched to file, commit it, and // release. The original root docfile is then instantiated and CRC'd. // The CRCs are compared to verify that original file is unchanged. // // Arguments:[argc] // [argv] // // Returns: HRESULT // // History: 25-July-1996 NarindK Created. // // Notes: This test runs in direct, transacted, and transacted deny write // modes // // New Test Notes: // 1. Old File: LTSAVEAS.CXX // 2. Old name of test : LegitTransactedSaveAs // New Name of test : IROOTSTGTEST_100 // 3. To run the test, do the following at command prompt. // a. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-100 /dfRootMode:dirReadWriteShEx // /dfStgMode:dirReadWriteShEx // b. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-100 /dfRootMode:xactReadWriteShEx // /dfStgMode:xactReadWriteShEx // c. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-100 /dfRootMode:xactReadWriteShDenyW // /dfStgMode:xactReadWriteShEx // // BUGNOTE: Conversion: IROOTSTGTEST-100 NO - root stgs not suppd in nss // // Note: The IRootStorage interface is used to switch the underlying disk file // that IStorage Objects are being saved to. SwitchToFile makes a new // copy of the file underlying this Istorage and associated IStorage // object with this new file, rather than its current file, including // uncommitted changes. //----------------------------------------------------------------------------- HRESULT IROOTSTGTEST_100a(int argc, char *argv[], LPTSTR ptAlt) { HRESULT hr = S_OK; HRESULT hr2 = S_OK; ChanceDF *pTestChanceDF = NULL; VirtualDF *pTestVirtualDF = NULL; VirtualCtrNode *pVirtualDFRoot = NULL; LPTSTR pFileName = NULL; LPTSTR pNewRootDocFileName = NULL; LPOLESTR poszNewRootDocFileName = NULL; DWORD dwCRCOrg = 0; DWORD dwCRCNew = 0; DWORD dwRootMode = 0; DWORD dwStgMode = 0; LPSTORAGE pStgRootOrg = NULL; LPSTORAGE pStgRootNew = NULL; LPROOTSTORAGE pStgIRootStg = NULL; DG_STRING *pdgu = NULL; DG_INTEGER *pdgi = NULL; USHORT usErr = 0; ULONG ulRef = 0; BOOL fPass = TRUE; // Not for 2phase. Bail. if (DoingDistrib ()) { return S_OK; } DH_FUNCENTRY(NULL, DH_LVL_DFLIB, _TEXT("IROOTSTGTEST_100")); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_100 started.")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("IRootStorage-SwitchToFile, Save as. Modify DF, comp org DF."))); // Create the new ChanceDocFile tree that would consist of chance nodes. if (S_OK == hr) { pTestChanceDF = new ChanceDF(); if(NULL == pTestChanceDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestChanceDF->CreateFromParams(argc, argv); DH_HRCHECK(hr, TEXT("pTestChanceDF->CreateFromParams")) ; } if (S_OK == hr) { dwRootMode = pTestChanceDF->GetRootMode(); dwStgMode = pTestChanceDF->GetStgMode(); DH_TRACE(( DH_LVL_TRACE1, TEXT("Run Mode for IROOTSTGTEST_100, Access mode: %lx"), dwRootMode)); } // Create the VirtualDocFile tree from the ChanceDocFile tree created in // the previous step. The VirtualDocFile tree consists of VirtualCtrNodes // and VirtualStmNodes. if (S_OK == hr) { pTestVirtualDF = new VirtualDF(); if(NULL == pTestVirtualDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestVirtualDF->GenerateVirtualDF(pTestChanceDF, &pVirtualDFRoot); DH_HRCHECK(hr, TEXT("pTestVirtualDF->GenerateVirtualDF")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - successfully created."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - failed, hr = 0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCommitAllOpenStgs( pVirtualDFRoot, STGC_DEFAULT, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCommitAllOpenStgs")) ; } // Commit root. if(S_OK == hr) { hr = pVirtualDFRoot->Commit(STGC_DEFAULT); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit unsuccessful, hr=0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCloseOpenStgsStms( pVirtualDFRoot, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCloseOpenStgsStms")) ; } // Calculate CRC for entire DocFile without the RootDocfile name if(S_OK == hr) { pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_INC_TOPSTG_NAME, &dwCRCOrg); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Get the IRootStorage interface pointer by doing QueryInterface. if(S_OK == hr) { hr = pVirtualDFRoot->QueryInterface( IID_IRootStorage, (LPVOID *) &pStgIRootStg); DH_HRCHECK(hr, TEXT("VirtualCtrNode::QueryInterface")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface unsuccessful, hr=0x%lx."), hr)); } // Get DG_STRING object pointer if (S_OK == hr) { pdgu = pTestVirtualDF->GetDataGenUnicode(); DH_ASSERT(NULL != pdgu) ; } // Generates a new name for DocFile that we would switch to using the // IRootStorage::SwitchToFile if(S_OK == hr) { // Generate random name for new docfile that we would switch to hr = GenerateRandomName(pdgu,MINLENGTH,MAXLENGTH,&pNewRootDocFileName); DH_HRCHECK(hr, TEXT("GenerateRandomName")) ; } //prepend drive so IRootStorage::SwitchToFile goes onto a different drive. if(S_OK == hr && NULL != ptAlt) { LPTSTR ptszNewName = new TCHAR[_tcslen ((LPTSTR)pNewRootDocFileName)+4]; if (NULL != ptszNewName) { _stprintf (ptszNewName, TEXT("%s%s"), ptAlt, pNewRootDocFileName); delete []pNewRootDocFileName; pNewRootDocFileName = ptszNewName; } } if(S_OK == hr) { // Convert the new name to OLECHAR hr = TStringToOleString(pNewRootDocFileName, &poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("TStringToOleString")) ; } // Call IRootStorage::SwitchToFile if(S_OK == hr) { // Call DeleteFile just to make sure that pNewRootDocFileName doesn't // exist, before calling SwitchToFile DeleteFile(pNewRootDocFileName); DH_TRACE ((DH_LVL_TRACE1, TEXT("SwitchToFile: %s"), pNewRootDocFileName)); hr = pStgIRootStg->SwitchToFile(poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("IRootStorage::SwitchToFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile unsuccessful, hr=0x%lx."), hr)); } // Release the pStgIRootStg pointer if(S_OK == hr) { // Release the Reference count that was added by QueryInterface call. ulRef = pStgIRootStg->Release(); DH_ASSERT(1 == ulRef); } // Get DG_INTEGER object pointer if (S_OK == hr) { pdgi = pTestVirtualDF->GetDataGenInteger(); DH_ASSERT(NULL != pdgi) ; } // ModifyDocFile call. All the changes should be reflected to new docfile // (the one switched to) rather than original, since SwitchToFile asso // -ciated the ISotrage object with switchedto file rather than original // file. if (S_OK == hr) { hr = ModifyDocFile( pTestVirtualDF, pVirtualDFRoot, pdgi, pdgu, dwStgMode, TRUE); DH_HRCHECK(hr, TEXT("ModifyDocFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destroy/Open/Close elem- passed as exp."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destry/Open/Close elem- failed, hr=0x%lx"), hr)); } // Try to open second time when flags are STGM_DENY_WRITE. This should // fail with STG_E_LOCKVIOLATION error. if (S_OK == hr) { if(dwRootMode & STGM_SHARE_DENY_WRITE) { if(S_OK == hr) { hr = StgOpenStorage( poszNewRootDocFileName, NULL, dwRootMode, NULL, 0, &pStgRootNew); } if(STG_E_LOCKVIOLATION == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("STGM_SHARE_DENY_WRITE: StgOpenStg hr = 0x%lx exp"), hr)); hr = S_OK; } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("STGM_SHARE_DENY_WRITE:StgOpenStg hr = 0x%lx unexp"), hr)); fPass = FALSE; } } } // Close the Original DocFile if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Open the original Root DocFile again if(S_OK == hr) { hr = pVirtualDFRoot->Open(NULL, dwRootMode, NULL, 0); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Open")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open unsuccessful, hr=0x%lx."), hr)); } // Calculate CRC for entire original DocFile without the RootDocfile name. // This CRC should match with CRC calculated for original DocFile since // all the changes being made after first CRC calculation should have been // to switched to file. if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_INC_TOPSTG_NAME, &dwCRCNew); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's if(S_OK == hr) { if(dwCRCOrg == dwCRCNew) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match, original file unchanged as expected."))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match, original file got changed unexp."))); } } // Close original file. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Get some info about the test TCHAR szFileSystemInfoBuffer[10] = {TEXT(" :(")}; GetVolumeInformation (ptAlt, NULL, //lpVolumeNameBuffer 0, //nVolumeNameSize NULL, NULL, NULL, //lpFileSystemFlags &szFileSystemInfoBuffer[3], sizeof (szFileSystemInfoBuffer)-4); _tcscat (szFileSystemInfoBuffer, TEXT(")")); if (NULL != ptAlt) { *szFileSystemInfoBuffer = *ptAlt; } // if everything goes well, log test as passed else failed. if ((S_OK == hr) && (TRUE == fPass)) { DH_LOG((LOG_PASS, TEXT("Test IROOTSTGTEST_100 passed. %s"), szFileSystemInfoBuffer)); } else { DH_LOG((LOG_FAIL, TEXT("Test IROOTSTGTEST_100 failed, hr = 0x%lx. %s"), hr, szFileSystemInfoBuffer)); DH_DUMPCMD((LOG_FAIL, TEXT(" /seed:%u %s%c"), pTestChanceDF->GetSeed(), NULL == ptAlt ? TEXT("") : TEXT("/altpath:"), NULL == ptAlt ? TCHAR('\0') : TCHAR(*ptAlt))); // test failed. make it look like it failed. hr = FirstError (hr, E_FAIL); } // Cleanup // Get the name of file, will be used later to delete the file if(NULL != pVirtualDFRoot) { pFileName= new TCHAR[_tcslen(pTestVirtualDF->GetDocFileName())+1]; if (pFileName != NULL) { _tcscpy(pFileName, pTestVirtualDF->GetDocFileName()); } } // Delete Chance docfile tree if(NULL != pTestChanceDF) { hr2 = pTestChanceDF->DeleteChanceDocFileTree( pTestChanceDF->GetChanceDFRoot()); DH_HRCHECK(hr2, TEXT("pTestChanceDF->DeleteChanceFileDocTree")) ; delete pTestChanceDF; pTestChanceDF = NULL; } // Delete Virtual docfile tree if(NULL != pTestVirtualDF) { hr2 = pTestVirtualDF->DeleteVirtualDocFileTree(pVirtualDFRoot); DH_HRCHECK(hr2, TEXT("pTestVirtualDF->DeleteVirtualFileDocTree")) ; delete pTestVirtualDF; pTestVirtualDF = NULL; } // Delete the original docfile on disk if((S_OK == hr) && (NULL != pFileName)) { if(FALSE == DeleteFile(pFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete the new docfile on disk if((S_OK == hr) && (NULL != pNewRootDocFileName)) { if(FALSE == DeleteFile(pNewRootDocFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete temp string if(NULL != pFileName) { delete pFileName; pFileName = NULL; } if(NULL != poszNewRootDocFileName) { delete poszNewRootDocFileName; poszNewRootDocFileName = NULL; } if(NULL != pNewRootDocFileName) { delete pNewRootDocFileName; pNewRootDocFileName = NULL; } // Stop logging the test DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_100 finished")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); return hr; } //---------------------------------------------------------------------------- // // Test: IROOTSTGTEST_101a // // Synopsis: A random docfile with random number of storages/streams is // created/committed/closed. The root docfile is instantiated, // modified, and then CRC' is calculated for that. We then do // do QueryInterface for an IRootStorage and SwitchToFile to // a new root docfile. The new docfile is CRC'd and compared to // the original, they should match at this point. This docfile is // then modified, CRC'd, and released. This docfile is then // re-instantiated, CRC'd, and the previous two CRCs are compared. // The original root docfile is then instantiated and CRC'd and // the CRC is compared against the orignal CRC. // // Arguments:[argc] // [argv] // // Returns: HRESULT // // History: 25-July-1996 NarindK Created. // // Notes: This test runs in direct, transacted, and transacted deny write // modes // // New Test Notes: // 1. Old File: LTSVBOTH.CXX // 2. Old name of test : LegitTransactedSaveAsBoth // New Name of test : IROOTSTGTEST_101 // 3. To run the test, do the following at command prompt. // a. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-101 /dfRootMode:dirReadWriteShEx // /dfStgMode:dirReadWriteShEx // b. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-101 /dfRootMode:xactReadWriteShEx // /dfStgMode:xactReadWriteShEx // c. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-101 /dfRootMode:xactReadWriteShDenyW // /dfStgMode:xactReadWriteShEx // // BUGNOTE: Conversion: IROOTSTGTEST-101 NO - root stgs not suppd in nss // // Note: The IRootStorage interface is used to switch the underlying disk file // that IStorage Objects are being saved to. SwitchToFile makes a new // copy of the file underlying this Istorage and associated IStorage // object with this new file, rather than its current file, including // uncommitted changes. //----------------------------------------------------------------------------- HRESULT IROOTSTGTEST_101a(int argc, char *argv[], LPTSTR ptAlt) { HRESULT hr = S_OK; HRESULT hr2 = S_OK; ChanceDF *pTestChanceDF = NULL; VirtualDF *pTestVirtualDF = NULL; VirtualCtrNode *pVirtualDFRoot = NULL; LPTSTR pFileName = NULL; LPTSTR pNewRootDocFileName = NULL; LPOLESTR poszNewRootDocFileName = NULL; DWORD dwCRCOrg = 0; DWORD dwCRCNew = 0; DWORD dwCRCTemp = 0; DWORD dwRootMode = 0; DWORD dwStgMode = 0; LPSTORAGE pStgRootOrg = NULL; LPSTORAGE pStgRootNew = NULL; LPROOTSTORAGE pStgIRootStg = NULL; DG_STRING *pdgu = NULL; DG_INTEGER *pdgi = NULL; USHORT usErr = 0; ULONG ulRef = 0; BOOL fPass = TRUE; // Not for 2phase. Bail. if (DoingDistrib ()) { return S_OK; } DH_FUNCENTRY(NULL, DH_LVL_DFLIB, _TEXT("IROOTSTGTEST_101")); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_101 started.")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("IRootStorage-SwitchToFile, Save as both. Modify both DF/cmp"))); // Create the new ChanceDocFile tree that would consist of chance nodes. if (S_OK == hr) { pTestChanceDF = new ChanceDF(); if(NULL == pTestChanceDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestChanceDF->CreateFromParams(argc, argv); DH_HRCHECK(hr, TEXT("pTestChanceDF->CreateFromParams")) ; } if (S_OK == hr) { dwRootMode = pTestChanceDF->GetRootMode(); dwStgMode = pTestChanceDF->GetStgMode(); DH_TRACE(( DH_LVL_TRACE1, TEXT("Run Mode for IROOTSTGTEST_101, Access mode: %lx"), dwRootMode)); } // Create the VirtualDocFile tree from the ChanceDocFile tree created in // the previous step. The VirtualDocFile tree consists of VirtualCtrNodes // and VirtualStmNodes. if (S_OK == hr) { pTestVirtualDF = new VirtualDF(); if(NULL == pTestVirtualDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestVirtualDF->GenerateVirtualDF(pTestChanceDF, &pVirtualDFRoot); DH_HRCHECK(hr, TEXT("pTestVirtualDF->GenerateVirtualDF")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - successfully created."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - failed, hr = 0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCommitAllOpenStgs( pVirtualDFRoot, STGC_DEFAULT, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCommitAllOpenStgs")) ; } // Commit root. if(S_OK == hr) { hr = pVirtualDFRoot->Commit(STGC_DEFAULT); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit unsuccessful, hr=0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCloseOpenStgsStms( pVirtualDFRoot, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCloseOpenStgsStms")) ; } // Get DG_INTEGER object pointer if (S_OK == hr) { pdgi = pTestVirtualDF->GetDataGenInteger(); DH_ASSERT(NULL != pdgi) ; } // Get DG_STRING object pointer if (S_OK == hr) { pdgu = pTestVirtualDF->GetDataGenUnicode(); DH_ASSERT(NULL != pdgu) ; } // Modify original docfile now and then calculate CRC for it which would // be the original CRC value. if (S_OK == hr) { hr = ModifyDocFile( pTestVirtualDF, pVirtualDFRoot, pdgi, pdgu, dwStgMode, TRUE); DH_HRCHECK(hr, TEXT("ModifyDocFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destroy/Open/Close elem- passed as exp."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destry/Open/Close elem- failed, hr=0x%lx"), hr)); } // Calculate CRC for entire DocFile without the RootDocfile name for // original DocFile after making changes, but before calling SwitchToFile. // This is the original CRC value. if(S_OK == hr) { pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCOrg); DH_TRACE ((DH_LVL_TRACE2, TEXT("CRC original file %#x"), dwCRCOrg)); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Get the IRootStorage interface pointer by doing QueryInterface on it. if(S_OK == hr) { hr = pVirtualDFRoot->QueryInterface( IID_IRootStorage, (LPVOID *) &pStgIRootStg); DH_HRCHECK(hr, TEXT("VirtualCtrNode::QueryInterface")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface unsuccessful, hr=0x%lx."), hr)); } // Generates a new name for DocFile that we would switch to using the // IRootStorage::SwitchToFile if(S_OK == hr) { // Generate random name for new docfile that we would switch to hr = GenerateRandomName(pdgu,MINLENGTH,MAXLENGTH,&pNewRootDocFileName); DH_HRCHECK(hr, TEXT("GenerateRandomName")) ; } //prepend drive so IRootStorage::SwitchToFile goes onto a different drive. if(S_OK == hr && NULL != ptAlt) { LPTSTR ptszNewName = new TCHAR[_tcslen ((LPTSTR)pNewRootDocFileName)+4]; if (NULL != ptszNewName) { _stprintf (ptszNewName, TEXT("%s%s"), ptAlt, pNewRootDocFileName); delete []pNewRootDocFileName; pNewRootDocFileName = ptszNewName; } } if(S_OK == hr) { // Convert the new name to OLECHAR hr = TStringToOleString(pNewRootDocFileName, &poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("TStringToOleString")) ; } // Call IRootStorage::SwitchToFile. Therafter the IStorage would become // assocaited with new switched to file rather than original file and all // changes, including uncommitted ones, would be reflected to the new // switched to file rather than original file. if(S_OK == hr) { // Call DeleteFile just to make sure that pNewRootDocFileName doesn't // exist, before calling SwitchToFile DeleteFile(pNewRootDocFileName); DH_TRACE ((DH_LVL_TRACE1, TEXT("SwitchToFile: %s"), pNewRootDocFileName)); hr = pStgIRootStg->SwitchToFile(poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("IRootStorage::SwitchToFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile unsuccessful, hr=0x%lx."), hr)); } // Release the pStgIRootStg pointer if(S_OK == hr) { // Release the Reference count that was added by QueryInterface call. ulRef = pStgIRootStg->Release(); DH_ASSERT(1 == ulRef); } // Get the new root DocFile CRC after switching to File, should be the // same as original root DocFile CRC at this point. Calculate CRC and // compare to make sure. if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_TRACE ((DH_LVL_TRACE2, TEXT("CRC switched file %#x"), dwCRCTemp)); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's at this point, these should match if(S_OK == hr) { if(dwCRCOrg == dwCRCTemp) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match of org & switched to file as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match of org & switched to file unexp"))); } } // Call ModifyDocFile call. All the canges are being getting reflected to // the new root DocFile since SwitchToFile associated IStorage with switch // to file rather than original file. if (S_OK == hr) { hr = ModifyDocFile( pTestVirtualDF, pVirtualDFRoot, pdgi, pdgu, dwStgMode, TRUE); DH_HRCHECK(hr, TEXT("ModifyDocFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destroy/Open/Close elem- passed as exp."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destry/Open/Close elem- failed, hr=0x%lx"), hr)); } // Get new root DocFile CRC after making changes to new DocFile and commit // ing them. This will be compared to the new docfile CRC after release // and reinstantiation. if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCNew); DH_TRACE ((DH_LVL_TRACE2, TEXT("CRC switched/modified file %#x"), dwCRCNew)); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Close the Original DocFile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Open the new Root DocFile. The CRC will be computed on it, this // is expected to match dwCRCNew that was calculated before. if(S_OK == hr) { hr = StgOpenStorage( poszNewRootDocFileName, NULL, dwRootMode, NULL, 0, &pStgRootNew); DH_HRCHECK(hr, TEXT("StgOpenStorage")) ; } // Calculate the CRC on this new root DocFile if(S_OK == hr) { dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootNew, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_TRACE ((DH_LVL_TRACE2, TEXT("CRC new (after switch) file %#x"), dwCRCTemp)); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's at this point. The CRC of this new docfile and the // DocFile that was switched to and then modified should match. if(S_OK == hr) { if(dwCRCNew == dwCRCTemp) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match of new & switched to file as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match of new & switched to file unexp"))); } } // Close the new root DocFile if(S_OK == hr) { ulRef = pStgRootNew->Release(); DH_ASSERT(0 == ulRef); pStgRootNew = NULL; } // Open the original Root DocFile again. The CRC would be calculated on // this, it is expected to match dwCRCOrg, thereby verifying that because // of SwitchToFile, the original file remained unchanged. if(S_OK == hr) { hr = pVirtualDFRoot->Open(NULL, dwRootMode, NULL, 0); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Open")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open unsuccessful, hr=0x%lx."), hr)); } // Calculate CRC for entire DocFile without the RootDocfile name if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_TRACE ((DH_LVL_TRACE2, TEXT("CRC original file again %#x"), dwCRCTemp)); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's of the this orginal docfile after reinstantiation and // the original value before SwitchToFile was done. These should match. if(S_OK == hr) { if(dwCRCTemp == dwCRCOrg) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match, original file unchanged as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match, original file changed unexp"))); } } // Close original root docfile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Get some info about the test TCHAR szFileSystemInfoBuffer[10] = {TEXT(" :(")}; GetVolumeInformation (ptAlt, NULL, //lpVolumeNameBuffer 0, //nVolumeNameSize NULL, NULL, NULL, //lpFileSystemFlags &szFileSystemInfoBuffer[3], sizeof (szFileSystemInfoBuffer)-4); _tcscat (szFileSystemInfoBuffer, TEXT(")")); if (NULL != ptAlt) { *szFileSystemInfoBuffer = *ptAlt; } // if everything goes well, log test as passed else failed. if ((S_OK == hr) && (TRUE == fPass)) { DH_LOG((LOG_PASS, TEXT("Test variation IROOTSTGTEST_101 passed. %s"), szFileSystemInfoBuffer) ); } else { DH_LOG((LOG_FAIL, TEXT("Test variation IROOTSTGTEST_101 failed, hr = 0x%lx. %s"), hr, szFileSystemInfoBuffer) ); DH_DUMPCMD((LOG_FAIL, TEXT(" /seed:%u %s%c"), pTestChanceDF->GetSeed(), NULL == ptAlt ? TEXT("") : TEXT("/altpath:"), NULL == ptAlt ? TCHAR('\0') : TCHAR(*ptAlt))); // test failed. make it look like it failed. hr = FirstError (hr, E_FAIL); } // Cleanup // Get the name of file, will be used later to delete the file if(NULL != pVirtualDFRoot) { pFileName= new TCHAR[_tcslen(pTestVirtualDF->GetDocFileName())+1]; if (pFileName != NULL) { _tcscpy(pFileName, pTestVirtualDF->GetDocFileName()); } } // Delete Chance docfile tree if(NULL != pTestChanceDF) { hr2 = pTestChanceDF->DeleteChanceDocFileTree( pTestChanceDF->GetChanceDFRoot()); DH_HRCHECK(hr2, TEXT("pTestChanceDF->DeleteChanceFileDocTree")) ; delete pTestChanceDF; pTestChanceDF = NULL; } // Delete Virtual docfile tree if(NULL != pTestVirtualDF) { hr2 = pTestVirtualDF->DeleteVirtualDocFileTree(pVirtualDFRoot); DH_HRCHECK(hr2, TEXT("pTestVirtualDF->DeleteVirtualFileDocTree")) ; delete pTestVirtualDF; pTestVirtualDF = NULL; } // Delete the original docfile on disk if((S_OK == hr) && (NULL != pFileName)) { if(FALSE == DeleteFile(pFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete the new docfile on disk if((S_OK == hr) && (NULL != pNewRootDocFileName)) { if(FALSE == DeleteFile(pNewRootDocFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete temp string if(NULL != pFileName) { delete pFileName; pFileName = NULL; } if(NULL != pNewRootDocFileName) { delete pNewRootDocFileName; pNewRootDocFileName = NULL; } if(NULL != poszNewRootDocFileName) { delete poszNewRootDocFileName; poszNewRootDocFileName = NULL; } // Stop logging the test DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_101 finished")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); return hr; } //---------------------------------------------------------------------------- // // Test: IROOTSTGTEST_102 // // Synopsis: A random docfile with random number of storages/streams is // created/committed/closed. The root docfile is instantiated, // and CRC is calculated for the docfile. It is then modified & // CRC'd again. The test then calls QueryInterface to get an // IRootStorage and SwitchesToFile on a new name. The new docfile // is committed, released, reinstantiated, and CRC'd. This CRC // should match the CRC of the modified original root docfile. // The original docfile is then instantiated and CRC'd. This // CRC should match the *first* CRC of the original root docfile // since we called SwitchToFile() before committing the changes. // // Arguments:[argc] // [argv] // // Returns: HRESULT // // History: 26-July-1996 NarindK Created. // // Notes: This test runs in transacted, and transacted deny write modes. // // New Test Notes: // 1. Old File: LTSVNEW.CXX // 2. Old name of test : LegitTransactedSaveAsNew // New Name of test : IROOTSTGTEST_102 // 3. To run the test, do the following at command prompt. // b. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-102 /dfRootMode:xactReadWriteShEx // /dfStgMode:xactReadWriteShEx // c. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-102 /dfRootMode:xactReadWriteShDenyW // /dfStgMode:xactReadWriteShEx // // BUGNOTE: Conversion: IROOTSTGTEST-102 NO - root stgs not suppd in nss // // Note: The IRootStorage interface is used to switch the underlying disk file // that IStorage Objects are being saved to. SwitchToFile makes a new // copy of the file underlying this Istorage and associated IStorage // object with this new file, rather than its current file, including // uncommitted changes. //----------------------------------------------------------------------------- HRESULT IROOTSTGTEST_102a(int argc, char *argv[], LPTSTR ptAlt) { HRESULT hr = S_OK; HRESULT hr2 = S_OK; ChanceDF *pTestChanceDF = NULL; VirtualDF *pTestVirtualDF = NULL; VirtualCtrNode *pVirtualDFRoot = NULL; LPTSTR pFileName = NULL; LPTSTR pNewRootDocFileName = NULL; LPOLESTR poszNewRootDocFileName = NULL; DWORD dwCRCOrg = 0; DWORD dwCRCNew = 0; DWORD dwCRCTemp = 0; DWORD dwRootMode = 0; DWORD dwStgMode = 0; LPSTORAGE pStgRootOrg = NULL; LPSTORAGE pStgRootNew = NULL; LPROOTSTORAGE pStgIRootStg = NULL; DG_STRING *pdgu = NULL; DG_INTEGER *pdgi = NULL; USHORT usErr = 0; ULONG ulRef = 0; BOOL fPass = TRUE; // Not for 2phase. Bail. if (DoingDistrib ()) { return S_OK; } DH_FUNCENTRY(NULL, DH_LVL_DFLIB, _TEXT("IROOTSTGTEST_102")); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_102 started.")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("IRootStorage-SwitchToFile, Save as new."))); // Create the new ChanceDocFile tree that would consist of chance nodes. if (S_OK == hr) { pTestChanceDF = new ChanceDF(); if(NULL == pTestChanceDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestChanceDF->CreateFromParams(argc, argv); DH_HRCHECK(hr, TEXT("pTestChanceDF->CreateFromParams")) ; } if (S_OK == hr) { dwRootMode = pTestChanceDF->GetRootMode(); dwStgMode = pTestChanceDF->GetStgMode(); DH_TRACE(( DH_LVL_TRACE1, TEXT("Run Mode for IROOTSTGTEST_102, Access mode: %lx"), dwRootMode)); } // Create the VirtualDocFile tree from the ChanceDocFile tree created in // the previous step. The VirtualDocFile tree consists of VirtualCtrNodes // and VirtualStmNodes. if (S_OK == hr) { pTestVirtualDF = new VirtualDF(); if(NULL == pTestVirtualDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestVirtualDF->GenerateVirtualDF(pTestChanceDF, &pVirtualDFRoot); DH_HRCHECK(hr, TEXT("pTestVirtualDF->GenerateVirtualDF")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - successfully created."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - failed, hr = 0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCommitAllOpenStgs( pVirtualDFRoot, STGC_DEFAULT, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCommitAllOpenStgs")) ; } // Commit root. if(S_OK == hr) { hr = pVirtualDFRoot->Commit(STGC_DEFAULT); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit unsuccessful, hr=0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCloseOpenStgsStms( pVirtualDFRoot, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCloseOpenStgsStms")) ; } // Get DG_INTEGER object pointer if (S_OK == hr) { pdgi = pTestVirtualDF->GetDataGenInteger(); DH_ASSERT(NULL != pdgi) ; } // Get DG_STRING object pointer if (S_OK == hr) { pdgu = pTestVirtualDF->GetDataGenUnicode(); DH_ASSERT(NULL != pdgu) ; } // Calculate CRC for entire DocFile without the RootDocfile name for // original DocFile before making changes. Then modify DocFile, but // don't commit the changes. Get a new CRC reflecting these changes // and then switch to a new file *but* don't commit first. if(S_OK == hr) { pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCOrg); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; DH_TRACE ((DH_LVL_TRACE4, TEXT("CRC for docfile: %#lx"), dwCRCOrg)); } // Modify original docfile now, but don't commit the changes to root. if (S_OK == hr) { hr = ModifyDocFile( pTestVirtualDF, pVirtualDFRoot, pdgi, pdgu, dwStgMode, FALSE); DH_HRCHECK(hr, TEXT("ModifyDocFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destroy/Open/Close elem- passed as exp."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destry/Open/Close elem- failed, hr=0x%lx"), hr)); } // Calculate CRC for entire DocFile without the RootDocfile name for // original DocFile after making changes, but not commiting these to // root. Let this be the new CRC value. if(S_OK == hr) { hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCNew); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; DH_TRACE ((DH_LVL_TRACE4, TEXT("CRC for docfile: %#lx"), dwCRCNew)); } // Get the IRootStorage interface pointer by doing QueryInterface on it. if(S_OK == hr) { hr = pVirtualDFRoot->QueryInterface( IID_IRootStorage, (LPVOID *) &pStgIRootStg); DH_HRCHECK(hr, TEXT("VirtualCtrNode::QueryInterface")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface unsuccessful, hr=0x%lx."), hr)); } // Generates a new name for DocFile that we would switch to using the // IRootStorage::SwitchToFile if(S_OK == hr) { // Generate random name for new docfile that we would switch to hr = GenerateRandomName(pdgu,MINLENGTH,MAXLENGTH,&pNewRootDocFileName); DH_HRCHECK(hr, TEXT("GenerateRandomName")) ; } //prepend drive so IRootStorage::SwitchToFile goes onto a different drive. if(S_OK == hr && NULL != ptAlt) { LPTSTR ptszNewName = new TCHAR[_tcslen ((LPTSTR)pNewRootDocFileName)+4]; if (NULL != ptszNewName) { _stprintf (ptszNewName, TEXT("%s%s"), ptAlt, pNewRootDocFileName); delete []pNewRootDocFileName; pNewRootDocFileName = ptszNewName; } } // Call IRootStorage::SwitchToFile. Therafter the IStorage would become // assocaited with new switched to file rather than original file and all // changes, including uncommitted ones, would be reflected to the new // switched to file rather than original file. if (S_OK == hr) { // Convert name to OLECHAR hr =TStringToOleString(pNewRootDocFileName,&poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("TStringToOleString")) ; } if(S_OK == hr) { // Call DeleteFile just to make sure that pNewRootDocFileName doesn't // exist, before calling SwitchToFile DeleteFile(pNewRootDocFileName); DH_TRACE ((DH_LVL_TRACE1, TEXT("SwitchToFile: %s"), pNewRootDocFileName)); hr = pStgIRootStg->SwitchToFile(poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("IRootStorage::SwitchToFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile unsuccessful, hr=0x%lx."), hr)); } // Release the pStgIRootStg pointer if(S_OK == hr) { // Release the Reference count that was added by QueryInterface call. ulRef = pStgIRootStg->Release(); DH_ASSERT(1 == ulRef); } // Commit the Original DocFile. if(S_OK == hr) { hr = pVirtualDFRoot->Commit(STGC_DEFAULT); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit unsuccessful, hr=0x%lx."), hr)); } // Close the Original DocFile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Open the new Root DocFile. The CRC will be computed on it, this // is expected to match dwCRCNew that was calculated before. if(S_OK == hr) { hr = StgOpenStorage( poszNewRootDocFileName, NULL, dwRootMode, NULL, 0, &pStgRootNew); DH_HRCHECK(hr, TEXT("StgOpenStorage")) ; } // Calculate the CRC on this new root DocFile if(S_OK == hr) { dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootNew, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; DH_TRACE ((DH_LVL_TRACE4, TEXT("CRC for docfile: %#lx"), dwCRCTemp)); } // Compare CRC's at this point. The CRC of this new docfile and the // DocFile that was switched to and then modified should match. if(S_OK == hr) { if(dwCRCNew == dwCRCTemp) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match of new & switched to file as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match of new & switched to file unexp"))); } } // Close the new root DocFile if(S_OK == hr) { ulRef = pStgRootNew->Release(); DH_ASSERT(0 == ulRef); pStgRootNew = NULL; } // Open the original Root DocFile again. The CRC would be calculated on // this, it is expected to match dwCRCOrg, thereby verifying that because // of SwitchToFile, the original file remained unchanged. if(S_OK == hr) { hr = pVirtualDFRoot->Open(NULL, dwRootMode, NULL, 0); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Open")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open unsuccessful, hr=0x%lx."), hr)); } // Calculate CRC for original DocFile without the RootDocfile name if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; DH_TRACE ((DH_LVL_TRACE4, TEXT("CRC for docfile: %#lx"), dwCRCTemp)); } // Compare CRC's of the this orginal docfile after reinstantiation and // the original value before SwitchToFile was done. These should match. if(S_OK == hr) { if(dwCRCTemp == dwCRCOrg) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match, original file unchanged as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match, original file changed unexp"))); } } // Close original root docfile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Get some info about the test TCHAR szFileSystemInfoBuffer[10] = {TEXT(" :(")}; GetVolumeInformation (ptAlt, NULL, //lpVolumeNameBuffer 0, //nVolumeNameSize NULL, NULL, NULL, //lpFileSystemFlags &szFileSystemInfoBuffer[3], sizeof (szFileSystemInfoBuffer)-4); _tcscat (szFileSystemInfoBuffer, TEXT(")")); if (NULL != ptAlt) { *szFileSystemInfoBuffer = *ptAlt; } // if everything goes well, log test as passed else failed. if ((S_OK == hr) && (TRUE == fPass)) { DH_LOG((LOG_PASS, TEXT("Test variation IROOTSTGTEST_102 passed. %s"), szFileSystemInfoBuffer) ); } else { DH_LOG((LOG_FAIL, TEXT("Test variation IROOTSTGTEST_102 failed, hr = 0x%lx. %s"), hr, szFileSystemInfoBuffer) ); DH_DUMPCMD((LOG_FAIL, TEXT(" /seed:%u %s%c"), pTestChanceDF->GetSeed(), NULL == ptAlt ? TEXT("") : TEXT("/altpath:"), NULL == ptAlt ? TCHAR('\0') : TCHAR(*ptAlt))); // test failed. make it look like it failed. hr = FirstError (hr, E_FAIL); } // Cleanup // Get the name of file, will be used later to delete the file if(NULL != pVirtualDFRoot) { pFileName= new TCHAR[_tcslen(pTestVirtualDF->GetDocFileName())+1]; if (pFileName != NULL) { _tcscpy(pFileName, pTestVirtualDF->GetDocFileName()); } } // Delete Chance docfile tree if(NULL != pTestChanceDF) { hr2 = pTestChanceDF->DeleteChanceDocFileTree( pTestChanceDF->GetChanceDFRoot()); DH_HRCHECK(hr2, TEXT("pTestChanceDF->DeleteChanceFileDocTree")) ; delete pTestChanceDF; pTestChanceDF = NULL; } // Delete Virtual docfile tree if(NULL != pTestVirtualDF) { hr2 = pTestVirtualDF->DeleteVirtualDocFileTree(pVirtualDFRoot); DH_HRCHECK(hr2, TEXT("pTestVirtualDF->DeleteVirtualFileDocTree")) ; delete pTestVirtualDF; pTestVirtualDF = NULL; } // Delete the original docfile on disk if((S_OK == hr) && (NULL != pFileName)) { if(FALSE == DeleteFile(pFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete the new docfile on disk if((S_OK == hr) && (NULL != pNewRootDocFileName)) { if(FALSE == DeleteFile(pNewRootDocFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete temp string if(NULL != pFileName) { delete pFileName; pFileName = NULL; } if(NULL != pNewRootDocFileName) { delete pNewRootDocFileName; pNewRootDocFileName = NULL; } if(NULL != poszNewRootDocFileName) { delete poszNewRootDocFileName; poszNewRootDocFileName = NULL; } // Stop logging the test DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_102 finished")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); return hr; } //---------------------------------------------------------------------------- // // Test: IROOTSTGTEST_103 // // Synopsis: A random docfile with random number of storages/streams is // created/committed/closed. The root docfile is instantiated, // and CRC is calculated for the docfile. It is then modified & // CRC'd again. The test then calls QueryInterface to get an // IRootStorage and SwitchesToFile on a new name. The new docfile // is reverted, released, reinstantiated, and CRC'd. This CRC // should match the *first* CRC of the original root DocfFile, // rather than the CRC of the modified original root docfile. // The original docfile is then instantiated and CRC'd. This // CRC should match the *first* CRC of the original root docfile // since we called SwitchToFile() before committing the changes. // // Arguments:[argc] // [argv] // // Returns: HRESULT // // History: 26-July-1996 NarindK Created. // // Notes: This test runs in transacted, and transacted deny write modes. // // New Test Notes: // 1. Old File: LTSVREV.CXX // 2. Old name of test : LegitTransactedSaveAsRevert // New Name of test : IROOTSTGTEST_103 // 3. To run the test, do the following at command prompt. // b. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-103 /dfRootMode:xactReadWriteShEx // /dfStgMode:xactReadWriteShEx // c. stgbase /seed:2 /dfdepth:1-1 /dfstg:1-3 /dfstm:0-3 // /t:IROOTSTGTEST-103 /dfRootMode:xactReadWriteShDenyW // /dfStgMode:xactReadWriteShEx // // BUGNOTE: Conversion: IROOTSTGTEST-103 NO - root stgs not suppd in nss // // Note: The IRootStorage interface is used to switch the underlying disk file // that IStorage Objects are being saved to. SwitchToFile makes a new // copy of the file underlying this Istorage and associated IStorage // object with this new file, rather than its current file, including // uncommitted changes. //----------------------------------------------------------------------------- HRESULT IROOTSTGTEST_103a(int argc, char *argv[], LPTSTR ptAlt) { HRESULT hr = S_OK; HRESULT hr2 = S_OK; ChanceDF *pTestChanceDF = NULL; VirtualDF *pTestVirtualDF = NULL; VirtualCtrNode *pVirtualDFRoot = NULL; LPTSTR pFileName = NULL; LPTSTR pNewRootDocFileName = NULL; LPOLESTR poszNewRootDocFileName = NULL; DWORD dwCRCOrg = 0; DWORD dwCRCNew = 0; DWORD dwCRCTemp = 0; DWORD dwRootMode = 0; DWORD dwStgMode = 0; LPSTORAGE pStgRootOrg = NULL; LPSTORAGE pStgRootNew = NULL; LPROOTSTORAGE pStgIRootStg = NULL; DG_STRING *pdgu = NULL; DG_INTEGER *pdgi = NULL; USHORT usErr = 0; ULONG ulRef = 0; BOOL fPass = TRUE; // Not for 2phase. Bail. if (DoingDistrib ()) { return S_OK; } DH_FUNCENTRY(NULL, DH_LVL_DFLIB, _TEXT("IROOTSTGTEST_103")); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_103 started.")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("IRootStorage-SwitchToFile, Save as Revert"))); // Create the new ChanceDocFile tree that would consist of chance nodes. if (S_OK == hr) { pTestChanceDF = new ChanceDF(); if(NULL == pTestChanceDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestChanceDF->CreateFromParams(argc, argv); DH_HRCHECK(hr, TEXT("pTestChanceDF->CreateFromParams")) ; } if (S_OK == hr) { dwRootMode = pTestChanceDF->GetRootMode(); dwStgMode = pTestChanceDF->GetStgMode(); DH_TRACE(( DH_LVL_TRACE1, TEXT("Run Mode for IROOTSTGTEST_103, Access mode: %lx"), dwRootMode)); } // Create the VirtualDocFile tree from the ChanceDocFile tree created in // the previous step. The VirtualDocFile tree consists of VirtualCtrNodes // and VirtualStmNodes. if (S_OK == hr) { pTestVirtualDF = new VirtualDF(); if(NULL == pTestVirtualDF) { hr = E_OUTOFMEMORY; } } if (S_OK == hr) { hr = pTestVirtualDF->GenerateVirtualDF(pTestChanceDF, &pVirtualDFRoot); DH_HRCHECK(hr, TEXT("pTestVirtualDF->GenerateVirtualDF")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - successfully created."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("DocFile - CreateFromParams - failed, hr = 0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCommitAllOpenStgs( pVirtualDFRoot, STGC_DEFAULT, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCommitAllOpenStgs")) ; } // Commit root. if(S_OK == hr) { hr = pVirtualDFRoot->Commit(STGC_DEFAULT); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Commit unsuccessful, hr=0x%lx."), hr)); } if(S_OK == hr) { hr = ParseVirtualDFAndCloseOpenStgsStms( pVirtualDFRoot, NODE_EXC_TOPSTG); DH_HRCHECK(hr, TEXT("ParseVirtualDFAndCloseOpenStgsStms")) ; } // Get DG_INTEGER object pointer if (S_OK == hr) { pdgi = pTestVirtualDF->GetDataGenInteger(); DH_ASSERT(NULL != pdgi) ; } // Get DG_STRING object pointer if (S_OK == hr) { pdgu = pTestVirtualDF->GetDataGenUnicode(); DH_ASSERT(NULL != pdgu) ; } // Calculate CRC for entire DocFile without the RootDocfile name for // original DocFile before making changes. Then modify DocFile, but // don't commit the changes to root. Get new CRC reflecting these changes // and then switch to a new file *but* don't commit first. if(S_OK == hr) { pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCOrg); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Modify original docfile now, but dont commit the changes to root. if (S_OK == hr) { hr = ModifyDocFile( pTestVirtualDF, pVirtualDFRoot, pdgi, pdgu, dwStgMode, FALSE); DH_HRCHECK(hr, TEXT("ModifyDocFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destroy/Open/Close elem- passed as exp."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("ModifyDF-Rename/Destry/Open/Close elem- failed, hr=0x%lx"), hr)); } // Calculate CRC for entire DocFile without the RootDocfile name for // original DocFile after making changes, but not commiting these to // root. Let this be the new CRC value. if(S_OK == hr) { hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCNew); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Get the IRootStorage interface pointer by doing QueryInterface on it. if(S_OK == hr) { hr = pVirtualDFRoot->QueryInterface( IID_IRootStorage, (LPVOID *) &pStgIRootStg); DH_HRCHECK(hr, TEXT("VirtualCtrNode::QueryInterface")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::QueryInterface unsuccessful, hr=0x%lx."), hr)); } // Generates a new name for DocFile that we would switch to using the // IRootStorage::SwitchToFile if(S_OK == hr) { // Generate random name for new docfile that we would switch to hr = GenerateRandomName(pdgu,MINLENGTH,MAXLENGTH,&pNewRootDocFileName); DH_HRCHECK(hr, TEXT("GenerateRandomName")) ; } //prepend drive so IRootStorage::SwitchToFile goes onto a different drive. if(S_OK == hr && NULL != ptAlt) { LPTSTR ptszNewName = new TCHAR[_tcslen ((LPTSTR)pNewRootDocFileName)+4]; if (NULL != ptszNewName) { _stprintf (ptszNewName, TEXT("%s%s"), ptAlt, pNewRootDocFileName); delete []pNewRootDocFileName; pNewRootDocFileName = ptszNewName; } } // Call IRootStorage::SwitchToFile. Therafter the IStorage would become // assocaited with new switched to file rather than original file and all // changes, including uncommitted ones, would be reflected to the new // switched to file rather than original file. if (S_OK == hr) { // Convert name to OLECHAR hr =TStringToOleString(pNewRootDocFileName,&poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("TStringToOleString")) ; } if(S_OK == hr) { // Call DeleteFile just to make sure that pNewRootDocFileName doesn't // exist, before calling SwitchToFile DeleteFile(pNewRootDocFileName); DH_TRACE ((DH_LVL_TRACE1, TEXT("SwitchToFile: %s"), pNewRootDocFileName)); hr = pStgIRootStg->SwitchToFile(poszNewRootDocFileName); DH_HRCHECK(hr, TEXT("IRootStorage::SwitchToFile")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("IRootStorage::SwitchToFile unsuccessful, hr=0x%lx."), hr)); } // Release the pStgIRootStg pointer if(S_OK == hr) { // Release the Reference count that was added by QueryInterface call. ulRef = pStgIRootStg->Release(); DH_ASSERT(1 == ulRef); } // Revert the Original DocFile. This revert will revert all the changes // made by the ModifyDocFile call. if(S_OK == hr) { hr = pVirtualDFRoot->Revert(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Commit")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Revert completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Revert unsuccessful, hr=0x%lx."), hr)); } // Close the Original DocFile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Open the new Root DocFile. The CRC will be computed on it, this // is expected to match dwCRCOrg that was calculated on original // DocFile before changes were made to it, because all the changes // were reverted by doing revert on root. if(S_OK == hr) { hr = StgOpenStorage( poszNewRootDocFileName, NULL, dwRootMode, NULL, 0, &pStgRootNew); DH_HRCHECK(hr, TEXT("StgOpenStorage")) ; } // Calculate the CRC on this new root DocFile if(S_OK == hr) { dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootNew, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's at this point. The CRC of this new docfile and the // original DocFile before any changes were made to it should match, // since the changes made were reverted. if(S_OK == hr) { if((dwCRCNew != dwCRCTemp) && (dwCRCOrg == dwCRCTemp)) { DH_TRACE(( DH_LVL_TRACE1, TEXT("crc's match of new and org before changes as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match of new & org before changes unexp"))); } } // Close the new root DocFile if(S_OK == hr) { ulRef = pStgRootNew->Release(); DH_ASSERT(0 == ulRef); pStgRootNew = NULL; } // Open the original Root DocFile again. The CRC would be calculated on // this, it is expected to match dwCRCOrg, thereby verifying that because // of SwitchToFile, the original file remained unchanged. if(S_OK == hr) { hr = pVirtualDFRoot->Open(NULL, dwRootMode, NULL, 0); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Open")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Open unsuccessful, hr=0x%lx."), hr)); } // Calculate CRC for original DocFile without the RootDocfile name if(S_OK == hr) { pStgRootOrg = NULL; pStgRootOrg = pVirtualDFRoot->GetIStoragePointer(); DH_ASSERT(NULL != pStgRootOrg); dwCRCTemp = 0; hr = CalculateCRCForDocFile( pStgRootOrg, VERIFY_EXC_TOPSTG_NAME, &dwCRCTemp); DH_HRCHECK(hr, TEXT("CalculateCRCForDocFile")) ; } // Compare CRC's of the this orginal docfile after reinstantiation and // the original value before SwitchToFile was done. These should match. if(S_OK == hr) { if(dwCRCTemp == dwCRCOrg) { DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's match, original file unchanged as exp"))); } else { fPass = FALSE; DH_TRACE(( DH_LVL_TRACE1, TEXT("CRC's don't match, original file changed unexp"))); } } // Close original root docfile. if(S_OK == hr) { hr = pVirtualDFRoot->Close(); DH_HRCHECK(hr, TEXT("VirtualCtrNode::Close")) ; } if (S_OK == hr) { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close completed successfully."))); } else { DH_TRACE(( DH_LVL_TRACE1, TEXT("VirtualCtrNode::Close unsuccessful, hr=0x%lx."), hr)); } // Get some info about the test TCHAR szFileSystemInfoBuffer[10] = {TEXT(" :(")}; GetVolumeInformation (ptAlt, NULL, //lpVolumeNameBuffer 0, //nVolumeNameSize NULL, NULL, NULL, //lpFileSystemFlags &szFileSystemInfoBuffer[3], sizeof (szFileSystemInfoBuffer)-4); _tcscat (szFileSystemInfoBuffer, TEXT(")")); if (NULL != ptAlt) { *szFileSystemInfoBuffer = *ptAlt; } // if everything goes well, log test as passed else failed. if ((S_OK == hr) && (TRUE == fPass)) { DH_LOG((LOG_PASS, TEXT("Test variation IROOTSTGTEST_103 passed. %s"), szFileSystemInfoBuffer) ); } else { DH_LOG((LOG_FAIL, TEXT("Test variation IROOTSTGTEST_103 failed, hr = 0x%lx. %s"), hr, szFileSystemInfoBuffer) ); DH_DUMPCMD((LOG_FAIL, TEXT(" /seed:%u %s%c"), pTestChanceDF->GetSeed(), NULL == ptAlt ? TEXT("") : TEXT("/altpath:"), NULL == ptAlt ? TCHAR('\0') : TCHAR(*ptAlt))); // test failed. make it look like it failed. hr = FirstError (hr, E_FAIL); } // Cleanup // Get the name of file, will be used later to delete the file if(NULL != pVirtualDFRoot) { pFileName= new TCHAR[_tcslen(pTestVirtualDF->GetDocFileName())+1]; if (pFileName != NULL) { _tcscpy(pFileName, pTestVirtualDF->GetDocFileName()); } } // Delete Chance docfile tree if(NULL != pTestChanceDF) { hr2 = pTestChanceDF->DeleteChanceDocFileTree( pTestChanceDF->GetChanceDFRoot()); DH_HRCHECK(hr2, TEXT("pTestChanceDF->DeleteChanceFileDocTree")) ; delete pTestChanceDF; pTestChanceDF = NULL; } // Delete Virtual docfile tree if(NULL != pTestVirtualDF) { hr2 = pTestVirtualDF->DeleteVirtualDocFileTree(pVirtualDFRoot); DH_HRCHECK(hr2, TEXT("pTestVirtualDF->DeleteVirtualFileDocTree")) ; delete pTestVirtualDF; pTestVirtualDF = NULL; } // Delete the original docfile on disk if((S_OK == hr) && (NULL != pFileName)) { if(FALSE == DeleteFile(pFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete the new docfile on disk if((S_OK == hr) && (NULL != pNewRootDocFileName)) { if(FALSE == DeleteFile(pNewRootDocFileName)) { hr2 = HRESULT_FROM_WIN32(GetLastError()) ; DH_HRCHECK(hr2, TEXT("DeleteFile")) ; } } // Delete temp string if(NULL != pFileName) { delete pFileName; pFileName = NULL; } if(NULL != pNewRootDocFileName) { delete pNewRootDocFileName; pNewRootDocFileName = NULL; } if(NULL != poszNewRootDocFileName) { delete poszNewRootDocFileName; poszNewRootDocFileName = NULL; } // Stop logging the test DH_TRACE((DH_LVL_TRACE1, TEXT("Test variation IROOTSTGTEST_103 finished")) ); DH_TRACE((DH_LVL_TRACE1, TEXT("--------------------------------------------")) ); return hr; }
28.512447
88
0.52863
npocmaka
4e7e029039f7c2c3cee7b8d1493150a03259b4a5
1,856
cpp
C++
font.cpp
darkoppressor/huberts-island-level-editor
a1d7b0ccc20b8d463b7c26886349e5f0b0ee0d8c
[ "MIT" ]
null
null
null
font.cpp
darkoppressor/huberts-island-level-editor
a1d7b0ccc20b8d463b7c26886349e5f0b0ee0d8c
[ "MIT" ]
null
null
null
font.cpp
darkoppressor/huberts-island-level-editor
a1d7b0ccc20b8d463b7c26886349e5f0b0ee0d8c
[ "MIT" ]
null
null
null
/* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */ /* See the file docs/COPYING.txt for copying permission. */ #include "font.h" #include "render.h" using namespace std; BitmapFont::BitmapFont(){ //Initialize the variables: bitmap_font_texture=NULL; w=0; h=0; } BitmapFont::~BitmapFont(){ //When the destructor is called, delete the font texture. glDeleteTextures(1,&bitmap_font_texture); } void BitmapFont::build_font(string font_location){ // bitmap_font_texture=load_texture(font_location); //Set the texture dimensions: w=4096; h=16; //Set the cell dimensions: double cellW=16; double cellH=16; //The current character we are setting. int currentChar=0; //Go through the cell columns. for(short cols=0;cols<256;cols++){ //Set the character offset: chars[currentChar].x=cellW*cols; chars[currentChar].y=0; //Set the dimensions of the character: chars[currentChar].w=cellW; chars[currentChar].h=cellH; //Go to the next character. currentChar++; } } void BitmapFont::show(double x,double y,string text,short font_color,double opacity){ //Temporary offsets. double X=x,Y=y; //Bind the texture object. glBindTexture(GL_TEXTURE_2D,bitmap_font_texture); //Go through the text. for(int show=0;text[show]!='\0';show++){ //Get the ASCII value of the character. int ascii=(unsigned char)text[show]; if(text[show]!='\xA'){ //Show the character. render_font((int)X,(int)Y,w,h,bitmap_font_texture,&chars[ascii],font_color,opacity); //Move over the width of the character with one pixel of padding. X+=chars[ascii].w-5; } else{ Y+=chars[ascii].h+8; X=x; } } }
25.777778
96
0.625539
darkoppressor
4e7f3e6af671ae4ceae882f9d82a0967b51bb84a
3,981
cc
C++
src/dns/cmn/dns.cc
sagarc-contrail/contrail-controller
834302367f3ff81f1ce93f4036b6b3788dfd6994
[ "Apache-2.0" ]
null
null
null
src/dns/cmn/dns.cc
sagarc-contrail/contrail-controller
834302367f3ff81f1ce93f4036b6b3788dfd6994
[ "Apache-2.0" ]
null
null
null
src/dns/cmn/dns.cc
sagarc-contrail/contrail-controller
834302367f3ff81f1ce93f4036b6b3788dfd6994
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <boost/assign.hpp> #include <base/logging.h> #include <base/task.h> #include <io/event_manager.h> #include <cmn/dns.h> #include <cmn/buildinfo.h> #include <sandesh/sandesh_types.h> #include <sandesh/sandesh.h> #include <sandesh/request_pipeline.h> #include "ifmap/client/config_client_manager.h" using namespace std; EventManager *Dns::event_mgr_; DnsManager *Dns::dns_mgr_; DnsConfigManager *Dns::dns_config_mgr_; XmppServer *Dns::xmpp_server_; uint32_t Dns::xmpp_srv_port_; DnsAgentXmppChannelManager *Dns::agent_xmpp_channel_mgr_; std::string Dns::host_name_; std::string Dns::prog_name_; std::string Dns::collector_; std::string Dns::self_ip_; uint32_t Dns::http_port_; uint32_t Dns::dns_port_ = ContrailPorts::DnsServerPort(); bool Dns::GetVersion(string &build_info_str) { return MiscUtils::GetBuildInfo(MiscUtils::Dns, BuildInfo, build_info_str); } void Dns::SetTaskSchedulingPolicy() { TaskScheduler *scheduler = TaskScheduler::GetInstance(); TaskPolicy exclude_all; const char *config_exclude_list[] = { "dns::Config", "dns::BindStatus", "db::DBTable", "db::IFMapTable", "io::ReaderTask", "timer::TimerTask", "bgp::Config", "xmpp::StateMachine", "ifmap::StateMachine", "sandesh::RecvQueue", "http::RequestHandlerTask", "dns::NamedSndRcv" }; int arraysize = sizeof(config_exclude_list) / sizeof(char *); for (int i = 0; i < arraysize; ++i) { int task_id = scheduler->GetTaskId(config_exclude_list[i]); exclude_all.push_back(TaskExclusion(task_id)); } scheduler->SetPolicy(scheduler->GetTaskId("dns::Config"), exclude_all); scheduler->SetPolicy(scheduler->GetTaskId("bgp::Config"), exclude_all); const char *bindstatus_exclude_list[] = { "io::ReaderTask", "bgp::Config", "xmpp::StateMachine", "sandesh::RecvQueue", "http::RequestHandlerTask", }; arraysize = sizeof(bindstatus_exclude_list) / sizeof(char *); TaskPolicy bindstatus_exclude; for (int i = 0; i < arraysize; ++i) { int task_id = scheduler->GetTaskId(bindstatus_exclude_list[i]); bindstatus_exclude.push_back(TaskExclusion(task_id)); } scheduler->SetPolicy(scheduler->GetTaskId("dns::BindStatus"), bindstatus_exclude); TaskPolicy exclude_io = boost::assign::list_of (TaskExclusion(scheduler->GetTaskId("io::ReaderTask"))) (TaskExclusion(scheduler->GetTaskId("sandesh::RecvQueue"))) (TaskExclusion(scheduler->GetTaskId("http::RequestHandlerTask"))); scheduler->SetPolicy(scheduler->GetTaskId("xmpp::StateMachine"), exclude_io); // Policy for cassandra::Reader Task. TaskPolicy cassadra_reader_policy = boost::assign::list_of (TaskExclusion(scheduler->GetTaskId("cassandra::FQNameReader"))); for (int idx = 0; idx < ConfigClientManager::GetNumConfigReader(); ++idx) { cassadra_reader_policy.push_back( TaskExclusion(scheduler->GetTaskId("cassandra::ObjectProcessor"), idx)); } scheduler->SetPolicy(scheduler->GetTaskId("cassandra::Reader"), cassadra_reader_policy); // Policy for cassandra::ObjectProcessor Task. TaskPolicy cassadra_obj_process_policy; for (int idx = 0; idx < ConfigClientManager::GetNumConfigReader(); ++idx) { cassadra_obj_process_policy.push_back( TaskExclusion(scheduler->GetTaskId("cassandra::Reader"), idx)); } scheduler->SetPolicy(scheduler->GetTaskId("cassandra::ObjectProcessor"), cassadra_obj_process_policy); // Policy for cassandra::FQNameReader Task. TaskPolicy fq_name_reader_policy = boost::assign::list_of (TaskExclusion(scheduler->GetTaskId("cassandra::Reader"))); scheduler->SetPolicy(scheduler->GetTaskId("cassandra::FQNameReader"), fq_name_reader_policy); }
36.522936
86
0.690781
sagarc-contrail
4e81115ab7d2f1b129ff498bd35b15abddc3dcb6
710
cpp
C++
src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.hpp" #include "Evolution/Systems/Burgers/BoundaryConditions/BoundaryCondition.hpp" #include "Evolution/Systems/Burgers/BoundaryConditions/Dirichlet.hpp" #include "Evolution/Systems/Burgers/BoundaryConditions/DirichletAnalytic.hpp" #include "Evolution/Systems/Burgers/BoundaryConditions/Outflow.hpp" #include "Parallel/RegisterDerivedClassesWithCharm.hpp" namespace Burgers::BoundaryConditions { void register_derived_with_charm() noexcept { Parallel::register_derived_classes_with_charm<BoundaryCondition>(); } } // namespace Burgers::BoundaryConditions
41.764706
84
0.840845
macedo22
4e829278fb9227290b2d2fe71b937f2cd66e3766
10,357
cpp
C++
src/driveshaft-config.cpp
tlalexan/driveshaft
122422e78e561053ec859015a4de5990f97a297b
[ "MIT" ]
43
2015-09-22T21:07:56.000Z
2020-08-05T16:10:03.000Z
src/driveshaft-config.cpp
tlalexan/driveshaft
122422e78e561053ec859015a4de5990f97a297b
[ "MIT" ]
16
2015-09-22T15:53:18.000Z
2020-08-10T16:22:48.000Z
src/driveshaft-config.cpp
tlalexan/driveshaft
122422e78e561053ec859015a4de5990f97a297b
[ "MIT" ]
11
2015-09-21T20:36:37.000Z
2020-06-16T13:40:05.000Z
#include <fstream> #include <boost/range/algorithm/copy.hpp> #include <boost/range/adaptors.hpp> #include <boost/filesystem.hpp> #include "driveshaft-config.h" namespace Driveshaft { namespace cfgkeys { static std::string GEARMAN_SERVERS_LIST = "gearman_servers_list"; static std::string POOLS_LIST = "pools_list"; static std::string POOL_WORKER_COUNT = "worker_count"; static std::string POOL_JOB_LIST = "jobs_list"; static std::string POOL_JOB_PROCESSING_URI = "job_processing_uri"; } DriveshaftConfig::DriveshaftConfig() noexcept : m_config_filename(), m_server_list(), m_pool_map(), m_load_time(0) { } bool DriveshaftConfig::load(const std::string& config_filename, std::shared_ptr<Json::CharReader> json_parser) { if (!this->needsConfigUpdate(config_filename)) { return false; } LOG4CXX_INFO(MainLogger, "Reloading config"); this->m_config_filename = config_filename; std::string config_file_contents(this->fetchFileContents(config_filename)); return this->parseConfig(config_file_contents, json_parser); } bool DriveshaftConfig::parseConfig(const std::string& config_data, std::shared_ptr<Json::CharReader> json_parser) { Json::Value tree; std::string parse_errors; if (!json_parser->parse(config_data.data(), config_data.data() + config_data.length(), &tree, &parse_errors)) { LOG4CXX_ERROR(MainLogger, "Failed to parse " << this->m_config_filename << ". Errors: " << parse_errors); throw std::runtime_error("config parse failure"); } if (!this->validateConfigNode(tree)) { throw std::runtime_error("config parse failure"); } this->m_load_time = std::time(nullptr); this->m_server_list.clear(); this->m_pool_map.clear(); this->parseServerList(tree); this->parsePoolList(tree); return true; } void DriveshaftConfig::supersede(DriveshaftConfig& old, PoolWatcher& watcher) const { StringSet pools_to_shut; std::tie(pools_to_shut, std::ignore) = old.compare(*this); for (const auto& pool : pools_to_shut) { old.clearWorkerCount(pool, watcher); } for (auto const& i : this->m_pool_map) { const auto &pool_name = i.first; const auto &pool_data = i.second; watcher.inform(pool_data.worker_count, pool_name, this->m_server_list, pool_data.job_list, pool_data.job_processing_uri); } } void DriveshaftConfig::clearWorkerCount(const std::string& pool_name, PoolWatcher& watcher) { auto pool_iter = this->m_pool_map.find(pool_name); if (pool_iter == this->m_pool_map.end()) { LOG4CXX_ERROR(MainLogger, "clearWorkerCounts requested, " << pool_name << " does not exist in config"); throw std::runtime_error("invalid config detected in clearWorkerCounts"); } auto& pool_data = pool_iter->second; pool_data.worker_count = 0; watcher.inform(0, pool_name, this->m_server_list, pool_data.job_list, pool_data.job_processing_uri); } void DriveshaftConfig::clearAllWorkerCounts(PoolWatcher& watcher) { for (const auto& i : this->m_pool_map) { this->clearWorkerCount(i.first, watcher); } } std::pair<StringSet, StringSet> DriveshaftConfig::compare(const DriveshaftConfig& that) const noexcept { LOG4CXX_DEBUG(MainLogger, "Beginning config compare"); StringSet current_pool_names, latest_pool_names; boost::copy(m_pool_map | boost::adaptors::map_keys, std::inserter(current_pool_names, current_pool_names.begin())); boost::copy(that.m_pool_map | boost::adaptors::map_keys, std::inserter(latest_pool_names, latest_pool_names.begin())); if (this->m_server_list != that.m_server_list) { // Everything needs restarting return std::pair<StringSet, StringSet>(std::move(current_pool_names), std::move(latest_pool_names)); } else { StringSet pools_turn_off, pools_turn_on; // See what's present in current and missing in new. This is to be turned off. std::set_difference(current_pool_names.begin(), current_pool_names.end(), latest_pool_names.begin(), latest_pool_names.end(), std::inserter(pools_turn_off, pools_turn_off.begin())); // Reverse of above. See what's to be turned on. std::set_difference(latest_pool_names.begin(), latest_pool_names.end(), current_pool_names.begin(), current_pool_names.end(), std::inserter(pools_turn_on, pools_turn_on.begin())); // Check for changed jobs or processing URI for (const auto& i : m_pool_map) { auto found = that.m_pool_map.find(i.first); if (found != that.m_pool_map.end()) { bool should_restart = false; if (found->second.job_processing_uri != i.second.job_processing_uri) { should_restart = true; } else { const auto& lhs_jobs_set = i.second.job_list; const auto& rhs_jobs_set = found->second.job_list; StringSet diff; std::set_symmetric_difference(lhs_jobs_set.begin(), lhs_jobs_set.end(), rhs_jobs_set.begin(), rhs_jobs_set.end(), std::inserter(diff, diff.begin())); if (diff.size()) { should_restart = true; } } if (should_restart) { pools_turn_off.insert(i.first); pools_turn_on.insert(i.first); } } } return std::pair<StringSet, StringSet>(std::move(pools_turn_off), std::move(pools_turn_on)); } } void DriveshaftConfig::parseServerList(const Json::Value& node) { const auto& servers_list = node[cfgkeys::GEARMAN_SERVERS_LIST]; for (auto i = servers_list.begin(); i != servers_list.end(); ++i) { if (!i->isString()) { LOG4CXX_ERROR(MainLogger, cfgkeys::GEARMAN_SERVERS_LIST << " does not contain strings"); throw std::runtime_error("config server list type failure"); } const auto& name = i->asString(); this->m_server_list.insert(name); LOG4CXX_DEBUG(MainLogger, "Read server: " << name); } } void DriveshaftConfig::parsePoolList(const Json::Value& node) { const auto& pools_list = node[cfgkeys::POOLS_LIST]; for (auto i = pools_list.begin(); i != pools_list.end(); ++i) { const auto& pool_name = i.name(); const auto& pool_node = *i; if (!pool_node.isMember(cfgkeys::POOL_WORKER_COUNT) || !pool_node.isMember(cfgkeys::POOL_JOB_LIST) || !pool_node.isMember(cfgkeys::POOL_JOB_PROCESSING_URI) || !pool_node[cfgkeys::POOL_WORKER_COUNT].isUInt() || !pool_node[cfgkeys::POOL_JOB_LIST].isArray() || !pool_node[cfgkeys::POOL_JOB_PROCESSING_URI].isString()) { LOG4CXX_ERROR( MainLogger, "Config (" << m_config_filename << ") has invalid " << cfgkeys::POOLS_LIST << " elements: (" << cfgkeys::POOL_WORKER_COUNT << ", " << cfgkeys::POOL_JOB_PROCESSING_URI << ", " << cfgkeys::POOL_JOB_LIST << ")" ); throw std::runtime_error("config jobs list parse failure"); } auto& pool_data = this->m_pool_map[pool_name]; pool_data.worker_count = pool_node[cfgkeys::POOL_WORKER_COUNT].asUInt(); pool_data.job_processing_uri = pool_node[cfgkeys::POOL_JOB_PROCESSING_URI].asString(); LOG4CXX_DEBUG( MainLogger, "Read pool: " << pool_name << " with count " << pool_data.worker_count << " and URI " << pool_data.job_processing_uri ); const auto& job_list = pool_node[cfgkeys::POOL_JOB_LIST]; for (auto j = job_list.begin(); j != job_list.end(); ++j) { if (!j->isString()) { LOG4CXX_ERROR(MainLogger, cfgkeys::POOL_JOB_LIST << " does not contain strings"); } const auto& name = j->asString(); pool_data.job_list.insert(name); LOG4CXX_DEBUG(MainLogger, "Pool " << pool_name << " adding job " << name); } } } bool DriveshaftConfig::needsConfigUpdate(const std::string& new_config_filename) const { boost::filesystem::path config_path(new_config_filename); boost::system::error_code ec; std::time_t modified_time = boost::filesystem::last_write_time(config_path, ec); if (ec) { LOG4CXX_ERROR( MainLogger, "Unable to ascertain config mtime " << new_config_filename << ". Error: " << ec.message() ); throw std::runtime_error("config stat failure"); } return modified_time > this->m_load_time; } std::string DriveshaftConfig::fetchFileContents(const std::string& filename) const { std::ifstream config_filestream(filename, std::ios::in | std::ios::binary); if (config_filestream.fail()) { LOG4CXX_ERROR(MainLogger, "Unable to load file " << filename); throw std::runtime_error("config read failure"); } std::ostringstream contents; contents << config_filestream.rdbuf(); config_filestream.close(); return contents.str(); } bool DriveshaftConfig::validateConfigNode(const Json::Value& node) const { using namespace cfgkeys; if (!node.isMember(GEARMAN_SERVERS_LIST) || !node.isMember(POOLS_LIST)) { LOG4CXX_ERROR( MainLogger, "Config is missing one or more elements (" << GEARMAN_SERVERS_LIST << ", " << POOLS_LIST << ")" ); return false; } if (!node[GEARMAN_SERVERS_LIST].isArray() || !node[POOLS_LIST].isObject()) { LOG4CXX_ERROR( MainLogger, "Config has one or more malformed elements (" << GEARMAN_SERVERS_LIST << ", " << POOLS_LIST << ")" ); return false; } return true; } } // namespace Driveshaft
38.359259
115
0.615043
tlalexan
4e83416ca4979e3362bbfa5c90b6e3f92def4009
5,113
cpp
C++
cppcache/integration/framework/GfshExecute.cpp
isabella232/geode-native
0d9a99d5e0632de62df17921950cf3f6640efb33
[ "Apache-2.0" ]
1
2018-09-08T05:05:22.000Z
2018-09-08T05:05:22.000Z
cppcache/integration/framework/GfshExecute.cpp
pivotal-jbarrett/geode-native
50a441c4c0f78679558d520eaf20022ae51de3ff
[ "Apache-2.0" ]
1
2021-02-23T12:27:00.000Z
2021-02-23T12:27:00.000Z
cppcache/integration/framework/GfshExecute.cpp
isabella232/geode-native
0d9a99d5e0632de62df17921950cf3f6640efb33
[ "Apache-2.0" ]
null
null
null
/* * 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. */ #include "GfshExecute.h" #include <mutex> #include <boost/log/trivial.hpp> #if defined(_WINDOWS) std::mutex g_child_mutex; #endif using boost::process::args; using boost::process::child; using boost::process::environment; using boost::process::ipstream; using boost::process::std_err; using boost::process::std_out; GfshExecuteException::GfshExecuteException(std::string message, int returnCode) : apache::geode::client::Exception(message), returnCode_(returnCode) {} GfshExecuteException::~GfshExecuteException() {} std::string GfshExecuteException::getName() const { return "GfshExecuteException"; } int GfshExecuteException::getGfshReturnCode() { return returnCode_; } void GfshExecute::execute(const std::string &command, const std::string &user, const std::string &password, const std::string &keyStorePath, const std::string &trustStorePath, const std::string &keyStorePassword, const std::string &trustStorePassword) { BOOST_LOG_TRIVIAL(info) << "Gfsh::execute: " << command; std::vector<std::string> commands; if (!connection_.empty()) { commands.push_back("-e"); commands.push_back(connection_); } commands.push_back("-e"); commands.push_back(command); auto env = boost::this_process::environment(); environment _env = env; // broken on windows env["JAVA_ARGS"] = "-Xmx1g -client"; ipstream outStream; ipstream errStream; auto gfsh = executeChild(commands, _env, outStream, errStream); std::string line; while (outStream && std::getline(outStream, line)) { BOOST_LOG_TRIVIAL(trace) << "Gfsh::execute: " << line; } while (errStream && std::getline(errStream, line)) { BOOST_LOG_TRIVIAL(debug) << "Gfsh::execute: " << line; } gfsh.wait(); auto exit_code = gfsh.exit_code(); BOOST_LOG_TRIVIAL(debug) << "Gfsh::execute: exit:" << exit_code; if (exit_code) { throw GfshExecuteException("gfsh error", exit_code); } extractConnectionCommand(command, user, password, keyStorePath, trustStorePath, keyStorePassword, trustStorePassword); } child GfshExecute::executeChild(std::vector<std::string> &commands, environment &env, ipstream &outStream, ipstream &errStream) { #if defined(_WINDOWS) // https://github.com/klemens-morgenstern/boost-process/issues/159 std::lock_guard<std::mutex> guard(g_child_mutex); #endif return child(getFrameworkString(FrameworkVariable::GfShExecutable), args = commands, env, std_out > outStream, std_err > errStream); } void GfshExecute::extractConnectionCommand(const std::string &command, const std::string &user, const std::string &password, const std::string &keyStorePath, const std::string &trustStorePath, const std::string &keyStorePassword, const std::string &trustStorePassword) { if (starts_with(command, std::string("connect"))) { connection_ = command; } else if (starts_with(command, std::string("start locator"))) { auto jmxManagerHost = std::string("localhost"); auto jmxManagerPort = std::string("1099"); std::regex jmxManagerHostRegex("bind-address=([^\\s]+)"); std::smatch jmxManagerHostMatch; if (std::regex_search(command, jmxManagerHostMatch, jmxManagerHostRegex)) { jmxManagerHost = jmxManagerHostMatch[1]; } std::regex jmxManagerPortRegex("jmx-manager-port=(\\d+)"); std::smatch jmxManagerPortMatch; if (std::regex_search(command, jmxManagerPortMatch, jmxManagerPortRegex)) { jmxManagerPort = jmxManagerPortMatch[1]; } connection_ = "connect --jmx-manager=" + jmxManagerHost + "[" + jmxManagerPort + "]"; if (!(user.empty() || password.empty())) { connection_ += " --user=" + user + " --password=" + password; } if(!(keyStorePath.empty() || trustStorePath.empty() || keyStorePassword.empty() || trustStorePassword.empty())) { connection_ += " --use-ssl=true --key-store=" + keyStorePath + " --trust-store=" + trustStorePath + " --key-store-password=" + keyStorePassword + " --trust-store-password=" + trustStorePassword; } } }
37.595588
120
0.673577
isabella232
4e849a62bed6f7e3b8b87854d60e114f1c5e8169
2,282
cpp
C++
src/Client/States/Game/AuthenticationState.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
src/Client/States/Game/AuthenticationState.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
src/Client/States/Game/AuthenticationState.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE #include <Client/States/Game/AuthenticationState.hpp> #include <Client/ClientApp.hpp> #include <Client/States/LoginState.hpp> #include <Client/States/Game/AssetDownloadState.hpp> namespace bw { AuthenticationState::AuthenticationState(std::shared_ptr<StateData> stateData, std::shared_ptr<ClientSession> clientSession) : StatusState(std::move(stateData)), m_clientSession(std::move(clientSession)) { m_onAuthFailedSlot.Connect(m_clientSession->OnAuthFailure, [this](ClientSession*, const Packets::AuthFailure& /*data*/) { UpdateStatus("Failed to authenticate", Nz::Color::Red); m_nextState = std::make_shared<LoginState>(GetStateDataPtr()); m_nextStateDelay = 3.f; }); m_onAuthSucceededSlot.Connect(m_clientSession->OnAuthSuccess, [this](ClientSession*, const Packets::AuthSuccess& data) { UpdateStatus("Authentication succeeded, waiting for match data...", Nz::Color::White); m_authSuccessPacket = data; }); m_onMatchDataSlot.Connect(m_clientSession->OnMatchData, [this](ClientSession*, const Packets::MatchData& data) { if (!m_authSuccessPacket) { UpdateStatus("Protocol error", Nz::Color::Red); m_nextState = std::make_shared<LoginState>(GetStateDataPtr()); m_nextStateDelay = 3.f; return; } UpdateStatus("Received match data", Nz::Color::White); m_nextState = std::make_shared<AssetDownloadState>(GetStateDataPtr(), m_clientSession, m_authSuccessPacket.value(), data); m_nextStateDelay = 0.5f; }); } void AuthenticationState::Enter(Ndk::StateMachine& fsm) { StatusState::Enter(fsm); ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings(); Packets::Auth authPacket; authPacket.players.emplace_back().nickname = playerConfig.GetStringValue("Player.Name"); m_clientSession->SendPacket(std::move(authPacket)); } bool AuthenticationState::Update(Ndk::StateMachine& fsm, float elapsedTime) { if (!StatusState::Update(fsm, elapsedTime)) return false; if (m_nextState) { if ((m_nextStateDelay -= elapsedTime) < 0.f) { fsm.ChangeState(m_nextState); return true; } } return true; } }
29.636364
127
0.73532
ImperatorS79
4e8b9458e71d2c7943d3be58c60a8da8b0c72a7c
20,431
cc
C++
C++/matrix/vector.cc
WaizungTaam/Strassen-Algorithm
85267a2a869d786a260174e7eb21a950def1cadd
[ "Apache-2.0" ]
null
null
null
C++/matrix/vector.cc
WaizungTaam/Strassen-Algorithm
85267a2a869d786a260174e7eb21a950def1cadd
[ "Apache-2.0" ]
null
null
null
C++/matrix/vector.cc
WaizungTaam/Strassen-Algorithm
85267a2a869d786a260174e7eb21a950def1cadd
[ "Apache-2.0" ]
null
null
null
/*Copyright 2016 WaizungTaam. 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 <vector> #include <iostream> #include <iomanip> #include <random> #include <algorithm> #include <limits> #include <cmath> #include <omp.h> #include "vector.h" Vector::Vector(int size) { vec = std::vector<double>(size, 0); } Vector::Vector(int size, double value) { vec = std::vector<double>(size, value); } Vector::Vector(int size, const std::string & mode, double param_1, double param_2) { bool is_uniform = (mode == "uniform") || (mode == "Uniform") || (mode == "UNIFORM") || (mode == "u") || (mode == "U"); bool is_normal = (mode == "normal") || (mode == "Normal") || (mode == "NORMAL") || (mode == "n") || (mode == "N"); bool is_binomial = (mode == "binomial") || (mode == "Binomial") || (mode == "BINOMIAL") || (mode == "b") || (mode == "B"); if (!(is_uniform || is_normal || is_binomial)) { throw "Unsupported mode"; } vec = std::vector<double>(size, 0); std::random_device rd; std::mt19937 gen(rd()); if (is_uniform) { std::uniform_real_distribution<> uni_dis(param_1, param_2); for (double & element : vec) { element = uni_dis(gen); } } else if (is_normal) { std::normal_distribution<> nor_dis(param_1, param_2); for (double & element : vec) { element = nor_dis(gen); } } else if (is_binomial) { std::binomial_distribution<int> bin_dis(param_1, param_2); for (double & element : vec) { element = static_cast<double>(bin_dis(gen)); } } } Vector::Vector(const std::vector<double> & vec_init) { vec = vec_init; } Vector::Vector(const std::initializer_list<double> & ls) : vec(ls) { } Vector & Vector::operator=(double value) { for (double & element : vec) { element = value; } return *this; } Vector & Vector::operator=(const std::vector<double> & vec_copy) { vec = vec_copy; return *this; } Vector & Vector::operator=(const std::initializer_list<double> & ls) { vec = ls; return *this; } std::vector<std::size_t> Vector::shape() const { std::vector<std::size_t> shape_vec(1); shape_vec[0] = vec.size(); return shape_vec; } Vector Vector::insert(double value, int index) const { if (index > vec.size()) { throw "Out-of-range"; } Vector vec_inserted = *this; vec_inserted.vec.insert(vec_inserted.vec.begin() + index, value); return vec_inserted; } Vector Vector::insert(const Vector & vec_to_insert, int index) const { if (index > vec.size()) { throw "Out-of-range"; } Vector vec_inserted = *this; for (const double element : vec_to_insert.vec) { vec_inserted.vec.insert(vec_inserted.vec.begin() + index, element); ++index; } return vec_inserted; } Vector Vector::remove(int index) const { if (index >= vec.size()) { throw "Out-of-range"; } Vector vec_removed = *this; vec_removed.vec.erase(vec_removed.vec.begin() + index); return vec_removed; } Vector Vector::remove(int idx_begin, int idx_end) const { if (idx_begin > idx_end) { int tmp_swap = idx_begin; idx_begin = idx_end; idx_end = tmp_swap; } if (idx_end >= vec.size()) { throw "Out-of-range"; } Vector vec_removed = *this; vec_removed.vec.erase(vec_removed.vec.begin() + idx_begin, vec_removed.vec.begin() + idx_end); return vec_removed; } Vector Vector::replace(const Vector & vec_to_replace, int index) const { if (index >= vec.size()) { return *this; } Vector vec_replaced = *this; int idx_rep; for (idx_rep = 0; idx_rep < vec_to_replace.vec.size() && idx_rep + index < vec_replaced.vec.size(); ++idx_rep) { vec_replaced[index + idx_rep] = vec_to_replace.vec[idx_rep]; } return vec_replaced; } Vector Vector::shuffle() const { std::random_device rd; std::mt19937 gen(rd()); Vector vec_shuffled = *this; std::shuffle(vec_shuffled.vec.begin(), vec_shuffled.vec.end(), gen); return vec_shuffled; } void Vector::clear() { vec.clear(); } bool Vector::empty() { if (vec.size() == 0) { return true; } else { return false; } } double Vector::sum() const { if (shape()[0] == 0) { return 0; } double sum = 0; // Experiments show that this method is faster then // either using omp or std::accumulate for (const double element : vec) { sum += element; } return sum; } double Vector::max() const { if (shape()[0] == 0) { return 0; } double max = vec[0]; int idx; // Experiments show that this is faster then std::max_element for (idx = 1; idx < shape()[0]; ++idx) { if (vec[idx] > max) { max = vec[idx]; } } return max; } double Vector::min() const { if (shape()[0] == 0) { return 0; } double min = vec[0]; int idx; for (idx = 1; idx < shape()[0]; ++idx) { if (vec[idx] < min) { min = vec[idx]; } } return min; } bool Vector::approx(const Vector & vec_to_compare, double error) const { int idx; error = std::abs(error); for (idx = 0; idx < vec.size(); ++idx) { // std::numeric_limits<double>::epsilon() returns the machine epsilon, // which is the difference between 1.0 and the next double value. // It is used here to avoid the rounding error. if (std::abs(vec[idx] - vec_to_compare.vec[idx]) - error > std::numeric_limits<double>::epsilon()) { return false; } } return true; } Vector Vector::approx(double value, double error) const { error = std::abs(error); int idx; Vector vec_is_approx(vec.size(), 0); for (idx = 0; idx < vec.size(); ++idx) { if (std::abs(vec[idx] - value) - error <= std::numeric_limits<double>::epsilon()) { vec_is_approx[idx] = 1; } } return vec_is_approx; } Vector operator+(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.vec.size() != vec_rhs.vec.size()) { throw "Inconsistent shape"; } Vector vec_sum = vec_lhs; // size_omp is the vector size that is used to // decide whether to use openmp or not. // Note that this is a approximate quantity obtained // from experiments. // This is applied to all the size_omp in this file. const int size_omp = 300; int idx; if (vec_sum.vec.size() < size_omp) { for (idx = 0; idx < vec_sum.vec.size(); ++idx) { vec_sum.vec[idx] = vec_sum.vec[idx] + vec_rhs.vec[idx]; } } else { #pragma omp parallel shared(vec_sum, vec_rhs) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_sum.vec.size(); ++idx) { vec_sum.vec[idx] = vec_sum.vec[idx] + vec_rhs.vec[idx]; } } } return vec_sum; } Vector operator+(const Vector & vec_lhs, double value) { Vector vec_sum = vec_lhs; const int size_omp = 350; if (vec_sum.vec.size() < size_omp) { for (double & element : vec_sum.vec) { element = element + value; } } else { int idx; #pragma omp parallel shared(vec_sum, value) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_sum.vec.size(); ++idx) { vec_sum[idx] = vec_sum[idx] + value; } } } return vec_sum; } Vector operator+(double value, const Vector & vec_rhs) { return operator+(vec_rhs, value); } Vector operator-(const Vector & vec_lhs, const Vector & vec_rhs) { return vec_lhs + ((-1) * vec_rhs); } Vector operator-(const Vector & vec_lhs, double value) { return vec_lhs + ((-1) * value); } Vector operator-(double value, const Vector & vec_rhs) { Vector vec_diff = operator-(vec_rhs, value); vec_diff = -1.0 * vec_diff; return vec_diff; } Vector operator*(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.vec.size() != vec_rhs.vec.size()) { throw "Inconsistent shape"; } Vector vec_prod = vec_lhs; const int size_omp = 300; int idx; if (vec_prod.vec.size() < size_omp) { for (idx = 0; idx < vec_prod.vec.size(); ++idx) { vec_prod.vec[idx] = vec_prod.vec[idx] * vec_rhs.vec[idx]; } } else { #pragma omp parallel shared(vec_prod, vec_rhs) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_prod.vec.size(); ++idx) { vec_prod.vec[idx] = vec_prod.vec[idx] * vec_rhs.vec[idx]; } } } return vec_prod; } Vector operator*(const Vector & vec_lhs, double value) { Vector vec_prod = vec_lhs; const int size_omp = 350; if (vec_prod.vec.size() < size_omp) { for (double & element : vec_prod.vec) { element = element * value; } } else { int idx; #pragma omp parallel shared(vec_prod, value) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_prod.vec.size(); ++idx) { vec_prod[idx] = vec_prod[idx] * value; } } } return vec_prod; } Vector operator*(double value, const Vector & vec_rhs) { return operator*(vec_rhs, value); } Vector operator/(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.vec.size() != vec_rhs.vec.size()) { throw "Inconsistent shape"; } Vector vec_quot = vec_lhs; const int size_omp = 300; int idx; if (vec_quot.vec.size() < size_omp) { for (idx = 0; idx < vec_quot.vec.size(); ++idx) { vec_quot.vec[idx] = static_cast<double>(vec_quot.vec[idx]) / vec_rhs.vec[idx]; } } else { #pragma omp parallel shared(vec_quot, vec_rhs) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_quot.vec.size(); ++idx) { vec_quot.vec[idx] = static_cast<double>(vec_quot.vec[idx]) / vec_rhs.vec[idx]; } } } return vec_quot; } Vector operator/(const Vector & vec_lhs, double value) { return vec_lhs * (1.0 / static_cast<double>(value)); } Vector operator/(double value, const Vector & vec_rhs) { Vector vec_quot = vec_rhs; const int size_omp = 350; if (vec_quot.vec.size() < size_omp) { for (double & element : vec_quot.vec) { element = static_cast<double>(value) / element; } } else { int idx; #pragma omp parallel shared(vec_quot, value) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_quot.vec.size(); ++idx) { vec_quot[idx] = static_cast<double>(value) / vec_quot[idx]; } } } return vec_quot; } void Vector::operator+=(double value) { (*this) = (*this) + value; } void Vector::operator+=(const Vector & vec_to_add) { (*this) = (*this) + vec_to_add; } void Vector::operator-=(double value) { (*this) = (*this) - value; } void Vector::operator-=(const Vector & vec_to_sub) { (*this) = (*this) - vec_to_sub; } void Vector::operator*=(double value) { (*this) = (*this) * value; } void Vector::operator*=(const Vector & vec_to_mul) { (*this) = (*this) * vec_to_mul; } void Vector::operator/=(double value) { (*this) = (*this) / value; } void Vector::operator/=(const Vector & vec_to_div) { (*this) = (*this) / vec_to_div; } bool operator==(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.vec.size() != vec_rhs.vec.size()) { return false; } int idx; for (idx = 0; idx < vec_lhs.vec.size(); ++idx) { if (!::approx(vec_lhs.vec[idx], vec_rhs.vec[idx])) { return false; } } return true; } Vector operator==(const Vector & vec_lhs, double value) { Vector vec_is_equ(vec_lhs.shape()[0], 0); const int size_omp = 360; int idx; if (vec_lhs.vec.size() < size_omp) { for (idx = 0; idx < vec_is_equ.shape()[0]; ++idx) { if (::approx(vec_lhs[idx], value)) { vec_is_equ[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_is_equ, value) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_equ.shape()[0]; ++idx) { if (::approx(vec_lhs[idx], value)) { vec_is_equ[idx] = 1.0; } } } } return vec_is_equ; } Vector operator==(double value, const Vector & vec_rhs) { return vec_rhs == value; } bool operator!=(const Vector & vec_lhs, const Vector & vec_rhs) { return !(vec_lhs == vec_rhs); } Vector operator!=(const Vector & vec_lhs, double value) { Vector vec_is_equ(vec_lhs.shape()[0], 0); const int size_omp = 360; int idx; if (vec_lhs.vec.size() < size_omp) { for (idx = 0; idx < vec_is_equ.shape()[0]; ++idx) { if (!::approx(value, vec_lhs[idx])) { vec_is_equ[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_is_equ, value) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_equ.shape()[0]; ++idx) { if (!::approx(value, vec_lhs[idx])) { vec_is_equ[idx] = 1.0; } } } } return vec_is_equ; } Vector operator!=(double value, const Vector & vec_rhs) { return vec_rhs != value; } Vector operator<(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.shape()[0] != vec_rhs.shape()[0]) { throw "Inconsistent shape"; } Vector vec_is_les(vec_lhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_les.vec.size() < size_omp) { for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (vec_lhs.vec[idx] < vec_rhs.vec[idx]) { vec_is_les.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_lhs, vec_rhs, vec_is_les) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (vec_lhs.vec[idx] < vec_rhs.vec[idx]) { vec_is_les.vec[idx] = 1.0; } } } } return vec_is_les; } Vector operator<(const Vector & vec_lhs, double value) { Vector vec_is_les(vec_lhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_les.vec.size() < size_omp) { for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (vec_lhs.vec[idx] < value) { vec_is_les.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_lhs, value, vec_is_les) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (vec_lhs.vec[idx] < value) { vec_is_les.vec[idx] = 1.0; } } } } return vec_is_les; } Vector operator<(double value, const Vector & vec_rhs) { Vector vec_is_les(vec_rhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_les.vec.size() < size_omp) { for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (value < vec_rhs.vec[idx]) { vec_is_les.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_rhs, value, vec_is_les) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_les.shape()[0]; ++idx) { if (value < vec_rhs.vec[idx]) { vec_is_les.vec[idx] = 1.0; } } } } return vec_is_les; } Vector operator<=(const Vector & vec_lhs, const Vector & vec_rhs) { if (vec_lhs.shape()[0] != vec_rhs.shape()[0]) { throw "Inconsistent shape"; } Vector vec_is_leq(vec_lhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_leq.vec.size() < size_omp) { for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (vec_lhs.vec[idx] <= vec_rhs.vec[idx]) { vec_is_leq.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_lhs, vec_rhs, vec_is_leq) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (vec_lhs.vec[idx] <= vec_rhs.vec[idx]) { vec_is_leq.vec[idx] = 1.0; } } } } return vec_is_leq; } Vector operator<=(const Vector & vec_lhs, double value) { Vector vec_is_leq(vec_lhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_leq.vec.size() < size_omp) { for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (vec_lhs.vec[idx] <= value) { vec_is_leq.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_lhs, value, vec_is_leq) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (vec_lhs.vec[idx] <= value) { vec_is_leq.vec[idx] = 1.0; } } } } return vec_is_leq; } Vector operator<=(double value, const Vector & vec_rhs) { Vector vec_is_leq(vec_rhs.shape()[0]); const int size_omp = 400; int idx; if (vec_is_leq.vec.size() < size_omp) { for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (value <= vec_rhs.vec[idx]) { vec_is_leq.vec[idx] = 1.0; } } } else { #pragma omp parallel shared(vec_rhs, value, vec_is_leq) private(idx) { #pragma omp for schedule(auto) for (idx = 0; idx < vec_is_leq.shape()[0]; ++idx) { if (value <= vec_rhs.vec[idx]) { vec_is_leq.vec[idx] = 1.0; } } } } return vec_is_leq; } Vector operator>(const Vector & vec_lhs, const Vector & vec_rhs) { return vec_rhs < vec_lhs; } Vector operator>(const Vector & vec_lhs, double value) { return value < vec_lhs; } Vector operator>(double value, const Vector & vec_rhs) { return vec_rhs < value; } Vector operator>=(const Vector & vec_lhs, const Vector & vec_rhs) { return vec_rhs <= vec_lhs; } Vector operator>=(const Vector & vec_lhs, double value) { return value <= vec_lhs; } Vector operator>=(double value, const Vector & vec_rhs) { return vec_rhs <= value; } double & Vector::operator[](int index) { if (index >= 0) { if (index >= vec.size()) { throw "Out-of-range"; } return vec.at(index); } else if (index < 0) { if ((-1) * index > vec.size()) { throw "Out-of-range"; } return vec.at(vec.size() + index); } } const double & Vector::operator[](int index) const { if (index >= 0) { if (index >= vec.size()) { throw "Out-of-range"; } return vec.at(index); } else if (index < 0) { if ((-1) * index > vec.size()) { throw "Out-of-range"; } return vec.at(vec.size() + index); } } Vector Vector::operator()(int idx_begin, int idx_end) const { if (idx_begin > idx_end) { int tmp_swap = idx_begin; idx_begin = idx_end; idx_end = tmp_swap; } if (idx_end > vec.size()) { throw "Out-of-range"; } Vector vec_partial(idx_end - idx_begin); vec_partial.vec = std::vector<double>(vec.begin() + idx_begin, vec.begin() + idx_end); return vec_partial; } std::ostream & operator<<(std::ostream & os, const Vector & vec_os) { os << "["; int idx = 0; for (const double element : vec_os.vec) { os << std::setw(15) << std::setprecision(8) << std::setfill(' ') << std::scientific << std::left << std::showpos << element; if (idx != vec_os.vec.size() - 1) { os << " "; } ++idx; } os << std::resetiosflags(std::ios_base::scientific) << std::resetiosflags(std::ios_base::right) << std::resetiosflags(std::ios_base::showpos); os << "]"; return os; } std::istream & operator>>(std::istream & is, Vector & vec_is) { if (vec_is.vec.size() == 0) { double element; while (is >> element) { vec_is.vec.push_back(element); } } else { for (double & element : vec_is.vec) { is >> element; } } return is; }
29.354885
77
0.580637
WaizungTaam
4e8c4643c574217df23249e076d4a0f507de4d5c
3,026
cpp
C++
engine/engine.cpp
geefr/vulkan-learning
47018427bb3322f8d6fd6c74ac4b8f0ff670b583
[ "BSD-3-Clause" ]
null
null
null
engine/engine.cpp
geefr/vulkan-learning
47018427bb3322f8d6fd6c74ac4b8f0ff670b583
[ "BSD-3-Clause" ]
null
null
null
engine/engine.cpp
geefr/vulkan-learning
47018427bb3322f8d6fd6c74ac4b8f0ff670b583
[ "BSD-3-Clause" ]
null
null
null
/* * Provided under the BSD 3-Clause License, see LICENSE. * * Copyright (c) 2020, Gareth Francis * All rights reserved. */ #include "engine.h" #include "renderer.h" #include "node.h" Engine::Engine() : mRend(new Renderer(*this)) , mNodeGraph(new Node()) , mQuit(false) {} Engine::~Engine() {} void Engine::run() { initRenderer(); mNodeGraph->init(*mRend.get()); mNodeGraph->upload(*mRend.get()); mTimeStart = std::chrono::high_resolution_clock::now(); mTimeCurrent = mTimeStart; loop(); cleanup(); } std::shared_ptr<Node> Engine::nodegraph() { return mNodeGraph; } void Engine::initRenderer() { mRend->initWindow(); mRend->initVK(); } void Engine::loop() { while (true) { try { // Calculate the frame time std::chrono::time_point<std::chrono::high_resolution_clock> current = std::chrono::high_resolution_clock::now(); auto deltaT = ((double)(current - mTimeCurrent).count()) / 1.0e9; mTimeCurrent = current; // Poll for events // TODO: Just handling the window here - should poll any // other input devices/systems like joysticks, VR controllers, etc mEventQueue.clear(); // Renderer can request a quit here - TODO: Should really handle as a QuitEvent instance if (!mRend->pollWindowEvents()) break; // Handle explicit event callbacks (Not bound to any particular node/script) callEventCallbacks(); // Renderer or other events may have asked us to stop rendering if (mQuit) break; // Perform the update traversal mNodeGraph->update(*this, deltaT); // Start the frame (Let the renderer reset what it needs) mRend->frameStart(); // Render the scene mNodeGraph->render(*mRend.get(), mCamera.mViewMatrix, mCamera.mProjectionMatrix); // Finish the frame, renderer sends commands to gpu here mRend->frameEnd(); } catch (...) { // Something went wrong, we don't know what but // it's critical that we unwind the renderer's resources properly cleanup(); // And just forward the error to whoever is listening throw; } } } void Engine::cleanup() { mRend->waitIdle(); mNodeGraph->cleanup(*mRend.get()); mRend->cleanup(); } Camera& Engine::camera() { return mCamera; } float Engine::windowWidth() const { return static_cast<float>(mRend->windowWidth()); } float Engine::windowHeight() const { return static_cast<float>(mRend->windowHeight()); } void Engine::addEvent(std::shared_ptr<Event> e) { mEventQueue.emplace_back(e); } void Engine::addEvent(Event* e) { mEventQueue.emplace_back(e); } void Engine::addGlobalEventCallback(Engine::GlobalEventCallback callback) { mGlobalEventCallbacks.emplace_back(callback); } void Engine::callEventCallbacks() { for (auto& e : mEventQueue) { for (auto& c : mGlobalEventCallbacks) { c(*this, *e.get()); } } } const std::list<std::shared_ptr<Event>>& Engine::events() const { return mEventQueue; } void Engine::quit() { mQuit = true; }
26.778761
118
0.665235
geefr
4e8c6449fdf88de8b6820f9925ebd7946112ca71
2,095
cpp
C++
Vic2ToHoI4/Source/HOI4World/Technologies.cpp
CarbonY26/Vic2ToHoI4
af3684d6aaaafea81aaadfb64a21a2b696f618e1
[ "MIT" ]
25
2018-12-10T03:41:49.000Z
2021-10-04T10:42:36.000Z
Vic2ToHoI4/Source/HOI4World/Technologies.cpp
CarbonY26/Vic2ToHoI4
af3684d6aaaafea81aaadfb64a21a2b696f618e1
[ "MIT" ]
739
2018-12-13T02:01:20.000Z
2022-03-28T02:57:13.000Z
Vic2ToHoI4/Source/HOI4World/Technologies.cpp
CarbonY26/Vic2ToHoI4
af3684d6aaaafea81aaadfb64a21a2b696f618e1
[ "MIT" ]
43
2018-12-10T03:41:58.000Z
2022-03-22T23:55:41.000Z
#include "Technologies.h" HoI4::technologies::technologies(const Mappers::TechMapper& techMapper, const Mappers::ResearchBonusMapper& researchBonusMapper, const std::set<std::string>& oldTechnologiesAndInventions) { for (const auto& techMapping: techMapper.getTechMappings()) { bool requirementViolated = false; for (const auto& requirement: techMapping.getVic2Requirements()) { if (!oldTechnologiesAndInventions.contains(requirement)) { requirementViolated = true; break; } } if (requirementViolated) { continue; } const auto& limit = techMapping.getLimit(); for (const auto& technology: techMapping.getTechs()) { auto [itr, inserted] = technologiesByLimits.insert(std::make_pair(limit, std::set{technology})); if (!inserted) { itr->second.insert(technology); } } } for (const auto& bonusMapping: researchBonusMapper.getResearchBonusMappings()) { bool requirementViolated = false; for (const auto& requirement: bonusMapping.getVic2Requirements()) { if (!oldTechnologiesAndInventions.contains(requirement)) { requirementViolated = true; break; } } if (requirementViolated) { continue; } for (const auto& bonus: bonusMapping.getResearchBonuses()) { setResearchBonus(bonus.first, bonus.second); } } } int HoI4::technologies::getTechnologyCount() const { int totalTechnologies = 0; for (const auto& [unused, technologies]: technologiesByLimits) { totalTechnologies += static_cast<int>(technologies.size()); } return totalTechnologies; } void HoI4::technologies::setResearchBonus(const std::string& tech, int bonus) { std::map<std::string, int>::iterator researchBonusEntry = researchBonuses.find(tech); if ((researchBonusEntry == researchBonuses.end()) || (researchBonusEntry->second < bonus)) { researchBonuses[tech] = bonus; } } bool HoI4::technologies::hasTechnology(const std::string& technology) const { for (const auto& [unused, technologies]: technologiesByLimits) { if (technologies.contains(technology)) { return true; } } return false; }
22.526882
99
0.717422
CarbonY26
4e8f378117d7cf1af642fddb5a300b0e295ecb84
11,861
cc
C++
ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
216
2018-09-09T11:53:56.000Z
2022-03-19T13:41:35.000Z
ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc
gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
13
2018-10-23T08:29:09.000Z
2021-09-08T06:45:34.000Z
ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
41
2018-09-13T08:50:41.000Z
2022-02-23T00:33:54.000Z
//============================================================================= // // CLASS NewtonSolver - IMPLEMENTATION // //============================================================================= //== INCLUDES ================================================================= #include "NewtonSolver.hh" #include <CoMISo/Solver/CholmodSolver.hh> #include <Base/Debug/DebTime.hh> //== NAMESPACES =============================================================== namespace COMISO { //== IMPLEMENTATION ========================================================== // solve int NewtonSolver:: solve(NProblemGmmInterface* _problem) { DEB_enter_func; #if COMISO_SUITESPARSE_AVAILABLE // get problem size int n = _problem->n_unknowns(); // hesse matrix NProblemGmmInterface::SMatrixNP H; // gradient std::vector<double> x(n), x_new(n), dx(n), g(n); // get initial x, initial grad and initial f _problem->initial_x(P(x)); double f = _problem->eval_f(P(x)); double reg = 1e-3; COMISO::CholmodSolver chol; for(int i=0; i<max_iters_; ++i) { _problem->eval_gradient(P(x), P(g)); // check for convergence if( gmm::vect_norm2(g) < eps_) { DEB_line(2, "Newton Solver converged after " << i << " iterations"); _problem->store_result(P(x)); return true; } // get current hessian _problem->eval_hessian(P(x), H); // regularize double reg_comp = reg*gmm::mat_trace(H)/double(n); for(int j=0; j<n; ++j) H(j,j) += reg_comp; // solve linear system bool factorization_ok = false; if(constant_hessian_structure_ && i != 0) factorization_ok = chol.update_system_gmm(H); else factorization_ok = chol.calc_system_gmm(H); bool improvement = false; if(factorization_ok) if(chol.solve( dx, g)) { gmm::add(x, gmm::scaled(dx,-1.0),x_new); double f_new = _problem->eval_f(P(x_new)); if( f_new < f) { // swap x and x_new (and f and f_new) x_new.swap(x); f = f_new; improvement = true; DEB_line(2, "energy improved to " << f); } } // adapt regularization if(improvement) { if(reg > 1e-9) reg *= 0.1; } else { if(reg < 1e4) reg *= 10.0; else { _problem->store_result(P(x)); DEB_line(2, "Newton solver reached max regularization but did not " "converge"); return false; } } } _problem->store_result(P(x)); DEB_line(2, "Newton Solver did not converge!!! after iterations."); return false; #else DEB_warning(1,"NewtonSolver requires not-available CholmodSolver"); return false; #endif } //----------------------------------------------------------------------------- int NewtonSolver::solve(NProblemInterface* _problem, const SMatrixD& _A, const VectorD& _b) { DEB_time_func_def; const double KKT_res_eps = 1e-6; const int max_KKT_regularization_iters = 40; double regularize_constraints_limit = 1e-6; const double max_allowed_constraint_violation2 = 1e-12; // number of unknowns size_t n = _problem->n_unknowns(); // number of constraints size_t m = _b.size(); DEB_line(2, "optimize via Newton with " << n << " unknowns and " << m << " linear constraints"); // initialize vectors of unknowns VectorD x(n); _problem->initial_x(x.data()); double initial_constraint_violation2 = (_A*x-_b).squaredNorm(); // storage of update vector dx and rhs of KKT system VectorD dx(n+m), rhs(n+m), g(n); rhs.setZero(); // resize temp vector for line search (and set to x1 to approx Hessian correctly if problem is non-quadratic!) x_ls_ = x; // indicate that system matrix is symmetric lu_solver_.isSymmetric(true); // start with no regularization double regularize_hessian(0.0); double regularize_constraints(0.0); int iter=0; bool first_factorization = true; while( iter < max_iters_) { double kkt_res2(0.0); double constraint_res2(0.0); int reg_iters(0); do { // get Newton search direction by solving LSE bool fact_ok = factorize(_problem, _A, _b, x, regularize_hessian, regularize_constraints, first_factorization); first_factorization = false; if(fact_ok) { // get rhs _problem->eval_gradient(x.data(), g.data()); rhs.head(n) = -g; rhs.tail(m) = _b - _A*x; // solve KKT system solve_kkt_system(rhs, dx); // check numerical stability of KKT system and regularize if necessary kkt_res2 = (KKT_*dx-rhs).squaredNorm(); constraint_res2 = (_A*dx.head(n)-rhs.tail(m)).squaredNorm(); } if(!fact_ok || kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2) { DEB_warning(2, "Numerical issues in KKT system"); // alternate hessian and constraints regularization if(reg_iters % 2 == 0 || regularize_constraints >= regularize_constraints_limit) { DEB_line(2, "residual ^ 2 " << kkt_res2 << "->regularize hessian"); if(regularize_hessian == 0.0) regularize_hessian = 1e-6; else regularize_hessian *= 2.0; } else { DEB_line(2, "residual^2 " << kkt_res2 << " -> regularize constraints"); if(regularize_constraints == 0.0) regularize_constraints = 1e-8; else regularize_constraints *= 2.0; } } ++reg_iters; } while( (kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2) && reg_iters < max_KKT_regularization_iters); // no valid step could be found? if(kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2 || reg_iters >= max_KKT_regularization_iters) { DEB_error("numerical issues in KKT system could not be resolved " "-> terminating NewtonSolver with current solution"); _problem->store_result(x.data()); return 0; } // get maximal reasonable step double t_max = std::min(1.0, 0.5 * _problem->max_feasible_step(x.data(), dx.data())); // perform line-search double newton_decrement(0.0); double fx(0.0); double t = backtracking_line_search(_problem, x, g, dx, newton_decrement, fx, t_max); // perform update x += dx.head(n)*t; double constraint_violation2 = (_A*x-_b).squaredNorm(); if(constraint_violation2 > 2*initial_constraint_violation2 && constraint_violation2 > max_allowed_constraint_violation2) { DEB_warning(2, "Numerical issues in KKT system lead to " "constraint violation -> recovery phase"); // restore old solution x -= dx.head(n)*t; regularize_constraints *= 0.5; regularize_constraints_limit = regularize_constraints; } DEB_line(2, "iter: " << iter << ", f(x) = " << fx << ", t = " << t << " (tmax=" << t_max << ")" << (t < t_max ? " _clamped_" : "") << ", eps = [Newton decrement] = " << newton_decrement << ", constraint violation prior = " << rhs.tail(m).norm() << ", after = " << (_b - _A*x).norm() << ", KKT residual^2 = " << kkt_res2); // converged? if(newton_decrement < eps_ || std::abs(t) < eps_ls_) break; ++iter; } // store result _problem->store_result(x.data()); // return success return 1; } //----------------------------------------------------------------------------- bool NewtonSolver::factorize(NProblemInterface* _problem, const SMatrixD& _A, const VectorD& _b, const VectorD& _x, double& _regularize_hessian, double& _regularize_constraints, const bool _first_factorization) { DEB_enter_func; const int n = _problem->n_unknowns(); const int m = _A.rows(); const int nf = n+m; // get hessian of quadratic problem SMatrixD H(n,n); _problem->eval_hessian(_x.data(), H); // set up KKT matrix // create sparse matrix std::vector< Triplet > trips; trips.reserve(H.nonZeros() + 2*_A.nonZeros()); // add elements of H for (int k=0; k<H.outerSize(); ++k) for (SMatrixD::InnerIterator it(H,k); it; ++it) trips.push_back(Triplet(it.row(),it.col(),it.value())); // add elements of _A for (int k=0; k<_A.outerSize(); ++k) for (SMatrixD::InnerIterator it(_A,k); it; ++it) { // insert _A block below trips.push_back(Triplet(it.row()+n,it.col(),it.value())); // insert _A^T block right trips.push_back(Triplet(it.col(),it.row()+n,it.value())); } // regularize constraints // if(_regularize_constraints != 0.0) for( int i=0; i<m; ++i) trips.push_back(Triplet(n+i,n+i,_regularize_constraints)); // regularize Hessian // if(_regularize_hessian != 0.0) { double ad(0.0); for( int i=0; i<n; ++i) ad += H.coeffRef(i,i); ad *= _regularize_hessian/double(n); for( int i=0; i<n; ++i) trips.push_back(Triplet(i,i,ad)); } // create KKT matrix KKT_.resize(nf,nf); KKT_.setFromTriplets(trips.begin(), trips.end()); // compute LU factorization if(_first_factorization) analyze_pattern(KKT_); return numerical_factorization(KKT_); } //----------------------------------------------------------------------------- double NewtonSolver::backtracking_line_search(NProblemInterface* _problem, VectorD& _x, VectorD& _g, VectorD& _dx, double& _newton_decrement, double& _fx, const double _t_start) { DEB_enter_func; size_t n = _x.size(); // pre-compute objective double fx = _problem->eval_f(_x.data()); // pre-compute dot product double gtdx = _g.transpose()*_dx.head(n); _newton_decrement = std::abs(gtdx); // current step size double t = _t_start; // backtracking (stable in case of NAN and with max 100 iterations) for(int i=0; i<100; ++i) { // current update x_ls_ = _x + _dx.head(n)*t; double fx_ls = _problem->eval_f(x_ls_.data()); if( fx_ls <= fx + alpha_ls_*t*gtdx ) { _fx = fx_ls; return t; } else t *= beta_ls_; } DEB_warning(1, "line search could not find a valid step within 100 " "iterations"); _fx = fx; return 0.0; } //----------------------------------------------------------------------------- void NewtonSolver::analyze_pattern(SMatrixD& _KKT) { DEB_enter_func; switch(solver_type_) { case LS_EigenLU: lu_solver_.analyzePattern(_KKT); break; #if COMISO_SUITESPARSE_AVAILABLE case LS_Umfpack: umfpack_solver_.analyzePattern(_KKT); break; #endif default: DEB_warning(1, "selected linear solver not availble"); } } //----------------------------------------------------------------------------- bool NewtonSolver::numerical_factorization(SMatrixD& _KKT) { DEB_enter_func; switch(solver_type_) { case LS_EigenLU: lu_solver_.factorize(_KKT); return (lu_solver_.info() == Eigen::Success); #if COMISO_SUITESPARSE_AVAILABLE case LS_Umfpack: umfpack_solver_.factorize(_KKT); return (umfpack_solver_.info() == Eigen::Success); #endif default: DEB_warning(1, "selected linear solver not availble!"); return false; } } //----------------------------------------------------------------------------- void NewtonSolver::solve_kkt_system(const VectorD& _rhs, VectorD& _dx) { DEB_enter_func; switch(solver_type_) { case LS_EigenLU: _dx = lu_solver_.solve(_rhs); break; #if COMISO_SUITESPARSE_AVAILABLE case LS_Umfpack: _dx = umfpack_solver_.solve(_rhs); break; #endif default: DEB_warning(1, "selected linear solver not availble"); break; } } //============================================================================= } // namespace COMISO //=============================================================================
27.329493
136
0.579715
shubhMaheshwari
4e909e9fc4eb891a24ec781bdfed79964a7da3a9
861
hpp
C++
include/dca/testing/type_testing.hpp
NunoEdgarGFlowHub/DCA
51d0085084c9c3eb628893b78596eacfaf2d3ace
[ "BSD-3-Clause" ]
27
2018-08-02T04:28:23.000Z
2021-07-08T02:14:20.000Z
include/dca/testing/type_testing.hpp
cosdis/DCA
3cfd2a4f4bb876fb69f9c22e7ad06332fb5ebbe5
[ "BSD-3-Clause" ]
200
2018-08-02T18:19:03.000Z
2022-03-16T21:28:41.000Z
include/dca/testing/type_testing.hpp
PDoakORNL/DCA-2
5a373f6af5a7d4b5be69199f60ec75a16e58c626
[ "BSD-3-Clause" ]
22
2018-08-15T15:50:00.000Z
2021-09-30T13:41:46.000Z
// Copyright (C) 2019 ETH Zurich // Copyright (C) 2019 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Doak (doakpw@ornl.gov) // // This class provides an alternative output mode which produces minimal amount of information about // tests. Only failed assertions are disclosed. #ifndef DCA_TESTING_TYPE_TESTING_HPP #define DCA_TESTING_TYPE_TESTING_HPP #include <type_traits> namespace dca { namespace testing { template<typename...> using void_t = void; template<typename, typename, typename = void> struct can_compare : std::false_type {}; template<typename A, typename B> struct can_compare<A, B, void_t<decltype(std::declval<A>() == std::declval<B>())> > : std::true_type {}; } } #endif
24.6
100
0.720093
NunoEdgarGFlowHub
4e97145d1a7f70cbbc569a43001af03503cb7612
10,760
cpp
C++
modules/media/test/apps/test_game_tokens.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
modules/media/test/apps/test_game_tokens.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
1
2016-01-25T13:03:03.000Z
2016-01-25T13:03:03.000Z
modules/media/test/apps/test_game_tokens.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 Clyde Stanfield * * 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 <nyra/test/Test.h> #include <nyra/media/GameTokens.h> //===========================================================================// nyra::media::GameTokens make(const std::string& filename) { nyra::media::GameTokens tokens; tokens.initialize(filename); return tokens; } namespace nyra { namespace media { //===========================================================================// TEST(GameTokens, Country) { GameTokens token; token = make("Sample Game (1).bin"); EXPECT_EQ("Country: Japan & Korea", test::stdout(token)); token = make("Sample Game (A).bin"); EXPECT_EQ("Country: Australia", test::stdout(token)); token = make("Sample Game (B).bin"); EXPECT_EQ("Country: Non USA", test::stdout(token)); token = make("Sample Game (C).bin"); EXPECT_EQ("Country: China", test::stdout(token)); token = make("Sample Game (E).bin"); EXPECT_EQ("Country: Europe", test::stdout(token)); token = make("Sample Game (F).bin"); EXPECT_EQ("Country: France", test::stdout(token)); token = make("Sample Game (FC).bin"); EXPECT_EQ("Country: French Canadian", test::stdout(token)); token = make("Sample Game (FN).bin"); EXPECT_EQ("Country: Finland", test::stdout(token)); token = make("Sample Game (G).bin"); EXPECT_EQ("Country: Germany", test::stdout(token)); token = make("Sample Game (GR).bin"); EXPECT_EQ("Country: Greece", test::stdout(token)); token = make("Sample Game (HK).bin"); EXPECT_EQ("Country: Hong Kong", test::stdout(token)); token = make("Sample Game (D).bin"); EXPECT_EQ("Country: Dutch", test::stdout(token)); token = make("Sample Game (4).bin"); EXPECT_EQ("Country: USA & Brazil", test::stdout(token)); token = make("Sample Game (J).bin"); EXPECT_EQ("Country: Japan", test::stdout(token)); token = make("Sample Game (K).bin"); EXPECT_EQ("Country: Korea", test::stdout(token)); token = make("Sample Game (NL).bin"); EXPECT_EQ("Country: Netherlands", test::stdout(token)); token = make("Sample Game (PD).bin"); EXPECT_EQ("Country: Public Domain", test::stdout(token)); token = make("Sample Game (S).bin"); EXPECT_EQ("Country: Spain", test::stdout(token)); token = make("Sample Game (Sw).bin"); EXPECT_EQ("Country: Sweden", test::stdout(token)); token = make("Sample Game (U).bin"); EXPECT_EQ("Country: USA", test::stdout(token)); token = make("Sample Game (UK).bin"); EXPECT_EQ("Country: England", test::stdout(token)); token = make("Sample Game (Unk).bin"); EXPECT_EQ("Country: Unknown", test::stdout(token)); token = make("Sample Game (I).bin"); EXPECT_EQ("Country: Italy", test::stdout(token)); token = make("Sample Game (Unl).bin"); EXPECT_EQ("Country: Unlicensed", test::stdout(token)); token = make("Sample Game.bin"); EXPECT_EQ("Country: Unknown", test::stdout(token)); token = make("Sample Game (foo).bin"); EXPECT_EQ("Country: Unknown\n" "Miscellaneous Codes:\n" " (foo)", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Hack) { GameTokens token; const std::string expected = "Country: USA\n" "Hack: "; token = make("Sample Game (U) [h1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [h2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [h1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [hfoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Fixed) { GameTokens token; const std::string expected = "Country: USA\n" "Fixed: "; token = make("Sample Game (U) [f1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [f2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [f1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [ffoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Alternative) { GameTokens token; const std::string expected = "Country: USA\n" "Alternative: "; token = make("Sample Game (U) [a1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [a2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [a1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [afoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Overdump) { GameTokens token; const std::string expected = "Country: USA\n" "Overdump: "; token = make("Sample Game (U) [o1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [o2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [o1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [ofoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Trainer) { GameTokens token; const std::string expected = "Country: USA\n" "Trainer: "; token = make("Sample Game (U) [t1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [t2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [t1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [tfoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Pirated) { GameTokens token; const std::string expected = "Country: USA\n" "Pirated: "; token = make("Sample Game (U) [p1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [p2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [p1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [pfoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, BadDump) { GameTokens token; const std::string expected = "Country: USA\n" "Bad Dump: "; token = make("Sample Game (U) [b1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [b2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [b1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [bfoo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, OldTranslation) { GameTokens token; const std::string expected = "Country: USA\n" "Old Translation: "; token = make("Sample Game (U) [T-1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [T-2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [T-1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [T-foo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, NewTranslation) { GameTokens token; const std::string expected = "Country: USA\n" "New Translation: "; token = make("Sample Game (U) [T+1].bin"); EXPECT_EQ(expected + "1", test::stdout(token)); token = make("Sample Game (U) [T+2].bin"); EXPECT_EQ(expected + "2", test::stdout(token)); token = make("Sample Game (U) [T+1000].bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); token = make("Sample Game (U) [T+foo].bin"); EXPECT_EQ(expected + "foo", test::stdout(token)); } //===========================================================================// TEST(GameTokens, Version) { GameTokens token; const std::string expected = "Country: USA\n" "Version: "; token = make("Sample Game (U) (V1.1).bin"); EXPECT_EQ(expected + "1.1", test::stdout(token)); token = make("Sample Game (U) (V1.2).bin"); EXPECT_EQ(expected + "1.2", test::stdout(token)); token = make("Sample Game (U) (V1000).bin"); EXPECT_EQ(expected + "1000", test::stdout(token)); } //===========================================================================// TEST(GameTokens, LessThan) { GameTokens token1; GameTokens token2; token1 = make("Sample Game (U) [!].bin"); EXPECT_TRUE(token1 < token2); EXPECT_FALSE(token2 < token1); EXPECT_FALSE(token1 < token1); EXPECT_FALSE(token2 < token1); } } } NYRA_TEST()
35.278689
79
0.560409
LCClyde
4e9c86d8dd802f0a91038b54f776b20993f9ba62
7,818
hpp
C++
RobWorkSim/src/rwsim/dynamics/FixedLink.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWorkSim/src/rwsim/dynamics/FixedLink.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWorkSim/src/rwsim/dynamics/FixedLink.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 RWSIM_DYNAMICS_FIXEDLINK_HPP_ #define RWSIM_DYNAMICS_FIXEDLINK_HPP_ //! @file FixedLink.hpp #include "Body.hpp" #include <rw/math/Jacobian.hpp> #include <rw/math/Vector3D.hpp> #include <rw/models/Joint.hpp> namespace rw { namespace kinematics { class Frame; }} // namespace rw::kinematics namespace rw { namespace models { class Device; }} // namespace rw::models namespace rwsim { namespace dynamics { //! @addtogroup rwsim_dynamics //! @{ /** * @brief */ class FixedLink : public Body { public: /*FixedLink( const std::string &material, rw::kinematics::Frame *base, std::vector<FixedLink*> parents, rw::models::Device &dev, rw::models::Joint &j, rw::kinematics::State &state); */ FixedLink (const BodyInfo& info, rw::kinematics::Frame* base, std::vector< FixedLink* > parents, rw::models::Device& dev, rw::models::Joint& j, const std::vector< rw::kinematics::Frame* >& frames, rw::kinematics::State& state); virtual ~FixedLink (); public: // functions that need to be implemented by specialized class virtual void saveState (double h, rw::kinematics::State& state); virtual void rollBack (rw::kinematics::State& state); virtual void updateVelocity (double h, rw::kinematics::State& state); virtual void updatePosition (double h, rw::kinematics::State& state); virtual void updateImpulse (); rw::math::Vector3D<> getPointVelW (const rw::math::Vector3D<>& wPp); rw::math::InertiaMatrix<> getEffectiveMassW (const rw::math::Vector3D<>& wPc); void resetState (rw::kinematics::State& state); virtual void reset () { rw::math::Vector3D<> zeroVec = rw::math::Vector3D<> (0.0, 0.0, 0.0); _force = zeroVec; _torque = zeroVec; } void calcAuxVarialbles (rw::kinematics::State& state) {} double calcEnergy () { return 0; }; public: rw::math::InertiaMatrix<> getEffectiveMass (); void addQd (double vel); void addTorque (double t); double getQd () { return _vel; } void setAcc (double acc) { _acc = acc; } const std::string& getMaterial () { return _materialID; } /** * @brief Adds a force described in parent frame to the * center of mass of this body */ virtual void addForce (const rw::math::Vector3D<>& force) { _force += force; } /** * @brief Adds a force described in world frame to the * center of mass of this body */ virtual void addForceW (const rw::math::Vector3D<>& force) { _force += _bTw.R () * force; } /** * @brief Adds a force described in parent frame to this body * which is working on a specific position pos that is described relative to * this body. */ virtual void addForceToPos (const rw::math::Vector3D<>& force, const rw::math::Vector3D<>& pos) { // calculate the center force contribution _force += force; // calculate the torque contribution _torque += cross (pos, force); } /** * @brief Adds a force described in world frame to this body * which is worked on a specific position pos that is described * relative to world */ virtual void addForceWToPosW (const rw::math::Vector3D<>& force, const rw::math::Vector3D<>& pos); /** * @brief Adds a impulse described in parent frame to this body * which is working on a specific position pos that is described relative to * this body. */ virtual void addImpulseToPos (const rw::math::Vector3D<>& impulse, const rw::math::Vector3D<>& pos) { // calculate the center force contribution _linImpulse += impulse; // calculate the torque contribution _angImpulse += cross (pos, impulse); } /** * @brief Adds a impulse described in world frame to this body * which is worked on a specific position pos that is described * relative to world */ virtual void addImpulseWToPosW (const rw::math::Vector3D<>& impulse, const rw::math::Vector3D<>& pos); /** * @brief adds gravitation to the body where the gravitation is * described in body frame */ virtual void addGravitation (const rw::math::Vector3D<>& grav){ //_force += grav * _mass; }; /** * @brief adds gravitation to the body where the gravitation is * described in world frame */ virtual void addGravitationW (const rw::math::Vector3D<>& grav){ //_force += (_pTw.R() * grav) * _mass; }; /** * @brief */ void addChild (FixedLink* child) { _children.push_back (child); } /** * @brief get the body inertia of the link */ rw::math::InertiaMatrix<> getInertia () { return rw::math::InertiaMatrix<> (1, 1, 1); } void setTargetVel (double vel) { _targetVel = vel; } /* void setAcc(double acc){ _maxAcc = acc; }*/ rw::models::Joint* getJoint () { return &_jointFrame; } private: std::string _materialID; std::vector< FixedLink* > _children, _parents; rw::models::Joint& _jointFrame; rw::models::Device& _dev; rw::math::Jacobian _jac, _jacRB; rw::math::Vector3D<> _force, _forceRB, // accumulated force in parent frame _torque, _torqueRB; // accumulated torque in parent frame rw::math::Vector3D<> _linImpulse, _linImpulseRB, // linear impulse in parent frame _angImpulse, _angImpulseRB; // angular impulse in parent frame rw::math::Transform3D<> _wTb, _wTbRB, // world to body _bTw, _bTwRB; // body to world rw::math::Transform3D<> _wTbase, _baseTw; // world to base rw::math::Transform3D<> _baseTb, _bTbase; rw::math::Transform3D<> _baseTbRB; rw::math::Transform3D<> _bTbaseRB; double _vel, _pos, _acc, _posRB, _velRB; double _targetVel; rw::kinematics::Frame* _base; int _impulseIterations; size_t _jointNr; }; //! @} }} // namespace rwsim::dynamics #endif /*LINK_HPP_*/
33.410256
100
0.553978
ZLW07
4e9d9f7a9a6f5f95ca34946c0031440deee25059
2,086
cpp
C++
2015/9.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
2
2020-08-06T22:14:51.000Z
2020-08-10T19:42:36.000Z
2015/9.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
2015/9.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> int index(std::string location) { switch(location[0]) { case 'F': return 2; case 'N': return 3; case 'A': switch(location[1]) { case 'l':return 0; case 'r':return 1; } break; case 'S': switch(location[1]) { case 'n': return 4; case 't': return 5; } break; case 'T': switch(location[1]) { case 'a':return 6; case 'r':return 7; } } std::cout<<"UNKNOWN LOCATION: "; for (unsigned i=0;i<location.size();i++) { std::cout<<location[i]<<'('<<static_cast<int>(location[i])<<')'; }std::cout<<std::endl; return 0; } int main() { std::string location_0, location_1; static unsigned long distances[8][8]; unsigned minimal=-1,maximal=0; unsigned route[8] = {0,1,2,3,4,5,6,7}; while (true) { std::getline(std::cin, location_0,' '); if(std::cin.eof()) break; else if (std::cin.get()!='t') std::cout<<"ILL FORMED INPUT"<<std::endl; else if(std::cin.get()!='o') std::cout<<"ILL FORMED_INPUT"<<std::endl; else if(std::cin.get()!=' ') std::cout<<"ILL_FORMED_INPUT"<<std::endl; std::getline(std::cin, location_1,' '); if (std::cin.get()!='=') std::cout<<"ILL INPUT"<<std::endl; else if(std::cin.get() !=' ') std::cout<<"ILL_INPUT"<<std::endl; std::cin>>distances[index(location_0)][index(location_1)]; distances[index(location_1)][index(location_0)] = distances[index(location_0)][index(location_1)]; std::cin.get();//Gobble newline } do { unsigned max = 0,min=-1; unsigned tot_dist=0; for (int i=0;i<8;i++) { unsigned dummy = distances[route[i]][route[(i+1)%8]]; tot_dist += dummy; if (dummy > max) { max = dummy; } if (dummy < min) { min = dummy; } } if (tot_dist - max < minimal) minimal = tot_dist - max; if (tot_dist - min > maximal) maximal = tot_dist - min; } while (std::next_permutation(route, route+8)); std::cout<<minimal<<' '<<maximal<<std::endl;; return 0; }
24.833333
103
0.5628
wgevaert
4e9e563229c8da756e113d4b5e469c976289f0a3
967
hpp
C++
C++ Programming/CPTS 122/Programming Assignments/BST Data Analysis/BST.hpp
subhamb123/WSU-Coding-Projects
bb2910d76ac446f190ce641b869e68ae86d9b760
[ "MIT" ]
1
2020-09-03T07:09:05.000Z
2020-09-03T07:09:05.000Z
C++ Programming/CPTS 122/Programming Assignments/BST Data Analysis/BST.hpp
subhamb123/WSU-Coding-Projects
bb2910d76ac446f190ce641b869e68ae86d9b760
[ "MIT" ]
null
null
null
C++ Programming/CPTS 122/Programming Assignments/BST Data Analysis/BST.hpp
subhamb123/WSU-Coding-Projects
bb2910d76ac446f190ce641b869e68ae86d9b760
[ "MIT" ]
null
null
null
/************************************************************************ * Programmer: Subham Behera * * Class: CptS 122; Lab Section 13 * * Programming Assignment: PA 8 - Data Analysis using Binary Search Trees* * Date: 4/10/2021 * * Description: This program simulates product ownership using BST * ************************************************************************/ //Guard Code #pragma once //Header Files #include "TransactionNode.hpp" //Classes class BST { public: BST(); ~BST(); void setRoot(Node* pRoot); Node* getRoot() const; void insert(int units, string data); void inOrderTraversal(); TransactionNode& findSmallest(); TransactionNode& findLargest(); private: void destroyTree(Node* pTree); void insert(Node*& pT, int units, string data); void inOrderTraversal(Node* pTree); Node* mpRoot; };
31.193548
73
0.509824
subhamb123
4ea17060b3ee1a6c462fd96f99afe957f375c45a
7,740
cpp
C++
tests/ip/address_v4.cpp
chriskohlhoff/ip-address
38251ff2f9a2cb5e4152c7314e14d2e65e69f27d
[ "BSL-1.0" ]
31
2015-01-25T13:09:27.000Z
2021-04-22T04:58:14.000Z
tests/ip/address_v4.cpp
chriskohlhoff/ip-address
38251ff2f9a2cb5e4152c7314e14d2e65e69f27d
[ "BSL-1.0" ]
1
2018-12-06T07:06:53.000Z
2018-12-06T07:06:53.000Z
tests/ip/address_v4.cpp
chriskohlhoff/ip-address
38251ff2f9a2cb5e4152c7314e14d2e65e69f27d
[ "BSL-1.0" ]
7
2016-01-10T07:20:12.000Z
2021-08-07T01:22:07.000Z
// // address_v4.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Test that header file is self-contained. #include "std/net/ip/address_v4.hpp" #include "../unit_test.hpp" #include <sstream> #include "std/net/ip/address_v6.hpp" //------------------------------------------------------------------------------ // ip_address_v4_compile test // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // The following test checks that all public member functions on the class // ip::address_v4 compile and link correctly. Runtime failures are ignored. namespace ip_address_v4_compile { void test() { namespace ip = std::experimental::net::ip; try { std::error_code ec; std::string string_value; // address_v4 constructors. ip::address_v4 addr1; const ip::address_v4::bytes_type const_bytes_value(127, 0, 0, 1); ip::address_v4 addr2(const_bytes_value); const unsigned long const_ulong_value = 0x7F000001; ip::address_v4 addr3(const_ulong_value); ip::address_v4 addr4("127.0.0.1"); ip::address_v4 addr5("127.0.0.1", ec); ip::address_v4 addr6(string_value); ip::address_v4 addr7(string_value, ec); // address_v4 functions. bool b = addr1.is_loopback(); (void)b; b = addr1.is_unspecified(); (void)b; b = addr1.is_class_a(); (void)b; b = addr1.is_class_b(); (void)b; b = addr1.is_class_c(); (void)b; b = addr1.is_multicast(); (void)b; ip::address_v4::bytes_type bytes_value = addr1.to_bytes(); (void)bytes_value; unsigned long ulong_value = addr1.to_ulong(); (void)ulong_value; string_value = addr1.to_string(); string_value = addr1.to_string(ec); // address_v4 static functions. addr1 = ip::address_v4::any(); addr1 = ip::address_v4::loopback(); addr1 = ip::address_v4::broadcast(); addr1 = ip::address_v4::broadcast(addr2, addr3); // address_v4 comparisons. b = (addr1 == addr2); (void)b; b = (addr1 != addr2); (void)b; b = (addr1 < addr2); (void)b; b = (addr1 > addr2); (void)b; b = (addr1 <= addr2); (void)b; b = (addr1 >= addr2); (void)b; // address_v4 creation. addr1 = ip::make_address_v4(const_bytes_value); addr1 = ip::make_address_v4(const_ulong_value); addr1 = ip::make_address_v4(ip::v4_mapped, ip::address_v6()); addr1 = ip::make_address_v4("127.0.0.1"); addr1 = ip::make_address_v4("127.0.0.1", ec); addr1 = ip::make_address_v4(string_value); addr1 = ip::make_address_v4(string_value, ec); // address_v4 I/O. std::ostringstream os; os << addr1; std::wostringstream wos; wos << addr1; } catch (std::exception&) { } } } // namespace ip_address_v4_compile //------------------------------------------------------------------------------ // ip_address_v4_runtime test // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // The following test checks that the various public member functions meet the // necessary postconditions. namespace ip_address_v4_runtime { void test() { using std::experimental::net::ip::address_v4; address_v4 a1; STDNET_CHECK(a1.to_bytes()[0] == 0); STDNET_CHECK(a1.to_bytes()[1] == 0); STDNET_CHECK(a1.to_bytes()[2] == 0); STDNET_CHECK(a1.to_bytes()[3] == 0); STDNET_CHECK(a1.to_ulong() == 0); address_v4::bytes_type b1(1, 2, 3, 4); address_v4 a2(b1); STDNET_CHECK(a2.to_bytes()[0] == 1); STDNET_CHECK(a2.to_bytes()[1] == 2); STDNET_CHECK(a2.to_bytes()[2] == 3); STDNET_CHECK(a2.to_bytes()[3] == 4); STDNET_CHECK(((a2.to_ulong() >> 24) & 0xFF) == b1[0]); STDNET_CHECK(((a2.to_ulong() >> 16) & 0xFF) == b1[1]); STDNET_CHECK(((a2.to_ulong() >> 8) & 0xFF) == b1[2]); STDNET_CHECK((a2.to_ulong() & 0xFF) == b1[3]); address_v4 a3(0x01020304); STDNET_CHECK(a3.to_bytes()[0] == 1); STDNET_CHECK(a3.to_bytes()[1] == 2); STDNET_CHECK(a3.to_bytes()[2] == 3); STDNET_CHECK(a3.to_bytes()[3] == 4); STDNET_CHECK(a3.to_ulong() == 0x01020304); STDNET_CHECK(address_v4(0x7F000001).is_loopback()); STDNET_CHECK(address_v4(0x7F000002).is_loopback()); STDNET_CHECK(!address_v4(0x00000000).is_loopback()); STDNET_CHECK(!address_v4(0x01020304).is_loopback()); STDNET_CHECK(address_v4(0x00000000).is_unspecified()); STDNET_CHECK(!address_v4(0x7F000001).is_unspecified()); STDNET_CHECK(!address_v4(0x01020304).is_unspecified()); STDNET_CHECK(address_v4(0x01000000).is_class_a()); STDNET_CHECK(address_v4(0x7F000000).is_class_a()); STDNET_CHECK(!address_v4(0x80000000).is_class_a()); STDNET_CHECK(!address_v4(0xBFFF0000).is_class_a()); STDNET_CHECK(!address_v4(0xC0000000).is_class_a()); STDNET_CHECK(!address_v4(0xDFFFFF00).is_class_a()); STDNET_CHECK(!address_v4(0xE0000000).is_class_a()); STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_a()); STDNET_CHECK(!address_v4(0xF0000000).is_class_a()); STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_a()); STDNET_CHECK(!address_v4(0x01000000).is_class_b()); STDNET_CHECK(!address_v4(0x7F000000).is_class_b()); STDNET_CHECK(address_v4(0x80000000).is_class_b()); STDNET_CHECK(address_v4(0xBFFF0000).is_class_b()); STDNET_CHECK(!address_v4(0xC0000000).is_class_b()); STDNET_CHECK(!address_v4(0xDFFFFF00).is_class_b()); STDNET_CHECK(!address_v4(0xE0000000).is_class_b()); STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_b()); STDNET_CHECK(!address_v4(0xF0000000).is_class_b()); STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_b()); STDNET_CHECK(!address_v4(0x01000000).is_class_c()); STDNET_CHECK(!address_v4(0x7F000000).is_class_c()); STDNET_CHECK(!address_v4(0x80000000).is_class_c()); STDNET_CHECK(!address_v4(0xBFFF0000).is_class_c()); STDNET_CHECK(address_v4(0xC0000000).is_class_c()); STDNET_CHECK(address_v4(0xDFFFFF00).is_class_c()); STDNET_CHECK(!address_v4(0xE0000000).is_class_c()); STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_c()); STDNET_CHECK(!address_v4(0xF0000000).is_class_c()); STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_c()); STDNET_CHECK(!address_v4(0x01000000).is_multicast()); STDNET_CHECK(!address_v4(0x7F000000).is_multicast()); STDNET_CHECK(!address_v4(0x80000000).is_multicast()); STDNET_CHECK(!address_v4(0xBFFF0000).is_multicast()); STDNET_CHECK(!address_v4(0xC0000000).is_multicast()); STDNET_CHECK(!address_v4(0xDFFFFF00).is_multicast()); STDNET_CHECK(address_v4(0xE0000000).is_multicast()); STDNET_CHECK(address_v4(0xEFFFFFFF).is_multicast()); STDNET_CHECK(!address_v4(0xF0000000).is_multicast()); STDNET_CHECK(!address_v4(0xFFFFFFFF).is_multicast()); address_v4 a4 = address_v4::any(); STDNET_CHECK(a4.to_bytes()[0] == 0); STDNET_CHECK(a4.to_bytes()[1] == 0); STDNET_CHECK(a4.to_bytes()[2] == 0); STDNET_CHECK(a4.to_bytes()[3] == 0); STDNET_CHECK(a4.to_ulong() == 0); address_v4 a5 = address_v4::loopback(); STDNET_CHECK(a5.to_bytes()[0] == 0x7F); STDNET_CHECK(a5.to_bytes()[1] == 0); STDNET_CHECK(a5.to_bytes()[2] == 0); STDNET_CHECK(a5.to_bytes()[3] == 0x01); STDNET_CHECK(a5.to_ulong() == 0x7F000001); address_v4 a6 = address_v4::broadcast(); STDNET_CHECK(a6.to_bytes()[0] == 0xFF); STDNET_CHECK(a6.to_bytes()[1] == 0xFF); STDNET_CHECK(a6.to_bytes()[2] == 0xFF); STDNET_CHECK(a6.to_bytes()[3] == 0xFF); STDNET_CHECK(a6.to_ulong() == 0xFFFFFFFF); } } // namespace ip_address_v4_runtime //------------------------------------------------------------------------------ STDNET_TEST_SUITE ( "ip/address_v4", STDNET_TEST_CASE(ip_address_v4_compile::test) STDNET_TEST_CASE(ip_address_v4_runtime::test) )
30.352941
80
0.669121
chriskohlhoff
4ea4e9f0cc62d073d6339d00521078963ef87afa
19,627
cpp
C++
admin/snapin/smonlog/smlogcfg/smtprov.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/smonlog/smlogcfg/smtprov.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/smonlog/smlogcfg/smtprov.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) 1998-1999 Microsoft Corporation Module Name: smtprov.cpp Abstract: This object is used to store the list of all current trace providers in the system. --*/ #include "Stdafx.h" #include <wbemidl.h> #include <initguid.h> #include <wmistr.h> #include <evntrace.h> #include "smtracsv.h" #include "smtprov.h" USE_HANDLE_MACROS("SMLOGCFG(smtprov.cpp)"); #define WIN32_FROM_HRESULT(x)((x) & 0x0000FFFF) LPCWSTR CSmTraceProviders::m_cszBackslash = L"\\"; LPCWSTR CSmTraceProviders::m_cszKernelLogger = KERNEL_LOGGER_NAMEW; // From evntrace.h LPCWSTR CSmTraceProviders::m_cszDefaultNamespace = L"root\\wmi"; LPCWSTR CSmTraceProviders::m_cszTraceProviderClass = L"EventTrace"; LPCWSTR CSmTraceProviders::m_cszDescription = L"Description"; LPCWSTR CSmTraceProviders::m_cszGuid = L"Guid"; // // Constructor CSmTraceProviders::CSmTraceProviders ( CSmTraceLogService* pSvc ) : m_pWbemServices ( NULL ), m_pTraceLogService ( pSvc ), m_iBootState ( -1 ) { m_KernelTraceProvider.strDescription = L""; m_KernelTraceProvider.strGuid = L""; return; } // // Destructor CSmTraceProviders::~CSmTraceProviders ( ) { ASSERT ( 0 == (INT)m_arrGenTraceProvider.GetSize ( ) ); m_arrGenTraceProvider.RemoveAll ( ); return; } // // Open function. Initialize provider array from Wbem. // DWORD CSmTraceProviders::Open ( const CString& rstrMachineName ) { DWORD dwStatus = ERROR_SUCCESS; DWORD dwLength; CString strTemp; MFC_TRY if ( !rstrMachineName.IsEmpty ( ) ) { m_strMachineName = rstrMachineName; if ( 0 != lstrcmpi ( m_cszBackslash, m_strMachineName.Left(1) ) ) { strTemp = m_cszBackslash; strTemp += m_cszBackslash; m_strMachineName = strTemp + m_strMachineName; } } else { // get the local machine name & default name space if the caller // has passed in a NULL machine name dwLength = MAX_COMPUTERNAME_LENGTH + 1; if ( GetComputerName ( m_strMachineName.GetBufferSetLength( dwLength ), &dwLength ) ) { m_strMachineName.ReleaseBuffer(); strTemp = m_cszBackslash; strTemp += m_cszBackslash; m_strMachineName = strTemp + m_strMachineName; } else { dwStatus = GetLastError(); m_strMachineName.ReleaseBuffer(); } } MFC_CATCH_DWSTATUS if ( ERROR_SUCCESS != dwStatus ) { m_strMachineName.Empty(); } return dwStatus; } // // Close Function // Frees allocated memory // DWORD CSmTraceProviders::Close ( ) { DWORD dwStatus = ERROR_SUCCESS; m_arrGenTraceProvider.RemoveAll ( ); if ( NULL != m_pWbemServices ) { m_pWbemServices->Release ( ); m_pWbemServices = NULL; } return dwStatus; } // // AddProvider // Add the specified provider strings to the array // DWORD CSmTraceProviders::AddProvider ( const CString& rstrDescription, const CString& rstrGuid, INT iIsEnabled, INT iIsActive ) { DWORD dwStatus = ERROR_SUCCESS; SLQ_TRACE_PROVIDER slqTProv; // If inactive, cannot be enabled. ASSERT ( ( 0 == iIsActive ) ? ( 0 == iIsEnabled ) : TRUE ); MFC_TRY slqTProv.strDescription = rstrDescription; slqTProv.strGuid = rstrGuid; slqTProv.iIsEnabled = iIsEnabled; slqTProv.iIsActive = iIsActive; m_arrGenTraceProvider.Add( slqTProv ); MFC_CATCH_DWSTATUS return dwStatus; } // // ConnectToServer // Connects to the Wbem server. // HRESULT CSmTraceProviders::ConnectToServer ( void ) { HRESULT hr = NOERROR; if ( NULL == m_pWbemServices ) { IWbemLocator *pWbemLocator = NULL; IWbemServices *pWbemServices = NULL; // connect to locator hr = CoCreateInstance ( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, ( LPVOID * )&pWbemLocator ); if ( SUCCEEDED (hr) ) { BSTR bstrTemp = NULL; CString strNamespace; MFC_TRY strNamespace = m_strMachineName; strNamespace += m_cszBackslash; strNamespace += m_cszDefaultNamespace; bstrTemp = strNamespace.AllocSysString(); MFC_CATCH_HR if ( SUCCEEDED ( hr ) ) { // try to connect to the service hr = pWbemLocator->ConnectServer ( bstrTemp, NULL, NULL, 0, 0L, 0, 0, &pWbemServices ); ::SysFreeString ( bstrTemp ); } if ( SUCCEEDED ( hr ) ) { hr = CoSetProxyBlanket((IUnknown*)pWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); } // free the locator pWbemLocator->Release ( ); } if ( SUCCEEDED ( hr ) ) { m_pWbemServices = pWbemServices; } } return hr; } // // GetBootState // Connects to the registry. // HRESULT CSmTraceProviders::GetBootState ( INT& riBootState ) { HRESULT hr = NOERROR; if ( -1 == m_iBootState ) { HKEY hKeyMachine; ASSERT ( NULL != m_pTraceLogService ); hKeyMachine = m_pTraceLogService->GetMachineKey ( ); if ( NULL != hKeyMachine ) { HKEY hKeyOption; DWORD dwStatus = ERROR_SUCCESS; dwStatus = RegOpenKeyEx ( hKeyMachine, (LPCWSTR)L"System\\CurrentControlSet\\Control\\Safeboot\\Option", 0, KEY_READ, &hKeyOption ); // The Option key and OptionValue value only exist if booting in // safe mode, so failure indicates Normal mode (0). // Safe mode = 1, Safe mode with network = 2. if ( ERROR_SUCCESS == dwStatus ) { DWORD dwType = 0; DWORD dwBufSize = sizeof (INT ); dwStatus = RegQueryValueExW ( hKeyOption, L"OptionValue", NULL, &dwType, (LPBYTE)&m_iBootState, &dwBufSize); if ( ERROR_SUCCESS != dwStatus ) { // Normal mode m_iBootState = 0; } RegCloseKey(hKeyOption); } else { // Normal mode m_iBootState = 0; } } else { // Unable to access registry hr = E_FAIL; } } riBootState = m_iBootState; return hr; } // // SyncWithConfiguration // Reads the current list of providers from Wbem // and reloads the internal values to match // HRESULT CSmTraceProviders::SyncWithConfiguration ( void ) { typedef struct _LOG_INFO { EVENT_TRACE_PROPERTIES Properties; WCHAR szLoggerName[MAX_PATH+1]; // Must follow Properties } LOG_INFO, FAR* PLOG_INFO; IEnumWbemClassObject *pEnumProviders = NULL; CString strDescription; CString strGuid; CString strBracketedGuid; BSTR bstrTemp; INT iIndex; INT iIsEnabled =0; HRESULT hr; PTRACE_GUID_PROPERTIES* arrGuidProperties = NULL; ULONG ulGuidCount; PVOID pGuidStorage = NULL; m_arrGenTraceProvider.RemoveAll ( ); hr = ConnectToServer( ); if ( SUCCEEDED ( hr ) ) { hr = LoadGuidArray( &pGuidStorage, &ulGuidCount ); } if ( SUCCEEDED ( hr ) ) { arrGuidProperties = (PTRACE_GUID_PROPERTIES *)pGuidStorage; ASSERT ( NULL != arrGuidProperties ); } //If Connection succeeded and registered Guids gathered. if ( SUCCEEDED ( hr ) ) { // Create an enumerator of the Trace Provider class MFC_TRY bstrTemp = SysAllocString(m_cszTraceProviderClass); hr = m_pWbemServices->CreateClassEnum ( bstrTemp, WBEM_FLAG_SHALLOW|WBEM_FLAG_USE_AMENDED_QUALIFIERS, NULL, &pEnumProviders ); ::SysFreeString ( bstrTemp ); MFC_CATCH_HR if ( SUCCEEDED ( hr ) ) { BSTR bsDescription = NULL; BSTR bsGuid = NULL; VARIANT vValue; DWORD dwRtnCount; IWbemQualifierSet *pQualSet = NULL; IWbemClassObject *pThisClass = NULL; WCHAR szSystemTraceControlGuid[39]; ULONG Status; VariantInit ( &vValue ); ZeroMemory ( szSystemTraceControlGuid, sizeof ( szSystemTraceControlGuid ) ); ::StringFromGUID2( SystemTraceControlGuid, szSystemTraceControlGuid, 39); MFC_TRY bsDescription = SysAllocString(m_cszDescription); bsGuid = SysAllocString(m_cszGuid); MFC_CATCH_HR if ( SUCCEEDED ( hr ) ) { iIsEnabled = 0; while ( SUCCEEDED ( hr ) ) { hr = pEnumProviders->Next ( 0, // timeout 1, // return only 1 object &pThisClass, &dwRtnCount ); if ( SUCCEEDED ( hr ) ) { // no more classes if ( dwRtnCount == 0 ) break; pThisClass->GetQualifierSet ( &pQualSet ); if ( pQualSet != NULL ) { hr = pQualSet->Get ( bsGuid, 0, &vValue, 0 ); if ( SUCCEEDED ( hr ) ) { strGuid = ( LPWSTR )V_BSTR ( &vValue ); VariantClear ( &vValue ); hr = pQualSet->Get ( bsDescription, 0, &vValue, 0 ); if ( SUCCEEDED ( hr ) ) { strDescription = ( LPWSTR )V_BSTR ( &vValue ); VariantClear ( &vValue ); } else { hr = ERROR_SUCCESS; strDescription = strGuid; } } pQualSet->Release(); } // The Win2000 Kernel trace provider is handled separately. if ( SUCCEEDED ( hr ) ) { MFC_TRY if ( L'{' != strGuid[0] ) { strBracketedGuid.Format ( L"{%s}", strGuid ); } else { strBracketedGuid = strGuid; } MFC_CATCH_HR if ( 0 == strBracketedGuid.CompareNoCase( szSystemTraceControlGuid ) ) { PLOG_INFO pLoggerInfo = NULL; TRACEHANDLE LoggerHandle = 0; // Kernel trace provider. Need to pass GUID as name. MFC_TRY pLoggerInfo = new LOG_INFO; ZeroMemory ( pLoggerInfo, sizeof ( LOG_INFO ) ); pLoggerInfo->Properties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); pLoggerInfo->Properties.Wnode.BufferSize = sizeof( LOG_INFO ); pLoggerInfo->Properties.Wnode.Flags = WNODE_FLAG_TRACED_GUID; pLoggerInfo->Properties.Wnode.Guid = SystemTraceControlGuid; Status = QueryTrace(LoggerHandle, m_cszKernelLogger, &(pLoggerInfo->Properties) ); iIsEnabled = (Status == 0) ? 1 : 0; m_KernelTraceProvider.strDescription = strDescription; m_KernelTraceProvider.strGuid = strBracketedGuid; m_KernelTraceProvider.iIsEnabled = iIsEnabled; m_KernelTraceProvider.iIsActive = 1; MFC_CATCH_HR if ( NULL != pLoggerInfo ) { delete pLoggerInfo; } } else { //loop on all the registered guids INT iIsActive = 0; GUID guidTemp; // Todo: Init BOOL bSuccess; ZeroMemory ( &guidTemp, sizeof (GUID) ); bSuccess = wGUIDFromString (strGuid, &guidTemp ); if ( bSuccess ) { for (iIndex = 0 ; iIndex < (INT)ulGuidCount; iIndex ++){ if ( guidTemp == arrGuidProperties[iIndex]->Guid ) { DWORD dwStatus; iIsActive = 1; dwStatus = AddProvider ( strDescription, strBracketedGuid, arrGuidProperties[iIndex]->IsEnable, iIsActive ); if ( ERROR_OUTOFMEMORY == dwStatus ) { hr = E_OUTOFMEMORY; } else if ( ERROR_SUCCESS != dwStatus ) { hr = E_FAIL; } break; } } } // Todo: Error message on invalid Guid string. if ( 0 == iIsActive ) { DWORD dwStatus; dwStatus = AddProvider ( strDescription, strBracketedGuid, 0, iIsActive ); if ( ERROR_OUTOFMEMORY == dwStatus ) { hr = E_OUTOFMEMORY; } else if ( ERROR_SUCCESS != dwStatus ) { hr = E_FAIL; } } } } pThisClass->Release ( ); } } ::SysFreeString ( bsGuid ); ::SysFreeString ( bsDescription ); } } } // Done with these objects. if ( NULL != pGuidStorage ) { G_FREE ( pGuidStorage ); } if ( NULL != pEnumProviders ) { pEnumProviders->Release ( ); } return hr; } // // Get specified provider in provider list // SLQ_TRACE_PROVIDER* CSmTraceProviders::GetProviderInfo ( INT iIndex ) { return &m_arrGenTraceProvider[iIndex]; } // // Return a pointer to the Kernel provider. // SLQ_TRACE_PROVIDER* CSmTraceProviders::GetKernelProviderInfo ( void ) { return &m_KernelTraceProvider; } // // Return the index of the provider specified by Guid // INT CSmTraceProviders::IndexFromGuid ( const CString& rstrGuid ) { int iIndex; int iCount = (INT)m_arrGenTraceProvider.GetSize ( ); for ( iIndex = 0; iIndex < iCount; iIndex++ ) { if ( 0 == m_arrGenTraceProvider[iIndex].strGuid.CompareNoCase( rstrGuid ) ) { break; } } // Signal not found with -1. if ( iIndex == iCount ) { iIndex = -1; } return iIndex; } // // Get provider list count // INT CSmTraceProviders::GetGenProvCount ( ) { return (INT)m_arrGenTraceProvider.GetSize ( ); } // // LoadGuidArray copied from evntrprv.cpp 9/12/01 // HRESULT CSmTraceProviders::LoadGuidArray( PVOID* Storage, PULONG pnGuidCount ) { ULONG i; ULONG nGuidArray = 16; ULONG nGuidCount = 0; DWORD dwSize; PTRACE_GUID_PROPERTIES* GuidPropertiesArray; PTRACE_GUID_PROPERTIES pStorage; HRESULT hr = ERROR_SUCCESS; do { dwSize = nGuidArray * (sizeof(TRACE_GUID_PROPERTIES) + sizeof(PTRACE_GUID_PROPERTIES)); MFC_TRY *Storage = G_ALLOC(dwSize); MFC_CATCH_HR if ( FAILED (hr) || *Storage == NULL) { if (*Storage == NULL) { hr = E_OUTOFMEMORY; } break; } else { RtlZeroMemory(*Storage, dwSize); GuidPropertiesArray = (PTRACE_GUID_PROPERTIES *)(*Storage); pStorage = (PTRACE_GUID_PROPERTIES)((char*)(*Storage) + nGuidArray * sizeof(PTRACE_GUID_PROPERTIES)); for (i=0; i < nGuidArray; i++) { GuidPropertiesArray[i] = pStorage; pStorage = (PTRACE_GUID_PROPERTIES)((char*)pStorage + sizeof(TRACE_GUID_PROPERTIES)); } hr = EnumerateTraceGuids(GuidPropertiesArray,nGuidArray,&nGuidCount); if ( hr == ERROR_MORE_DATA ) { if( nGuidCount <= nGuidArray ){ hr = WBEM_E_INVALID_PARAMETER; break; } nGuidArray = nGuidCount; G_FREE(*Storage); (*Storage) = NULL; } } }while( hr == ERROR_MORE_DATA ); if( ERROR_SUCCESS == hr ){ *pnGuidCount = nGuidCount; }else{ *pnGuidCount = 0; } return hr; }
31.605475
135
0.456463
npocmaka
4ea7caa0902b92b741a1d815d0e82c3879e9dc0f
306
cpp
C++
Wumpus.cpp
GoldenMean58/wumpus
51d7b850523383f1f1d4304c8fc763d58205f641
[ "Apache-2.0" ]
null
null
null
Wumpus.cpp
GoldenMean58/wumpus
51d7b850523383f1f1d4304c8fc763d58205f641
[ "Apache-2.0" ]
null
null
null
Wumpus.cpp
GoldenMean58/wumpus
51d7b850523383f1f1d4304c8fc763d58205f641
[ "Apache-2.0" ]
null
null
null
#include "Wumpus.h" Wumpus::Wumpus() : _dead(false) { this->_type = ObjectType::WumpusType; } Wumpus::Wumpus(int x, int y) : _dead(false) { this->_x = x; this->_y = y; this->_type = ObjectType::WumpusType; } bool Wumpus::is_dead() { return this->_dead; } void Wumpus::kill() { this->_dead = true; }
27.818182
73
0.643791
GoldenMean58
4ea807cc70b45cf25e04b55c444390a629c7365a
7,240
cpp
C++
UNITTESTS/drivers/PwmOut/test_pwmout.cpp
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
3,897
2015-09-04T13:42:23.000Z
2022-03-30T16:53:07.000Z
UNITTESTS/drivers/PwmOut/test_pwmout.cpp
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
13,030
2015-09-17T10:30:05.000Z
2022-03-31T13:36:44.000Z
UNITTESTS/drivers/PwmOut/test_pwmout.cpp
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
2,950
2015-09-08T19:07:05.000Z
2022-03-31T13:37:23.000Z
/* * Copyright (c) 2019 Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "gtest/gtest.h" #include "gmock/gmock.h" #include "drivers/PwmOut.h" using namespace mbed; class MbedPowerMgmtInterface { public: virtual ~MbedPowerMgmtInterface() {} virtual void sleep_manager_unlock_deep_sleep_internal() = 0; virtual void sleep_manager_lock_deep_sleep_internal() = 0; }; class MockMbedPowerMgmt : public MbedPowerMgmtInterface { public: virtual ~MockMbedPowerMgmt() {} MOCK_METHOD0(sleep_manager_unlock_deep_sleep_internal, void()); MOCK_METHOD0(sleep_manager_lock_deep_sleep_internal, void()); static MockMbedPowerMgmt *get_instance() { if (_instance == nullptr) { _instance = new MockMbedPowerMgmt(); } ++_ref_counter; return _instance; } static void release_instance() { --_ref_counter; if ((_instance != nullptr) && (_ref_counter == 0)) { delete _instance; _instance = nullptr; } } static void sleep_manager_unlock_deep_sleep() { // Do not increment the call count unless it's done by a test // case. if (_instance) { _instance->sleep_manager_unlock_deep_sleep_internal(); } } static void sleep_manager_lock_deep_sleep() { // Do not increment the call count unless it's done by a test // case. if (_instance) { _instance->sleep_manager_lock_deep_sleep_internal(); } } MockMbedPowerMgmt(MockMbedPowerMgmt const &) = delete; void operator=(MockMbedPowerMgmt const &) = delete; private: MockMbedPowerMgmt() {} static MockMbedPowerMgmt *_instance; static int _ref_counter; }; MockMbedPowerMgmt *MockMbedPowerMgmt::_instance = nullptr; int MockMbedPowerMgmt::_ref_counter = 0; void sleep_manager_unlock_deep_sleep(void) { MockMbedPowerMgmt::sleep_manager_unlock_deep_sleep(); } void sleep_manager_lock_deep_sleep(void) { MockMbedPowerMgmt::sleep_manager_lock_deep_sleep(); } class TestPwmOut : public testing::Test { protected: PwmOut *pwm_obj; MockMbedPowerMgmt *mbed_mgmt_mock; void SetUp() { pwm_obj = new PwmOut(PTC1); // Create a mock object singleton after the PwmOut object // instantiation so the sleep_manager_lock_deep_sleep call by the // constructor does not increment the call count. // Now it is ok because a test case is about to start. mbed_mgmt_mock = MockMbedPowerMgmt::get_instance(); } void TearDown() { // Destroy the mock object singleton before the PwmOut destruction // because it will increment the sleep_manager_unlock_deep_sleep call // count. MockMbedPowerMgmt::release_instance(); delete pwm_obj; } }; // *INDENT-ON* /** Test if the constructor locks deepsleep Given an instantiated Pmw When the constructor is called Then the deep sleep lock is acquired */ TEST_F(TestPwmOut, test_constructor) { using ::testing::Mock; EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_lock_deep_sleep_internal() ).Times(1); PwmOut pmw(PTC1); // Force gMock to verify a mock object singleton before it is destructed // by the teardown Mock::VerifyAndClearExpectations(mbed_mgmt_mock); // Suppress the memory leak error. The mock singleton will be released and // deleted in the TearDown call. Mock::AllowLeak(mbed_mgmt_mock); } /** Test if the destructor unlocks deepsleep Given an instantiated Pmw When the destructor is called Then the deep sleep lock is released */ TEST_F(TestPwmOut, test_destructor) { using ::testing::Mock; EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_unlock_deep_sleep_internal() ).Times(1); PwmOut *pmw = new PwmOut(PTC1); delete pmw; // Force gMock to verify a mock object singleton before it is destructed // by the teardown Mock::VerifyAndClearExpectations(mbed_mgmt_mock); // Suppress the memory leak error. The mock singleton will be released and // deleted in the TearDown call. Mock::AllowLeak(mbed_mgmt_mock); } /** Test if `suspend` unlocks deepsleep Given an initialised Pmw with a deep sleep lock When the instance is suspended Then the deep sleep lock is released once */ TEST_F(TestPwmOut, test_suspend) { using ::testing::Mock; EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_unlock_deep_sleep_internal() ).Times(1); pwm_obj->suspend(); pwm_obj->suspend(); // Force gMock to verify a mock object singleton before it is destructed // by the teardown Mock::VerifyAndClearExpectations(mbed_mgmt_mock); // Suppress the memory leak error. The mock singleton will be released and // deleted in the TearDown call. Mock::AllowLeak(mbed_mgmt_mock); } /** Test if `resume` lock deepsleep Given an initialised Pmw in a suspended state When the instance is resumed Then the deep sleep lock is re-acquired once */ TEST_F(TestPwmOut, test_resume) { using ::testing::Mock; EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_lock_deep_sleep_internal() ).Times(1); pwm_obj->suspend(); pwm_obj->resume(); pwm_obj->resume(); // Force gMock to verify a mock object singleton before it is destructed // by the teardown Mock::VerifyAndClearExpectations(mbed_mgmt_mock); // Suppress the memory leak error. The mock singleton will be released and // deleted in the TearDown call. Mock::AllowLeak(mbed_mgmt_mock); } /** Test if `suspend`/`resume` unlock/lock deepsleep multiple times Given an initialised Pmw When the instance is suspended and then resumed Then the deep sleep lock can be unlocked and then locked again and again */ TEST_F(TestPwmOut, test_multiple_suspend_resume) { using ::testing::Mock; const int suspend_resume_max_cycle = 3; EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_unlock_deep_sleep_internal() ).Times(suspend_resume_max_cycle); EXPECT_CALL( *mbed_mgmt_mock, sleep_manager_lock_deep_sleep_internal() ).Times(suspend_resume_max_cycle); for (int i = 0; i < suspend_resume_max_cycle; i++) { pwm_obj->suspend(); pwm_obj->resume(); } // Force gMock to verify a mock object singleton before it is destructed // by the teardown Mock::VerifyAndClearExpectations(mbed_mgmt_mock); // Suppress the memory leak error. The mock singleton will be released and // deleted in the TearDown call. Mock::AllowLeak(mbed_mgmt_mock); }
27.953668
78
0.696271
pattyolanterns
4eaa821ea34976f9846029924a4311c94415d791
514
cpp
C++
src/OpenLoco/Map/SurfaceTile.cpp
JimmyAllnighter/OpenLoco
dda8245be39a033db5cadfa455f1679a3f24ff24
[ "MIT" ]
180
2018-01-18T07:56:44.000Z
2019-02-18T21:33:45.000Z
src/OpenLoco/Map/SurfaceTile.cpp
JimmyAllnighter/OpenLoco
dda8245be39a033db5cadfa455f1679a3f24ff24
[ "MIT" ]
186
2018-01-18T13:17:58.000Z
2019-02-10T12:28:35.000Z
src/OpenLoco/Map/SurfaceTile.cpp
JimmyAllnighter/OpenLoco
dda8245be39a033db5cadfa455f1679a3f24ff24
[ "MIT" ]
35
2018-01-18T12:38:26.000Z
2018-11-14T16:01:32.000Z
#include "../TownManager.h" #include "../ViewportManager.h" #include "TileManager.h" namespace OpenLoco::Map { void SurfaceElement::removeIndustry(const Map::Pos2& pos) { if (hasHighTypeFlag()) { setHighTypeFlag(false); setVar6SLR5(0); setIndustry(IndustryId(0)); auto z = baseHeight(); Ui::ViewportManager::invalidate(pos, z, z + 32, ZoomLevel::eighth); TownManager::sub_497DC1(pos, 0, 0, -30, 0); } } }
25.7
79
0.568093
JimmyAllnighter
4eaadad1ebb68857cb29ffd0c08d0f1b294c64be
1,309
cpp
C++
Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp
flygod1159/Arcane-Engine
bfb95cc6734a25e5737d4195c2b9e92e03117707
[ "MIT" ]
387
2016-10-04T03:30:38.000Z
2022-03-31T15:42:29.000Z
Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp
flygod1159/Arcane-Engine
bfb95cc6734a25e5737d4195c2b9e92e03117707
[ "MIT" ]
9
2017-04-04T04:23:47.000Z
2020-07-11T05:05:54.000Z
Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp
flygod1159/Arcane-Engine
bfb95cc6734a25e5737d4195c2b9e92e03117707
[ "MIT" ]
36
2017-07-02T07:11:40.000Z
2022-03-08T01:49:24.000Z
#include "arcpch.h" #include "ReflectionProbe.h" #include <Arcane/Graphics/Shader.h> #include <Arcane/Graphics/Texture/Texture.h> #include <Arcane/Graphics/Texture/Cubemap.h> namespace Arcane { Texture* ReflectionProbe::s_BRDF_LUT = nullptr; ReflectionProbe::ReflectionProbe(glm::vec3 &probePosition, glm::vec2 &probeResolution) : m_Position(probePosition), m_ProbeResolution(probeResolution), m_Generated(false), m_PrefilterMap(nullptr) {} ReflectionProbe::~ReflectionProbe() { delete m_PrefilterMap; } void ReflectionProbe::Generate() { // Generate the HDR reflection probe and set the generated flag CubemapSettings settings; settings.TextureFormat = GL_RGBA16F; settings.TextureMinificationFilterMode = GL_LINEAR_MIPMAP_LINEAR; settings.HasMips = true; m_PrefilterMap = new Cubemap(settings); for (int i = 0; i < 6; i++) { m_PrefilterMap->GenerateCubemapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, (unsigned int)m_ProbeResolution.x, (unsigned int)m_ProbeResolution.y, GL_RGB, nullptr); } m_Generated = true; } void ReflectionProbe::Bind(Shader *shader) { shader->SetUniform("reflectionProbeMipCount", REFLECTION_PROBE_MIP_COUNT); m_PrefilterMap->Bind(2); shader->SetUniform("prefilterMap", 2); s_BRDF_LUT->Bind(3); shader->SetUniform("brdfLUT", 3); } }
29.75
162
0.760886
flygod1159
4eac76ab7447bc9574b9464cab5f5017f536c72b
1,517
cpp
C++
TrendExtractor-C++/TrendExtractor.cpp
auyeongwy/TrendCrawler
5520c969ad7863f23d994a5cf9d711538363f879
[ "Apache-2.0" ]
null
null
null
TrendExtractor-C++/TrendExtractor.cpp
auyeongwy/TrendCrawler
5520c969ad7863f23d994a5cf9d711538363f879
[ "Apache-2.0" ]
null
null
null
TrendExtractor-C++/TrendExtractor.cpp
auyeongwy/TrendCrawler
5520c969ad7863f23d994a5cf9d711538363f879
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 Au Yeong Wing Yau 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. */ /** * @file TrendExtractor.cpp * Contains main() function of TrendExtractor, provides higest level control of the application. */ #include <iostream> #include <list> #include <utility> #include <string> #include <iostream> #include <stdlib.h> #include "ConfigReader.hpp" #include "DBMgr.hpp" using namespace std; static void do_abort(); /* Initialise static variables. */ boost::property_tree::ptree ConfigReader::v_tree; boost::mutex ConfigReader::v_mtx; /** * The main() function. */ int main() { ConfigReader configReader; DBMgr dbMgr; try { configReader.init(); dbMgr.connect(); bool result = dbMgr.runSQL("select * from urls"); if(!result) cout << "SQL problem" << endl; dbMgr.close(); } catch (exception *e) { cout << e->what() << endl; do_abort(); } return 0; } /** * Aborts the application when a fatal error occurs. */ static void do_abort() { cout << "Fatal error, aborting." << endl; abort(); }
20.226667
98
0.711931
auyeongwy
4eb1e5f442196822ac2f9b707c440f7676220cab
593
cpp
C++
src/problem132/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem132/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem132/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: int minCut(string s) { if (s == "") return 0; vector<int> dp(s.size() + 1, 0); dp[s.size()] = -1; vector<vector<bool>> bm(s.size(), vector<bool>(s.size(), false)); for (int i = s.size() - 1; i >= 0; --i) { dp[i] = INT_MAX; for (int j = i; j < s.size(); ++j) { if (s[j] == s[i] && (j - i < 2 || bm[i+1][j-1])) { bm[i][j] = true; dp[i] = min(dp[i], dp[j+1]+1); } } } return dp[0]; } };
28.238095
73
0.338954
MyYaYa
4eb9e7cdb180c1f5d36e3668bf7c461f74036694
217
cpp
C++
Tutorials/Programming/learn_C++_w3c/arrays.cpp
jmreis/Learning-Programming-With-W3C-School
0d62b841cf221cf2a4c55c782248fa06d2575528
[ "MIT" ]
1
2022-03-25T03:19:09.000Z
2022-03-25T03:19:09.000Z
Tutorials/Programming/learn_C++_w3c/arrays.cpp
jmreis/Learning-Programming-With-W3C-School
0d62b841cf221cf2a4c55c782248fa06d2575528
[ "MIT" ]
null
null
null
Tutorials/Programming/learn_C++_w3c/arrays.cpp
jmreis/Learning-Programming-With-W3C-School
0d62b841cf221cf2a4c55c782248fa06d2575528
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < 4; i++) { cout << cars[i] << endl; } return 0; }
19.727273
55
0.511521
jmreis
4ebb6cda05e82a436aa0724f8a471ce93d50e1b4
4,537
cpp
C++
src/core/LoaderComponent.cpp
talesm/glBoilerplate
46d8f418408290698e3f889b8cc053ac7ce4c824
[ "MIT" ]
null
null
null
src/core/LoaderComponent.cpp
talesm/glBoilerplate
46d8f418408290698e3f889b8cc053ac7ce4c824
[ "MIT" ]
null
null
null
src/core/LoaderComponent.cpp
talesm/glBoilerplate
46d8f418408290698e3f889b8cc053ac7ce4c824
[ "MIT" ]
null
null
null
#include "LoaderComponent.hpp" #include "Camera.hpp" #include "SceneDetail.hpp" #include "util/fastMath.hpp" using namespace std; inline int getAreaToReload(int offset) { int areaToReload = abs(offset) - (CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA); int remaining = areaToReload % CHUNK_LOAD_DELTA; if (remaining) { return areaToReload + CHUNK_LOAD_DELTA - remaining; } return areaToReload; } template<int axisI, int axisJ = (axisI + 1) % 3, int axisK = (axisI + 2) % 3> void checkAndRefreshChunk(Chunk* chunk, SceneLoader& generator, glm::ivec3& center, const glm::ivec3& delta) { if (delta[axisI] < -(CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA)) { int areaToReload = getAreaToReload(delta[axisI]); center[axisI] -= areaToReload; int r = floorMod(center[axisJ] - CHUNK_HALF_SIDE, CHUNK_SIDE); int q = floorMod(center[axisK] - CHUNK_HALF_SIDE, CHUNK_SIDE); glm::ivec3 lBound, hBound, offset; lBound[axisI] = CHUNK_SIDE - areaToReload; lBound[axisJ] = r; lBound[axisK] = q; hBound[axisI] = CHUNK_SIDE; hBound[axisJ] = CHUNK_SIDE; hBound[axisK] = CHUNK_SIDE; offset[axisI] = center[axisI] - CHUNK_SIDE * 3 / 2 + areaToReload; offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); if (r) { lBound[axisJ] = 0; lBound[axisK] = q; hBound[axisJ] = r; hBound[axisK] = CHUNK_SIDE; offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); } if (q) { lBound[axisJ] = r; lBound[axisK] = 0; hBound[axisJ] = CHUNK_SIDE; hBound[axisK] = q; offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); if (r) { lBound[axisJ] = 0; lBound[axisK] = 0; hBound[axisJ] = r; hBound[axisK] = q; offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); } } } else if (delta[axisI] >= (CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA)) { int areaToReload = getAreaToReload(delta[axisI]); center[axisI] += areaToReload; int r = floorMod(center[axisJ] - CHUNK_HALF_SIDE, CHUNK_SIDE); int q = floorMod(center[axisK] - CHUNK_HALF_SIDE, CHUNK_SIDE); glm::ivec3 lBound, hBound, offset; lBound[axisI] = 0; lBound[axisJ] = r; lBound[axisK] = q; hBound[axisI] = areaToReload; hBound[axisJ] = CHUNK_SIDE; hBound[axisK] = CHUNK_SIDE; offset[axisI] = center[axisI] - CHUNK_HALF_SIDE + areaToReload; offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); if (r) { lBound[axisJ] = 0; lBound[axisK] = q; hBound[axisJ] = r; hBound[axisK] = CHUNK_SIDE; offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); } if (q) { lBound[axisJ] = r; lBound[axisK] = 0; hBound[axisJ] = CHUNK_SIDE; hBound[axisK] = q; offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); if (r) { lBound[axisJ] = 0; lBound[axisK] = 0; hBound[axisJ] = r; hBound[axisK] = q; offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r; offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q; generator(lBound, hBound, offset, chunk); } } } } void LoaderComponent::onUpdate(float delta) { if (!generator) return; glm::ivec3 offset = glm::ivec3(scene()->camera->position()) - center; auto& chunk = scene()->chunk; checkAndRefreshChunk<0>(&chunk, generator, center, offset); checkAndRefreshChunk<1>(&chunk, generator, center, offset); checkAndRefreshChunk<2>(&chunk, generator, center, offset); } void LoaderComponent::reset() { if (!generator) { return; } center = glm::ivec3(CHUNK_SIDE / 2); generator( glm::ivec3(0), glm::vec3(CHUNK_SIDE), glm::vec3(0), &scene()->chunk); }
33.116788
77
0.616046
talesm
4ec06cb47d3b5f9e5853c6ee73687c2ec1d8cfff
226,398
cpp
C++
test/grapheme_iterator_06.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
null
null
null
test/grapheme_iterator_06.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
1
2021-03-05T12:56:59.000Z
2021-03-05T13:11:53.000Z
test/grapheme_iterator_06.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
3
2019-10-30T18:38:15.000Z
2021-03-05T12:10:13.000Z
// Warning! This file is autogenerated. #include <boost/text/grapheme_iterator.hpp> #include <boost/text/transcode_iterator.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(grapheme, iterator_06_0_fwd) { // ÷ 0903 ÷ AC01 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_0_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_0_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_0_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_0_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0xAC01 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_1_fwd) { // ÷ 0903 × 0308 ÷ AC01 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_1_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_1_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_1_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_1_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_2_fwd) { // ÷ 0903 ÷ 231A ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] WATCH (ExtPict) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_2_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_2_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_2_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_2_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x231A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_3_fwd) { // ÷ 0903 × 0308 ÷ 231A ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] WATCH (ExtPict) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_3_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_3_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_3_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_3_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0308, 0x231A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_4_fwd) { // ÷ 0903 × 0300 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_4_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_4_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_4_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_4_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0300 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_5_fwd) { // ÷ 0903 × 0308 × 0300 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_5_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_5_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_5_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_5_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_6_fwd) { // ÷ 0903 × 200D ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_6_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_6_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_6_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_6_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x200D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_7_fwd) { // ÷ 0903 × 0308 × 200D ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_7_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_7_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_7_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_7_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0308, 0x200D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_8_fwd) { // ÷ 0903 ÷ 0378 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_8_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_8_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_8_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_8_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0378 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_9_fwd) { // ÷ 0903 × 0308 ÷ 0378 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_9_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_9_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_9_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_9_utf8) { { // from UTF8 uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_10_fwd) { // ÷ 0903 ÷ D800 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_10_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_10_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_10_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } // Skipping from-utf8 test due to presence of surrogate code point. TEST(grapheme, iterator_06_11_fwd) { // ÷ 0903 × 0308 ÷ D800 ÷ // ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_11_rev) { { // reverse uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_11_fab) { { // forth and back uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_11_baf) { { // back and forth uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } // Skipping from-utf8 test due to presence of surrogate code point. TEST(grapheme, iterator_06_12_fwd) { // ÷ 1100 ÷ 0020 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] SPACE (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_12_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_12_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_12_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_12_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0020 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_13_fwd) { // ÷ 1100 × 0308 ÷ 0020 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] SPACE (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_13_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_13_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_13_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_13_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_14_fwd) { // ÷ 1100 ÷ 000D ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_14_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_14_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_14_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_14_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x000D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_15_fwd) { // ÷ 1100 × 0308 ÷ 000D ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_15_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_15_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_15_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x000D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_15_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x000D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_16_fwd) { // ÷ 1100 ÷ 000A ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_16_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_16_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_16_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_16_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x000A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_17_fwd) { // ÷ 1100 × 0308 ÷ 000A ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_17_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_17_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_17_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x000A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_17_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x000A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_18_fwd) { // ÷ 1100 ÷ 0001 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_18_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_18_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_18_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_18_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0001 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_19_fwd) { // ÷ 1100 × 0308 ÷ 0001 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_19_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_19_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_19_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_19_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_20_fwd) { // ÷ 1100 × 034F ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_20_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_20_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_20_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_20_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x034F }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_21_fwd) { // ÷ 1100 × 0308 × 034F ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_21_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_21_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_21_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x034F }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_21_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x034F }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_22_fwd) { // ÷ 1100 ÷ 1F1E6 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_22_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_22_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_22_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_22_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x1F1E6 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_23_fwd) { // ÷ 1100 × 0308 ÷ 1F1E6 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_23_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_23_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_23_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_23_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_24_fwd) { // ÷ 1100 ÷ 0600 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_24_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_24_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_24_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_24_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0600 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_25_fwd) { // ÷ 1100 × 0308 ÷ 0600 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_25_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_25_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_25_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_25_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_26_fwd) { // ÷ 1100 × 0903 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_26_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_26_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_26_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_26_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0903 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_27_fwd) { // ÷ 1100 × 0308 × 0903 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_27_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_27_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_27_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_27_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_28_fwd) { // ÷ 1100 × 1100 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_28_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_28_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_28_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_28_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x1100 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_29_fwd) { // ÷ 1100 × 0308 ÷ 1100 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_29_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_29_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_29_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_29_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_30_fwd) { // ÷ 1100 × 1160 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_30_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_30_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_30_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_30_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x1160 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_31_fwd) { // ÷ 1100 × 0308 ÷ 1160 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_31_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_31_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_31_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_31_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_32_fwd) { // ÷ 1100 ÷ 11A8 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_32_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_32_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_32_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_32_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x11A8 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_33_fwd) { // ÷ 1100 × 0308 ÷ 11A8 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_33_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_33_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_33_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_33_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_34_fwd) { // ÷ 1100 × AC00 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_34_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_34_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_34_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_34_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0xAC00 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_35_fwd) { // ÷ 1100 × 0308 ÷ AC00 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_35_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_35_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_35_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_35_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_36_fwd) { // ÷ 1100 × AC01 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_36_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_36_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_36_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_36_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0xAC01 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_37_fwd) { // ÷ 1100 × 0308 ÷ AC01 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_37_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_37_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_37_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_37_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_38_fwd) { // ÷ 1100 ÷ 231A ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] WATCH (ExtPict) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_38_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_38_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_38_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_38_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x231A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_39_fwd) { // ÷ 1100 × 0308 ÷ 231A ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] WATCH (ExtPict) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_39_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_39_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_39_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x231A }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_39_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x231A }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_40_fwd) { // ÷ 1100 × 0300 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_40_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_40_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_40_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_40_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0300 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_41_fwd) { // ÷ 1100 × 0308 × 0300 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_41_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_41_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_41_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_41_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_42_fwd) { // ÷ 1100 × 200D ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_42_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_42_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_42_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_42_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x200D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_43_fwd) { // ÷ 1100 × 0308 × 200D ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_43_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_43_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); } } TEST(grapheme, iterator_06_43_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x200D }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_43_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x200D }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_44_fwd) { // ÷ 1100 ÷ 0378 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_44_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_44_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_44_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_44_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0378 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_45_fwd) { // ÷ 1100 × 0308 ÷ 0378 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_45_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_45_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_45_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_45_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_46_fwd) { // ÷ 1100 ÷ D800 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_46_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_46_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_46_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } // Skipping from-utf8 test due to presence of surrogate code point. TEST(grapheme, iterator_06_47_fwd) { // ÷ 1100 × 0308 ÷ D800 ÷ // ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3] { uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_47_rev) { { // reverse uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_47_fab) { { // forth and back uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_47_baf) { { // back and forth uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } // Skipping from-utf8 test due to presence of surrogate code point. TEST(grapheme, iterator_06_48_fwd) { // ÷ 1160 ÷ 0020 ÷ // ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] SPACE (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1160, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_48_rev) { { // reverse uint32_t const cps[] = { 0x1160, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_48_fab) { { // forth and back uint32_t const cps[] = { 0x1160, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); } } TEST(grapheme, iterator_06_48_baf) { { // back and forth uint32_t const cps[] = { 0x1160, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2); EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 1); ++it; EXPECT_EQ(it.base(), cps + 1); EXPECT_EQ((*it).begin(), cps + 1); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_48_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1160, 0x0020 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[1]); ++it; EXPECT_EQ(*it.base(), cps[1]); EXPECT_EQ(*it->begin(), cps[1]); EXPECT_EQ(it.base().base(), cus + cp_indices[1]); EXPECT_EQ(it->begin().base(), cus + cp_indices[1]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin(), (*it).end()); } } TEST(grapheme, iterator_06_49_fwd) { // ÷ 1160 × 0308 ÷ 0020 ÷ // ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] SPACE (Other) ÷ [0.3] { uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_49_rev) { { // reverse uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_49_fab) { { // forth and back uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3); EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); } } TEST(grapheme, iterator_06_49_baf) { { // back and forth uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 }; boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3); EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); --it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); --it; EXPECT_EQ(it.base(), cps + 0); EXPECT_EQ((*it).begin(), cps + 0); EXPECT_EQ((*it).end(), cps + 2); ++it; EXPECT_EQ(it.base(), cps + 2); EXPECT_EQ((*it).begin(), cps + 2); EXPECT_EQ((*it).end(), cps + 3); ++it; EXPECT_EQ(it.base(), cps + 3); EXPECT_EQ((*it).begin(), (*it).end()); } } TEST(grapheme, iterator_06_49_utf8) { { // from UTF8 uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 }; char cus[1024] = { 0 }; int cp_indices[1024] = { 0 }; std::copy( boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3), boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3), cus); boost::text::null_sentinel sentinel; int * index_it = cp_indices; for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) { *index_it++ = it.base() - cus; if (it == sentinel) break; } using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>; boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it( iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel); EXPECT_EQ(*it.base(), cps[0]); EXPECT_EQ(*it->begin(), cps[0]); EXPECT_EQ(*it->end(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[0]); EXPECT_EQ(it->begin().base(), cus + cp_indices[0]); EXPECT_EQ(it->end().base(), cus + cp_indices[2]); ++it; EXPECT_EQ(*it.base(), cps[2]); EXPECT_EQ(*it->begin(), cps[2]); EXPECT_EQ(it.base().base(), cus + cp_indices[2]); EXPECT_EQ(it->begin().base(), cus + cp_indices[2]); EXPECT_EQ(it->end().base(), cus + cp_indices[3]); ++it; EXPECT_EQ(it.base().base(), cus + cp_indices[3]); EXPECT_EQ(it->begin(), (*it).end()); } }
28.148452
157
0.502959
eightysquirrels
4ec2ce4271211ca8b20a2ff6db692b3ce2e98d99
5,994
cpp
C++
src/joystick.cpp
allender/emulator
8310afee84b74cff7d91ecd78f7976264a8df900
[ "MIT" ]
53
2017-01-19T08:08:40.000Z
2022-01-26T03:01:24.000Z
src/joystick.cpp
allender/emulator
8310afee84b74cff7d91ecd78f7976264a8df900
[ "MIT" ]
15
2017-03-10T22:55:53.000Z
2021-04-14T13:29:38.000Z
src/joystick.cpp
allender/emulator
8310afee84b74cff7d91ecd78f7976264a8df900
[ "MIT" ]
1
2019-07-09T07:19:53.000Z
2019-07-09T07:19:53.000Z
/* MIT License Copyright (c) 2016-2017 Mark Allender 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 <stdio.h> #include "SDL.h" #include "apple2emu_defs.h" #include "apple2emu.h" #include "memory.h" #include "joystick.h" static int Num_controllers; static const char *Game_controller_mapping_file = "gamecontrollerdb.txt"; // information for joysticks class controller { public: bool m_initialized; // is this joystick initialized SDL_GameController *m_gc; // pointer to game controller structure const char *m_name; // name of controller int8_t m_button_state[SDL_CONTROLLER_BUTTON_MAX]; int16_t m_axis_state[SDL_CONTROLLER_AXIS_MAX]; uint32_t m_axis_timer_state[SDL_CONTROLLER_AXIS_MAX]; SDL_GameControllerButton m_buttons[SDL_CONTROLLER_BUTTON_MAX]; // mapping from button number to button enum SDL_GameControllerAxis m_axis[SDL_CONTROLLER_AXIS_MAX]; // mapping from axis number to axis enum controller() :m_initialized(false) {}; }; const float Joystick_cycles_scale = 2816.0f / 255.0f; // ~2816 total cycles for 558 timer const int Max_controllers = 16; controller Controllers[Max_controllers]; // reads the status of button num from the joystick structures static uint8_t joystick_read_button(int button_num) { uint8_t val = SDL_GameControllerGetButton(Controllers[0].m_gc, Controllers[0].m_buttons[button_num]); // signals is active low. So return 0 when on, and high bit set when not return val ? 0x80 : 0; } static uint8_t joystick_read_axis(int axis_num) { // timer state for paddles is controlled by ths number of cycles. The axis // timer state will have been previously set to the total cycles run // plus the axis value * number of cycles if (Total_cycles < Controllers[0].m_axis_timer_state[axis_num]) { return 0x80; } return 0; } uint8_t joystick_soft_switch_handler(uint16_t addr, uint8_t val, bool write) { UNREFERENCED(write); UNREFERENCED(val); uint8_t return_val = 0; addr = addr & 0xff; switch (addr) { case 0x61: case 0x62: case 0x63: return_val = joystick_read_button(addr - 0x61); break; case 0x64: case 0x65: case 0x66: case 0x67: return_val = joystick_read_axis(addr - 0x64); break; // this function initiates the analog to digital conversion from the // controllers (paddles/joysticks) to 0-255 digital value which will // be read from the axis read handler. Basically set up // internal timer to indicate when the 558 timer should time out // based on the paddle/joystick value. Read Inside the Apple ][e // chapter 10 for more information case 0x70: // set the axis timer state to be current cycle count // plus the cycle count when the timer should time out. // The internal paddle read routine reads every 11ms for (auto i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) { int16_t value = SDL_GameControllerGetAxis(Controllers[0].m_gc, Controllers[0].m_axis[i]); value = (uint16_t)(floor((float)(value + 32768) * (float)(255.0f / 65535.0f))); // from kegs and other emulators. I need to dig into why this is necessary because // based on timings, it should not work like this. Currently, I am getting a value // back from the pdl read code of around 235 when axis at max value (instead of // 255). So this code (as is in other emulators) will force us to get to 255. But // seems like we should solve this the real way with timing. if (value >= 255) { value = 280; } Controllers[0].m_axis_timer_state[i] = Total_cycles + uint32_t(value * Joystick_cycles_scale); } } if (write) { return 0; } return return_val | memory_read_floating_bus(); } void joystick_init() { // load game controller mappings int num_mappings = SDL_GameControllerAddMappingsFromFile(Game_controller_mapping_file); if (num_mappings == -1) { printf("Unable to load mappings file %s for SDL game controllers.\n", Game_controller_mapping_file); return; } Num_controllers = SDL_NumJoysticks(); for (auto i = 0; i < Num_controllers; i++) { if (SDL_IsGameController(i)) { Controllers[i].m_gc = SDL_GameControllerOpen(i); if (Controllers[i].m_gc != nullptr) { Controllers[i].m_initialized = true; Controllers[i].m_name = SDL_GameControllerNameForIndex(i); for (auto j = 0; j < SDL_CONTROLLER_BUTTON_MAX; j++) { Controllers[i].m_button_state[j] = 0; Controllers[i].m_buttons[j] = static_cast<SDL_GameControllerButton>(static_cast<int>(SDL_CONTROLLER_BUTTON_A) + j); } for (auto j = 0; j < SDL_CONTROLLER_AXIS_MAX; j++) { Controllers[i].m_axis_state[j] = 0; Controllers[i].m_axis_timer_state[j] = 0; Controllers[i].m_axis[j] = static_cast<SDL_GameControllerAxis>(static_cast<int>(SDL_CONTROLLER_AXIS_LEFTX) + j); } } } } } void joystick_shutdown() { for (auto i = 0; i < Num_controllers; i++) { if (Controllers[i].m_initialized == true) { SDL_GameControllerClose(Controllers[i].m_gc); } } }
35.467456
120
0.72973
allender
4ec80fde7b7c5457c8fbd6f93bd04ec2013f1625
100,040
cpp
C++
src/parallel/PetscSolverFeti.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
src/parallel/PetscSolverFeti.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
src/parallel/PetscSolverFeti.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
/****************************************************************************** * * AMDiS - Adaptive multidimensional simulations * * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved. * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis * * Authors: * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * This file is part of AMDiS * * See also license.opensource.txt in the distribution. * ******************************************************************************/ #include "MatrixVector.h" #include "parallel/PetscHelper.hpp" #include "parallel/PetscSolverFeti.hpp" #include "parallel/PetscSolverFetiDebug.hpp" #include "parallel/PetscSolverFetiMonitor.hpp" #include "parallel/PetscSolverFetiStructs.hpp" #include "parallel/PetscSolverFetiOperators.hpp" #include "parallel/PetscSolverFetiTimings.hpp" #include "parallel/StdMpi.hpp" #include "parallel/MpiHelper.hpp" #include "parallel/PetscSolverGlobalMatrix.hpp" #include "io/VtkWriter.hpp" namespace AMDiS { namespace Parallel { using namespace std; PetscSolverFeti::PetscSolverFeti(string name) : PetscSolver(name), fetiSolverType(EXACT), dofMapSubDomain(FESPACE_WISE, true), primalDofMap(COMPONENT_WISE), dualDofMap(COMPONENT_WISE), interfaceDofMap(COMPONENT_WISE), localDofMap(COMPONENT_WISE), lagrangeMap(COMPONENT_WISE), interiorDofMap(COMPONENT_WISE), schurPrimalSolver(0), levelMode(1), subDomainIsLocal(true), subdomain(NULL), massMatrixSolver(NULL), printTimings(false), augmentedLagrange(false), nRankEdges(0), nOverallEdges(0), dirichletMode(0), stokesMode(false), pressureComponent(-1) { FUNCNAME("PetscSolverFeti::PetscSolverFeti()"); string preconditionerName = ""; Parameters::get(name + "->left precon", preconditionerName); if (preconditionerName == "" || preconditionerName == "no") { MSG("Create FETI-DP solver with no preconditioner!\n"); fetiPreconditioner = FETI_NONE; } else if (preconditionerName == "dirichlet") { MSG("Create FETI-DP solver with Dirichlet preconditioner!\n"); fetiPreconditioner = FETI_DIRICHLET; } else if (preconditionerName == "lumped") { MSG("Create FETI-DP solver with lumped preconditioner!\n"); fetiPreconditioner = FETI_LUMPED; } else { ERROR_EXIT("Preconditioner \"%s\" not available!\n", preconditionerName.c_str()); } preconditionerName = ""; Parameters::get(name + "->right precon", preconditionerName); if (preconditionerName != "" && preconditionerName != "no") { ERROR_EXIT("FETI-DP does not support right preconditioning! (parameter \"%s->right precon\" has value \"%s\")\n", name.c_str(), preconditionerName.c_str()); } Parameters::get(name + "->feti->schur primal solver", schurPrimalSolver); TEST_EXIT(schurPrimalSolver == 0 || schurPrimalSolver == 1) ("Wrong solver \"%d\"for the Schur primal complement!\n", schurPrimalSolver); Parameters::get(name + "->feti->stokes mode", stokesMode); if (stokesMode) { Parameters::get(name + "->feti->pressure component", pressureComponent); TEST_EXIT(pressureComponent >= 0) ("FETI-DP in Stokes mode, no pressure component defined!\n"); } Parameters::get(name + "->feti->augmented lagrange", augmentedLagrange); Parameters::get(name + "->feti->symmetric", isSymmetric); { MSG("WARNING: CHECK THIS HERE BEFORE GOING INTO RUNNING MULTILEVEL FETI-DP!\n"); Parameters::get("parallel->level mode", levelMode); } { int tmp = 0; Parameters::get(name + "->feti->inexact", tmp); if (tmp == 1) fetiSolverType = INEXACT; if (tmp == 2) fetiSolverType = INEXACT_REDUCED; } Parameters::get("parallel->print timings", printTimings); } void PetscSolverFeti::init(vector<const FiniteElemSpace*>& fe0, vector<const FiniteElemSpace*>& fe1, bool createGlobalMapping) { FUNCNAME_DBG("PetscSolverFeti::init()"); super::init(fe0, fe1, createGlobalMapping); MeshLevelData& levelData = meshDistributor->getMeshLevelData(); int nLevels = levelData.getNumberOfLevels(); TEST_EXIT_DBG(nLevels >= 1)("nLevels < 1! Should not happen!\n"); if (createGlobalMapping) { if (meshLevel + 1 < nLevels && levelData.getMpiComm(meshLevel + 1) != MPI::COMM_SELF) { dofMapSubDomain.init(componentSpaces, feSpaces); dofMapSubDomain.setMpiComm(levelData.getMpiComm(meshLevel + 1)); dofMapSubDomain.setDofComms(meshDistributor->getDofComms(), meshLevel + 1); dofMapSubDomain.clear(); meshDistributor->registerDofMap(dofMapSubDomain); } } } void PetscSolverFeti::initialize() { FUNCNAME("PetscSolverFeti::initialize()"); #if (DEBUG != 0) MSG("Init FETI-DP on mesh level %d\n", meshLevel); #endif TEST_EXIT_DBG(meshLevel + 2 <= meshDistributor->getMeshLevelData().getNumberOfLevels()) ("Mesh hierarchy does not contain at least %d levels!\n", meshLevel + 2); MeshLevelData& levelData = meshDistributor->getMeshLevelData(); subDomainIsLocal = (levelData.getMpiComm(meshLevel + 1) == MPI::COMM_SELF); if (subdomain == NULL) { string subSolverInitStr = name + "->subsolver"; string solverType = "petsc"; Parameters::get(subSolverInitStr, solverType); solverType = "p_" + solverType; LinearSolverCreator* solverCreator = dynamic_cast<LinearSolverCreator*>(CreatorMap<LinearSolverInterface>::getCreator(solverType, name)); TEST_EXIT(solverCreator) ("No valid solver type found in parameter \"%s\"\n", name.c_str()); solverCreator->setName(subSolverInitStr); subdomain = dynamic_cast<PetscSolver*>(solverCreator->create()); subdomain->setSymmetric(isSymmetric); subdomain->setHandleDirichletRows(dirichletMode == 0); subdomain->setMeshDistributor(meshDistributor, meshLevel + 1); subdomain->init(componentSpaces, feSpaces); delete solverCreator; } primalDofMap.init(componentSpaces, feSpaces); dualDofMap.init(componentSpaces, feSpaces, false); localDofMap.init(componentSpaces, feSpaces, !subDomainIsLocal); lagrangeMap.init(componentSpaces, feSpaces); if (stokesMode) interfaceDofMap.init(componentSpaces, feSpaces); if (fetiPreconditioner == FETI_DIRICHLET) { TEST_EXIT(levelMode == 1) ("Dirichlet preconditioner not yet implemented for multilevel FETI-DP\n"); interiorDofMap.init(componentSpaces, feSpaces, false); } } void PetscSolverFeti::createDirichletData(Matrix<DOFMatrix*>& mat) { FUNCNAME("PetscSolverFeti::createDirichletData()"); if (dirichletMode == 1) { int nComponents = mat.getNumRows(); for (int component = 0; component < nComponents; component++) { DOFMatrix* dofMat = mat[component][component]; if (!dofMat) continue; dirichletRows[component] = dofMat->getDirichletRows(); } } } void PetscSolverFeti::createFetiData() { FUNCNAME("PetscSolverFeti::createFetiData()"); double timeCounter = MPI::Wtime(); MeshLevelData& levelData = meshDistributor->getMeshLevelData(); primalDofMap.clear(); dualDofMap.clear(); lagrangeMap.clear(); localDofMap.clear(); if (fetiPreconditioner == FETI_DIRICHLET) interiorDofMap.clear(); primalDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel); lagrangeMap.setDofComms(meshDistributor->getDofComms(), meshLevel); primalDofMap.setMpiComm(levelData.getMpiComm(meshLevel)); dualDofMap.setMpiComm(levelData.getMpiComm(meshLevel)); lagrangeMap.setMpiComm(levelData.getMpiComm(meshLevel)); localDofMap.setMpiComm(levelData.getMpiComm(meshLevel + 1)); if (fetiPreconditioner == FETI_DIRICHLET) interiorDofMap.setMpiComm(levelData.getMpiComm(meshLevel + 1)); localDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel + 1); if (stokesMode) { interfaceDofMap.clear(); interfaceDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel); interfaceDofMap.setMpiComm(levelData.getMpiComm(0)); } int nComponents = componentSpaces.size(); for (int component = 0; component < nComponents; component++) { createPrimals(component); createDuals(component); createInterfaceNodes(component); createIndexB(component); } primalDofMap.update(); dualDofMap.update(); localDofMap.update(); if (fetiPreconditioner == FETI_DIRICHLET) interiorDofMap.update(); if (stokesMode) interfaceDofMap.update(); for (int component = 0; component < nComponents; component++) { createLagrange(component); createAugmentedLagrange(component); } lagrangeMap.update(); // === === if (subDomainIsLocal) { MSG("WARNING: MAKE GENERAL!\n"); rStartInterior = 0; int localDofs = localDofMap.getOverallDofs(); mpi::getDofNumbering(domainComm, localDofs, rStartInterior, nGlobalOverallInterior); } else { MSG("WARNING: MAKE GENERAL!\n"); MeshLevelData& levelData = meshDistributor->getMeshLevelData(); int groupRowsInterior = 0; if (levelData.getMpiComm(1).Get_rank() == 0) groupRowsInterior = localDofMap.getOverallDofs(); mpi::getDofNumbering(domainComm, groupRowsInterior, rStartInterior, nGlobalOverallInterior); int tmp = 0; if (levelData.getMpiComm(1).Get_rank() == 0) tmp = rStartInterior; levelData.getMpiComm(1).Allreduce(&tmp, &rStartInterior, 1, MPI_INT, MPI_SUM); } for (int i = 0; i < static_cast<int>(componentSpaces.size()); i++) { const FiniteElemSpace* feSpace = componentSpaces[i]; MSG("FETI-DP data for %d-ith component (FE space %p):\n", i, feSpace); if (i == pressureComponent) { MSG(" nRankInterface = %d nOverallInterface = %d\n", interfaceDofMap[i].nRankDofs, interfaceDofMap[i].nOverallDofs); } else { MSG(" nRankPrimals = %d nLocalPrimals = %d nOverallPrimals = %d\n", primalDofMap[i].nRankDofs, primalDofMap[i].nLocalDofs, primalDofMap[i].nOverallDofs); MSG(" nRankDuals = %d nOverallDuals = %d\n", dualDofMap[i].nRankDofs, dualDofMap[i].nOverallDofs); MSG(" nRankLagrange = %d nOverallLagrange = %d\n", lagrangeMap[i].nRankDofs, lagrangeMap[i].nOverallDofs); MSG(" nRankLocal = %d nOverallLocal = %d\n", localDofMap[i].nRankDofs, localDofMap[i].nOverallDofs); } } subdomain->setDofMapping(&localDofMap); subdomain->setCoarseSpaceDofMapping(&primalDofMap); if (stokesMode) subdomain->setCoarseSpaceDofMapping(&interfaceDofMap, pressureComponent); if (printTimings) { MPI::COMM_WORLD.Barrier(); timeCounter = MPI::Wtime() - timeCounter; MSG("FETI-DP timing 01: %.5f seconds (creation of basic data structures)\n", timeCounter); } bool writePrimals = false; Parameters::get("parallel->debug->write primals", writePrimals); if (writePrimals) PetscSolverFetiDebug::writePrimalFiles(*this); } void PetscSolverFeti::createPrimals(int component) { FUNCNAME("PetscSolverFeti::createPrimals()"); if (component == pressureComponent) return; const FiniteElemSpace* feSpace = componentSpaces[component]; // === Define all vertices on the interior boundaries of the macro mesh === // === to be primal variables. === // Set of DOF indices that are considered to be primal variables. DofContainerSet& vertices = meshDistributor->getBoundaryDofInfo(feSpace, meshLevel).geoDofs[VERTEX]; DofIndexSet primals; for (DofContainerSet::iterator it = vertices.begin(); it != vertices.end(); ++it) { if (dirichletRows[component].count(**it)) continue; if (meshLevel == 1 && not (*interiorMap)[component].isSet(**it)) continue; if (subDomainIsLocal) { primals.insert(**it); } else { double e = 1e-8; WorldVector<double> c; feSpace->getMesh()->getDofIndexCoords(*it, feSpace, c); if ((fabs(c[0]) < e && fabs(c[1] - 12.5) < e) || (fabs(c[0] - 25.0) < e && fabs(c[1] - 12.5) < e) || (fabs(c[0] - 12.5) < e && fabs(c[1]) < e) || (fabs(c[0] - 12.5) < e && fabs(c[1] - 25.0) < e) || (fabs(c[0] - 12.5) < e && fabs(c[1] - 12.5) < e)) { MSG("PRIMAL COORD %f %f\n", c[0], c[1]); primals.insert(**it); } else { MSG("OMMIT SOME PRIMAL!\n"); } } } // === Calculate the number of primals that are owned by the rank and === // === create local indices of the primals starting at zero. === for (DofIndexSet::iterator it = primals.begin(); it != primals.end(); ++it) { if (dofMap[feSpace].isRankDof(*it)) { primalDofMap[component].insertRankDof(*it); } else { primalDofMap[component].insertNonRankDof(*it); } } } void PetscSolverFeti::createDuals(int component) { FUNCNAME("PetscSolverFeti::createDuals()"); if (component == pressureComponent) return; const FiniteElemSpace* feSpace = componentSpaces[component]; // === Create global index of the dual nodes on each rank. === DofContainer allBoundaryDofs; meshDistributor->getAllBoundaryDofs(feSpace, meshLevel, allBoundaryDofs); for (DofContainer::iterator it = allBoundaryDofs.begin(); it != allBoundaryDofs.end(); ++it) { if (dirichletRows[component].count(**it)) continue; if (isPrimal(component, **it)) continue; if (meshLevel == 1 && not (*interiorMap)[component].isSet(**it)) continue; if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(**it)) dualDofMap[component].insertRankDof(**it); } } void PetscSolverFeti::createInterfaceNodes(int component) { FUNCNAME("PetscSolverFeti::createInterfaceNodes()"); if (component != pressureComponent) return; const FiniteElemSpace* feSpace = componentSpaces[component]; DofContainer allBoundaryDofs; meshDistributor->getAllBoundaryDofs(feSpace, meshLevel, allBoundaryDofs); for (DofContainer::iterator it = allBoundaryDofs.begin(); it != allBoundaryDofs.end(); ++it) { if (dirichletRows[component].count(**it)) continue; if (dofMap[feSpace].isRankDof(**it)) interfaceDofMap[component].insertRankDof(**it); else interfaceDofMap[component].insertNonRankDof(**it); } } void PetscSolverFeti::createLagrange(int component) { FUNCNAME("PetscSolverFeti::createLagrange()"); if (component == pressureComponent) return; const FiniteElemSpace* feSpace = componentSpaces[component]; Mesh* mesh = feSpace->getMesh(); boundaryDofRanks[feSpace].clear(); // Stores for all rank owned communication DOFs, if the counterpart is // a rank owned DOF in its subdomain. Thus, the following map stores to // each rank number all DOFs that fulfill this requirenment. map<int, std::set<DegreeOfFreedom>> subDomainRankDofs; if (not subDomainIsLocal) { StdMpi<vector<int>> stdMpi(domainComm); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace); !it.end(); it.nextRank()) { vector<int> dofs; dofs.reserve(it.getDofs().size()); for (; !it.endDofIter(); it.nextDof()) { if (dofMapSubDomain[feSpace].isRankDof(it.getDofIndex())) dofs.push_back(1); else dofs.push_back(0); } stdMpi.send(it.getRank(), dofs); } for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace); !it.end(); it.nextRank()) stdMpi.recv(it.getRank()); stdMpi.startCommunication(); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace); !it.end(); it.nextRank()) for (; !it.endDofIter(); it.nextDof()) if (!isPrimal(component, it.getDofIndex()) && stdMpi.getRecvData(it.getRank())[it.getDofCounter()] == 1) subDomainRankDofs[it.getRank()].insert(it.getDofIndex()); } if (dualDofMap[component].nLocalDofs == 0) return; // === Create for each dual node that is owned by the rank, the set === // === of ranks that contain this node (denoted by W(x_j)). === int mpiRank = domainComm.Get_rank(); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace); !it.end(); it.nextRank()) { for (; !it.endDofIter(); it.nextDof()) { if (!isPrimal(component, it.getDofIndex())) { boundaryDofRanks[feSpace][it.getDofIndex()].insert(mpiRank); // If the subdomain is local, always add the counterpart rank, // otherwise check if the other rank is the owner of the DOF in // its subdomain. if (subDomainIsLocal || subDomainRankDofs[it.getRank()].count(it.getDofIndex())) boundaryDofRanks[feSpace][it.getDofIndex()].insert(it.getRank()); } } } // === Communicate these sets for all rank owned dual nodes to other === // === ranks that also have this node. === StdMpi<vector<std::set<int>>> stdMpi(meshDistributor->getMpiComm(meshLevel)); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace); !it.end(); it.nextRank()) for (; !it.endDofIter(); it.nextDof()) if (!isPrimal(component, it.getDofIndex())) if (subDomainIsLocal || subDomainRankDofs[it.getRank()].count(it.getDofIndex())) stdMpi.getSendData(it.getRank()).push_back(boundaryDofRanks[feSpace][it.getDofIndex()]); stdMpi.updateSendDataSize(); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace); !it.end(); it.nextRank()) { bool recvFromRank = false; for (; !it.endDofIter(); it.nextDof()) { if (!isPrimal(component, it.getDofIndex())) { if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(it.getDofIndex())) { recvFromRank = true; break; } } } if (recvFromRank) stdMpi.recv(it.getRank()); } stdMpi.startCommunication(); for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace); !it.end(); it.nextRank()) { int i = 0; for (; !it.endDofIter(); it.nextDof()) { if (!isPrimal(component, it.getDofIndex())) { if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(it.getDofIndex())) { boundaryDofRanks[feSpace][it.getDofIndex()] = stdMpi.getRecvData(it.getRank())[i++]; } else { lagrangeMap[component].insertNonRankDof(it.getDofIndex()); } } } } // === Reserve for each dual node, on the rank that owns this node, the === // === appropriate number of Lagrange constraints. === int nRankLagrange = 0; DofMap& dualMap = dualDofMap[component].getMap(); for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it) { if (dofMap[feSpace].isRankDof(it->first)) { lagrangeMap[component].insertRankDof(it->first, nRankLagrange); int degree = boundaryDofRanks[feSpace][it->first].size(); nRankLagrange += (degree * (degree - 1)) / 2; } else { lagrangeMap[component].insertNonRankDof(it->first); } } lagrangeMap[component].nRankDofs = nRankLagrange; } void PetscSolverFeti::createAugmentedLagrange(int component) { FUNCNAME("PetscSolverFeti::createAugmentedLagrange()"); if (!augmentedLagrange) return; } void PetscSolverFeti::createIndexB(int component) { FUNCNAME("PetscSolverFeti::createIndexB()"); const FiniteElemSpace* feSpace = componentSpaces[component]; DOFAdmin* admin = feSpace->getAdmin(); // === To ensure that all interior node on each rank are listen first in === // === the global index of all B nodes, insert all interior nodes first, === // === without defining a correct index. === int nLocalInterior = 0; for (int i = 0; i < admin->getUsedSize(); i++) { if (admin->isDofFree(i) || isPrimal(component, i) || isDual(component, i) || isInterface(component, i) || dirichletRows[component].count(i)) continue; if (meshLevel == 1 && not (*interiorMap)[component].isSet(i)) continue; if (subDomainIsLocal) { localDofMap[component].insertRankDof(i, nLocalInterior); if (fetiPreconditioner == FETI_DIRICHLET) interiorDofMap[component].insertRankDof(i, nLocalInterior); nLocalInterior++; } else { if (dofMapSubDomain[feSpace].isRankDof(i)) localDofMap[component].insertRankDof(i); else localDofMap[component].insertNonRankDof(i); TEST_EXIT_DBG(fetiPreconditioner == FETI_NONE) ("Not yet implemnted!\n"); } } // === And finally, add the global indicies of all dual nodes. === for (DofMap::iterator it = dualDofMap[component].getMap().begin(); it != dualDofMap[component].getMap().end(); ++it) { if (subDomainIsLocal) { localDofMap[component].insertRankDof(it->first); } else { if (dofMapSubDomain[feSpace].isRankDof(it->first)) localDofMap[component].insertRankDof(it->first); else localDofMap[component].insertNonRankDof(it->first); } } } void PetscSolverFeti::createMatLagrange() { FUNCNAME("PetscSolverFeti::createMatLagrange()"); double wtime = MPI::Wtime(); int mpiRank = domainComm.Get_rank(); // === Create distributed matrix for Lagrange constraints. === MatCreateAIJ(domainComm, lagrangeMap.getRankDofs(), localDofMap.getRankDofs(), lagrangeMap.getOverallDofs(), nGlobalOverallInterior, 2, PETSC_NULL, 2, PETSC_NULL, &mat_lagrange); MatSetOption(mat_lagrange, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); Vec vec_scale_lagrange; createVec(lagrangeMap, vec_scale_lagrange); // === Create for all duals the corresponding Lagrange constraints. On === // === each rank we traverse all pairs (n, m) of ranks, with n < m, === // === that contain this node. If the current rank number is r, and === // === n == r, the rank sets 1.0 for the corresponding constraint, if === // === m == r, than the rank sets -1.0 for the corresponding === // === constraint. === for (unsigned int component = 0; component < componentSpaces.size(); component++) { DofMap& dualMap = dualDofMap[component].getMap(); for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it) { TEST_EXIT_DBG(boundaryDofRanks[componentSpaces[component]].count(it->first)) ("Should not happen!\n"); // Global index of the first Lagrange constriant for this node. int index = lagrangeMap.getMatIndex(component, it->first); // Copy set of all ranks that contain this dual node. vector<int> W(boundaryDofRanks[componentSpaces[component]][it->first].begin(), boundaryDofRanks[componentSpaces[component]][it->first].end()); // Number of ranks that contain this dual node. int degree = W.size(); TEST_EXIT_DBG(degree > 1)("Should not happen!\n"); int counter = 0; for (int i = 0; i < degree; i++) { for (int j = i + 1; j < degree; j++) { if (W[i] == mpiRank || W[j] == mpiRank) { MatSetValue(mat_lagrange, index + counter, localDofMap.getMatIndex(component, it->first) + rStartInterior, (W[i] == mpiRank ? 1.0 : -1.0), INSERT_VALUES); } counter++; } } // === Create scaling factors for scaling the lagrange matrix, which === // === is required for FETI-DP preconditioners. === if (dofMap[componentSpaces[component]].isRankDof(it->first)) { int nConstraints = (degree * (degree - 1)) / 2; for (int i = 0; i < nConstraints; i++) { VecSetValue(vec_scale_lagrange, index + i, 1.0 / static_cast<double>(degree), INSERT_VALUES); } } } } MatAssemblyBegin(mat_lagrange, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_lagrange, MAT_FINAL_ASSEMBLY); #if (DEBUG != 0) { int nZeroRows = PetscSolverFetiDebug::testZeroRows(mat_lagrange); int m,n; MatGetSize(mat_lagrange, &m ,&n); mpi::globalAdd(domainComm, nZeroRows); MSG("Lagrange matrix has %d zero rows and global size of %d %d!\n", nZeroRows, m, n); TEST_EXIT(nZeroRows == 0)("Lagrange matrix has zero rows!\n"); } #endif // === If required, create \ref mat_lagrange_scaled === VecAssemblyBegin(vec_scale_lagrange); VecAssemblyEnd(vec_scale_lagrange); if (fetiPreconditioner != FETI_NONE || fetiSolverType == INEXACT || stokesMode) { MatDuplicate(mat_lagrange, MAT_COPY_VALUES, &mat_lagrange_scaled); MatDiagonalScale(mat_lagrange_scaled, vec_scale_lagrange, PETSC_NULL); } VecDestroy(&vec_scale_lagrange); // === Print final timings. === if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 05: %.5f seconds (creation of lagrange constraint matrix)\n", MPI::Wtime() - wtime); } } bool PetscSolverFeti::testWirebasketEdge(BoundaryObject& edge, const FiniteElemSpace* feSpace) { FUNCNAME("PetscSolverFeti::testWirebasketEdge()"); return true; if (meshDistributor->getMesh()->getDim() == 2) return true; if (meshDistributor->getIntBoundary(meshLevel).getDegreeOwn(edge) != 3) return false; return true; Element* el = edge.el; int i0 = el->getVertexOfEdge(edge.ithObj, 0); int i1 = el->getVertexOfEdge(edge.ithObj, 1); DegreeOfFreedom d0 = el->getDof(i0, 0); DegreeOfFreedom d1 = el->getDof(i1, 0); WorldVector<double> c0, c1; el->getMesh()->getDofIndexCoords(d0, feSpace, c0); el->getMesh()->getDofIndexCoords(d1, feSpace, c1); bool xe = fabs(c0[0] - c1[0]) < 1e-8; bool ye = fabs(c0[1] - c1[1]) < 1e-8; bool ze = fabs(c0[2] - c1[2]) < 1e-8; int counter = static_cast<int>(xe) + static_cast<int>(ye) + static_cast<int>(ze); return (counter == 2); } vector<vector<BoundaryObject>> PetscSolverFeti::getCoarseEdges() { FUNCNAME("PetscSolverFeti::getAugmentedLagrange()"); InteriorBoundary& intBound = meshDistributor->getIntBoundary(meshLevel); std::set<BoundaryObject> allEdges; for (InteriorBoundary::iterator it(intBound.getOwn()); !it.end(); ++it) if (it->rankObj.subObj == EDGE && testWirebasketEdge(it->rankObj, feSpaces[0]) && allEdges.count(it->rankObj) == 0) allEdges.insert(it->rankObj); int nEmptyEdges = 0; vector<vector<BoundaryObject>> data; for (std::set<BoundaryObject>::iterator it = allEdges.begin(); it != allEdges.end(); ++it) { DofContainer edgeDofs; it->el->getAllDofs(feSpaces[0], *it, edgeDofs); if (edgeDofs.size() == 0) { nEmptyEdges++; } else { vector<BoundaryObject> oneBoundary; oneBoundary.push_back(*it); data.push_back(oneBoundary); } } int nEdges = allEdges.size(); mpi::globalAdd(nEdges); mpi::globalAdd(nEmptyEdges); MSG("Coarse space edges: %d (empty: %d)\n", nEdges, nEmptyEdges); return data; } vector<vector<BoundaryObject>> PetscSolverFeti::getCoarseFaces() { FUNCNAME("PetscSolverFeti::getAugmentedLagrange()"); InteriorBoundary& intBound = meshDistributor->getIntBoundary(meshLevel); map<int, std::set<BoundaryObject>> allFaces; for (InteriorBoundary::iterator it(intBound.getOwn()); !it.end(); ++it) if (it->rankObj.subObj == FACE) allFaces[it.getRank()].insert(it->rankObj); #if 0 std::set<BoundaryObject> allMyEdges; TraverseStack stack; ElInfo* elInfo = stack.traverseFirst(meshDistributor->getMesh(), 0, Mesh::CALL_EL_LEVEL | Mesh::FILL_BOUND); while (elInfo) { Element* el = elInfo->getElement(); for (int i = 0; i < el->getGeo(EDGE); i++) { BoundaryObject bobj(el, elInfo->getType(), EDGE, i); if (intBound.getDegreeOwn(bobj) == 1 && elInfo->getBoundary(EDGE, i) == INTERIOR) { allMyEdges.insert(bobj); } } elInfo = stack.traverseNext(elInfo); } for (map<int, std::set<BoundaryObject>>::iterator it = allFaces.begin(); it != allFaces.end(); ++it) { if (it->second.size() == 2) { vector<AtomicBoundary>& bs = intBound.getOwn()[it->first]; for (int i = 0; i < static_cast<int>(bs.size()); i++) { if (bs[i].rankObj.subObj == EDGE && intBound.getDegreeOwn(bs[i].rankObj) == 1 && allMyEdges.count(bs[i].rankObj)) { MSG("FOUND AN EDGE: %d %d %d\n", bs[i].rankObj.elIndex, bs[i].rankObj.subObj, bs[i].rankObj.ithObj); it->second.insert(bs[i].rankObj); } } } } #endif int nEmptyFaces = 0; vector<vector<BoundaryObject>> data; for (map<int, std::set<BoundaryObject>>::iterator it = allFaces.begin(); it != allFaces.end(); ++it) { vector<BoundaryObject> oneBoundary; for (std::set<BoundaryObject>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) { DofContainer faceDofs; bIt->el->getAllDofs(feSpaces[0], *bIt, faceDofs); if (faceDofs.size()) oneBoundary.push_back(*bIt); } if (oneBoundary.size()) data.push_back(oneBoundary); else nEmptyFaces++; } int nFaces = allFaces.size(); mpi::globalAdd(nFaces); mpi::globalAdd(nEmptyFaces); MSG("Coarse space faces: %d (empty: %d)\n", nFaces, nEmptyFaces); return data; } void PetscSolverFeti::createMatAugmentedLagrange() { FUNCNAME("PetscSolverFeti::createMatAugmentedLagrange()"); if (!augmentedLagrange) return; double wtime = MPI::Wtime(); vector<vector<BoundaryObject>> allEdges = getCoarseEdges(); vector<vector<BoundaryObject>> allFaces = getCoarseFaces(); allEdges.insert(allEdges.end(), allFaces.begin(), allFaces.end()); nRankEdges = allEdges.size(); int rStartEdges = 0; mpi::getDofNumbering(domainComm, nRankEdges, rStartEdges, nOverallEdges); MSG("nRankEdges = %d, nOverallEdges = %d\n", nRankEdges, nOverallEdges); nRankEdges *= componentSpaces.size(); rStartEdges *= componentSpaces.size(); nOverallEdges *= componentSpaces.size(); MatCreateAIJ(domainComm, nRankEdges, lagrangeMap.getRankDofs(), nOverallEdges, lagrangeMap.getOverallDofs(), 2, PETSC_NULL, 2, PETSC_NULL, &mat_augmented_lagrange); MatSetOption(mat_augmented_lagrange, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); int rowCounter = rStartEdges; for (vector<vector<BoundaryObject>>::iterator it = allEdges.begin(); it != allEdges.end(); ++it) { for (int component = 0; component < static_cast<int>(componentSpaces.size()); component++) { for (vector<BoundaryObject>::iterator edgeIt = it->begin(); edgeIt != it->end(); ++edgeIt) { DofContainer edgeDofs; edgeIt->el->getAllDofs(componentSpaces[component], *edgeIt, edgeDofs); TEST_EXIT(edgeDofs.size())("Should not happen!\n"); for (DofContainer::iterator it = edgeDofs.begin(); it != edgeDofs.end(); ++it) { TEST_EXIT(isPrimal(component, **it) == false) ("Should not be primal!\n"); int col = lagrangeMap.getMatIndex(component, **it); double value = 1.0; MatSetValue(mat_augmented_lagrange, rowCounter, col, value, INSERT_VALUES); } } rowCounter++; } } MatAssemblyBegin(mat_augmented_lagrange, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_augmented_lagrange, MAT_FINAL_ASSEMBLY); int nZeroRows = PetscSolverFetiDebug::testZeroRows(mat_augmented_lagrange); int m,n; MatGetSize(mat_augmented_lagrange, &m ,&n); MSG("Augmented lagrange matrix has %d zero rows and global size of %d %d!\n", nZeroRows, m, n); if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 05a: %.5f seconds (creation of augmented lagrange constraint matrix)\n", MPI::Wtime() - wtime); } } void PetscSolverFeti::createSchurPrimalKsp() { FUNCNAME("PetscSolverFeti::createSchurPrimalKsp()"); if (schurPrimalSolver == 0) { MSG("Create iterative schur primal solver on level %d!\n", meshLevel); if (augmentedLagrange == false) { schurPrimalData.subSolver = subdomain; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &(schurPrimalData.tmp_vec_b)); createVec(primalDofMap, schurPrimalData.tmp_vec_primal); MatCreateShell(domainComm, primalDofMap.getRankDofs(), primalDofMap.getRankDofs(), primalDofMap.getOverallDofs(), primalDofMap.getOverallDofs(), &schurPrimalData, &mat_schur_primal); MatShellSetOperation(mat_schur_primal, MATOP_MULT, (void(*)(void))petscMultMatSchurPrimal); } else { schurPrimalAugmentedData.subSolver = subdomain; schurPrimalAugmentedData.nestedVec = true; createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b0, nGlobalOverallInterior); createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b1, nGlobalOverallInterior); createVec(primalDofMap, schurPrimalAugmentedData.tmp_vec_primal); createVec(lagrangeMap, schurPrimalAugmentedData.tmp_vec_lagrange); schurPrimalAugmentedData.mat_lagrange = &mat_lagrange; schurPrimalAugmentedData.mat_augmented_lagrange = &mat_augmented_lagrange; MatCreateShell(domainComm, primalDofMap.getRankDofs() + nRankEdges, primalDofMap.getRankDofs() + nRankEdges, primalDofMap.getOverallDofs() + nOverallEdges, primalDofMap.getOverallDofs() + nOverallEdges, &schurPrimalAugmentedData, &mat_schur_primal); MatShellSetOperation(mat_schur_primal, MATOP_MULT, (void(*)(void))petscMultMatSchurPrimalAugmented); } KSPCreate(domainComm, &ksp_schur_primal); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal); #else KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal, SAME_NONZERO_PATTERN); #endif KSPSetOptionsPrefix(ksp_schur_primal, "schur_primal_"); KSPSetType(ksp_schur_primal, KSPGMRES); KSPSetFromOptions(ksp_schur_primal); } else { MSG("Create direct schur primal solver!\n"); double wtime = MPI::Wtime(); // === Create explicit matrix representation of the Schur primal system. === if (!augmentedLagrange) createMatExplicitSchurPrimal(); else createMatExplicitAugmentedSchurPrimal(); // === Create KSP solver object and set appropriate solver options. === KSPCreate(domainComm, &ksp_schur_primal); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal); #else KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal, SAME_NONZERO_PATTERN); #endif KSPSetOptionsPrefix(ksp_schur_primal, "schur_primal_"); KSPSetType(ksp_schur_primal, KSPPREONLY); PC pc_schur_primal; KSPGetPC(ksp_schur_primal, &pc_schur_primal); PCSetType(pc_schur_primal, PCLU); PCFactorSetMatSolverPackage(pc_schur_primal, MATSOLVERMUMPS); KSPSetFromOptions(ksp_schur_primal); // === And finally print timings, if required. === if (printTimings) { MPI::COMM_WORLD.Barrier(); MatInfo minfo; MatGetInfo(mat_schur_primal, MAT_GLOBAL_SUM, &minfo); MSG("Schur primal matrix nnz = %f\n", minfo.nz_used); MSG("FETI-DP timing 06: %.5f seconds (creation of schur primal matrix)\n", MPI::Wtime() - wtime); wtime = MPI::Wtime(); KSPSetUp(ksp_schur_primal); KSPSetUpOnBlocks(ksp_schur_primal); MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 07: %.5f seconds (factorization of primal schur matrix).\n", MPI::Wtime() - wtime); } } } void PetscSolverFeti::createMatExplicitSchurPrimal() { FUNCNAME("PetscSolverFeti::createMatExplicitSchurPrimal()"); int creationMode = 0; Parameters::get(name + "->feti->schur primal creation mode", creationMode); if (creationMode == 0) { // matK = inv(A_BB) A_BPi Mat matK; petsc_helper::blockMatMatSolve(domainComm, subdomain->getSolver(), subdomain->getMatInteriorCoarse(), matK); // mat_schur_primal = A_PiPi - A_PiB inv(A_BB) A_BPi // = A_PiPi - A_PiB matK MatMatMult(subdomain->getMatCoarseInterior(), matK, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat_schur_primal); MatAYPX(mat_schur_primal, -1.0, subdomain->getMatCoarse(), DIFFERENT_NONZERO_PATTERN); MatDestroy(&matK); } else { schurPrimalData.subSolver = subdomain; createVec(localDofMap, schurPrimalData.tmp_vec_b, nGlobalOverallInterior); createVec(primalDofMap, schurPrimalData.tmp_vec_primal); Mat tmp; MatCreateShell(domainComm, primalDofMap.getRankDofs(), primalDofMap.getRankDofs(), primalDofMap.getOverallDofs(), primalDofMap.getOverallDofs(), &schurPrimalData, &tmp); MatShellSetOperation(tmp, MATOP_MULT, (void(*)(void))petscMultMatSchurPrimal); MatComputeExplicitOperator(tmp, &mat_schur_primal); MatDestroy(&tmp); schurPrimalData.subSolver = NULL; VecDestroy(&schurPrimalData.tmp_vec_b); VecDestroy(&schurPrimalData.tmp_vec_primal); } } void PetscSolverFeti::createMatExplicitAugmentedSchurPrimal() { FUNCNAME("PetscSolverFeti::createMatExplicitAugmentedSchurPrimal()"); int creationMode = 0; Parameters::get("parallel->feti->schur primal creation mode", creationMode); if (creationMode == 0) { // qj = -Q J Mat qj; MatMatMult(mat_augmented_lagrange, mat_lagrange, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &qj); MatScale(qj, -1.0); // matTmp = inv(A_BB) A_BPi Mat matTmp; petsc_helper::blockMatMatSolve(domainComm, subdomain->getSolver(), subdomain->getMatInteriorCoarse(), matTmp); // mat00 = A_PiPi - A_PiB inv(A_BB) A_BPi // = A_PiPi - A_PiB matTmp Mat mat00; MatMatMult(subdomain->getMatCoarseInterior(), matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat00); MatAYPX(mat00, -1.0, subdomain->getMatCoarse(), DIFFERENT_NONZERO_PATTERN); // mat10 = -Q J inv(A_BB) A_BPi // = qj matTmp Mat mat10; MatMatMult(qj, matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat10); // matTmp = inv(A_BB) trans(J) trans(Q) Mat qT, jTqT; MatTranspose(mat_augmented_lagrange, MAT_INITIAL_MATRIX, &qT); MatTransposeMatMult(mat_lagrange, qT, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &jTqT); petsc_helper::blockMatMatSolve(domainComm, subdomain->getSolver(), jTqT, matTmp); MatDestroy(&qT); MatDestroy(&jTqT); // mat01 = -A_PiB inv(A_BB) trans(J) trans(Q) // = -A_PiB matTmp Mat mat01; MatMatMult(subdomain->getMatCoarseInterior(), matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat01); MatScale(mat01, -1.0); // mat11 = -Q J inv(A_BB) trans(J) trans(Q) // = qj matTmp Mat mat11; MatMatMult(qj, matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat11); MatDestroy(&matTmp); MatDestroy(&qj); Mat nestMat[4] = {mat00, mat01, mat10, mat11}; MatCreateNest(PETSC_COMM_WORLD, 2, PETSC_NULL, 2, PETSC_NULL, nestMat, &matTmp); petsc_helper::matNestConvert(matTmp, mat_schur_primal); MatDestroy(&mat00); MatDestroy(&mat01); MatDestroy(&mat10); MatDestroy(&mat11); MatDestroy(&matTmp); } else { Mat tmp; schurPrimalAugmentedData.subSolver = subdomain; schurPrimalAugmentedData.nestedVec = false; createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b0, nGlobalOverallInterior); createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b1, nGlobalOverallInterior); createVec(primalDofMap, schurPrimalAugmentedData.tmp_vec_primal); createVec(lagrangeMap, schurPrimalAugmentedData.tmp_vec_lagrange); schurPrimalAugmentedData.mat_lagrange = &mat_lagrange; schurPrimalAugmentedData.mat_augmented_lagrange = &mat_augmented_lagrange; MatCreateShell(domainComm, primalDofMap.getRankDofs() + nRankEdges, primalDofMap.getRankDofs() + nRankEdges, primalDofMap.getOverallDofs() + nOverallEdges, primalDofMap.getOverallDofs() + nOverallEdges, &schurPrimalAugmentedData, &tmp); MatShellSetOperation(tmp, MATOP_MULT, (void(*)(void))petscMultMatSchurPrimalAugmented); MatComputeExplicitOperator(tmp, &mat_schur_primal); MatDestroy(&tmp); schurPrimalAugmentedData.subSolver = NULL; schurPrimalAugmentedData.mat_lagrange = NULL; schurPrimalAugmentedData.mat_augmented_lagrange = NULL; VecDestroy(&schurPrimalAugmentedData.tmp_vec_b0); VecDestroy(&schurPrimalAugmentedData.tmp_vec_b1); VecDestroy(&schurPrimalAugmentedData.tmp_vec_primal); VecDestroy(&schurPrimalAugmentedData.tmp_vec_lagrange); } } void PetscSolverFeti::destroySchurPrimalKsp() { FUNCNAME("PetscSolverFeti::destroySchurPrimal()"); if (schurPrimalSolver == 0) { if (augmentedLagrange == false) { schurPrimalData.subSolver = NULL; VecDestroy(&schurPrimalData.tmp_vec_b); VecDestroy(&schurPrimalData.tmp_vec_primal); } else { schurPrimalAugmentedData.subSolver = NULL; schurPrimalAugmentedData.mat_lagrange = NULL; schurPrimalAugmentedData.mat_augmented_lagrange = NULL; VecDestroy(&schurPrimalAugmentedData.tmp_vec_b0); VecDestroy(&schurPrimalAugmentedData.tmp_vec_b1); VecDestroy(&schurPrimalAugmentedData.tmp_vec_primal); VecDestroy(&schurPrimalAugmentedData.tmp_vec_lagrange); } } MatDestroy(&mat_schur_primal); KSPDestroy(&ksp_schur_primal); } void PetscSolverFeti::createFetiKsp() { FUNCNAME("PetscSolverFeti::createFetiKsp()"); switch (fetiSolverType) { case EXACT: createFetiExactKsp(); break; case INEXACT: createFetiInexactKsp(); break; case INEXACT_REDUCED: createFetiInexactReducedKsp(); break; default: ERROR_EXIT("Should not happen!\n"); } } void PetscSolverFeti::createFetiExactKsp() { FUNCNAME("PetscSolverFeti::createFetiExactKsp()"); // === Create FETI-DP solver object. === fetiData.mat_lagrange = &mat_lagrange; fetiData.subSolver = subdomain; fetiData.ksp_schur_primal = &ksp_schur_primal; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &(fetiData.tmp_vec_b0)); createVec(lagrangeMap, fetiData.tmp_vec_lagrange); createVec(primalDofMap, fetiData.tmp_vec_primal0); if (stokesMode == false) { MatCreateShell(domainComm, lagrangeMap.getRankDofs(), lagrangeMap.getRankDofs(), lagrangeMap.getOverallDofs(), lagrangeMap.getOverallDofs(), &fetiData, &mat_feti); if (augmentedLagrange == false) { MatShellSetOperation(mat_feti, MATOP_MULT, (void(*)(void))petscMultMatFeti); } else { fetiData.mat_augmented_lagrange = &mat_augmented_lagrange; createVec(primalDofMap, fetiData.tmp_vec_primal1); MatShellSetOperation(mat_feti, MATOP_MULT, (void(*)(void))petscMultMatFetiAugmented); } } else { TEST_EXIT_DBG(!augmentedLagrange)("Not yet implemented!\n"); createVec(localDofMap, fetiData.tmp_vec_b1, nGlobalOverallInterior); createVec(primalDofMap, fetiData.tmp_vec_primal1); createVec(interfaceDofMap, fetiData.tmp_vec_interface); MatCreateShell(domainComm, interfaceDofMap.getRankDofs() + lagrangeMap.getRankDofs(), interfaceDofMap.getRankDofs() + lagrangeMap.getRankDofs(), interfaceDofMap.getOverallDofs() + lagrangeMap.getOverallDofs(), interfaceDofMap.getOverallDofs() + lagrangeMap.getOverallDofs(), &fetiData, &mat_feti); MatShellSetOperation(mat_feti, MATOP_MULT, (void(*)(void))petscMultMatFetiInterface); } KSPCreate(domainComm, &ksp_feti); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(ksp_feti, mat_feti, mat_feti); #else KSPSetOperators(ksp_feti, mat_feti, mat_feti, SAME_NONZERO_PATTERN); #endif KSPSetOptionsPrefix(ksp_feti, "feti_"); KSPSetType(ksp_feti, KSPGMRES); KSPSetTolerances(ksp_feti, 0, 1e-8, 1e+3, 1000); KSPSetFromOptions(ksp_feti); // === Set KSP monitor. === bool monitor = false; Parameters::get(name + "->feti->monitor", monitor); if (monitor) { if (stokesMode) KSPMonitorSet(ksp_feti, KSPMonitorFetiStokes, &fetiKspData, PETSC_NULL); else KSPMonitorSet(ksp_feti, KSPMonitorTrueResidualNorm, PETSC_NULL, PETSC_NULL); } // === Create null space objects. === createNullSpace(); switch (fetiPreconditioner) { case FETI_DIRICHLET: KSPGetPC(ksp_feti, &precon_feti); createFetiPreconDirichlet(precon_feti); break; case FETI_LUMPED: KSPGetPC(ksp_feti, &precon_feti); createFetiPreconLumped(precon_feti); break; default: break; } } void PetscSolverFeti::createFetiInexactKsp() { FUNCNAME("PetscSolverFeti::createFetiInexactKsp()"); // === Init solver === int localSize = localDofMap.getRankDofs() + primalDofMap.getRankDofs() + lagrangeMap.getRankDofs(); int globalSize = nGlobalOverallInterior + primalDofMap.getOverallDofs() + lagrangeMap.getOverallDofs(); fetiInexactData.matBB = &(subdomain->getMatInterior()); fetiInexactData.matBPi = &(subdomain->getMatInteriorCoarse()); fetiInexactData.matPiB = &(subdomain->getMatCoarseInterior()); fetiInexactData.matPiPi = &(subdomain->getMatCoarse()); fetiInexactData.mat_lagrange = &mat_lagrange; createVec(localDofMap, fetiInexactData.tmp_vec_b0); createVec(localDofMap, fetiInexactData.tmp_vec_b1); MatCreateShell(domainComm, localSize, localSize, globalSize, globalSize, &fetiInexactData, &mat_feti); MatShellSetOperation(mat_feti, MATOP_MULT, (void(*)(void))petscMultMatFetiInexact); KSPCreate(domainComm, &ksp_feti); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(ksp_feti, mat_feti, mat_feti); #else KSPSetOperators(ksp_feti, mat_feti, mat_feti, SAME_NONZERO_PATTERN); #endif KSPSetOptionsPrefix(ksp_feti, "feti_"); KSPSetType(ksp_feti, KSPGMRES); KSPSetTolerances(ksp_feti, 0, 1e-8, 1e+3, 1000); KSPSetFromOptions(ksp_feti); // === Init preconditioner === fetiInexactPreconData.ksp_schur = ksp_schur_primal; fetiInexactPreconData.ksp_interior = subdomain->getSolver(); fetiInexactPreconData.matPiB = &(subdomain->getMatCoarseInterior()); fetiInexactPreconData.matBPi = &(subdomain->getMatInteriorCoarse()); fetiInexactPreconData.mat_lagrange = &mat_lagrange; createVec(localDofMap, fetiInexactPreconData.tmp_vec_b0); KSPCreate(domainComm, &(fetiInexactPreconData.ksp_pc_feti)); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(fetiInexactPreconData.ksp_pc_feti, mat_lagrange, mat_lagrange); #else KSPSetOperators(fetiInexactPreconData.ksp_pc_feti, mat_lagrange, mat_lagrange, SAME_NONZERO_PATTERN); #endif KSPGetPC(fetiInexactPreconData.ksp_pc_feti, &(fetiInexactPreconData.pc_feti)); createFetiPreconLumped(fetiInexactPreconData.pc_feti); PCSetUp(fetiInexactPreconData.pc_feti); // === Setup pc object === PC pc; KSPGetPC(ksp_feti, &pc); PCSetType(pc, PCSHELL); PCShellSetApply(pc, pcInexactFetiShell); PCShellSetContext(pc, &fetiInexactPreconData); } void PetscSolverFeti::createFetiInexactReducedKsp() { FUNCNAME("PetscSolverFeti::createFetiInexactReducedKsp()"); ERROR_EXIT("Not yet implemented!\n"); } void PetscSolverFeti::createFetiPreconLumped(PC pc) { FUNCNAME("PetscSolverFeti::createFetiPreconLumped()"); FetiLumpedPreconData* lumpedData = (stokesMode ? &fetiInterfaceLumpedPreconData : &fetiLumpedPreconData); lumpedData->mat_lagrange_scaled = &mat_lagrange_scaled; lumpedData->mat_duals_duals = &mat_duals_duals; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &(lumpedData->tmp_vec_b0)); MatGetVecs(mat_duals_duals, PETSC_NULL, &(lumpedData->tmp_vec_duals0)); MatGetVecs(mat_duals_duals, PETSC_NULL, &(lumpedData->tmp_vec_duals1)); for (int component = 0; component < static_cast<int>(componentSpaces.size()); component++) { if (stokesMode && component == pressureComponent) continue; DofMap& dualMap = dualDofMap[component].getMap(); for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it) { DegreeOfFreedom d = it->first; int matIndexLocal = localDofMap.getLocalMatIndex(component, d); int matIndexDual = dualDofMap.getLocalMatIndex(component, d); lumpedData->localToDualMap[matIndexLocal] = matIndexDual; } } if (stokesMode) { // === Create mass matrix solver === const FiniteElemSpace* pressureFeSpace = componentSpaces[pressureComponent]; // Create parallel DOF mapping in pressure space. ParallelDofMapping* massMapping = NULL; if (massMatrixSolver) { massMapping = massMatrixSolver->getDofMapping(); } else { massMapping = new ParallelDofMapping(COMPONENT_WISE, true); massMapping->init(pressureFeSpace, pressureFeSpace); massMapping->setDofComms(meshDistributor->getDofComms(), meshLevel); massMapping->setMpiComm(meshDistributor->getMeshLevelData().getMpiComm(0)); } (*massMapping)[0] = interfaceDofMap[pressureComponent]; massMapping->update(); DOFMatrix massMatrix(pressureFeSpace, pressureFeSpace); Operator op(pressureFeSpace, pressureFeSpace); Simple_ZOT zot; op.addTerm(&zot); massMatrix.assembleOperator(op); if (!massMatrixSolver) { massMatrixSolver = new PetscSolverGlobalMatrix(""); massMatrixSolver->setKspPrefix("mass_"); massMatrixSolver->setMeshDistributor(meshDistributor, meshLevel); massMatrixSolver->setDofMapping(massMapping); } massMatrixSolver->fillPetscMatrix(&massMatrix); int r, c; MatGetSize(massMatrixSolver->getMatInterior(), &r, &c); MatInfo info; MatGetInfo(massMatrixSolver->getMatInterior(), MAT_GLOBAL_SUM, &info); MSG("MASS MAT INFO: size = %d x %d nnz = %d\n", r, c, static_cast<int>(info.nz_used)); fetiInterfaceLumpedPreconData.ksp_mass = massMatrixSolver->getSolver(); // === Create tmp vectors === createVec(localDofMap, fetiInterfaceLumpedPreconData.tmp_vec_b1); createVec(primalDofMap, fetiInterfaceLumpedPreconData.tmp_primal); fetiInterfaceLumpedPreconData.subSolver = subdomain; } // === Set PC object === PCSetType(pc, PCSHELL); if (stokesMode) { PCShellSetContext(pc, static_cast<void*>(&fetiInterfaceLumpedPreconData)); PCShellSetApply(pc, petscApplyFetiInterfaceLumpedPrecon); } else { PCShellSetContext(pc, static_cast<void*>(&fetiLumpedPreconData)); PCShellSetApply(pc, petscApplyFetiLumpedPrecon); } } void PetscSolverFeti::createFetiPreconDirichlet(PC pc) { FUNCNAME("PetscSolverFeti::createFetiPreconDirichlet()"); TEST_EXIT(subDomainIsLocal) ("Check for localDofMap.getLocalMatIndex, which should not work for multilevel FETI-DP!\n"); TEST_EXIT(!stokesMode) ("Stokes mode does not yet support the Dirichlet precondition!\n"); KSPCreate(PETSC_COMM_SELF, &ksp_interior); #if (PETSC_VERSION_MINOR >= 5) KSPSetOperators(ksp_interior, mat_interior_interior, mat_interior_interior); #else KSPSetOperators(ksp_interior, mat_interior_interior, mat_interior_interior, SAME_NONZERO_PATTERN); #endif KSPSetOptionsPrefix(ksp_interior, "precon_interior_"); KSPSetType(ksp_interior, KSPPREONLY); PC pc_interior; KSPGetPC(ksp_interior, &pc_interior); if (isSymmetric) { PCSetType(pc_interior, PCCHOLESKY); PCFactorSetMatSolverPackage(pc_interior, MATSOLVERMUMPS); } else { PCSetType(pc_interior, PCLU); PCFactorSetMatSolverPackage(pc_interior, MATSOLVERUMFPACK); } KSPSetFromOptions(ksp_interior); fetiDirichletPreconData.mat_lagrange_scaled = &mat_lagrange_scaled; fetiDirichletPreconData.mat_interior_interior = &mat_interior_interior; fetiDirichletPreconData.mat_duals_duals = &mat_duals_duals; fetiDirichletPreconData.mat_interior_duals = &mat_interior_duals; fetiDirichletPreconData.mat_duals_interior = &mat_duals_interior; fetiDirichletPreconData.ksp_interior = &ksp_interior; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &(fetiDirichletPreconData.tmp_vec_b)); MatGetVecs(mat_duals_duals, PETSC_NULL, &(fetiDirichletPreconData.tmp_vec_duals0)); MatGetVecs(mat_duals_duals, PETSC_NULL, &(fetiDirichletPreconData.tmp_vec_duals1)); MatGetVecs(mat_interior_interior, PETSC_NULL, &(fetiDirichletPreconData.tmp_vec_interior)); TEST_EXIT_DBG(subDomainIsLocal) ("Should not happen, check usage of localDofMap!\n"); for (unsigned int component = 0; component < componentSpaces.size(); component++) { DofMap& dualMap = dualDofMap[component].getMap(); for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it) { DegreeOfFreedom d = it->first; int matIndexLocal = localDofMap.getLocalMatIndex(component, d); int matIndexDual = dualDofMap.getLocalMatIndex(component, d); fetiDirichletPreconData.localToDualMap[matIndexLocal] = matIndexDual; } } PCSetType(pc, PCSHELL); PCShellSetContext(pc, static_cast<void*>(&fetiDirichletPreconData)); PCShellSetApply(pc, petscApplyFetiDirichletPrecon); // For the case, that we want to print the timings, we force the LU // factorization of the local problems to be done here explicitly. if (printTimings) { double wtime = MPI::Wtime(); KSPSetUp(ksp_interior); KSPSetUpOnBlocks(ksp_interior); MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 08: %.5f seconds (factorization of Dirichlet preconditoner matrices)\n", MPI::Wtime() - wtime); } } void PetscSolverFeti::destroyFetiKsp() { FUNCNAME("PetscSolverFeti::destroyFetiKsp()"); switch (fetiSolverType) { case EXACT: destroyFetiExactKsp(); break; case INEXACT: destroyFetiInexactKsp(); break; case INEXACT_REDUCED: destroyFetiInexactReducedKsp(); break; default: ERROR_EXIT("Should not happen!\n"); } } void PetscSolverFeti::destroyFetiExactKsp() { FUNCNAME("PetscSolverFeti::destroyFetiExactKsp()"); // === Destroy FETI-DP solver object. === fetiData.mat_lagrange = PETSC_NULL; fetiData.subSolver = NULL; fetiData.ksp_schur_primal = PETSC_NULL; VecDestroy(&fetiData.tmp_vec_b0); VecDestroy(&fetiData.tmp_vec_lagrange); VecDestroy(&fetiData.tmp_vec_primal0); if (augmentedLagrange) { fetiData.mat_augmented_lagrange = PETSC_NULL; VecDestroy(&fetiData.tmp_vec_primal1); } if (stokesMode) { VecDestroy(&fetiData.tmp_vec_b1); VecDestroy(&fetiData.tmp_vec_primal1); VecDestroy(&fetiData.tmp_vec_interface); } MatDestroy(&mat_feti); KSPDestroy(&ksp_feti); // === Destroy FETI-DP preconditioner object. === switch (fetiPreconditioner) { case FETI_DIRICHLET: KSPDestroy(&ksp_interior); fetiDirichletPreconData.mat_lagrange_scaled = NULL; fetiDirichletPreconData.mat_interior_interior = NULL; fetiDirichletPreconData.mat_duals_duals = NULL; fetiDirichletPreconData.mat_interior_duals = NULL; fetiDirichletPreconData.mat_duals_interior = NULL; fetiDirichletPreconData.ksp_interior = NULL; VecDestroy(&fetiDirichletPreconData.tmp_vec_b); VecDestroy(&fetiDirichletPreconData.tmp_vec_duals0); VecDestroy(&fetiDirichletPreconData.tmp_vec_duals1); VecDestroy(&fetiDirichletPreconData.tmp_vec_interior); MatDestroy(&mat_lagrange_scaled); break; case FETI_LUMPED: { FetiLumpedPreconData& lumpedData = (stokesMode ? fetiInterfaceLumpedPreconData : fetiLumpedPreconData); lumpedData.mat_lagrange_scaled = NULL; lumpedData.mat_duals_duals = NULL; VecDestroy(&lumpedData.tmp_vec_b0); VecDestroy(&lumpedData.tmp_vec_duals0); VecDestroy(&lumpedData.tmp_vec_duals1); } break; default: break; } } void PetscSolverFeti::destroyFetiInexactKsp() { FUNCNAME("PetscSolverFeti::destroyFetiInexactKsp()"); VecDestroy(&(fetiInexactData.tmp_vec_b0)); VecDestroy(&(fetiInexactData.tmp_vec_b1)); MatDestroy(&mat_feti); KSPDestroy(&ksp_feti); VecDestroy(&(fetiInexactPreconData.tmp_vec_b0)); KSPDestroy(&(fetiInexactPreconData.ksp_pc_feti)); } void PetscSolverFeti::destroyFetiInexactReducedKsp() { FUNCNAME("PetscSolverFeti::destroyFetiInexactReducedKsp()"); } void PetscSolverFeti::createNullSpace() { FUNCNAME("PetscSolverFeti::createNullSpace()"); if (!stokesMode) return; const FiniteElemSpace* pressureFeSpace = componentSpaces[pressureComponent]; Vec ktest0, ktest1; createLocalVec(localDofMap, ktest0); createLocalVec(localDofMap, ktest1); DofMap& m = localDofMap[pressureComponent].getMap(); for (DofMap::iterator it = m.begin(); it != m.end(); ++it) { if (dofMap[pressureFeSpace].isRankDof(it->first)) { int index = localDofMap.getLocalMatIndex(pressureComponent, it->first); VecSetValue(ktest0, index, 1.0, INSERT_VALUES); } } VecAssemblyBegin(ktest0); VecAssemblyEnd(ktest0); MatMult(subdomain->getMatInterior(), ktest0, ktest1); PetscScalar* valarray; Vec ktest2, ktest3; VecGetArray(ktest1, &valarray); VecCreateMPIWithArray(PETSC_COMM_WORLD, 1, localDofMap.getRankDofs(), nGlobalOverallInterior, valarray, &ktest2); createVec(localDofMap, ktest3, nGlobalOverallInterior); Vec vecArray[2]; createVec(interfaceDofMap, vecArray[0]); createVec(lagrangeMap, vecArray[1]); VecSet(vecArray[0], 1.0); MatMult(subdomain->getMatInteriorCoarse(1), vecArray[0], ktest3); VecAXPY(ktest3, 1.0, ktest2); MatMult(mat_lagrange_scaled, ktest3, vecArray[1]); VecScale(vecArray[1], -1.0); Vec nullSpaceBasis; VecCreateNest(domainComm, 2, PETSC_NULL, vecArray, &nullSpaceBasis); #if (DEBUG != 0) PetscSolverFetiDebug::writeNullSpace(*this, nullSpaceBasis); #endif MatNullSpace matNullSpace; MatNullSpaceCreate(domainComm, PETSC_FALSE, 1, &nullSpaceBasis, &matNullSpace); MatSetNullSpace(mat_feti, matNullSpace); KSPSetNullSpace(ksp_feti, matNullSpace); MatNullSpaceDestroy(&matNullSpace); VecDestroy(&ktest0); VecDestroy(&ktest1); VecDestroy(&ktest2); VecDestroy(&ktest3); VecDestroy(&(vecArray[0])); VecDestroy(&(vecArray[1])); VecDestroy(&nullSpaceBasis); } void PetscSolverFeti::dbgMatrix(Matrix<DOFMatrix*>* mat) { FUNCNAME("PetscSolverFeti::dbgMatrix()"); if (levelMode == 2 && meshLevel == 0) { MSG("WARNING: MAKE MORE GENERAL!\n"); return; } #if (DEBUG != 0) PetscInt nRow, nCol; MatGetLocalSize(subdomain->getMatInterior(), &nRow, &nCol); mpi::globalAdd(nRow); mpi::globalAdd(nCol); MatInfo minfo; MatGetInfo(subdomain->getMatInterior(), MAT_GLOBAL_SUM, &minfo); int nnz = static_cast<int>(minfo.nz_used); mpi::globalAdd(nnz); MSG("Interior matrices [%d x %d] nnz = %d\n", nRow, nCol, nnz); MatGetSize(subdomain->getMatCoarse(), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarse(), MAT_GLOBAL_SUM, &minfo); MSG("Primal matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatCoarseInterior(), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarseInterior(), MAT_GLOBAL_SUM, &minfo); MSG("Primal-Interior matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatInteriorCoarse(), &nRow, &nCol); MatGetInfo(subdomain->getMatInteriorCoarse(), MAT_GLOBAL_SUM, &minfo); MSG("Interior-Primal matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); if (stokesMode) { MatGetSize(subdomain->getMatCoarse(1, 1), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarse(1, 1), MAT_GLOBAL_SUM, &minfo); MSG("Interface matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatCoarseInterior(1), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarseInterior(1), MAT_GLOBAL_SUM, &minfo); MSG("Interface-Interior matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatInteriorCoarse(1), &nRow, &nCol); MatGetInfo(subdomain->getMatInteriorCoarse(1), MAT_GLOBAL_SUM, &minfo); MSG("Interior-Interface matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatCoarse(1, 0), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarse(1, 0), MAT_GLOBAL_SUM, &minfo); MSG("Interface-Primal matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); MatGetSize(subdomain->getMatCoarse(0, 1), &nRow, &nCol); MatGetInfo(subdomain->getMatCoarse(0, 1), MAT_GLOBAL_SUM, &minfo); MSG("Primal-Interface matrix [%d x %d] nnz = %d\n", nRow, nCol, static_cast<int>(minfo.nz_used)); } #endif int writeInteriorMatrix = -1; Parameters::get("parallel->debug->write interior matrix", writeInteriorMatrix); if (writeInteriorMatrix >= 0 && writeInteriorMatrix == MPI::COMM_WORLD.Get_rank()) { PetscViewer petscView; PetscViewerBinaryOpen(PETSC_COMM_SELF, "interior.mat", FILE_MODE_WRITE, &petscView); MatView(subdomain->getMatInterior(), petscView); PetscViewerDestroy(&petscView); } bool checkInteriorMatrix = false;; Parameters::get("parallel->debug->check interior matrix", checkInteriorMatrix); if (checkInteriorMatrix) { int nZeroRows = PetscSolverFetiDebug::testZeroRows(subdomain->getMatInterior()); MSG("Interior matrix has %d zero rows!\n", nZeroRows); } bool printDirichlet = false; Parameters::get("parallel->debug->print dirichlet information", printDirichlet); if (printDirichlet) { int nComponents = mat->getSize(); for (int component = 0; component < nComponents; component++) { DOFMatrix* seqMat = (*mat)[component][component]; if (!seqMat) continue; const FiniteElemSpace* feSpace = seqMat->getRowFeSpace(); TEST_EXIT(feSpace)("Should not happen!\n"); std::set<DegreeOfFreedom>& dirichletRows = seqMat->getDirichletRows(); for (std::set<DegreeOfFreedom>::iterator it = dirichletRows.begin(); it != dirichletRows.end(); ++it) { if (localDofMap[component].isSet(*it)) { MSG("Dirichlet dof %d in component %d with interior mat index %d\n", *it, component, localDofMap.getMatIndex(component, *it)); } } } } int writeCoarseMatrix = 0; Parameters::get("parallel->debug->write coarse matrix", writeCoarseMatrix); if (writeCoarseMatrix > 0) { PetscViewer petscView; PetscViewerBinaryOpen(PETSC_COMM_WORLD, "coarse.mat", FILE_MODE_WRITE, &petscView); MatView(subdomain->getMatCoarse(), petscView); PetscViewerDestroy(&petscView); } int writeSchurPrimalMatrix = 0; Parameters::get("parallel->debug->write schur primal matrix", writeSchurPrimalMatrix); if (writeSchurPrimalMatrix) { PetscViewer petscView; PetscViewerBinaryOpen(PETSC_COMM_WORLD, "schurprimal.mat", FILE_MODE_WRITE, &petscView); MatView(mat_schur_primal, petscView); PetscViewerDestroy(&petscView); } } void PetscSolverFeti::recoverSolution(Vec& vec_sol_b, Vec& vec_sol_primal, SystemVector& vec) { FUNCNAME("PetscSolverFeti::recoverSolution()"); // === Get local part of the solution for B variables. === PetscScalar* localSolB; VecGetArray(vec_sol_b, &localSolB); PetscInt bsize; VecGetLocalSize(vec_sol_b, &bsize); // === Create scatter to get solutions of all primal nodes that are === // === contained in rank's domain. === unsigned int nComponents = vec.getSize(); vector<PetscInt> globalIsIndex, localIsIndex; globalIsIndex.reserve(primalDofMap.getLocalDofs()); localIsIndex.reserve(primalDofMap.getLocalDofs()); { int cnt = 0; for (unsigned int component = 0; component < nComponents; component++) { DofMap& dofMap = primalDofMap[component].getMap(); for (DofMap::iterator it = dofMap.begin(); it != dofMap.end(); ++it) { globalIsIndex.push_back(primalDofMap.getMatIndex(component, it->first)); localIsIndex.push_back(cnt++); } } TEST_EXIT_DBG(cnt == primalDofMap.getLocalDofs()) ("Should not happen!\n"); } IS globalIs, localIs; ISCreateGeneral(PETSC_COMM_SELF, globalIsIndex.size(), &(globalIsIndex[0]), PETSC_USE_POINTER, &globalIs); ISCreateGeneral(PETSC_COMM_SELF, localIsIndex.size(), &(localIsIndex[0]), PETSC_USE_POINTER, &localIs); Vec local_sol_primal; VecCreateSeq(PETSC_COMM_SELF, localIsIndex.size(), &local_sol_primal); VecScatter primalScatter; VecScatterCreate(vec_sol_primal, globalIs, local_sol_primal, localIs, &primalScatter); VecScatterBegin(primalScatter, vec_sol_primal, local_sol_primal, INSERT_VALUES, SCATTER_FORWARD); VecScatterEnd(primalScatter, vec_sol_primal, local_sol_primal, INSERT_VALUES, SCATTER_FORWARD); ISDestroy(&globalIs); ISDestroy(&localIs); VecScatterDestroy(&primalScatter); PetscScalar* localSolPrimal; VecGetArray(local_sol_primal, &localSolPrimal); // === And copy from PETSc local vectors to the DOF vectors. === int cnt = 0; for (unsigned int component = 0; component < nComponents; component++) { DOFVector<double>& dofVec = *(vec.getDOFVector(component)); for (DofMap::iterator it = localDofMap[component].getMap().begin(); it != localDofMap[component].getMap().end(); ++it) { if (subDomainIsLocal) { int petscIndex = localDofMap.getLocalMatIndex(component, it->first); dofVec[it->first] = localSolB[petscIndex]; } else { if (dofMapSubDomain[componentSpaces[component]].isRankDof(it->first)) { int petscIndex = localDofMap.getLocalMatIndex(component, it->first); TEST_EXIT(petscIndex < bsize)("Should not happen!\n"); dofVec[it->first] = localSolB[petscIndex]; } } } for (DofMap::iterator it = primalDofMap[component].getMap().begin(); it != primalDofMap[component].getMap().end(); ++it) dofVec[it->first] = localSolPrimal[cnt++]; } VecRestoreArray(vec_sol_b, &localSolB); VecRestoreArray(local_sol_primal, &localSolPrimal); VecDestroy(&local_sol_primal); } void PetscSolverFeti::recoverInterfaceSolution(Vec& vecInterface, SystemVector& vec) { FUNCNAME("PetscSolverFeti::recoverInterfaceSolution()"); if (!stokesMode) return; vector<PetscInt> globalIsIndex, localIsIndex; globalIsIndex.reserve(interfaceDofMap.getLocalDofs()); localIsIndex.reserve(interfaceDofMap.getLocalDofs()); int cnt = 0; DofMap& dofMap = interfaceDofMap[pressureComponent].getMap(); for (DofMap::iterator it = dofMap.begin(); it != dofMap.end(); ++it) { globalIsIndex.push_back(interfaceDofMap.getMatIndex(pressureComponent, it->first)); localIsIndex.push_back(cnt++); } IS globalIs, localIs; ISCreateGeneral(PETSC_COMM_SELF, globalIsIndex.size(), &(globalIsIndex[0]), PETSC_USE_POINTER, &globalIs); ISCreateGeneral(PETSC_COMM_SELF, localIsIndex.size(), &(localIsIndex[0]), PETSC_USE_POINTER, &localIs); Vec local_sol_interface; VecCreateSeq(PETSC_COMM_SELF, localIsIndex.size(), &local_sol_interface); VecScatter interfaceScatter; VecScatterCreate(vecInterface, globalIs, local_sol_interface, localIs, &interfaceScatter); VecScatterBegin(interfaceScatter, vecInterface, local_sol_interface, INSERT_VALUES, SCATTER_FORWARD); VecScatterEnd(interfaceScatter, vecInterface, local_sol_interface, INSERT_VALUES, SCATTER_FORWARD); ISDestroy(&globalIs); ISDestroy(&localIs); VecScatterDestroy(&interfaceScatter); PetscScalar* localSolInterface; VecGetArray(local_sol_interface, &localSolInterface); // === And copy from PETSc local vectors to the DOF vectors. === cnt = 0; DOFVector<double>& dofVec = *(vec.getDOFVector(pressureComponent)); for (DofMap::iterator it = interfaceDofMap[pressureComponent].getMap().begin(); it != interfaceDofMap[pressureComponent].getMap().end(); ++it) { dofVec[it->first] = localSolInterface[cnt++]; } VecRestoreArray(local_sol_interface, &localSolInterface); VecDestroy(&local_sol_interface); } void PetscSolverFeti::fillPetscMatrix(Matrix<DOFMatrix*>* mat) { FUNCNAME("PetscSolverFeti::fillPetscMatrix()"); // === Create all sets and indices. === initialize(); createDirichletData(*mat); createFetiData(); // === Create matrices for the FETI-DP method. === if (printTimings) MPI::COMM_WORLD.Barrier(); double wtime = MPI::Wtime(); subdomain->fillPetscMatrix(mat); // === SUPER TRICK === if (meshLevel == 1) { MSG("START MAT TRICK!\n"); mlSubdomain = new PetscSolverGlobalMatrix(""); mlSubdomain->setSymmetric(isSymmetric); mlSubdomain->setHandleDirichletRows(dirichletMode == 0); mlSubdomain->setMeshDistributor(meshDistributor, meshLevel); mlSubdomain->init(componentSpaces, feSpaces); mlSubdomain->setDofMapping(interiorMap); mlSubdomain->setCoarseSpaceDofMapping(coarseSpaceMap[0]); mlSubdomain->fillPetscMatrix(mat); this->mat = mlSubdomain->getMat(); MSG("END MAT TRICK!\n"); } if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 02: %.5f seconds (creation of interior matrices)\n", MPI::Wtime() - wtime); // For the case, that we want to print the timings, we force the LU // factorization of the local problems to be done here explicitly. wtime = MPI::Wtime(); KSPSetUp(subdomain->getSolver()); KSPSetUpOnBlocks(subdomain->getSolver()); MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 04: %.5f seconds (factorization of subdomain matrices)\n", MPI::Wtime() - wtime); } // === Create matrices for FETI-DP preconditioner. === createPreconditionerMatrix(mat); // === Create and fill PETSc matrix for Lagrange constraints. === createMatLagrange(); // === === createMatAugmentedLagrange(); // === Create PETSc solver for the Schur complement on primal variables. === createSchurPrimalKsp(); // === Create PETSc solver for the FETI-DP operator. === createFetiKsp(); // === If required, run debug tests. === dbgMatrix(mat); } void PetscSolverFeti::fillPetscRhs(SystemVector* vec) { FUNCNAME("PetscSolverFeti::fillPetscRhs()"); subdomain->fillPetscRhs(vec); if (meshLevel == 1) { MSG("START VEC TRICK!\n"); mlSubdomain->fillPetscRhs(vec); this->vecRhs = mlSubdomain->getVecRhs(); MSG("END VEC TRICK!\n"); } } void PetscSolverFeti::createPreconditionerMatrix(Matrix<DOFMatrix*>* mat) { FUNCNAME("PetscSolverFeti::createPreconditionerMatrix()"); if (fetiPreconditioner == FETI_NONE && fetiSolverType == EXACT) return; double wtime = MPI::Wtime(); int nRowsDual = dualDofMap.getRankDofs(); MatCreateSeqAIJ(PETSC_COMM_SELF, nRowsDual, nRowsDual, 100, PETSC_NULL, &mat_duals_duals); MatSetOption(mat_duals_duals, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); if (fetiPreconditioner == FETI_DIRICHLET) { int nRowsInterior = interiorDofMap.getRankDofs(); MatCreateSeqAIJ(PETSC_COMM_SELF, nRowsInterior, nRowsInterior, 100, PETSC_NULL, &mat_interior_interior); MatSetOption(mat_interior_interior, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); MatCreateSeqAIJ(PETSC_COMM_SELF, nRowsInterior, nRowsDual, 100, PETSC_NULL, &mat_interior_duals); MatSetOption(mat_interior_duals, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); MatCreateSeqAIJ(PETSC_COMM_SELF, nRowsDual, nRowsInterior, 100, PETSC_NULL, &mat_duals_interior); MatSetOption(mat_duals_interior, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); } // === Prepare traverse of sequentially created matrices. === using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end; namespace traits = mtl::traits; typedef DOFMatrix::base_matrix_type Matrix; typedef traits::range_generator<row, Matrix>::type cursor_type; typedef traits::range_generator<nz, cursor_type>::type icursor_type; vector<int> colsLocal, colsLocalOther; vector<double> valuesLocal, valuesLocalOther; colsLocal.reserve(300); colsLocalOther.reserve(300); valuesLocal.reserve(300); valuesLocalOther.reserve(300); // === Traverse all sequentially created matrices and add the values to === // === the global PETSc matrices. === int nComponents = mat->getSize(); for (int rowComponent = 0; rowComponent < nComponents; rowComponent++) { for (int colComponent = 0; colComponent < nComponents; colComponent++) { DOFMatrix* dofMat = (*mat)[rowComponent][colComponent]; if (!dofMat) continue; TEST_EXIT_DBG(dofMat->getRowFeSpace() == componentSpaces[rowComponent]) ("Wrong matrix row FE space!\n"); TEST_EXIT_DBG(dofMat->getColFeSpace() == componentSpaces[colComponent]) ("Wrong matrix col FE space!!\n"); if (stokesMode && (rowComponent == pressureComponent || colComponent == pressureComponent)) continue; // const FiniteElemSpace *rowFeSpace = dofMat->getRowFeSpace(); // const FiniteElemSpace *colFeSpace = dofMat->getColFeSpace(); traits::col<Matrix>::type col(dofMat->getBaseMatrix()); traits::const_value<Matrix>::type value(dofMat->getBaseMatrix()); // Traverse all rows. for (cursor_type cursor = begin<row>(dofMat->getBaseMatrix()), cend = end<row>(dofMat->getBaseMatrix()); cursor != cend; ++cursor) { if (dirichletRows[rowComponent].count(cursor.value())) continue; if (isPrimal(rowComponent, cursor.value())) continue; if (fetiPreconditioner == FETI_DIRICHLET) { colsLocal.clear(); colsLocalOther.clear(); valuesLocal.clear(); valuesLocalOther.clear(); // Traverse all columns. for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); icursor != icend; ++icursor) { if (dirichletRows[colComponent].count(col(*icursor))) continue; if (isPrimal(colComponent, col(*icursor))) continue; if (!isDual(rowComponent, cursor.value())) { if (!isDual(colComponent, col(*icursor))) { int colIndex = interiorDofMap.getLocalMatIndex(colComponent, col(*icursor)); colsLocal.push_back(colIndex); valuesLocal.push_back(value(*icursor)); } else { int colIndex = dualDofMap.getLocalMatIndex(colComponent, col(*icursor)); colsLocalOther.push_back(colIndex); valuesLocalOther.push_back(value(*icursor)); } } else { if (!isDual(colComponent, col(*icursor))) { int colIndex = interiorDofMap.getLocalMatIndex(colComponent, col(*icursor)); colsLocalOther.push_back(colIndex); valuesLocalOther.push_back(value(*icursor)); } else { int colIndex = dualDofMap.getLocalMatIndex(colComponent, col(*icursor)); colsLocal.push_back(colIndex); valuesLocal.push_back(value(*icursor)); } } } // for each nnz in row if (!isDual(rowComponent, cursor.value())) { int rowIndex = interiorDofMap.getLocalMatIndex(rowComponent, cursor.value()); MatSetValues(mat_interior_interior, 1, &rowIndex, colsLocal.size(), &(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES); if (colsLocalOther.size()) MatSetValues(mat_interior_duals, 1, &rowIndex, colsLocalOther.size(), &(colsLocalOther[0]), &(valuesLocalOther[0]), INSERT_VALUES); } else { int rowIndex = dualDofMap.getLocalMatIndex(rowComponent, cursor.value()); MatSetValues(mat_duals_duals, 1, &rowIndex, colsLocal.size(), &(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES); if (colsLocalOther.size()) MatSetValues(mat_duals_interior, 1, &rowIndex, colsLocalOther.size(), &(colsLocalOther[0]), &(valuesLocalOther[0]), INSERT_VALUES); } } if (fetiPreconditioner == FETI_LUMPED || fetiSolverType == INEXACT) { if (!isDual(rowComponent, cursor.value())) continue; colsLocal.clear(); valuesLocal.clear(); // Traverse all columns. for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); icursor != icend; ++icursor) { if (dirichletRows[colComponent].count(col(*icursor))) continue; if (!isDual(colComponent, col(*icursor))) continue; int colIndex = dualDofMap.getLocalMatIndex(colComponent, col(*icursor)); colsLocal.push_back(colIndex); valuesLocal.push_back(value(*icursor)); } int rowIndex = dualDofMap.getLocalMatIndex(rowComponent, cursor.value()); MatSetValues(mat_duals_duals, 1, &rowIndex, colsLocal.size(), &(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES); } } } } // === Start global assembly procedure for preconditioner matrices. === if (fetiPreconditioner == FETI_LUMPED || fetiSolverType == INEXACT) { MatAssemblyBegin(mat_duals_duals, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_duals_duals, MAT_FINAL_ASSEMBLY); } if (fetiPreconditioner == FETI_DIRICHLET) { MatAssemblyBegin(mat_interior_interior, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_interior_interior, MAT_FINAL_ASSEMBLY); MatAssemblyBegin(mat_duals_duals, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_duals_duals, MAT_FINAL_ASSEMBLY); MatAssemblyBegin(mat_interior_duals, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_interior_duals, MAT_FINAL_ASSEMBLY); MatAssemblyBegin(mat_duals_interior, MAT_FINAL_ASSEMBLY); MatAssemblyEnd(mat_duals_interior, MAT_FINAL_ASSEMBLY); } if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 03: %.5f seconds (creation of preconditioner matrices)\n", MPI::Wtime() - wtime); } } void PetscSolverFeti::solveFeti(Vec& rhsInterior, Vec& rhsCoarse, Vec& solInterior, Vec& solCoarse) { FUNCNAME("PetscSolverFeti::solveFeti()"); switch (fetiSolverType) { case EXACT: solveFetiExact(rhsInterior, rhsCoarse, solInterior, solCoarse); break; case INEXACT: solveFetiInexact(rhsInterior, rhsCoarse, solInterior, solCoarse); break; case INEXACT_REDUCED: solveFetiInexactReduced(rhsInterior, rhsCoarse, solInterior, solCoarse); break; default: ERROR_EXIT("Should not happen!\n"); } } void PetscSolverFeti::solveFetiExact(Vec& rhsInterior, Vec& rhsCoarse, Vec& solInterior, Vec& solCoarse) { FUNCNAME("PetscSolverFeti::solveFetiExact()"); // === Some temporary vectors. === Vec tmp_b1; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &tmp_b1); Vec tmp_primal1; createVec(primalDofMap, tmp_primal1); Vec tmp_lagrange; MatGetVecs(mat_lagrange, PETSC_NULL, &tmp_lagrange); // === Create RHS and solution vectors. === Vec vecRhs, vecSol; Vec vecRhsLagrange, vecSolLagrange; MatGetVecs(mat_lagrange, PETSC_NULL, &vecRhsLagrange); MatGetVecs(mat_lagrange, PETSC_NULL, &vecSolLagrange); vecRhs = vecRhsLagrange; vecSol = vecSolLagrange; VecDuplicate(vecSol, &fetiKspData.draft); // === Create reduced RHS === double wtime = MPI::Wtime(); // d = L inv(K_BB) f_B - L inv(K_BB) K_BPi inv(S_PiPi) [f_Pi - K_PiB inv(K_BB) f_B] // vecRhs = L * inv(K_BB) * f_B subdomain->solveGlobal(rhsInterior, solInterior); MatMult(mat_lagrange, solInterior, vecRhsLagrange); // solCoarse = M_PiB * inv(K_BB) * f_B MatMult(subdomain->getMatCoarseInterior(), solInterior, solCoarse); // solCoarse = f_Pi - M_PiB * inv(K_BB) * f_B VecAXPBY(solCoarse, 1.0, -1.0, rhsCoarse); double wtime2 = MPI::Wtime(); // solCoarse = inv(S_PiPi) (f_Pi - M_PiB * inv(K_BB) * f_B) KSPSolve(ksp_schur_primal, solCoarse, solCoarse); if (printTimings) { MSG("FETI-DP timing 09a: %.5f seconds (create rhs vector)\n", MPI::Wtime() - wtime2); } MatMult(subdomain->getMatInteriorCoarse(), solCoarse, solInterior); subdomain->solveGlobal(solInterior, solInterior); MatMult(mat_lagrange, solInterior, tmp_lagrange); VecAXPY(vecRhsLagrange, -1.0, tmp_lagrange); if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 09: %.5f seconds (create rhs vector)\n", MPI::Wtime() - wtime); wtime = MPI::Wtime(); FetiTimings::reset(); } // === Optionally run some debug procedures on the FETI-DP system. === PetscSolverFetiDebug::debugFeti(*this, vecRhs); // === Solve with FETI-DP operator. === KSPSolve(ksp_feti, vecRhs, vecSol); if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 10: %.5f seconds (application of FETI-DP operator)\n", MPI::Wtime() - wtime); wtime = MPI::Wtime(); MSG("FETI-DP timing 10a: %.5f [ %.5f %.5f ] seconds (FETI-DP KSP Solve)\n", FetiTimings::fetiSolve, FetiTimings::fetiSolve01, FetiTimings::fetiSolve02); MSG("FETI-DP timing 10b: %.5f seconds (FETI-DP KSP Solve)\n", FetiTimings::fetiPreconditioner); } // === Solve for u_primals. === MatMultTranspose(mat_lagrange, vecSol, solInterior); VecAYPX(solInterior, -1.0, rhsInterior); subdomain->solveGlobal(solInterior, tmp_b1); MatMult(subdomain->getMatCoarseInterior(), tmp_b1, solCoarse); VecAYPX(solCoarse, -1.0, rhsCoarse); KSPSolve(ksp_schur_primal, solCoarse, solCoarse); // === Solve for u_b. === MatMult(subdomain->getMatInteriorCoarse(), solCoarse, tmp_b1); VecAXPY(solInterior, -1.0, tmp_b1); subdomain->solveGlobal(solInterior, solInterior); // === Print timings and delete data. === if (printTimings) { MPI::COMM_WORLD.Barrier(); MSG("FETI-DP timing 11: %.5f seconds (Inner solve and solution recovery)\n", MPI::Wtime() - wtime); } VecDestroy(&vecRhs); VecDestroy(&vecSol); VecDestroy(&tmp_b1); VecDestroy(&tmp_lagrange); VecDestroy(&tmp_primal1); } void PetscSolverFeti::solveFetiInexact(Vec& rhsInterior, Vec& rhsCoarse, Vec& solInterior, Vec& solCoarse) { FUNCNAME("PetscSolverFeti::solveFetiInexact()"); Vec tmpLagrange0, tmpLagrange1; createVec(lagrangeMap, tmpLagrange0); createVec(lagrangeMap, tmpLagrange1); VecSet(tmpLagrange0, 0.0); VecSet(tmpLagrange1, 0.0); Vec nestVecRhs[3]; nestVecRhs[0] = rhsInterior; nestVecRhs[1] = rhsCoarse; nestVecRhs[2] = tmpLagrange0; Vec nestVecSol[3]; nestVecSol[0] = solInterior; nestVecSol[1] = solCoarse; nestVecSol[2] = tmpLagrange1; Vec vecRhs, vecSol; VecCreateNest(domainComm, 3, PETSC_NULL, nestVecRhs, &vecRhs); VecCreateNest(domainComm, 3, PETSC_NULL, nestVecSol, &vecSol); KSPSolve(ksp_feti, vecRhs, vecSol); VecDestroy(&vecRhs); VecDestroy(&vecSol); VecDestroy(&tmpLagrange0); VecDestroy(&tmpLagrange1); } void PetscSolverFeti::solveFetiInexactReduced(Vec& rhsInterior, Vec& rhsCoarse, Vec& solInterior, Vec& solCoarse) { FUNCNAME("PetscSolverFeti::solveFetiInexactReduced()"); ERROR_EXIT("Not yet implemented!\n"); } void PetscSolverFeti::destroyMatrixData() { FUNCNAME("PetscSolverFeti::destroyMatrixData()"); MatDestroy(&mat_lagrange); if (augmentedLagrange) MatDestroy(&mat_augmented_lagrange); // === Destroy preconditioner data structures. === if (fetiPreconditioner != FETI_NONE) MatDestroy(&mat_duals_duals); if (fetiPreconditioner == FETI_DIRICHLET) { MatDestroy(&mat_interior_interior); MatDestroy(&mat_interior_duals); MatDestroy(&mat_duals_interior); } destroySchurPrimalKsp(); destroyFetiKsp(); subdomain->destroyMatrixData(); } void PetscSolverFeti::destroyVectorData() { FUNCNAME("PetscSolverFeti::destroyVectorData()"); subdomain->destroyVectorData(); } void PetscSolverFeti::solvePetscMatrix(SystemVector& vec, AdaptInfo& adaptInfo) { FUNCNAME("PetscSolverFeti::solvePetscMatrix()"); Vec solInterior; VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel), localDofMap.getRankDofs(), nGlobalOverallInterior, &solInterior); Vec solCoarse; createVec(primalDofMap, solCoarse); solveFeti(subdomain->getVecRhsInterior(), subdomain->getVecRhsCoarse(), solInterior, solCoarse); // === And recover AMDiS solution vectors. === recoverSolution(solInterior, solCoarse, vec); VecDestroy(&solInterior); VecDestroy(&solCoarse); MeshDistributor::globalMeshDistributor->synchVector(vec); } void PetscSolverFeti::solveGlobal(Vec& rhs, Vec& sol) { FUNCNAME("PetscSolverFeti::solveGlobal()"); Vec rhsInterior, rhsCoarse, solInterior, solCoarse; VecCreateMPI(domainComm, localDofMap.getRankDofs(), nGlobalOverallInterior, &rhsInterior); createVec(primalDofMap, rhsCoarse); VecDuplicate(rhsInterior, &solInterior); VecDuplicate(rhsCoarse, &solCoarse); int offset = 0; { int domainLocal = 0, nSuperLocal = 0; if (domainComm.Get_rank() == 0) domainLocal = interiorMap->getOverallDofs(); mpi::getDofNumbering(meshDistributor->getMpiComm(meshLevel - 1), domainLocal, offset, nSuperLocal); int tmp = 0; if (domainComm.Get_rank() == 0) tmp = offset; domainComm.Allreduce(&tmp, &offset, 1, MPI_INT, MPI_SUM); } vector<int> localFromRhs, coarseFromRhs; vector<int> rhsToLocal, rhsToCoarse; int nComponents = componentSpaces.size(); for (int i = 0; i < nComponents; i++) { DofMap& dMap = localDofMap[i].getMap(); for (DofMap::iterator it = dMap.begin(); it != dMap.end(); ++it) { int matL = localDofMap.getMatIndex(i, it->first) + rStartInterior; int matI = interiorMap->getMatIndex(i, it->first) + offset; localFromRhs.push_back(matL); rhsToLocal.push_back(matI); } } for (int i = 0; i < nComponents; i++) { DofMap& dMap = primalDofMap[i].getMap(); for (DofMap::iterator it = dMap.begin(); it != dMap.end(); ++it) { int matL = primalDofMap.getMatIndex(i, it->first); int matI = interiorMap->getMatIndex(i, it->first) + offset; coarseFromRhs.push_back(matL); rhsToCoarse.push_back(matI); } } copyVec(rhs, rhsInterior, rhsToLocal, localFromRhs); copyVec(rhs, rhsCoarse, rhsToCoarse, coarseFromRhs); solveFeti(rhsInterior, rhsCoarse, solInterior, solCoarse); copyVec(solInterior, sol, localFromRhs, rhsToLocal); copyVec(solCoarse, sol, coarseFromRhs, rhsToCoarse); MPI::COMM_WORLD.Barrier(); VecDestroy(&rhsInterior); VecDestroy(&rhsCoarse); VecDestroy(&solInterior); VecDestroy(&solCoarse); } } } // end namespaces
33.683502
121
0.602279
spraetor
4ec90784fc25d0c39dc37fc4151197064263ad21
1,130
cpp
C++
Redline/Renderer/BRDF/CookTorrence/Functions/GGX_Geometry.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
1
2019-02-03T04:47:21.000Z
2019-02-03T04:47:21.000Z
Redline/Renderer/BRDF/CookTorrence/Functions/GGX_Geometry.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
null
null
null
Redline/Renderer/BRDF/CookTorrence/Functions/GGX_Geometry.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "GGX_Geometry.h" using namespace mathfu; using namespace Redline; using namespace CookTorrenceBRDF; float GGX_Geometry::Geometry( const vec3& incommingAngle, const vec3& outgoingAngle, const vec3& normal, const vec3& halfAngle, float roughness) const { const float incomming = GGX_Geometry_Partial( incommingAngle, normal, halfAngle, roughness ); const float outgoing = GGX_Geometry_Partial( outgoingAngle, normal, halfAngle, roughness ); return incomming * outgoing; } float GGX_Geometry::GGX_Geometry_Partial( const vec3& incidentAngle, const vec3& normal, const vec3& halfAngle, float roughness) const { const float VoH = Saturate(vec3::DotProduct(incidentAngle, halfAngle)); const float VoN = Saturate(vec3::DotProduct(incidentAngle, normal)); const float chi = (VoH / VoN); if(chi <= 0.0f) { return 0.0f; } const float VoH2 = VoH * VoH; const float a2 = roughness * roughness; const float tan2 = (1.0f - VoH2) / VoH2; const float num = 2.0f * VoN; const float denom = (VoN + sqrt(a2 + (1.0f - a2) * VoN*VoN)); return Saturate(num / denom); }
19.824561
72
0.717699
64-bit
4eca6a6280a9c00c8567b67e506ae22dc21604c6
13,055
cpp
C++
src/UIController.cpp
nselikoff/Cinder-MinimalUI
f5ace74b8e514a372869d7211e5d76122d573241
[ "MIT" ]
6
2015-03-12T12:33:49.000Z
2018-04-20T18:30:28.000Z
src/UIController.cpp
nselikoff/Cinder-MinimalUI
f5ace74b8e514a372869d7211e5d76122d573241
[ "MIT" ]
null
null
null
src/UIController.cpp
nselikoff/Cinder-MinimalUI
f5ace74b8e514a372869d7211e5d76122d573241
[ "MIT" ]
3
2020-04-20T21:34:16.000Z
2020-05-06T19:24:42.000Z
#include "UIController.h" #include "UIElement.h" #include "Slider.h" #include "Button.h" #include "Label.h" #include "Image.h" #include "Graph.h" using namespace ci; using namespace ci::app; using namespace std; using namespace MinimalUI; class FontStyleExc; int UIController::DEFAULT_PANEL_WIDTH = 216; int UIController::DEFAULT_MARGIN_LARGE = 10; int UIController::DEFAULT_MARGIN_SMALL = 4; int UIController::DEFAULT_UPDATE_FREQUENCY = 2; int UIController::DEFAULT_FBO_WIDTH = 2048; ci::ColorA UIController::DEFAULT_STROKE_COLOR = ci::ColorA( 0.07f, 0.26f, 0.29f, 1.0f ); ci::ColorA UIController::ACTIVE_STROKE_COLOR = ci::ColorA( 0.19f, 0.66f, 0.71f, 1.0f ); ci::ColorA UIController::DEFAULT_NAME_COLOR = ci::ColorA( 0.14f, 0.49f, 0.54f, 1.0f ); ci::ColorA UIController::DEFAULT_BACKGROUND_COLOR = ci::ColorA( 0.0f, 0.0f, 0.0f, 1.0f ); UIController::UIController( app::WindowRef aWindow, const string &aParamString ) : mWindow( aWindow ), mParamString( aParamString ) { JsonTree params( mParamString ); mVisible = params.hasChild( "visible" ) ? params["visible"].getValue<bool>() : true; mAlpha = mVisible ? 1.0f : 0.0f; mWidth = params.hasChild( "width" ) ? params["width"].getValue<int>() : DEFAULT_PANEL_WIDTH; mX = params.hasChild( "x" ) ? params["x"].getValue<int>() : 0; mY = params.hasChild( "y" ) ? params["y"].getValue<int>() : 0; if ( params.hasChild( "height" ) ) { mHeightSpecified = true; mHeight = params["height"].getValue<int>(); } else { mHeightSpecified = false; mHeight = getWindow()->getHeight(); } mCentered = params.hasChild( "centered" ) ? params["centered"].getValue<bool>() : false; mDepth = params.hasChild( "depth" ) ? params["depth"].getValue<int>() : 0; mForceInteraction = params.hasChild( "forceInteraction" ) ? params["forceInteraction"].getValue<bool>() : false; mMarginLarge = params.hasChild( "marginLarge" ) ? params["marginLarge"].getValue<int>() : DEFAULT_MARGIN_LARGE; // JSON doesn't support hex literals... std::stringstream str; string panelColor = params.hasChild( "panelColor" ) ? params["panelColor"].getValue<string>() : "0xCC000000"; str << panelColor; uint32_t hexValue; str >> std::hex >> hexValue; mPanelColor = ColorA::hexA( hexValue ); if ( params.hasChild( "defaultStrokeColor" ) ) { string strValue = params["defaultStrokeColor"].getValue<string>(); str.clear(); str << strValue; str >> std::hex >> hexValue; UIController::DEFAULT_STROKE_COLOR = ColorA::hexA( hexValue ); } if ( params.hasChild( "activeStrokeColor" ) ) { string strValue = params["activeStrokeColor"].getValue<string>(); str.clear(); str << strValue; str >> std::hex >> hexValue; UIController::ACTIVE_STROKE_COLOR = ColorA::hexA( hexValue ); } if ( params.hasChild( "defaultNameColor" ) ) { string strValue = params["defaultNameColor"].getValue<string>(); str.clear(); str << strValue; str >> std::hex >> hexValue; UIController::DEFAULT_NAME_COLOR = ColorA::hexA( hexValue ); } if ( params.hasChild( "defaultBackgroundColor" ) ) { string strValue = params["defaultBackgroundColor"].getValue<string>(); str.clear(); str << strValue; str >> std::hex >> hexValue; UIController::DEFAULT_BACKGROUND_COLOR = ColorA::hexA( hexValue ); } resize(); mCbMouseDown = mWindow->getSignalMouseDown().connect( mDepth + 99, std::bind( &UIController::mouseDown, this, std::placeholders::_1 ) ); // set default fonts setFont( "label", Font( "Arial", 16 * 2 ) ); setFont( "smallLabel", Font( "Arial", 12 * 2 ) ); setFont( "icon", Font( "Arial", 22 * 2 ) ); setFont( "header", Font( "Arial", 48 * 2 ) ); setFont( "body", Font( "Arial", 19 * 2 ) ); setFont( "footer", Font( "Arial Italic", 14 * 2 ) ); mInsertPosition = Vec2i( mMarginLarge, mMarginLarge ); mFboNumSamples = params.hasChild( "fboNumSamples" ) ? params["fboNumSamples"].getValue<int>() : 0; if (params.hasChild("backgroundImage")) { mBackgroundTexture = gl::Texture(loadImage(loadAsset(params["backgroundImage"].getValue<string>()))); } setupFbo(); } UIControllerRef UIController::create( const string &aParamString, app::WindowRef aWindow ) { return shared_ptr<UIController>( new UIController( aWindow, aParamString ) ); } void UIController::resize() { Vec2i size; if ( mCentered ) { size = Vec2i( mWidth, mHeight ); mPosition = getWindow()->getCenter() - size / 2; } else if ( mHeightSpecified ) { size = Vec2i( mWidth, mHeight ); mPosition = Vec2i( mX, mY ); } else { size = Vec2i( mWidth, getWindow()->getHeight() ); mPosition = Vec2i( mX, mY ); } mBounds = Area( Vec2i::zero(), size ); } void UIController::mouseDown( MouseEvent &event ) { if ( mVisible ) { if ( (mBounds + mPosition).contains( event.getPos() ) || mForceInteraction ) { event.setHandled(); } } } void UIController::drawBackground() { gl::pushMatrices(); gl::color(Color::white()); // draw the background texture if it's defined if (mBackgroundTexture) gl::draw(mBackgroundTexture, mBounds); gl::popMatrices(); } void UIController::draw() { if (!mVisible) return; // save state gl::pushMatrices(); glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_LINE_BIT | GL_CURRENT_BIT); // disable depth read (otherwise any 3d drawing done after this will be obscured by the FBO; not exactly sure why) gl::disableDepthRead(); // optimization if (getElapsedFrames() % DEFAULT_UPDATE_FREQUENCY == 0) { // start drawing to the Fbo mFbo.bindFramebuffer(); gl::lineWidth(toPixels(2.0f)); gl::enable(GL_LINE_SMOOTH); gl::enableAlphaBlending(); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // clear and set viewport and matrices gl::clear(ColorA(0.0f, 0.0f, 0.0f, 0.0f)); gl::setViewport(toPixels(mBounds + mPosition)); gl::setMatricesWindow(toPixels(mBounds.getSize()), false); // draw backing panel gl::color(mPanelColor); gl::drawSolidRect(toPixels(mBounds)); // draw the background drawBackground(); // draw elements for (unsigned int i = 0; i < mUIElements.size(); i++) { mUIElements[i]->draw(); } // finish drawing to the Fbo mFbo.unbindFramebuffer(); } // reset the matrices and blending gl::setViewport( toPixels( getWindow()->getBounds() ) ); gl::setMatricesWindow( toPixels( getWindow()->getSize() ) ); gl::enableAlphaBlending( true ); // if forcing interaction, draw an overlay over the whole window if ( mForceInteraction ) { gl::color(ColorA( 0.0f, 0.0f, 0.0f, 0.5f * mAlpha)); gl::drawSolidRect( toPixels( getWindow()->getBounds() ) ); } // draw the FBO to the screen gl::color( ColorA( mAlpha, mAlpha, mAlpha, mAlpha ) ); gl::draw( mFbo.getTexture() ); gl::disableAlphaBlending(); // restore state glPopAttrib(); gl::popMatrices(); } void UIController::update() { if ( !mVisible ) return; if ( getElapsedFrames() % DEFAULT_UPDATE_FREQUENCY == 0 ) { for (unsigned int i = 0; i < mUIElements.size(); i++) { mUIElements[i]->update(); } } } void UIController::show() { mVisible = true; timeline().apply( &mAlpha, 1.0f, 0.25f ); } void UIController::hide() { timeline().apply( &mAlpha, 0.0f, 0.25f ).finishFn( [&]{ mVisible = false; } ); } UIElementRef UIController::addSlider( const string &aName, float *aValueToLink, const string &aParamString ) { UIElementRef sliderRef = Slider::create( this, aName, aValueToLink, aParamString ); addElement( sliderRef ); return sliderRef; } UIElementRef UIController::addButton( const string &aName, const function<void( bool )> &aEventHandler, const string &aParamString ) { UIElementRef buttonRef = Button::create( this, aName, aEventHandler, aParamString ); addElement( buttonRef ); return buttonRef; } UIElementRef UIController::addLinkedButton( const string &aName, const function<void( bool )> &aEventHandler, bool *aLinkedState, const string &aParamString ) { UIElementRef linkedButtonRef = LinkedButton::create( this, aName, aEventHandler, aLinkedState, aParamString ); addElement( linkedButtonRef ); return linkedButtonRef; } UIElementRef UIController::addLabel( const string &aName, const string &aParamString ) { UIElementRef labelRef = Label::create( this, aName, aParamString ); addElement( labelRef ); return labelRef; } UIElementRef UIController::addImage( const string &aName, ImageSourceRef aImage, const string &aParamString ) { UIElementRef imageRef = Image::create( this, aName, aImage, aParamString ); addElement( imageRef ); return imageRef; } UIElementRef UIController::addSlider2D( const string &aName, Vec2f *aValueToLink, const string &aParamString ) { UIElementRef slider2DRef = Slider2D::create( this, aName, aValueToLink, aParamString ); addElement( slider2DRef ); return slider2DRef; } UIElementRef UIController::addSliderCallback( const std::string &aName, float *aValueToLink, const std::function<void ()> &aEventHandler, const std::string &aParamString ) { UIElementRef sliderCallbackRef = SliderCallback::create( this, aName, aValueToLink, aEventHandler, aParamString ); addElement( sliderCallbackRef ); return sliderCallbackRef; } UIElementRef UIController::addToggleSlider( const string &aSliderName, float *aValueToLink, const string &aButtonName, const function<void (bool)> &aEventHandler, const string &aSliderParamString, const string &aButtonParamString ) { // create the slider UIElementRef toggleSliderRef = Slider::create( this, aSliderName, aValueToLink, aSliderParamString ); // add the slider to the controller addElement( toggleSliderRef ); // create the button UIElementRef newButtonRef = Button::create( this, aButtonName, aEventHandler, aButtonParamString ); // add an additional event handler to link the button to the slider std::shared_ptr<class Button> newButton = std::static_pointer_cast<class Button>(newButtonRef); newButton->addEventHandler( std::bind(&Slider::setLocked, toggleSliderRef, std::placeholders::_1 ) ); // add the button to the controller addElement( newButton ); return toggleSliderRef; } // without event handler UIElementRef UIController::addMovingGraph(const string &aName, float *aValueToLink, const string &aParamString) { UIElementRef movingGraphRef = MovingGraph::create(this, aName, aValueToLink, aParamString); addElement(movingGraphRef); return movingGraphRef; } // with event handler // note: this would be an overloaded addMovingGraph function for consistency, were it not for a visual studio compiler defect (see http://cplusplus.github.io/LWG/lwg-active.html#2132) UIElementRef UIController::addMovingGraphButton(const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString) { UIElementRef movingGraphRef = MovingGraph::create(this, aName, aValueToLink, aEventHandler, aParamString); addElement(movingGraphRef); return movingGraphRef; } void UIController::releaseGroup( const string &aGroup ) { for (unsigned int i = 0; i < mUIElements.size(); i++) { if (mUIElements[i]->getGroup() == aGroup ) { mUIElements[i]->release(); } } } void UIController::selectGroupElementByName(const std::string &aGroup, const std::string &aName) { for (unsigned int i = 0; i < mUIElements.size(); i++) { if ( mUIElements[i]->getGroup() == aGroup ) { if ( mUIElements[i]->getName() == aName ) { mUIElements[i]->press(); } else { mUIElements[i]->release(); } } } } void UIController::setLockedByGroup( const std::string &aGroup, const bool &locked ) { for (unsigned int i = 0; i < mUIElements.size(); i++) { if (mUIElements[i]->getGroup() == aGroup ) { mUIElements[i]->setLocked( locked ); } } } void UIController::setPressedByGroup( const std::string &aGroup, const bool &pressed ) { for (unsigned int i = 0; i < mUIElements.size(); i++) { if (mUIElements[i]->getGroup() == aGroup ) { pressed ? mUIElements[i]->press() : mUIElements[i]->release(); } } } Font UIController::getFont( const string &aStyle ) { if ( aStyle == "label" ) { return mLabelFont; } else if ( aStyle == "icon" ) { return mIconFont; } else if ( aStyle == "header" ) { return mHeaderFont; } else if ( aStyle == "body" ) { return mBodyFont; } else if ( aStyle == "footer" ) { return mFooterFont; } else if ( aStyle == "smallLabel" ) { return mSmallLabelFont; } else { throw FontStyleExc( aStyle ); } } void UIController::setFont( const string &aStyle, const ci::Font &aFont ) { if ( aStyle == "label" ) { mLabelFont = aFont; } else if ( aStyle == "icon" ) { mIconFont = aFont; } else if ( aStyle == "header" ) { mHeaderFont = aFont; } else if ( aStyle == "body" ) { mBodyFont = aFont; } else if ( aStyle == "footer" ) { mFooterFont = aFont; } else if ( aStyle == "smallLabel" ) { mSmallLabelFont = aFont; } else { throw FontStyleExc( aStyle ); } } void UIController::setupFbo() { mFormat.enableDepthBuffer( false ); mFormat.setSamples( mFboNumSamples ); mFbo = gl::Fbo( DEFAULT_FBO_WIDTH, DEFAULT_FBO_WIDTH, mFormat ); mFbo.bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); mFbo.unbindFramebuffer(); }
31.841463
231
0.704175
nselikoff
4ecd712da91a3780130429066135de39eddafd50
5,766
cc
C++
sg_agent/test/naming_registry_strategy_unittest.cc
wuxianxingkong/octo-ns
2833e7517472d5b9655d4b6c031c12f7054cf984
[ "Apache-2.0" ]
324
2018-12-20T11:16:10.000Z
2022-03-11T14:02:13.000Z
sg_agent/test/naming_registry_strategy_unittest.cc
wuxianxingkong/octo-ns
2833e7517472d5b9655d4b6c031c12f7054cf984
[ "Apache-2.0" ]
18
2019-08-09T02:00:51.000Z
2021-12-14T21:16:35.000Z
sg_agent/test/naming_registry_strategy_unittest.cc
wuxianxingkong/octo-ns
2833e7517472d5b9655d4b6c031c12f7054cf984
[ "Apache-2.0" ]
84
2018-12-20T10:52:41.000Z
2022-03-23T07:25:18.000Z
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * 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. */ #include "config_loader.h" #include <gtest/gtest.h> #include "base_errors_consts.h" #include "registry_service.h" #include "base_mns_consts.h" #define private public #define protected public #include "../mns/registry_strategy.h" #undef private #undef protected using namespace meituan_mns; class RegistryStrategyTest : public testing::Test { public: void SetUp() { node.__set_appkey("octo.naming.service.yangjie"); node.__set_protocol("thrift"); node.__set_envir(1); node.__set_version("chrion_test"); node.__set_fweight(10.0); node.__set_weight(10); node.__set_status(2); node1.__set_appkey("octo.naming.service.yangjie"); node1.__set_protocol("thrift"); node1.__set_envir(1); node1.__set_version("chrion_test"); node1.__set_fweight(10.0); node1.__set_weight(10); node1.__set_status(2); register_service_ = RegistryService::GetInstance(); } public: SGService node; SGService node1; CXmlFile cxml_file_; RegistryService *register_service_; RegistryStrategy register_strategy_; }; #if 0 TEST_F(RegistryStrategyTest, zkNodeNotExist) { } //测试加载 TEST_F(RegistryStrategyTest, registryInfoLoad) { cxml_file_.CXmlFileInit(); } //测试 TEST_F(RegistryStrategyTest, hotelRegistryTest) { int port = 10086; std::string cell = "test"; node.__set_ip("127.0.0.1); node.__set_port(port); std::cout<<"the test registry"<<std::endl; EXPECT_EQ(SUCCESS, register_service_->RegistryStart(node, 1)); } TEST_F(RegistryStrategyTest, IsAllowedRegistryTest) { EXPECT_EQ(0, register_strategy_.IsAllowedRegistry(node)); node.__set_appkey(""); EXPECT_EQ(ERR_EMPTY_APPKEY, register_strategy_.IsAllowedRegistry(node)); node.__set_appkey("octo.naming.travel.dsg.crmtag"); EXPECT_EQ(-1, register_strategy_.IsAllowedRegistry(node)); node.__set_appkey("test-benchmark-web");//双框架appkey EXPECT_EQ(-1, register_strategy_.IsAllowedRegistry(node)); } TEST_F(RegistryStrategyTest, IsRepeatedRegisterTest) { EXPECT_TRUE(register_strategy_.IsRepeatedRegister(node,node1,UptCmd::ADD)); } TEST_F(RegistryStrategyTest, CheckAllowedProtocolRegistryTest) { node.__set_protocol("thrift"); EXPECT_EQ(0, register_strategy_.CheckAllowedProtocolRegistry(node)); node.__set_protocol("http"); EXPECT_EQ(0, register_strategy_.CheckAllowedProtocolRegistry(node)); node.__set_protocol("unknown"); EXPECT_EQ(-1, register_strategy_.CheckAllowedProtocolRegistry(node)); } TEST_F(RegistryStrategyTest, CheckArgsTest) { node._set_appkey(""); EXPECT_EQ(-1, register_strategy_.CheckArgs(node)); node.__set_appkey("octo.naming.~.)");//非法字符的appkey EXPECT_EQ(-1, register_strategy_.CheckArgs(node)); } TEST_F(RegistryStrategyTest, CheckArgsTest1) { node.__set_weight(-1); EXPECT_EQ(ERR_INVALID_WEIGHT, register_strategy_.CheckArgs(node)); } TEST_F(RegistryStrategyTest, CheckArgsTest2) { node.__set_fweight(-1); EXPECT_EQ(ERR_INVALID_WEIGHT, register_strategy_.CheckArgs(node)); } TEST_F(RegistryStrategyTest, CheckArgsTest3) { node.__set_ip("10.4"); EXPECT_EQ(ERR_INVALID_PORT, register_strategy_.CheckArgs(node)); } TEST_F(RegistryStrategyTest, CheckArgsTest3) { node.__set_port(-1); EXPECT_EQ(ERR_INVALID_PORT, register_strategy_.CheckArgs(node)); } TEST_F(RegistryStrategyTest, IsAllowMacRegisterTest) { CXmlFile::GetAppenv()->SetTypeEnv(Appenv::DEV); node.__set_appkey("octo.naming.travel.dsg.trace"); EXPECT_TRUE(register_strategy_.IsAllowMacRegister(node)); } TEST_F(RegistryStrategyTest, IsAllowMacRegisterTest1) { CXmlFile::GetAppenv()->SetTypeEnv(Appenv::TEST); EXPECT_TRUE(register_strategy_.IsAllowMacRegister(node)); } TEST_F(RegistryStrategyTest, IsAllowMacRegisterTest2) { CXmlFile::GetAppenv()->SetTypeEnv(Appenv::TEST); node.__set_appkey("octo.naming.travel.dsg.trace"); EXPECT_TRUE(register_strategy_.IsAllowMacRegister(node)); } TEST_F(RegistryStrategyTest, RegistryFilterByCacheTest) { EXPECT_EQ(0, register_strategy_.RegistryFilterByCache(node)); node.__set_appkey("test-benchmark-web");//双框架appkey EXPECT_EQ(-1, register_strategy_.RegistryFilterByCache(node)); } TEST_F(RegistryStrategyTest,RegistryFilterCheckTest) { node.__set_appkey("octo.naming.inf.sg_agent"); EXPECT_TRUE(register_strategy_.RegistryFilterCheck(node)); node.__set_appkey("octo.naming.service.yangjie");//开启强制 EXPECT_TRUE(register_strategy_.RegistryFilterCheck(node)); } TEST_F(RegistryStrategyTest, IsLimitOnZkTest){ node.__set_appkey("octo.naming.service.yangjie");//开启强制 EXPECT_TRUE(register_strategy_.IsLimitOnZk(node)); node.__set_appkey("test"); EXPECT_FALSE(register_strategy_.IsLimitOnZk(node)); } TEST_F(RegistryStrategyTest, CheckLegalOnOpsTest) { node.__set_appkey("test"); EXPECT_FALSE(register_strategy_.CheckLegalOnOps(node)); node.__set_appkey("octo.naming.service.tmy"); EXPECT_TRUE(register_strategy_.CheckLegalOnOps(node)); } #endif
31.336957
77
0.773673
wuxianxingkong
4ecf3705018615222bf6a218551f06d534fbf648
24,170
hpp
C++
code/vpp/docs/conceptual/headers/vppContainers.hpp
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
code/vpp/docs/conceptual/headers/vppContainers.hpp
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
code/vpp/docs/conceptual/headers/vppContainers.hpp
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
/* Copyright 2016-2018 SOFT-ERG, Przemek Kuczmierczyk (www.softerg.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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. */ // ----------------------------------------------------------------------------- namespace vpp { // ----------------------------------------------------------------------------- /** \brief Generic STL-style vector allocating memory on the GPU. \ref gvector is general purpose container for GPU data. Depending on the USAGE template parameter, it can be used for various data buffers used in graphics and compute shaders. Single \ref gvector instance may have multiple uses, hence the parameter is bitwise OR of following values: - Buf::VERTEX - vertex attributes array. - Buf::INDIRECT - buffer holding indirect draw ranges. - Buf::INDEX - vertex index array for indexed primitives. - Buf::UNIFORM - read-only common data (uniform buffer). - Buf::STORAGE - read & write array (storage buffer). - Buf::UNITEX - read-only formatted data (uniform texel buffer). - Buf::STORTEX - read & write formatted data (storage texel buffer). - Buf::SOURCE - source buffer for transfer operations. - Buf::TARGET - target buffer for transfer operations. The vector usually allocates memory on GPU side, but it is also accessible on CPU side in a way depending on the value of memProfile parameter of the constructor. This parameter can have the following values: - MemProfile::DEVICE_STATIC - most frequently used, also known as staging buffer mode. There are two physical memory blocks allocated: one on the device side and another one on host size. The data is synchronized on demand. The access to the memory on both sides is fastest among available modes, but on-demand synchronization takes additional time. - MemProfile::DEVICE_DYNAMIC - single memory block shared between a device and host. Prefferably allocated on device side, or on host side as a fallback. Automatically synchronized by hardware. Efficient on architectures where CPU and GPU memory is common. - MemProfile::DEVICE_FEEDBACK - similar to DEVICE_DYNAMIC, but always allocated on host and visible to the device. - MemProfile::HOST_STATIC - like DEVICE_FEEDBACK, allocated on host, may be also cached on host. Used internally by DEVICE_STATIC for host-side part of the buffer. Typically just use DEVICE_STATIC. Object of this class is reference-counted and may be passed by value. Generally, functions accepting a buffer, bound buffer and certain kinds of views, do accept a gvector instance as well. Therefore you can fill a \ref gvector with e.g. vertex, index, indirect or uniform data and bind it directly. Texel buffers require creating a view explicitly but this view also accepts gvector as data source. */ template< typename ItemT, unsigned int USAGE > class gvector : public Buffer< USAGE >, public MemoryBinding< Buffer< USAGE >, DeviceMemory > { public: /** \brief Random access iterator. */ typedef ItemT* iterator; /** \brief Random access const iterator. */ typedef const ItemT* const_iterator; /** \brief Constructor. The vector has fixed capacity, but varying number of valid elements (size). */ gvector ( size_t maxItemCount, MemProfile::ECharacteristic memProfile, const Device& hDevice ); /** \brief Iterator to begin of the vector. */ iterator begin() { return d_pBegin; } /** \brief Iterator to the end of the valid range (but not whole area). */ iterator end() { return d_pBegin + d_size; } /** \brief Const iterator to begin of the vector. */ const_iterator cbegin() const { return d_pBegin; } /** \brief Const iterator to the end of the valid range (but not whole area). */ const_iterator cend() const { return d_pBegin + d_size; } /** \brief Checks whether the valid range is empty. */ bool empty() const { return d_size == 0; } /** \brief Returns the size of the valid range. */ size_t size() const { return d_size; } /** \brief Returns the size of the whole allocated area (maximum number of elements). */ size_t capacity() const { return d_capacity; } /** \brief Adds element to the end of the valid range. */ void push_back ( const ItemT& item ); /** \brief Constructs element in place at the end of the valid range. */ template< typename ... ArgsT > void emplace_back ( ArgsT... args ); /** \brief Allocates space for new item without constructing it. */ ItemT* allocate_back(); /** \brief Resizes the vector in proper way (constructing/destructing elements). This does not allocate/deallocate any memory nor invalidate iterators. The capacity of the vector is static. Resizing it only affects the number of valid items inside the vector. */ void resize ( size_t newSize, const ItemT& value = ItemT() ); /** \brief Resizes the vector in dumb way (just setting the size without initialization). Use for numeric or vector types only. */ void setSize ( size_t newSize ); /** \brief Empties the valid range. */ void clear(); /** \brief Access to indexed element. */ ItemT& operator[] ( size_t index ) /** \brief Access to const indexed element. */ const ItemT& operator[] ( size_t index ) const; /** \brief Generates a command ensuring that valid elements have been synchronized from host to device. Optionally can be restricted to a range. */ void cmdCommit ( CommandBuffer cmdBuffer, size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Generates a command ensuring that entire memory area has been synchronized from host to device. Optionally can be restricted to a range. */ void cmdCommitAll ( CommandBuffer cmdBuffer, size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Generates a command (to implicit context) which ensures valid elements has been synchronized from host to device. */ void cmdCommit ( size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Generates a command (to implicit context) which ensures that entire buffer area has been synchronized from host to device. */ void cmdCommitAll ( size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Generates a command ensuring that valid elements have been synchronized from device to host. Optionally can be restricted to a range. Caution: the vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void cmdLoad ( CommandBuffer cmdBuffer, size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Generates a command (to implicit context) which ensures valid elements have been synchronized from device to host. Caution: the vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void cmdLoad ( size_t firstItem = 0, size_t nItems = std::numeric_limits< size_t >::max() ); /** \brief Synchronizes entire buffer from host to device. Submits a command to specified queue. Does not wait for completion, uses specified semaphores and fence. */ void commit ( EQueueType eQueue = Q_GRAPHICS, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore() ); /** \brief Synchronizes entire buffer from host to device and waits for completion. */ void commitAndWait ( EQueueType eQueue = Q_GRAPHICS ); /** \brief Synchronizes entire buffer from device to host. Submits a command to specified queue. Does not wait for completion, uses specified semaphores and fence. Caution: the vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void load ( EQueueType eQueue = Q_GRAPHICS, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore() ); /** \brief Synchronizes entire buffer from device to host and waits for completion. Caution: the vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void loadAndWait ( EQueueType eQueue = Q_GRAPHICS ); /** \brief Generates a command to copy the buffer contents to specified image. Caution: may generate other auxiliary commands as well. The vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void cmdCopyToImage ( CommandBuffer hCmdBuffer, const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command (to the default context) to copy the buffer contents to specified image. Caution: may generate other auxiliary commands as well. The vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void cmdCopyToImage ( const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents to specified image. Caution: may generate other auxiliary commands as well. The vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void copyToImage ( EQueueType eQueue, const Img& img, VkImageLayout targetLayout, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore(), std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents to specified image, waits for completion. Caution: may generate other auxiliary commands as well. The vector must explicitly list Buf::SOURCE flag in order to be able to use this function. */ void copyToImageAndWait ( EQueueType eQueue, const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command to copy the buffer contents from specified image. Caution: may generate other auxiliary commands as well. Changes the layout of the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL. */ void cmdCopyFromImage ( CommandBuffer hCmdBuffer, const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command (to the default context) to copy the buffer contents from specified image. Caution: may generate other auxiliary commands as well. Changes the layout of the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL. */ void cmdCopyFromImage ( const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents from specified image. Caution: may generate other auxiliary commands as well. Changes the layout of the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL. */ void copyFromImage ( EQueueType eQueue, const Img& img, VkImageLayout sourceImageLayout, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore(), std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents from specified image. Waits for completion. Caution: may generate other auxiliary commands as well. Changes the layout of the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL. */ void copyFromImageAndWait ( EQueueType eQueue, const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); }; // ----------------------------------------------------------------------------- /** \brief Utility subclass representing a vector of indirect draw ranges. This object is reference-counted and may be passed by value. */ class IndirectCommands : public gvector< VkDrawIndirectCommand, Buf::INDIRECT > { public: IndirectCommands ( size_t maxItemCount, MemProfile::ECharacteristic memProfile, Device hDevice ); }; // ----------------------------------------------------------------------------- /** \brief Utility subclass representing a vector of indexed indirect draw ranges. This object is reference-counted and may be passed by value. */ class IndexedIndirectCommands : public gvector< VkDrawIndexedIndirectCommand, Buf::INDIRECT > { public: IndexedIndirectCommands ( size_t maxItemCount, MemProfile::ECharacteristic memProfile, Device hDevice ); }; // ----------------------------------------------------------------------------- /** \brief Utility subclass representing a vector of indirect dispatch ranges. This object is reference-counted and may be passed by value. */ class DispatchIndirectCommands : public gvector< VkDispatchIndirectCommand, Buf::INDIRECT > { public: DispatchIndirectCommands ( size_t maxItemCount, MemProfile::ECharacteristic memProfile, Device hDevice ); }; // ----------------------------------------------------------------------------- /** \brief Utility subclass representing a vector of indices for indexed draws. This object is reference-counted and may be passed by value. */ class Indices : public gvector< std::uint32_t, Buf::INDEX > { public: Indices ( size_t maxItemCount, MemProfile::ECharacteristic memProfile, Device hDevice ); }; // ----------------------------------------------------------------------------- /** \brief Array allocated entirely on GPU side, without any mapping to the CPU side. Use this class for buffers of data which are generated and consumed entirely on GPU side, without a need to transfer to/from CPU. Such transfers are still possible but require explicit transfer command to be issued. This vector class does not offer a staging buffer functionality, therefore has less memory overhead than gvector (no buffer copy on CPU side). Use for best performance during multiple-staged GPU computations. */ template< typename ItemT, unsigned int USAGE > class dgvector : public Buffer< USAGE >, public MemoryBinding< Buffer< USAGE >, DeviceMemory > { public: dgvector ( size_t maxItemCount, const Device& hDevice ); /** \brief Generates a command to copy the buffer contents to specified image. */ void cmdCopyToImage ( CommandBuffer hCmdBuffer, const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command (to the implicit context) to copy the buffer contents to specified image. */ void cmdCopyToImage ( const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents to specified image. */ void copyToImage ( EQueueType eQueue, const Img& img, VkImageLayout targetLayout, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore(), std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents to specified image, waits for completion. */ void copyToImageAndWait ( EQueueType eQueue, const Img& img, VkImageLayout targetLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command to copy the buffer contents from specified image. */ void cmdCopyFromImage ( CommandBuffer hCmdBuffer, const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Generates a command (to the implicit context) to copy the buffer contents from specified image. */ void cmdCopyFromImage ( const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents from specified image. */ void copyFromImage ( EQueueType eQueue, const Img& img, VkImageLayout sourceImageLayout, const Fence& signalFenceOnEnd = Fence(), const Semaphore& waitOnBegin = Semaphore(), const Semaphore& signalOnEnd = Semaphore(), std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); /** \brief Submits a command to copy the buffer contents from specified image. Waits for completion. */ void copyFromImageAndWait ( EQueueType eQueue, const Img& img, VkImageLayout sourceImageLayout, std::uint32_t mipLevel = 0, std::uint32_t layer = 0, const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 }, const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 }, VkDeviceSize bufferOffset = 0, std::uint32_t bufferRowLength = 0, std::uint32_t bufferImageHeight = 0 ); }; // ----------------------------------------------------------------------------- } // namespace vpp // -----------------------------------------------------------------------------
40.690236
94
0.631485
maikebing
4ed14106689212e65d37eafc191f2f4c5b193666
10,302
cpp
C++
QPaintedWidgets/QPaintedWidgets/components/TextOutlined.cpp
SammyEnigma/QPaintedWidgets
95ada72bf35bd7f8c959466e7353ba0363c0cd09
[ "MIT" ]
6
2019-11-07T13:18:12.000Z
2021-11-07T14:10:40.000Z
QPaintedWidgets/QPaintedWidgets/components/TextOutlined.cpp
SammyEnigma/QPaintedWidgets
95ada72bf35bd7f8c959466e7353ba0363c0cd09
[ "MIT" ]
null
null
null
QPaintedWidgets/QPaintedWidgets/components/TextOutlined.cpp
SammyEnigma/QPaintedWidgets
95ada72bf35bd7f8c959466e7353ba0363c0cd09
[ "MIT" ]
5
2019-11-13T19:45:41.000Z
2020-12-17T07:18:52.000Z
#include "TextOutlined.hpp" // ============================================================================= template <typename T> static bool field_changed(T& curr_value, const T& new_value) { const bool changed = (curr_value != new_value); curr_value = new_value; return changed; } bool QPaintedWidgets::components::TextOutlined::CacheParams::update( int outline_distance, const QColor &outline_color, const QColor &text_color, const Qt::Alignment text_align, const QFont &text_font, const QString &text_text) { // Update previous state & return result is something changed const bool f1 = field_changed(_outline_distance, outline_distance); const bool f2 = field_changed(_outline_color, outline_color); const bool f3 = field_changed(_text_color, text_color); const bool f4 = field_changed(_text_align, text_align); const bool f5 = field_changed(_text_font, text_font); const bool f6 = field_changed(_text_text, text_text); return (f1 || f2 || f3 || f4 || f5 || f6); } // ============================================================================= QPaintedWidgets::components::TextOutlined::self_t &QPaintedWidgets::components::TextOutlined::setOutlineColor(const QColor &color) { if(_outline_color == color) return (*this); _outline_color = color; this->update(); return (*this); } QColor QPaintedWidgets::components::TextOutlined::getOutlineColor() const { return _outline_color; } // ----------------------------------------------------------------------------- QPaintedWidgets::components::TextOutlined::self_t &QPaintedWidgets::components::TextOutlined::setOutlineDistance(int distance) { if(_outline_distance == distance) return (*this); _outline_distance = distance; this->update(); return (*this); } int QPaintedWidgets::components::TextOutlined::getOutlineDistance() const { return _outline_distance; } // ----------------------------------------------------------------------------- QPaintedWidgets::components::TextOutlined::self_t &QPaintedWidgets::components::TextOutlined::setOutline(const QColor &color, int distance) { setOutlineColor(color); setOutlineDistance(distance); return (*this); } QPaintedWidgets::components::TextOutlined::self_t &QPaintedWidgets::components::TextOutlined::setOutlineDisabled() { return setOutline(Qt::transparent, 0); } // ----------------------------------------------------------------------------- bool QPaintedWidgets::components::TextOutlined::isOutlineEnabled() const { return (_outline_color != Qt::transparent) && (_outline_distance > 0); } // ----------------------------------------------------------------------------- #include <QPainter> #include "QPaintedWidgets/painting/pos_from_alignment.hpp" #include <QFontMetrics> #include "QPaintedWidgets/painting/signed_distance_field.hpp" QImage make_sdf_outline(int distance, const QColor& outline_color, const QSize& img_size, Qt::Alignment text_align, const QFont& text_font, const QColor& text_color, const QString& text) { /* IMPORTANT NOTE: Instead of simple QImage format `RGBA8888` used `RGBA8888_Premultiplied` for corrent pictures displaying. On some platforms/Qt-versions text over outline displayed good without it. BUT on Qt5.3 it is required to use such format, since otherwise text looks "dirty". */ // Create transparent image for drawing text upon it QImage img_text(img_size, QImage::Format_RGBA8888_Premultiplied); img_text.fill(Qt::transparent); // Draw text { QPainter painter(&img_text); // Disable text (subpixel) antialiasing, since its produces 'dirty' pixels :) painter.setRenderHint(QPainter::RenderHint::Antialiasing, false); painter.setRenderHint(QPainter::RenderHint::TextAntialiasing, false); painter.setFont(text_font); painter.setPen(text_color); painter.setBrush(Qt::NoBrush); painter.drawText(0, 0, img_text.width(), img_text.height(), text_align, text); } // ------------------------------------------------------------------------- QImage img_field(img_size, QImage::Format_RGBA8888_Premultiplied); img_field.fill(Qt::transparent); const auto pixel_search_func = [&img_text](int x, int y) -> bool { // Since text displayed semi-transperent, we calculate distance only for // the only for most opaque pixels const QRgb pixel = img_text.pixel(x, y); return qAlpha(pixel) > 128; }; const auto field = QPaintedWidgets::sdf::make_field(distance, img_size.width(), img_size.height(), pixel_search_func); for(int x = 0; x < img_size.width(); ++x) { for(int y = 0; y < img_size.height(); ++y) { const int idx = (x + (y * img_size.width())); const float& distance = field[idx]; // // ---------------------------------------- // // Debug grayscale drawing: // const int gray = (distance * 255); // const QRgb col = qRgb(gray, gray, gray); // img_field.setPixel(x, y, col); // // ---------------------------------------- if( distance < 1.0 ) { // TODO: future: currently here is only 'linear beavior' - alpha // the same as distance. BUT it may be flexible! For example by // using solid/cosine/trapesoid functions, which give alpha by // normalized distance. This may be cool feature, for tweakable // outlining or even multiple! const int alpha = (distance * 255); const QRgb outline = qRgba(outline_color.red(), outline_color.green(), outline_color.blue(), alpha); const QRgb outline_premultiplied = qPremultiply(outline); // Needed to utilize color glitches. Used since QImage format is RGBA >PREMULTIPLIED< img_field.setPixel(x, y, outline_premultiplied); } } } // ------------------------------------------------------------------------- // Draw image-with-text over image-with-outline { QPainter painter(&img_field); painter.drawImage(img_field.rect(), img_text); } return img_field; } /* // STUPID NAIVE DIRTY SINGLE-PIXEL GARBAGE CODE, STORED HERE FOR HISTORICAL REASON. // instead it used Signed-Distance-Field with additiona caching const QColor color_text = _pen.color(); const QColor color_outline = _outline_color; const QColor color_back = Qt::transparent; QImage img(rect.size(), QImage::Format_RGBA8888); img.fill(color_back); { QPainter img_painter(&img); img_painter.setRenderHint(QPainter::RenderHint::Antialiasing, false); img_painter.setRenderHint(QPainter::RenderHint::TextAntialiasing, false); img_painter.setFont(base_t::_font); // Draw text img_painter.setPen(color_text); img_painter.setBrush(Qt::NoBrush); img_painter.drawText(0, 0, img.width(), img.height(), _alignment, getText()); // Do single-pixel outlining. // This is really crappy algo, written in few minutes. { static const std::array<QPoint, 8> offsets = { QPoint(-1, -1), QPoint(0, -1), QPoint(+1, -1), // all: negative y QPoint(-1, 0), QPoint(+1, 0), // all: zero y QPoint(-1, +1), QPoint(0, +1), QPoint(+1, +1) // all: positive y }; // Traverse the whole image ... for(int y = 0; y < img.height(); ++y) { for(int x = 0; x < img.width(); ++x) { const QColor curr_pix_color = QColor::fromRgb( img.pixel(x, y) ); // And only for pixels with color of (rendered) text if(curr_pix_color == color_text) { // Check nearby pixels for(const QPoint& nearby : offsets) { const QPoint near_pos = QPoint(x, y) + nearby; // >>> It is safe, out-of-bounds not blow-up everything <<< const QColor near_color = QColor::fromRgb(img.pixel(near_pos.x(), near_pos.y())); // And each pixel, which NEAR text color, BUT not that color - mark as 'outline' if(near_color != color_text) { img.setPixel(near_pos, color_outline.rgb()); } } } } } } } */ void QPaintedWidgets::components::TextOutlined::draw(QPainter &p, const QPen &pen, const QRect &rect) { if( !isOutlineEnabled() ) { base_t::draw(p, pen, rect); } else // Outline enabled { p.save(); { const QSize rect_size = rect.size(); const QColor text_color = getPen().color(); const Qt::Alignment text_align = getAlignment(); const QFont text_font = getFont(); const QString text_text = getText(); const bool cache_need_to_update = _cache_params.update( _outline_distance, _outline_color, text_color, text_align, text_font, text_text); // Update cached pixmap on resize or parameters change. // It is really important to re-use pre-rendered pixmap, instead of // extremely slow SDF-re-calculation on each QWidget::paintEvent() if( (rect_size != _cache_pixmap.size()) || cache_need_to_update) { _cache_pixmap = QPixmap::fromImage( make_sdf_outline(_outline_distance, _outline_color, rect_size, text_align, text_font, text_color, text_text) ); } // Draw resulting image p.drawPixmap(rect, _cache_pixmap); } p.restore(); } }
34.34
159
0.560474
SammyEnigma
4ed8a96a4bd9643062f1c037ba2a03316ae436d7
7,229
cpp
C++
src/notifybyaudio_canberra.cpp
pasnox/knotifications
ef2871b2a485be5abe393e61c6cd93867420f896
[ "BSD-3-Clause" ]
1
2019-11-02T03:54:16.000Z
2019-11-02T03:54:16.000Z
src/notifybyaudio_canberra.cpp
pasnox/knotifications
ef2871b2a485be5abe393e61c6cd93867420f896
[ "BSD-3-Clause" ]
2
2019-10-27T23:06:33.000Z
2020-01-11T00:44:07.000Z
src/notifybyaudio_canberra.cpp
brute4s99/knotifications
bc01688f99fcbdc2d3ceb4ad9475da1359441408
[ "BSD-3-Clause" ]
null
null
null
/* This file is part of the KDE libraries Copyright (C) 2014-2015 by Martin Klapetek <mklapetek@kde.org> Copyright (C) 2018 Kai Uwe Broulik <kde@privat.broulik.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "notifybyaudio_canberra.h" #include "debug_p.h" #include <QGuiApplication> #include <QFile> #include <QFileInfo> #include <QIcon> #include <QString> #include "knotifyconfig.h" #include "knotification.h" #include <canberra.h> NotifyByAudio::NotifyByAudio(QObject *parent) : KNotificationPlugin(parent) { qRegisterMetaType<uint32_t>("uint32_t"); int ret = ca_context_create(&m_context); if (ret != CA_SUCCESS) { qCWarning(LOG_KNOTIFICATIONS) << "Failed to initialize canberra context for audio notification:" << ca_strerror(ret); m_context = nullptr; return; } QString desktopFileName = QGuiApplication::desktopFileName(); // handle apps which set the desktopFileName property with filename suffix, // due to unclear API dox (https://bugreports.qt.io/browse/QTBUG-75521) if (desktopFileName.endsWith(QLatin1String(".desktop"))) { desktopFileName.chop(8); } ret = ca_context_change_props(m_context, CA_PROP_APPLICATION_NAME, qUtf8Printable(qApp->applicationDisplayName()), CA_PROP_APPLICATION_ID, qUtf8Printable(desktopFileName), CA_PROP_APPLICATION_ICON_NAME, qUtf8Printable(qApp->windowIcon().name()), nullptr); if (ret != CA_SUCCESS) { qCWarning(LOG_KNOTIFICATIONS) << "Failed to set application properties on canberra context for audio notification:" << ca_strerror(ret); } } NotifyByAudio::~NotifyByAudio() { if (m_context) { ca_context_destroy(m_context); } m_context = nullptr; } void NotifyByAudio::notify(KNotification *notification, KNotifyConfig *config) { const QString soundFilename = config->readEntry(QStringLiteral("Sound")); if (soundFilename.isEmpty()) { qCWarning(LOG_KNOTIFICATIONS) << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification"; finish(notification); return; } QUrl soundURL; const auto dataLocations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); for (const QString &dataLocation : dataLocations) { soundURL = QUrl::fromUserInput(soundFilename, dataLocation + QStringLiteral("/sounds"), QUrl::AssumeLocalFile); if (soundURL.isLocalFile() && QFileInfo::exists(soundURL.toLocalFile())) { break; } else if (!soundURL.isLocalFile() && soundURL.isValid()) { break; } soundURL.clear(); } if (soundURL.isEmpty()) { qCWarning(LOG_KNOTIFICATIONS) << "Audio notification requested, but sound file from notifyrc file was not found, aborting audio notification"; finish(notification); return; } // Looping happens in the finishCallback if (!playSound(m_currentId, soundURL)) { finish(notification); return; } if (notification->flags() & KNotification::LoopSound) { m_loopSoundUrls.insert(m_currentId, soundURL); } Q_ASSERT(!m_notifications.value(m_currentId)); m_notifications.insert(m_currentId, notification); ++m_currentId; } bool NotifyByAudio::playSound(quint32 id, const QUrl &url) { if (!m_context) { qCWarning(LOG_KNOTIFICATIONS) << "Cannot play notification sound without canberra context"; return false; } ca_proplist *props = nullptr; ca_proplist_create(&props); // We'll also want this cached for a time. volatile makes sure the cache is // dropped after some time or when the cache is under pressure. ca_proplist_sets(props, CA_PROP_MEDIA_FILENAME, QFile::encodeName(url.toLocalFile()).constData()); ca_proplist_sets(props, CA_PROP_CANBERRA_CACHE_CONTROL, "volatile"); int ret = ca_context_play_full(m_context, id, props, &ca_finish_callback, this); ca_proplist_destroy(props); if (ret != CA_SUCCESS) { qCWarning(LOG_KNOTIFICATIONS) << "Failed to play sound with canberra:" << ca_strerror(ret); return false; } return true; } void NotifyByAudio::ca_finish_callback(ca_context *c, uint32_t id, int error_code, void *userdata) { Q_UNUSED(c); QMetaObject::invokeMethod(static_cast<NotifyByAudio*>(userdata), "finishCallback", Q_ARG(uint32_t, id), Q_ARG(int, error_code)); } void NotifyByAudio::finishCallback(uint32_t id, int error_code) { KNotification *notification = m_notifications.value(id, nullptr); if (!notification) { // We may have gotten a late finish callback. return; } if (error_code == CA_SUCCESS) { // Loop the sound now if we have one const QUrl soundUrl = m_loopSoundUrls.value(id); if (soundUrl.isValid()) { if (!playSound(id, soundUrl)) { finishNotification(notification, id); } return; } } else if (error_code != CA_ERROR_CANCELED) { qCWarning(LOG_KNOTIFICATIONS) << "Playing audio notification failed:" << ca_strerror(error_code); } finishNotification(notification, id); } void NotifyByAudio::close(KNotification *notification) { if (!m_notifications.values().contains(notification)) { return; } const auto id = m_notifications.key(notification); if (m_context) { int ret = ca_context_cancel(m_context, id); if (ret != CA_SUCCESS) { qCWarning(LOG_KNOTIFICATIONS) << "Failed to cancel canberra context for audio notification:" << ca_strerror(ret); return; } } // Consider the notification finished. ca_context_cancel schedules a cancel // but we need to stop using the noficiation immediately or we could access // a notification past its lifetime (close() may, or indeed must, // schedule deletion of the notification). // https://bugs.kde.org/show_bug.cgi?id=398695 finishNotification(notification, id); } void NotifyByAudio::finishNotification(KNotification *notification, quint32 id) { m_notifications.remove(id); m_loopSoundUrls.remove(id); finish(notification); }
34.922705
150
0.678794
pasnox
4de56c2f1e5fa72d6ec33aeb6d98a3908b10cd9f
844
cc
C++
test/test_split.cc
embeddedawesome/cpp-subprocess
62635b57456baf41547315f4a5a8dd77cdf2c381
[ "MIT" ]
331
2016-03-19T12:19:14.000Z
2022-03-31T08:59:01.000Z
test/test_split.cc
mr132001/cpp-subprocess
f1ce916fdc52648da9481a386a24c221bf703f1d
[ "MIT" ]
50
2016-03-21T12:03:46.000Z
2022-03-15T17:37:31.000Z
test/test_split.cc
mr132001/cpp-subprocess
f1ce916fdc52648da9481a386a24c221bf703f1d
[ "MIT" ]
79
2016-03-20T19:58:10.000Z
2022-03-31T13:07:53.000Z
#include <iostream> #include <string> #include <vector> std::vector<std::string> split(const std::string& str, const std::string& delims=" \t") { std::vector<std::string> res; size_t init = 0; while (true) { auto pos = str.find_first_of(delims, init); if (pos == std::string::npos) { res.emplace_back(str.substr(init, str.length())); break; } res.emplace_back(str.substr(init, pos - init)); pos++; init = pos; } return res; } std::string join(const std::vector<std::string>& vec) { std::string res; for (auto& elem : vec) { res.append(elem + " "); } res.erase(--res.end()); return res; } int main() { auto vec = split ("a b c"); for (auto elem : vec) { std::cout << elem << std::endl; } std::cout << join(vec).length() << std::endl; return 0; }
19.627907
62
0.567536
embeddedawesome
4de57c438d087a5af5c53c646a0d9761a0d914c3
4,587
cpp
C++
IPCDemo/IPCPort.cpp
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
2
2021-04-27T07:08:07.000Z
2021-05-20T16:08:51.000Z
IPCDemo/IPCPort.cpp
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
null
null
null
IPCDemo/IPCPort.cpp
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ //! \file IPCMessage.cpp //! messaging used for IPC in SDK IPC demo example //! \project ARA SDK Examples //! \copyright Copyright (c) 2012-2021, Celemony Software GmbH, All Rights Reserved. //! \license 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 is a brief proof-of-concept demo that hooks up an ARA capable plug-in // in a separate process using IPC. // This educational example is not suitable for production code - // see MainProcess.cpp for a list of issues. //------------------------------------------------------------------------------ #include "IPCPort.h" #include "ARA_Library/Debug/ARADebug.h" // increase to several seconds while debugging so that staying in the debugger does not break program flow static constexpr auto messageTimeout { 0.1 }; IPCPort::IPCPort (CFMessagePortRef port) : _port { port } {} IPCPort::IPCPort (IPCPort&& other) noexcept { *this = std::move (other); } IPCPort& IPCPort::operator= (IPCPort&& other) noexcept { std::swap (_port, other._port); return *this; } IPCPort::~IPCPort () { if (_port) { CFMessagePortInvalidate (_port); CFRelease (_port); } } CFDataRef IPCPortCallBack (CFMessagePortRef /*port*/, SInt32 /*msgid*/, CFDataRef cfData, void* info) { const IPCMessage message { cfData }; return ((IPCPort::Callback) info) (message).createEncodedMessage (); } IPCPort IPCPort::createPublishingID (const char* remotePortID, Callback callback) { auto portID { CFStringCreateWithCStringNoCopy (kCFAllocatorDefault, remotePortID, kCFStringEncodingASCII, kCFAllocatorNull) }; CFMessagePortContext portContext { 0, (void*) callback, nullptr, nullptr, nullptr }; auto port { CFMessagePortCreateLocal (kCFAllocatorDefault, portID, &IPCPortCallBack, &portContext, nullptr) }; CFRelease (portID); CFRunLoopSourceRef runLoopSource { CFMessagePortCreateRunLoopSource (kCFAllocatorDefault, port, 0) }; CFRunLoopAddSource (CFRunLoopGetCurrent (), runLoopSource, kCFRunLoopDefaultMode); CFRelease (runLoopSource); ARA_INTERNAL_ASSERT (port != nullptr); return IPCPort { port }; } IPCPort IPCPort::createConnectedToID (const char* remotePortID) { auto timeout { 5.0 }; CFMessagePortRef port {}; // for some reason, the clang analyzer claims a potential leak of port here, even though it's either null or consumed... #if !defined (__clang_analyzer__) while (timeout > 0.0) { auto portID { CFStringCreateWithCStringNoCopy (kCFAllocatorDefault, remotePortID, kCFStringEncodingASCII, kCFAllocatorNull) }; if ((port = CFMessagePortCreateRemote (kCFAllocatorDefault, portID))) break; CFRelease (portID); constexpr auto waitTime { 0.01 }; CFRunLoopRunInMode (kCFRunLoopDefaultMode, waitTime, false); timeout -= waitTime; } ARA_INTERNAL_ASSERT (port != nullptr); #endif return IPCPort { port }; } void IPCPort::sendWithoutReply (const IPCMessage& message) { auto outgoingData { message.createEncodedMessage () }; const auto portSendResult { CFMessagePortSendRequest (_port, 0, outgoingData, messageTimeout, 0.0, nullptr, nullptr) }; CFRelease (outgoingData); ARA_INTERNAL_ASSERT (portSendResult == kCFMessagePortSuccess); } IPCMessage IPCPort::sendAndAwaitReply (const IPCMessage& message) { auto outgoingData { message.createEncodedMessage () }; auto incomingData { CFDataRef {} }; const auto portSendResult { CFMessagePortSendRequest (_port, 0, outgoingData, messageTimeout, messageTimeout, kCFRunLoopDefaultMode, &incomingData) }; CFRelease (outgoingData); ARA_INTERNAL_ASSERT (incomingData && (portSendResult == kCFMessagePortSuccess)); IPCMessage reply { incomingData }; CFRelease (incomingData); return reply; }
39.205128
154
0.669937
Celemony
4de81c0a7fe7af2277b25493cb4ad06339c8c6ab
5,053
cpp
C++
Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
1
2021-10-05T15:45:42.000Z
2021-10-05T15:45:42.000Z
Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
17
2021-10-05T13:47:01.000Z
2021-11-06T13:15:42.000Z
Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
9
2021-10-05T07:21:09.000Z
2021-10-20T08:31:03.000Z
#include <iostream> #include <cstdlib> #define MAX_VALUE 65536 using namespace std; class N { //node declaration public: int k; N *l, *r; bool leftTh, rightTh; }; class ThreadedBinaryTree { private: N *root; public: ThreadedBinaryTree() { //constructor to initialize the variables root= new N(); root->r= root->l= root; root->leftTh = true; root->k = MAX_VALUE; } void makeEmpty() { //clear tree root= new N(); root->r = root->l = root; root->leftTh = true; root->k = MAX_VALUE; } void insert(int key) { N *p = root; for (;;) { if (p->k< key) { / /move to right thread if (p->rightTh) break; p = p->r; } else if (p->k > key) { // move to left thread if (p->leftTh) break; p = p->l; } else { return; } } N *temp = new N(); temp->k = key; temp->rightTh= temp->leftTh= true; if (p->k < key) { temp->r = p->r; temp->l= p; p->r = temp; p->rightTh= false; } else { temp->r = p; temp->l = p->l; p->l = temp; p->leftTh = false; } } bool search(int key) { N *temp = root->l; for (;;) { if (temp->k < key) { //search in left thread if (temp->rightTh) return false; temp = temp->r; } else if (temp->k > key) { //search in right thread if (temp->leftTh) return false; temp = temp->l; } else { return true; } } } void Delete(int key) { N *dest = root->l, *p = root; for (;;) { //find Node and its parent. if (dest->k < key) { if (dest->rightTh) return; p = dest; dest = dest->r; } else if (dest->k > key) { if (dest->leftTh) return; p = dest; dest = dest->l; } else { break; } } N *target = dest; if (!dest->rightTh && !dest->leftTh) { p = dest; //has two children target = dest->l; //largest node at left child while (!target->rightTh) { p = target; target = target->r; } dest->k= target->k; //replace mode } if (p->k >= target->k) { //only left child if (target->rightTh && target->leftTh) { p->l = target->l; p->leftTh = true; } else if (target->rightTh) { N*largest = target->l; while (!largest->rightTh) { largest = largest->r; } largest->r = p; p->l= target->l; } else { N *smallest = target->r; while (!smallest->leftTh) { smallest = smallest->l; } smallest->l = target->l; p->l = target->r; } } else {//only right child if (target->rightTh && target->leftTh) { p->r= target->r; p->rightTh = true; } else if (target->rightTh) { N *largest = target->l; while (!largest->rightTh) { largest = largest->r; } largest->r= target->r; p->r = target->l; } else { N *smallest = target->r; while (!smallest->leftTh) { smallest = smallest->l; } smallest->l= p; p->r= target->r; } } } void displayTree() { //print the tree N *temp = root, *p; for (;;) { p = temp; temp = temp->r; if (!p->rightTh) { while (!temp->leftTh) { temp = temp->l; } } if (temp == root) break; cout<<temp->k<<" "; } cout<<endl; } }; int main() { ThreadedBinaryTree tbt; cout<<"ThreadedBinaryTree\n"; char ch; int c, v; while(1) { cout<<"1. Insert "<<endl; cout<<"2. Delete"<<endl; cout<<"3. Search"<<endl; cout<<"4. Clear"<<endl; cout<<"5. Display"<<endl; cout<<"6. Exit"<<endl; cout<<"Enter Your Choice: "; cin>>c; //perform switch operation switch (c) { case 1 : cout<<"Enter integer element to insert: "; cin>>v; tbt.insert(v); break; case 2 : cout<<"Enter integer element to delete: "; cin>>v; tbt.Delete(v); break; case 3 : cout<<"Enter integer element to search: "; cin>>v; if (tbt.search(v) == true) cout<<"Element "<<v<<" found in the tree"<<endl; else cout<<"Element "<<v<<" not found in the tree"<<endl; break; case 4 : cout<<"\nTree Cleared\n"; tbt.makeEmpty(); break; case 5: cout<<"Display tree: \n "; tbt.displayTree(); break; case 6: exit(1); default: cout<<"\nInvalid type! \n"; } } cout<<"\n"; return 0; }
24.293269
67
0.435385
sejalsingh417
4de9be458ee5e8a5a1fbceee7a061b00ba7112cf
633
cpp
C++
GummiShip/lazer.cpp
fonicartist/GummiShip
1977f3b4360321fc78da0b124ce1e57797e8911c
[ "MIT" ]
null
null
null
GummiShip/lazer.cpp
fonicartist/GummiShip
1977f3b4360321fc78da0b124ce1e57797e8911c
[ "MIT" ]
null
null
null
GummiShip/lazer.cpp
fonicartist/GummiShip
1977f3b4360321fc78da0b124ce1e57797e8911c
[ "MIT" ]
null
null
null
#include "lazer.h" Lazer::Lazer(float pos, float x, float y, int direction) { sprite.setPosition(pos, 640); velocity = sf::Vector2f(x, y); hit = false; printf("New lazer created at (%d,%d).\n", pos, 700); loadAssets(direction); } void Lazer::loadAssets(int direction) { texture.loadFromFile("..\\assets\\sprites\\lazer.png"); sprite.setTexture(texture); sprite.setTextureRect(sf::IntRect(25 * direction, 0, 25, 53)); sprite.setOrigin(13.f, 0.f); //sprite.setPosition(220, -60); sprite.setScale(sf::Vector2f(0.90f, 0.90f)); } void Lazer::update() { if (getY() > -100) sprite.move(velocity); } Lazer::~Lazer() { }
21.1
63
0.666667
fonicartist
4deb7026a232745d63f2132aa2f8693ead309392
577
cpp
C++
runtime/fpga/software/runtime/run_elf_zcu102.cpp
caesr-uwaterloo/MapleBoard
4687854d230ef6ca16270fc0168f8c627c7e7eac
[ "MIT" ]
1
2022-02-19T13:12:08.000Z
2022-02-19T13:12:08.000Z
runtime/fpga/software/runtime/run_elf_zcu102.cpp
caesr-uwaterloo/MapleBoard
4687854d230ef6ca16270fc0168f8c627c7e7eac
[ "MIT" ]
null
null
null
runtime/fpga/software/runtime/run_elf_zcu102.cpp
caesr-uwaterloo/MapleBoard
4687854d230ef6ca16270fc0168f8c627c7e7eac
[ "MIT" ]
null
null
null
#include "common.h" #include <iostream> #include <cstring> #include "loguru.hpp" using namespace std::chrono_literals; int main(int argc, char** argv) { _argc = argc; _argv = argv; std::cout << "ZCU102 Real Board" << std::endl; int exit_code; // NOTE: this function will launch a new thread test_main(&exit_code); auto handlerFuture = handlerDoneSignal.get_future(); // auto status = handlerFuture.wait_for(10000ms); handlerFuture.wait(); exitSignal.set_value(); handler_thread.join(); LOG_F(WARNING, "Exit Code: %d", exit_code); return 0; }
19.233333
54
0.691508
caesr-uwaterloo
4decca83a36b5e74bccd1c25fda6fbcfdecdbdb5
10,037
cpp
C++
reader.cpp
blackslender/LIBPRO
d0cc2f64f7a01f4a1bf8dfa2b6be54928247e0c9
[ "MIT" ]
null
null
null
reader.cpp
blackslender/LIBPRO
d0cc2f64f7a01f4a1bf8dfa2b6be54928247e0c9
[ "MIT" ]
null
null
null
reader.cpp
blackslender/LIBPRO
d0cc2f64f7a01f4a1bf8dfa2b6be54928247e0c9
[ "MIT" ]
null
null
null
#include "reader.h" #include "ui_reader.h" #include <QSqlQuery> #include <QDebug> #include <QSqlQueryModel> #include <QTableView> #include <QSqlRelationalTableModel> #include <QtWidgets> #include <muonsach.h> #include "book.h" #include "phieumuon.h" READER::READER(QSqlDatabase *db,USER *user,QWidget *parent) : QWidget(parent), ui(new Ui::READER) { ui->setupUi(this); this->db=db; this->user=user; ui->tableMuon->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->tableMuon,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(on_ContextMenu(QPoint))); FormLoad(); on_btnSearch_clicked(); } void READER::resizeEvent(QResizeEvent *event) { QRect rect=ui->stackedWidget->geometry(); QPoint bot=rect.bottomRight(); bot.setX(event->size().width()-20); bot.setY(event->size().height()-20); rect.setBottomRight(bot); ui->stackedWidget->setGeometry(rect); QWidget::resizeEvent(event); } void READER::on_ContextMenu(QPoint pos) { QMenu *menu=new QMenu(ui->tableMuon); QAction* info=new QAction("Chi tiết",ui->tableMuon); QAction* edit=new QAction("Chỉnh sửa",ui->tableMuon); QAction* del=new QAction("Xóa",this); if(ui->tableMuon->currentIndex().row()==-1) { info->setEnabled(false); edit->setEnabled(false); del->setEnabled(false); } connect(info,SIGNAL(triggered()),this,SLOT(on_Info())); connect(edit,SIGNAL(triggered()),this,SLOT(on_Edit())); connect(del,SIGNAL(triggered()),this,SLOT(on_Del())); menu->addAction(info); menu->addAction(edit); menu->addAction(del); menu->popup(QCursor::pos()); } void READER::on_Del() { QModelIndex index=ui->tableMuon->selectionModel()->currentIndex(); int id=ui->tableMuon->model()->sibling(index.row(),0,index).data().toInt(); PhieuMuon::Delete(id,db); tableMuonLoad(); } void READER::on_Edit() { QModelIndex index=ui->tableMuon->selectionModel()->currentIndex(); int id=ui->tableMuon->model()->sibling(index.row(),0,index).data().toInt(); PhieuMuon phieu(id,db); MuonSach *dialog=new MuonSach(user->getUserID(),phieu.getBook(),db,MuonSach::UPDATE,this); dialog->setModal(true); if(dialog->exec()==MuonSach::Accepted) tableMuonLoad(); } void READER::on_Info() { QModelIndex index=ui->tableMuon->selectionModel()->currentIndex(); int id=ui->tableMuon->model()->sibling(index.row(),0,index).data().toInt(); PhieuMuon phieu(id,db); MuonSach *dialog=new MuonSach(user->getUserID(),phieu.getBook(),db,MuonSach::VIEW,this);\ dialog->setModal(true); dialog->exec(); } void READER::FormLoad() { // //List widget ui->listWidget->addItem("Tìm kiếm sách"); ui->listWidget->addItem("Sách chờ duyệt"); ui->listWidget->addItem("Thông báo"); // //combo Box 1 ui->FilterBox->addItem("Tên sách"); ui->FilterBox->addItem("Tác giả"); ui->FilterBox->addItem("Loại sách"); ui->FilterBox->addItem("Nhà xuất bản"); ui->FilterBox->addItem("ID"); //Combo Box ui->Filter2->addItem("Sách đã duyệt"); ui->Filter2->addItem("Sách mới về"); ui->Filter2->addItem("Nhắc nhở trả sách"); ui->Filter2->addItem("Thông báo phạt"); // ui->tableMuon->setEditTriggers(QTableView::NoEditTriggers); tableBookLoad(); } void READER::on_listWidgetChangedIndex(int index) { ui->stackedWidget->setCurrentIndex(index); if(index==CHODUYET) tableMuonLoad(); } QSqlQueryModel* READER::Search(QString content, BOOKTYPE type) { QString pattern="%"+content.toLower()+"%"; QSqlQuery qr=QSqlQuery(*db); QString BookType; if(pattern=="") qr.prepare("SELECT * FROM BOOK"); else { switch(type) { case TENSACH: BookType="TenSach"; break; case TACGIA: BookType="TacGia";break; case LOAISACH: BookType="LoaiSach";break; case NXB: BookType="NXB";break; case ID: BookType="ID";break; } QString query("SELECT * FROM BOOK WHERE LOWER(%1) LIKE ?"); query=query.arg(BookType); qr.prepare(query); qr.addBindValue(pattern); } qr.exec(); QSqlQueryModel *model=new QSqlQueryModel(); model->setQuery(qr); model->setHeaderData(0,Qt::Horizontal,"ID"); model->setHeaderData(1,Qt::Horizontal,"Tên sách"); model->setHeaderData(2,Qt::Horizontal,"Tác giả"); model->setHeaderData(3,Qt::Horizontal,"Ngày nhập"); model->setHeaderData(4,Qt::Horizontal,"Loại sách"); model->setHeaderData(5,Qt::Horizontal,"Giá bìa"); model->setHeaderData(6,Qt::Horizontal,"Số lượng"); model->setHeaderData(7,Qt::Horizontal,"Nội dung"); model->setHeaderData(8,Qt::Horizontal,"NXB"); return model; } void READER::tableMuonLoad() { QSqlRelationalTableModel *model=new QSqlRelationalTableModel(this,*db); QString pattern="User=%1 AND DaMuon=0"; pattern=pattern.arg(QString::number(user->getUserID())); model->setTable("PHIEUMUON"); model->setFilter(pattern); model->setRelation(2,QSqlRelation("BOOK","ID","TenSach")); model->setHeaderData(2,Qt::Horizontal,"Tên sách"); model->setHeaderData(3,Qt::Horizontal,"Ngày lấy"); model->setHeaderData(4,Qt::Horizontal,"Ngày trả"); model->setHeaderData(5,Qt::Horizontal,"Số lượng"); model->select(); ui->tableMuon->setModel(model); ui->tableMuon->hideColumn(0); ui->tableMuon->hideColumn(1); ui->tableMuon->hideColumn(6); ui->tableMuon->hideColumn(7); ui->tableMuon->show(); } READER::~READER() { delete ui; } void READER::on_btnSearch_clicked() { QString content=ui->txtContent->text(); BOOKTYPE type=(BOOKTYPE)(ui->FilterBox->currentIndex()); QSqlQueryModel *model=Search(content,type); ui->tableBook->setModel(model); ui->tableBook->show(); ui->tableBook->resizeColumnsToContents(); } void READER::on_listWidget_currentRowChanged(int currentRow) { on_listWidgetChangedIndex(currentRow); } void READER::tableBookLoad() { ui->tableBook->setSelectionBehavior(QTableView::SelectRows); ui->tableBook->setSelectionMode(QTableView::SingleSelection); ui->tableMuon->setSelectionBehavior(QTableView::SelectRows); ui->tableMuon->setSelectionMode(QTableView::SingleSelection); } void READER::on_tableBook_doubleClicked(const QModelIndex &index) { int idBook=ui->tableBook->model()->sibling(index.row(),0,index).data().toInt(); MuonSach *dia=new MuonSach(user->getUserID(),idBook,db); dia->setModal(true); dia->exec(); } void READER::SachDaDuyet() { QSqlRelationalTableModel *model=new QSqlRelationalTableModel(this,*db); model->setTable("PHIEUMUON"); model->setFilter(QString("User=%1 AND DaMuon=1").arg(user->getUserID())); model->setRelation(2,QSqlRelation("BOOK","ID","TenSach")); model->setHeaderData(2,Qt::Horizontal,"Tên sách"); model->setHeaderData(3,Qt::Horizontal,"Ngày mượn"); model->setHeaderData(4,Qt::Horizontal,"Ngày trả"); model->setHeaderData(5,Qt::Horizontal,"Số lượng mượn"); model->select(); ui->tablenews->setModel(model); ui->tablenews->hideColumn(0); ui->tablenews->hideColumn(1); ui->tablenews->hideColumn(6); ui->tablenews->hideColumn(7); ui->tablenews->show(); } void READER::NhacNho() { QSqlRelationalTableModel *model=new QSqlRelationalTableModel(this,*db); model->setTable("PHIEUMUON"); model->setFilter("julianday(date('now'))-julianday(NgayTra)<3"); model->setRelation(2,QSqlRelation("BOOK","ID","TenSach")); model->setHeaderData(2,Qt::Horizontal,"Tên sách"); model->setHeaderData(3,Qt::Horizontal,"Ngày mượn"); model->setHeaderData(4,Qt::Horizontal,"Ngày trả"); model->setHeaderData(5,Qt::Horizontal,"Số lượng mượn"); model->select(); ui->tablenews->setModel(model); ui->tablenews->hideColumn(0); ui->tablenews->hideColumn(1); ui->tablenews->hideColumn(6); ui->tablenews->hideColumn(7); ui->tablenews->show(); } void READER::Phat() { QSqlRelationalTableModel *model=new QSqlRelationalTableModel(this,*db); model->setTable("PHIEUMUON"); model->setFilter(QString("User=%1 AND Phat=1").arg(user->getUserID())); model->setRelation(2,QSqlRelation("BOOK","ID","TenSach")); model->setHeaderData(2,Qt::Horizontal,"Tên sách"); model->setHeaderData(3,Qt::Horizontal,"Ngày mượn"); model->setHeaderData(4,Qt::Horizontal,"Ngày trả"); model->setHeaderData(5,Qt::Horizontal,"Số lượng mượn"); model->select(); ui->tablenews->setModel(model); ui->tablenews->hideColumn(0); ui->tablenews->hideColumn(1); ui->tablenews->hideColumn(6); ui->tablenews->hideColumn(7); ui->tablenews->show(); } void READER::SachMoiVe() { QSqlQueryModel *model=new QSqlQueryModel(); QSqlQuery qr(*db); qr.prepare("SELECT * FROM BOOK WHERE julianday(date('now'))-julianday(NgayNhap)<14"); qr.exec(); model->setQuery(qr); model->setHeaderData(0,Qt::Horizontal,"ID"); model->setHeaderData(1,Qt::Horizontal,"Tên sách"); model->setHeaderData(2,Qt::Horizontal,"Tác giả"); model->setHeaderData(3,Qt::Horizontal,"Ngày nhập"); model->setHeaderData(4,Qt::Horizontal,"Loại sách"); model->setHeaderData(5,Qt::Horizontal,"Giá bìa"); model->setHeaderData(6,Qt::Horizontal,"Số lượng"); model->setHeaderData(7,Qt::Horizontal,"Nội dung"); model->setHeaderData(8,Qt::Horizontal,"NXB"); model->setHeaderData(9,Qt::Horizontal,"Được mượn"); ui->tablenews->setModel(model); } void READER::on_Filter2_currentIndexChanged(int index) { switch (index) { case 0: SachDaDuyet(); break; case 1: SachMoiVe(); break; case 2: NhacNho(); break; case 3: Phat(); break; } }
33.568562
105
0.648002
blackslender
4ded86b2ab65bb903d7588cb593b902c90bf6c66
3,049
cxx
C++
Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx
itkvideo/ITK
5882452373df23463c2e9410c50bc9882ca1e8de
[ "Apache-2.0" ]
1
2015-10-12T00:14:09.000Z
2015-10-12T00:14:09.000Z
Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx
itkvideo/ITK
5882452373df23463c2e9410c50bc9882ca1e8de
[ "Apache-2.0" ]
null
null
null
Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx
itkvideo/ITK
5882452373df23463c2e9410c50bc9882ca1e8de
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * 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. * *=========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkProbabilityDistribution.h" namespace itk { namespace Statistics { class ProbabilityDistributionTestingHelper : public ProbabilityDistribution { public: typedef ProbabilityDistributionTestingHelper Self; typedef ProbabilityDistribution Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; itkTypeMacro(ProbabilityDistributionTestingHelper, ProbabilityDistribution); itkNewMacro(Self); virtual SizeValueType GetNumberOfParameters() const { return 42; } virtual double EvaluatePDF(double ) const { return 42.0; } virtual double EvaluatePDF(double , const ParametersType&) const { return 42.0; } virtual double EvaluateCDF(double ) const { return 42.0; } virtual double EvaluateCDF(double , const ParametersType&) const { return 42.0; } virtual double EvaluateInverseCDF(double ) const { return 42.0; } virtual double EvaluateInverseCDF(double , const ParametersType&) const { return 42.0; } virtual bool HasMean() const { return true; } virtual bool HasVariance() const { return true; } virtual double GetMean() const { return 42.0; } virtual double GetVariance() const { return 42.0; } void RunTests() { std::cout << "Superclass name = " << this->Superclass::GetNameOfClass() << std::endl; std::cout << "Parameters = " << this->Superclass::GetParameters() << std::endl; } }; } } int itkProbabilityDistributionTest(int, char* [] ) { std::cout << "itkProbabilityDistributionTest Test \n \n"; typedef itk::Statistics::ProbabilityDistributionTestingHelper DistributionType; DistributionType::Pointer distributionFunction = DistributionType::New(); std::cout << "GetNameOfClass() = " << distributionFunction->GetNameOfClass() << std::endl; std::cout << "HasMean() = " << distributionFunction->HasMean() << std::endl; std::cout << "HasVariance() = " << distributionFunction->HasVariance() << std::endl; std::cout << "Number of parameters = " << distributionFunction->GetNumberOfParameters() << std::endl; distributionFunction->Print( std::cout ); distributionFunction->RunTests(); return EXIT_SUCCESS; }
38.1125
103
0.677927
itkvideo
4defa947d2fdd0525563e4e097cbb1cf304c16aa
2,405
hpp
C++
gsa/wit/COIN/include/SbbCompareBase.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/include/SbbCompareBase.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/include/SbbCompareBase.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. #ifndef SbbCompareBase_H #define SbbCompareBase_H //############################################################################# /* These are alternative strategies for node traversal. They can take data etc for fine tuning At present the node list is stored as a heap and the "test" comparison function returns true if node y is better than node x. */ #include "SbbNode.hpp" class SbbModel; class SbbCompareBase { public: SbbCompareBase * test_; // Default Constructor SbbCompareBase () {test_=NULL;}; // This allows any method to change behavior as it is called // after each solution virtual void newSolution(SbbModel * model) {}; // This Also allows any method to change behavior as it is called // after each solution virtual void newSolution(SbbModel * model, double objectiveAtContinuous, int numberInfeasibilitiesAtContinuous) {}; // This allows any method to change behavior as it is called // after every 1000 nodes virtual void every1000Nodes(SbbModel * model,int numberNodes) {}; virtual ~SbbCompareBase() {}; /// This is test function virtual bool test (SbbNode * x, SbbNode * y) {return true;}; bool operator() (SbbNode * x, SbbNode * y) { return test(x,y); } }; class SbbCompare { public: SbbCompareBase * test_; // Default Constructor SbbCompare () {test_=NULL;}; virtual ~SbbCompare() {}; bool operator() (SbbNode * x, SbbNode * y) { return test_->test(x,y); } }; //############################################################################# /* These can be alternative strategies for choosing variables Any descendant can be passed in by setVariableChoice */ class SbbChooseVariable { public: // Default Constructor SbbChooseVariable () {}; virtual ~SbbChooseVariable() {}; /** If strong branching, then only those passed in (and movement is that length) . If not strong branching then all passed in and ignore movement. Returns which one chosen (or -1 if none). way should be +1 if branching up, -1 if down */ virtual int chosen (const SbbModel * model,int numberToLookAt, const int * which, const double * downMovement, const double * upMovement, const double * solution, int & way, double & value)=0; }; #endif
29.329268
82
0.649896
kant
4df15c604af1d762325a2f9c0a991157880794fb
9,012
hpp
C++
include/xll/detail/type_text.hpp
jbuonagurio/libxll
2e91163dbcbeeef3644add6ac583ee98a37b5aac
[ "BSL-1.0" ]
1
2021-03-23T12:40:56.000Z
2021-03-23T12:40:56.000Z
include/xll/detail/type_text.hpp
jbuonagurio/libxll
2e91163dbcbeeef3644add6ac583ee98a37b5aac
[ "BSL-1.0" ]
1
2022-03-15T04:23:18.000Z
2022-03-15T04:23:56.000Z
include/xll/detail/type_text.hpp
jbuonagurio/libxll
2e91163dbcbeeef3644add6ac583ee98a37b5aac
[ "BSL-1.0" ]
null
null
null
// Copyright 2020 John Buonagurio // // 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 #pragma once /** * \file type_text.hpp * Compile-time mapping from primitive type to pxTypeText identifier wchar array. * \sa https://docs.microsoft.com/en-us/office/client-developer/excel/xlfregister-form-1#data-types */ #include <xll/config.hpp> #include <xll/attributes.hpp> #include <xll/fp12.hpp> #include <xll/xloper.hpp> #include <xll/pstring.hpp> #include <xll/detail/type_traits.hpp> #include <boost/mp11/list.hpp> #include <boost/mp11/algorithm.hpp> #include <boost/mp11/function.hpp> #include <array> #include <cstdint> #include <functional> #include <tuple> #include <type_traits> namespace xll { namespace detail { template<typename T> struct is_array_type : std::false_type {}; template<std::size_t N> struct is_array_type<static_fp12<N> *> : std::true_type {}; // Variable-type worksheet values and arrays (XLOPER12) template<class T, class U = void> struct type_text_arg { static_assert(!std::is_base_of_v<detail::variant_common_type, T>, "invalid operand type"); static constexpr std::array<wchar_t, 1> value = { L'Q' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, variant *>>> { static constexpr std::array<wchar_t, 1> value = { L'Q' }; }; // Asynchronous call handle (XLOPER12, xlTypeBigData) template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, handle *>>> { static constexpr std::array<wchar_t, 1> value = { L'X' }; }; // Larger grid floating-point array structure (FP12) template<class T> struct type_text_arg<T, std::enable_if_t<is_array_type<T>::value>> { static constexpr std::array<wchar_t, 2> value = { L'K', L'%' }; }; // Asynchronous UDF return type template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, void>>> { static constexpr std::array<wchar_t, 1> value = { L'>' }; }; // Integral types template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, bool>>> { static constexpr std::array<wchar_t, 1> value = { L'A' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, bool *>>> { static constexpr std::array<wchar_t, 1> value = { L'L' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, uint16_t>>> { static constexpr std::array<wchar_t, 1> value = { L'H' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int16_t>>> { static constexpr std::array<wchar_t, 1> value = { L'I' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int16_t *>>> { static constexpr std::array<wchar_t, 1> value = { L'M' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int32_t>>> { static constexpr std::array<wchar_t, 1> value = { L'J' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int32_t *>>> { static constexpr std::array<wchar_t, 1> value = { L'N' }; }; // Floating-point types template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, double>>> { static constexpr std::array<wchar_t, 1> value = { L'B' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, double *>>> { static constexpr std::array<wchar_t, 1> value = { L'E' }; }; // Null-terminated ASCII byte string (max. 256 characters) template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, char *>>> { static constexpr std::array<wchar_t, 1> value = { L'C' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, const char *>>> { static constexpr std::array<wchar_t, 1> value = { L'C' }; }; // Null-terminated Unicode wide-character string (max. 32767 characters) template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, wchar_t *>>> { static constexpr std::array<wchar_t, 2> value = { L'C', L'%' }; }; template<class T> struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, const wchar_t *>>> { static constexpr std::array<wchar_t, 2> value = { L'C', L'%' }; }; template<class A> struct attribute_text_arg; // Function attributes template<> struct attribute_text_arg<tag::cluster_safe> { static constexpr std::array<wchar_t, 1> value = { L'&' }; }; template<> struct attribute_text_arg<tag::volatile_> { static constexpr std::array<wchar_t, 1> value = { L'!' }; }; template<> struct attribute_text_arg<tag::thread_safe> { static constexpr std::array<wchar_t, 1> value = { L'$' }; }; template<> struct attribute_text_arg<tag::macro_sheet_equivalent> { static constexpr std::array<wchar_t, 1> value = { L'#' }; }; // Get a pxTypeText wchar array for a callable type. Concatenates the // pxTypeText wchar arrays for the return type, arguments and attributes // at compile-time using tuples. // // Requires compiler support for std::tuple_cat with std::array, and C++17 // for std::apply and std::invoke_result_t. // // Attributes: // - Asynchronous // - Cannot be combined with Cluster Safe // - One 'X' parameter to store the async call handle (xlTypeBigData) // - void return type, '>' // - Cluster Safe // - Cannot be combined with Asynchronous // - No XLOPER12 arguments that support range references (type 'U'). // - Add '&' to end of type text // - Volatile // - Add '!' to end of type text // - Thread Safe // - Add '$' to end of type text // - Macro Sheet Equivalent // - Cannot be combined with Thread Safe or Cluster Safe // - Handled as Volatile when using type 'R' or type 'U' arguments. // - Add '#' to end of type text template<class Result, class... Args, class... Tags> constexpr auto type_text_impl(attribute_set<Tags...>) { using namespace boost::mp11; using async_handle_count = mp_count<mp_list<Args...>, handle *>; using is_asynchronous = mp_to_bool<async_handle_count>; using has_void_return = std::is_void<Result>; using is_cluster_safe = mp_contains<mp_list<Tags...>, tag::cluster_safe>; using is_thread_safe = mp_contains<mp_list<Tags...>, tag::thread_safe>; using is_macro_sheet_equivalent = mp_contains<mp_list<Tags...>, tag::macro_sheet_equivalent>; static_assert(!mp_any<std::is_void<Args>...>::value, "arguments cannot be void"); static_assert(mp_less<async_handle_count, mp_size_t<2>>::value, "multiple async handles in argument list"); static_assert(!mp_all<is_asynchronous, mp_not<has_void_return>>::value, "async functions must have void return type"); static_assert(!mp_all<is_asynchronous, is_cluster_safe>::value, "async functions cannot be cluster-safe"); static_assert(!mp_all<is_macro_sheet_equivalent, is_thread_safe>::value, "macro sheet equivalent functions cannot be thread-safe"); static_assert(!mp_all<is_macro_sheet_equivalent, is_cluster_safe>::value, "macro sheet equivalent functions cannot be cluster-safe"); // Construct tuple using std::tuple_cat specialization for std:array. constexpr auto tuple = std::tuple_cat( type_text_arg<extern_c_type_t<Result>>::value, type_text_arg<extern_c_type_t<Args>>::value..., attribute_text_arg<Tags>::value... ); // Construct wchar array from the flat tuple. constexpr auto make_array = [](auto&& ...x) { return std::array{x...}; }; return std::apply(make_array, tuple); } // Overloads for various calling conventions and attributes. #if BOOST_ARCH_X86_32 template<class F, class... Args, class... Tags> constexpr auto type_text(F (__cdecl *)(Args...), attribute_set<Tags...> attrs) { using result_t = std::invoke_result_t<F(Args...), Args...>; return detail::type_text_impl<result_t, Args...>(attrs); } template<class F, class... Args, class... Tags> constexpr auto type_text(F (__stdcall *)(Args...), attribute_set<Tags...> attrs) { using result_t = std::invoke_result_t<F(Args...), Args...>; return detail::type_text_impl<result_t, Args...>(attrs); } template<class F, class... Args, class... Tags> constexpr auto type_text(F (__fastcall *)(Args...), attribute_set<Tags...> attrs) { using result_t = std::invoke_result_t<F(Args...), Args...>; return detail::type_text_impl<result_t, Args...>(attrs); } template<class F, class... Args, class... Tags> constexpr auto type_text(F (__vectorcall *)(Args...), attribute_set<Tags...> attrs) { using result_t = std::invoke_result_t<F(Args...), Args...>; return detail::type_text_impl<result_t, Args...>(attrs); } #else template<class F, class... Args, class... Tags> constexpr auto type_text(F (*)(Args...), attribute_set<Tags...> attrs) { using result_t = std::invoke_result_t<F(Args...), Args...>; return detail::type_text_impl<result_t, Args...>(attrs); } #endif // BOOST_ARCH_X86_32 } // namespace detail } // namespace xll
32.770909
99
0.694075
jbuonagurio
4df1d2b11318142a5d6080ee7f14f528f0fa8c65
2,124
cpp
C++
cpp/roman-to-int.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
cpp/roman-to-int.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
cpp/roman-to-int.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int romanToInt(string s) { if (s.empty()) return 0; unordered_map<const char *, int> roman_to_int = {std::make_pair("I", 1), std::make_pair("V", 5), std::make_pair("X", 10), std::make_pair("L", 50), std::make_pair("C", 100), std::make_pair("D", 500), std::make_pair("M", 1000)}; if (s.size() == 1) return roman_to_int[&s[0]]; int sum = 0; for (auto it = s.begin(); it != s.end();) { vector<int> nums(1, roman_to_int[&(*it)]); bool standard_order = true; // Ok, we just read a number ++it; while (it != s.end()) { auto next_num = roman_to_int[&(*it)]; if (next_num <= nums.back()) break; else { // This number is greater than the previous so we are reversing // the order standard_order = false; nums.push_back(next_num); // Read a number ++it; } } if (standard_order) { // We only read one number hopefully assert(nums.size() == 1); sum += nums.front(); } else { assert(nums.size() > 1); int sum_this_loop = nums.back(); for (auto nums_it = nums.rbegin() + 1; nums_it != nums.rend(); ++nums_it) sum_this_loop -= *nums_it; sum += sum_this_loop; } } return sum; } }; int main() { Solution soln; std::cout << soln.romanToInt("III") << std::endl; }
26.222222
89
0.392655
lindsayad
4df22f2837c6aee3c237eb2f94000fe2612f137c
477
cpp
C++
Main.cpp
shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman
6c7f6a260553a55bd95b400d286de4a76615429a
[ "MIT" ]
null
null
null
Main.cpp
shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman
6c7f6a260553a55bd95b400d286de4a76615429a
[ "MIT" ]
null
null
null
Main.cpp
shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman
6c7f6a260553a55bd95b400d286de4a76615429a
[ "MIT" ]
null
null
null
/** * Main Demo program for snowman exercise. * * Author: Shavit Luzon * Since : 2021-03 */ #include "snowman.hpp" #include <iostream> #include <stdexcept> using namespace std; using namespace ariel; int main() { int number; cout << "Type a number which represent a snowman: "; // Type a number and press enter cin >> number; // Get user input from the keyboard cout << "Your snowman is: " << snowman(number) << endl; // Display the input value }
22.714286
86
0.654088
shaCode256
4df3827815083eaaad9b713dbca753c12115665f
304
cpp
C++
C++ STL/Memberfunction_template_OutsideClass.cpp
junior-geek04/C-Stl
d7731c52616810f5067162453557075b524690a5
[ "Apache-2.0" ]
2
2021-05-27T12:18:32.000Z
2021-05-27T17:33:03.000Z
C++ STL/Memberfunction_template_OutsideClass.cpp
junior-geek04/C-Stl
d7731c52616810f5067162453557075b524690a5
[ "Apache-2.0" ]
null
null
null
C++ STL/Memberfunction_template_OutsideClass.cpp
junior-geek04/C-Stl
d7731c52616810f5067162453557075b524690a5
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; template<class t> class enjoy {public: t data; enjoy(t a) { data=a; } void display(); }; template<class t> void enjoy<t>::display() { cout<<data; } int main() { enjoy<int> e(94); cout<<e.data<<"\n"; e.display(); }
12.16
25
0.546053
junior-geek04
4df446b0d6258e7c84e7ea316ebba019ed3867cd
973
cpp
C++
libhydrosphere/source/common/compiler/memcpy.cpp
Kaenbyo/Hydrosphere
123143da54329dc678eea3ac3451bd9275a5513d
[ "Apache-2.0", "MIT" ]
17
2019-08-05T07:11:04.000Z
2019-11-27T11:55:04.000Z
libhydrosphere/source/common/compiler/memcpy.cpp
Kaenbyo/Hydrosphere
123143da54329dc678eea3ac3451bd9275a5513d
[ "Apache-2.0", "MIT" ]
1
2019-09-15T11:42:50.000Z
2019-09-15T11:42:50.000Z
libhydrosphere/source/common/compiler/memcpy.cpp
Kaenbyo/Hydrosphere
123143da54329dc678eea3ac3451bd9275a5513d
[ "Apache-2.0", "MIT" ]
3
2019-08-27T09:54:38.000Z
2019-09-11T09:50:08.000Z
/* * Copyright (c) 2019 Hydrosphère Developers * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ #include <stddef.h> #include <hs/hs_macro.hpp> // We define memcpy as we don't have any libraries that can provide it. // If there is any, as this is weak, it's going to be discared. extern "C" __HS_ATTRIBUTE_WEAK void *memcpy( void *dst, const void *src, size_t len) { const char *from = (const char *)src; char *to = reinterpret_cast<char *>(dst); while (len-- > 0) *to++ = *from++; return dst; } extern "C" __HS_ATTRIBUTE_WEAK void *memset( void *s, int c, size_t n) { unsigned char *p = reinterpret_cast<unsigned char *>(s); while (n--) *p++ = (unsigned char)c; return s; }
31.387097
71
0.67112
Kaenbyo
4df470f507cf3cc70118ea94ef7177fbcdae8d59
3,545
cpp
C++
_investigacion/contests/un_marzo/polygon_intersection.cpp
civilian/competitive_programing
a6ae7ad0db84240667c1dd6231c51c586ba040c7
[ "MIT" ]
1
2016-02-11T21:28:22.000Z
2016-02-11T21:28:22.000Z
_investigacion/contests/un_marzo/polygon_intersection.cpp
civilian/competitive_programing
a6ae7ad0db84240667c1dd6231c51c586ba040c7
[ "MIT" ]
null
null
null
_investigacion/contests/un_marzo/polygon_intersection.cpp
civilian/competitive_programing
a6ae7ad0db84240667c1dd6231c51c586ba040c7
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <cctype> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <list> #include <set> #include <map> #include <bitset> #include <algorithm> #include <numeric> #include <complex> #define D(x) cerr << #x << " = " << (x) << endl; #define REP(i,a,n) for(int i=(a); i<(int)(n); i++) #define foreach(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it) #define ALL(v) (v).begin(), (v).end() using namespace std; typedef long long int64; const int INF = (int)(1e9); const int64 INFLL = (int64)(1e18); const double EPS = 1e-13; const double PI = acos(-1.0); double sqr(double v) { return v*v; } struct point { double x, y; point(double _x=0, double _y= 0) { x = _x; y = _y; } double dist(const point& p) const { double cc = sqr(p.x - x) + sqr(p.y - y); return sqrt(cc); } } pivot; // solve system ecuation bool intersect(const point & A, const point & B, const point & C, const point & D, point& E) { double a, b, c, d, rx, ry, det, s, t, x, y; a = (B.x - A.x); // R' b = (C.x - D.x); // R c = (B.y - A.y); d = (C.y - D.y); rx = C.x - A.x; ry = C.y - A.y; det = a*d - b*c; // parallel lines if(fabs(det) < EPS) return false; // Not valid det = 0 s = (rx * d - b * ry) / det; t = (a * ry - rx * c) / det; // check if s, t are in [0,1] for an open line segment // if not they do not intersects if(s < 0.0 || s > 1.0 || t < 0.0 || t > 1.0) return false; // use s or t in any parametric ecuation x = A.x + (B.x - A.x) * s; y = A.y + (B.y - A.y) * s; E.x = x; E.y = y; return true; } double cross(point p, point q, point r) { return (r.x - q.x) * (p.y - q.y) - (r.y - q.y) * (p.x - q.x); } double angle(point a, point b, point c) { double ux = b.x - a.x, uy = b.y - a.y; double vx = c.x - a.x, vy = c.y - a.y; return acos((ux*vx + uy*vy) / sqrt((ux*ux + uy*uy) * (vx*vx + vy*vy))); } bool in_polygon(point p, vector<point> P) { if(P.size() == 0) return false; double sum = 0; for(int i = 0; i < P.size() - 1; i++) { if(cross(p, P[i], P[i+1]) < 0) sum -= angle(p, P[i], P[i+1]); else sum += angle(p, P[i], P[i+1]); } return (fabs(sum - 2*PI) < EPS || fabs(sum + 2*PI) < EPS); } vector<point> get_polygon(int n) { vector<point> p(n); for(int i = 0; i < n; i++) { cin >> p[i].x >> p[i].y; } p.push_back(p[0]); return p; } struct cmp { bool operator ()(point a, point b) const { if(fabs(a.x - b.x) < EPS) return a.y < b.y; return a.x < b.x; } }; int main() { ios_base::sync_with_stdio(false); int n, m; cout.precision(2); cout.setf(ios::fixed); while(cin >> n) { if(n < 3) break; vector<point> p1 = get_polygon(n); cin >> m; vector<point> p2 = get_polygon(m); set<point, cmp> ans; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { point e; if(intersect(p1[i], p1[i+1], p2[j], p2[j+1], e)) { ans.insert(e); } } } for(int i = 0; i < n; i++) if(in_polygon(p1[i], p2)) ans.insert(p1[i]); for(int i = 0; i < m; i++) if(in_polygon(p2[i], p1)) ans.insert(p2[i]); cout << (int)ans.size() << endl; if(!ans.empty()) { foreach(p, ans) { cout << p->x << " " << p->y << endl; } } } return 0; }
20.491329
94
0.514245
civilian
4df8e9d4deab18f1114c98c7a05e1c916c65f84f
320
cxx
C++
tomviz/Logger.cxx
sankhesh/tomviz
7116f4eb75b30534a24462f4ddfb1694fe41c308
[ "BSD-3-Clause" ]
284
2015-01-05T08:53:20.000Z
2022-03-31T07:35:16.000Z
tomviz/Logger.cxx
sankhesh/tomviz
7116f4eb75b30534a24462f4ddfb1694fe41c308
[ "BSD-3-Clause" ]
1,579
2015-03-19T15:56:44.000Z
2022-03-21T11:29:04.000Z
tomviz/Logger.cxx
sankhesh/tomviz
7116f4eb75b30534a24462f4ddfb1694fe41c308
[ "BSD-3-Clause" ]
74
2015-01-29T16:24:32.000Z
2022-03-07T21:52:29.000Z
/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "Logger.h" #include "PythonUtilities.h" #include <QDebug> namespace tomviz { void Logger::critical(const QString& msg) { qCritical() << msg; } } // namespace tomviz
20
71
0.7
sankhesh
4dfa60ed9c6171598f0a9edffa74f6a84d355fcb
10,144
cpp
C++
SPARKS/BaseSpark/ComponentSystem.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
SPARKS/BaseSpark/ComponentSystem.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
SPARKS/BaseSpark/ComponentSystem.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
#include "stdAfx.h" #include "Logger.h" #include "ErrorHandling.h" #include "fileops.h" #include "Component.h" #include "IConcurrent.h" #include "Configuration.h" #include "ComponentSystem.h" #include <fstream> #include <iostream> #include <sstream> using namespace std; map<string, string> ComponentSystem::typesConversion; map<string, string> ComponentSystem::interfacesConversion; void ComponentSystem::initializeComponents() { LoggerInfo("[FIONA-logger]Initializing components..."); for ( int i = 0; i < interfaceImplementationsRepository.instances.componentInstances.size(); i++ ) { LoggerInfo("[FIONA-logger]Initializing instance %s", interfaceImplementationsRepository.instances.componentInstances[i].first.c_str()); interfaceImplementationsRepository.instances.componentInstances[i].second->component->init(); } } void ComponentSystem::uninitializeComponents() { /* reverse iterator */ map<ComponentInstances::TInstanceName, ComponentInstanceData *>::reverse_iterator it; LoggerInfo("Quitting components..."); for (int i = interfaceImplementationsRepository.instances.componentInstances.size() - 1; i >= 0; i-- ) { LoggerInfo( "Uninittializing instance %s", interfaceImplementationsRepository.instances.componentInstances[i].first.c_str() ); interfaceImplementationsRepository.instances.componentInstances[i].second->component->quit(); } } void ComponentSystem::connectComponentInstances() { for ( int i = 0; i < interfaceImplementationsRepository.instances.componentInstances.size(); i++ ) { interfaceImplementationsRepository.instances.componentInstances[i].second->component->initializeRequiredInterfaces(); } } IApplication *ComponentSystem::getApplication() { pugi::xpath_node_set mainApplicationNodeSet; mainApplicationNodeSet = xmlParser.xpathQuery( "/ComponentNetwork/ApplicationDescription[@applicationComponent]" ); if (mainApplicationNodeSet.empty()) { ERR("No /ComponentNetwork/ApplicationDescription elements with attribute 'applicationComponent' found " "in component network XML" ); } if (mainApplicationNodeSet.size() > 1) { ERR("Only one /ComponentNetwork/ApplicationDescription element with attribute 'applicationComponent' allowed " "in component network XML" ); } const char *appInstanceName = mainApplicationNodeSet.first().node().attribute("applicationComponent").value(); Component *c = interfaceImplementationsRepository. instances.getInstance((char *)appInstanceName)->component; IApplication *app; app = dynamic_cast<IApplication *>(c); if (NULL == app) { ERR("Component instance %s does not implement IApplication", appInstanceName); } return app; } void ComponentSystem::startComponents() { for ( int idx = 0; idx < interfaceImplementationsRepository.instances.componentInstances.size(); idx++ ) { vector<string> &providedInterfaces = interfaceImplementationsRepository.instances.componentInstances[idx].second->componentDescription->providedInterfaces; for (int i = 0; i < providedInterfaces.size(); i++) { if (!strcmp("IConcurrent", providedInterfaces[i].c_str())) { IConcurrent *concurrentComponent; concurrentComponent = dynamic_cast<IConcurrent *>(interfaceImplementationsRepository.instances.componentInstances[idx].second->component); if (NULL == concurrentComponent) { ERR("Component instance %s does not implement IConcurrent", interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str() ); } LoggerInfo("Starting component instance: %s", interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str()); concurrentComponent->start(); break; } } } } void ComponentSystem::stopComponents() { for ( int idx = 0; idx < interfaceImplementationsRepository.instances.componentInstances.size(); idx++ ) { vector<string> &providedInterfaces = interfaceImplementationsRepository.instances.componentInstances[idx].second->componentDescription->providedInterfaces; for (int i = 0; i < providedInterfaces.size(); i++) { if (!strcmp("IConcurrent", providedInterfaces[i].c_str())) { IConcurrent *concurrentComponent; concurrentComponent = dynamic_cast<IConcurrent *>(interfaceImplementationsRepository.instances.componentInstances[idx].second->component); if (NULL == concurrentComponent) { ERR("Component instance %s does not implement IConcurrent", interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str() ); } LoggerInfo("Stopping component instance: %s", interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str()); concurrentComponent->stop(); break; } } } } void ComponentSystem::loadConfiguration(char * configFile) { pugi::xpath_node_set mainAppConfigFileNodeSet; mainAppConfigFileNodeSet = xmlParser.xpathQuery( "/ComponentNetwork/ApplicationDescription[@applicationConfig]" ); if (mainAppConfigFileNodeSet.empty()) { ERR("No /ComponentNetwork/ApplicationDescription element with attribute 'applicationConfig' found " "in component network XML" ); } if (mainAppConfigFileNodeSet.size() > 1) { ERR("Only one /ComponentNetwork/ApplicationDescription element with attribute 'applicationConfig' allowed " "in component network XML" ); } // Get config file path realtive to app data environment variable const char *appConfigFile = mainAppConfigFileNodeSet.first().node().attribute("applicationConfig").value(); // Get filesystem config file path char filesystemConfigFilePaht[1024]; getApplicationDataFileFullPath((char *)appConfigFile, filesystemConfigFilePaht, 1024); // Load session configuration file libconfig::Config temporal; if(configFile) { globalConfiguration.loadConfiguration(configFile); LoggerInfo("%s loaded", configFile); try{ for(int i = 0; i < globalConfiguration.configuration.getRoot().getLength(); i++) { saveSetting(temporal, globalConfiguration.configuration, globalConfiguration.configuration.getRoot()[i]); } } catch(libconfig::SettingNotFoundException &e){ LoggerError("loadConfiguration:%s",e.what()); } catch(libconfig::SettingTypeException &e){ LoggerError("loadConfiguration:%s",e.what()); } } // Load configuration file globalConfiguration.loadConfiguration(filesystemConfigFilePaht); LoggerInfo("%s loaded", filesystemConfigFilePaht); // Add session settings to configuration try { for(int i = 0; i < temporal.getRoot().getLength(); i++) { saveSetting(globalConfiguration.configuration, temporal, temporal.getRoot()[i]); } } catch(libconfig::SettingNotFoundException &e){ LoggerError("loadConfiguration:%s",e.what()); } catch(libconfig::SettingTypeException &e){ LoggerError("loadConfiguration:%s",e.what()); } } void ComponentSystem::loadTypesConversion() { ifstream is; string line, originalNameType, friendlyNameType; is.open ("/adele/dev/typesMap", ifstream::in); if(!is) { LoggerWarn("Could not find typesMap file, it must be placed in /adele/dev directory."); LoggerWarn("'Friendly names' will be disabled"); return; } while(!is.eof()){ getline(is, line); if(line.compare("")!=0){ istringstream iss(line); iss >> friendlyNameType; iss >> originalNameType; typesConversion.insert( pair<FriendlyNameType, OriginalNameType>(friendlyNameType, originalNameType) ); } } } void ComponentSystem::loadInterfacesConversion() { ifstream is; string line, originalNameType, friendlyNameType; is.open ("/adele/dev/interfacesMap", ifstream::in); if(!is) { LoggerWarn("Could not find interfacesMap file, it must be placed in /adele/dev directory."); LoggerWarn("'Friendly names' will be disabled"); return; } while(!is.eof()){ getline(is, line); if(line.compare("")!=0){ istringstream iss(line); iss >> friendlyNameType; iss >> originalNameType; interfacesConversion.insert( pair<FriendlyNameType, OriginalNameType>(friendlyNameType, originalNameType) ); } } } void ComponentSystem::run(char *componentNetworkFileName, char * configFile) { // Use PugiXML to parse component XML. xmlParser.parseXmlFile(componentNetworkFileName); // Local global configuration (path included in XML) loadConfiguration(configFile); // Load the mapping names between friendly and real names loadTypesConversion(); loadInterfacesConversion(); // Interpret component XML readComponentDescriptions(); readComponentInstances(); readComponentConnections(); connectComponentInstances(); /*** Run application ***/ initializeComponents(); startComponents(); try { IApplication *application = getApplication(); application->run(); } catch(Exception &ex) { LoggerError(ex.msg); } catch(...) { LoggerError("Unknown exception"); } stopComponents(); uninitializeComponents(); } void ComponentSystem::saveSetting(libconfig::Config & destConfig, libconfig::Config & sourceConfig, libconfig::Setting & setting) { const char * name = setting.getName(); // If the param exists, delete it and store the newest(from session) if(destConfig.getRoot().exists(name)) { LoggerWarn("Setting \"%s\" already exists. Updating...", name); destConfig.getRoot().remove(name); } int type = setting.getType(); libconfig::Setting & set = destConfig.getRoot().add(name, setting.getType()); switch(type) { case 5: bool b; sourceConfig.lookupValue(name, b); set = b; return; case 3: float f; sourceConfig.lookupValue(name, f); set = f; return; case 1: int i; sourceConfig.lookupValue(name, i); set = i; return; case 2: long long i64; sourceConfig.lookupValue(name, i64); set = i64; return; case 4: string s; sourceConfig.lookupValue(name, s); set = s; return; } }
30.011834
158
0.716285
adele-robots
4dfe8155469073b68112c037559d4dcd6a88e3e6
1,528
cpp
C++
Source/common/SoundBank.cpp
leduyquang753/tetrec
9f1da4485b1a6412af5b244ad99aa462b65a374b
[ "MIT" ]
16
2021-08-03T07:44:15.000Z
2022-01-17T15:14:17.000Z
Source/common/SoundBank.cpp
leduyquang753/tetrec
9f1da4485b1a6412af5b244ad99aa462b65a374b
[ "MIT" ]
1
2021-08-03T23:36:55.000Z
2021-08-04T03:01:36.000Z
Source/common/SoundBank.cpp
leduyquang753/tetrec
9f1da4485b1a6412af5b244ad99aa462b65a374b
[ "MIT" ]
null
null
null
#include <memory> #include <random> #include <string> #include <vector> #include "soloud.h" #include "soloud_wav.h" #include "common/Utils.h" #include "common/SoundBank.h" using namespace std::string_literals; // SoundBankSingle ------------------------------------------------------------- SoundBankSingle::SoundBankSingle() {} SoundBankSingle::SoundBankSingle(const std::string &name): SoundBank() { load(name); } void SoundBankSingle::load(const std::string &name) { std::string fileName = "Assets/Sounds/"s + name + ".ogg"s; buffer = std::make_shared<SoLoud::Wav>(); buffer->load(fileName.c_str()); } std::shared_ptr<SoLoud::Wav> SoundBankSingle::getOne() { return buffer; } // SoundBankMultiple ----------------------------------------------------------- std::default_random_engine SoundBankMultiple::randomEngine = Utils::getRandomEngine(); SoundBankMultiple::SoundBankMultiple() {} SoundBankMultiple::SoundBankMultiple( const std::string &name, const int count ) { load(name, count); } void SoundBankMultiple::load( const std::string &name, const int count ) { randomInt = std::uniform_int_distribution<int>(0, count-1); buffers.reserve(count); for (int i = 0; i != count; i++) { std::string fileName = "Assets/Sounds/"s + name + ' ' + std::to_string(i+1) + ".ogg"s; auto buffer = std::make_shared<SoLoud::Wav>(); buffer->load(fileName.c_str()); buffers.push_back(buffer); } } std::shared_ptr<SoLoud::Wav> SoundBankMultiple::getOne() { return buffers[randomInt(randomEngine)]; }
24.253968
80
0.655105
leduyquang753
15006fe04e62b248d130fe4904f72e3bfa5b0bdb
5,635
cpp
C++
pikoc/src/Frontend/PipeASTVisitor.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
15
2015-05-19T08:23:26.000Z
2021-11-26T02:59:36.000Z
pikoc/src/Frontend/PipeASTVisitor.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
null
null
null
pikoc/src/Frontend/PipeASTVisitor.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
4
2015-10-06T15:14:43.000Z
2020-02-20T13:17:11.000Z
#include "Frontend/clangUtilities.hpp" #include "Frontend/PipeASTVisitor.hpp" #include "Frontend/StageASTVisitor.hpp" bool PipeASTVisitor::VisitCXXRecordDecl(clang::CXXRecordDecl *decl) { // Stop if errors have occurred in compilation if(context.getDiagnostics().hasErrorOccurred()) { llvm::errs() << "Compilation errors have occurred. " << "Please resolve the above error messages.\n"; exit(5); return false; } if(pipeFound) return true; if(!decl->hasDefinition()) return true; clang::CXXRecordDecl *defn = decl->getDefinition(); if(!isPikoPipe(defn)) { return true; } pipeFound = true; psum->name = defn->getIdentifier()->getName(); bool constState_type_found = false; bool mutableState_type_found = false; bool input_type_found = false; //Add Stages to Pipe for(clang::RecordDecl::field_iterator bf = defn->field_begin(), ef = defn->field_end(); bf != ef; ++bf) { std::string var_name = bf->getNameAsString(); if(var_name == "constState_") { if(bf->getType()->isPointerType()) { const clang::QualType& qt = bf->getType()->getPointeeType(); psum->constState_type = qt.getAsString(); printf("Found constant state type %s\n", psum->constState_type.c_str()); constState_type_found = true; } else { __DEB; } } if(var_name == "mutableState_") { if(bf->getType()->isPointerType()) { const clang::QualType& qt = bf->getType()->getPointeeType(); psum->mutableState_type = qt.getAsString(); printf("Found mutable state type %s\n", psum->mutableState_type.c_str()); mutableState_type_found = true; } else { __DEB; } } if(!bf->getType()->isRecordType()) continue; clang::CXXRecordDecl *fieldClass = bf->getType()->getAsCXXRecordDecl(); if(var_name == "h_input") { if(fieldClass->getNameAsString() == "PikoArray") { assert(llvm::isa<clang::TemplateSpecializationType>(bf->getType())); const clang::TemplateSpecializationType* temptype = llvm::cast<clang::TemplateSpecializationType>(bf->getType()); assert(temptype->getNumArgs() == 1); psum->input_type = temptype->getArgs()[0].getAsType()->getAsCXXRecordDecl()->getNameAsString(); printf("Found input type %s\n", psum->input_type.c_str()); input_type_found = true; } else { __DEB; } } if(!StageASTVisitor::isPikoStage(fieldClass)) continue; if(!fieldClass->hasDefinition()) { llvm::errs() << "No definition for stage " << fieldClass->getNameAsString() << " used in pipe " << psum->name << "\n"; return false; } clang::CXXRecordDecl *fieldClassDefn = fieldClass->getDefinition(); if(!addStageToPipe(fieldClassDefn, *bf)) { llvm::errs() << "Unable to add stage \"" << bf->getNameAsString() << "\" of type \"" << fieldClass->getNameAsString() << "\" to pipe \"" << psum->name << "\"\n"; return false; } printf("Added stage %s\n", bf->getNameAsString().c_str()); } assert(constState_type_found && mutableState_type_found && input_type_found); //Find pikoConnect calls //for(CXXRecordDecl::ctor_iterator // bc = defn->ctor_begin(), ec = defn->ctor_end(); bc != ec; ++bc) { //} clang::Stmt *ctorBody = defn->ctor_begin()->getBody(); for(clang::Stmt::child_range child = ctorBody->children(); child; ++child) { //(*child)->dump(); if(!llvm::isa<clang::CallExpr>(*child)) { //printf(" exiting early\n"); continue; } else { } clang::CallExpr *pikoConn = llvm::cast<clang::CallExpr>(*child); if(getFuncName(pikoConn->getDirectCallee()) != "pikoConnect") { continue; } else { } clang::MemberExpr *outStage = llvm::cast<clang::MemberExpr>(unrollCasts(pikoConn->getArg(0))); clang::MemberExpr *inStage = llvm::cast<clang::MemberExpr>(unrollCasts(pikoConn->getArg(1))); std::string outStageName = outStage->getMemberNameInfo().getAsString(); std::string inStageName = inStage->getMemberNameInfo().getAsString(); stageSummary *outStageSum = psum->findStageByName(outStageName); stageSummary *inStageSum = psum->findStageByName(inStageName); llvm::APSInt outPortInt; llvm::APSInt inPortInt; if(!pikoConn->getArg(2)->EvaluateAsInt(outPortInt, context) || !pikoConn->getArg(3)->EvaluateAsInt(inPortInt, context)) { llvm::errs() << "pikoConnect port number arguments must " << "be compile-time constants\n"; return false; } int outPortNum = outPortInt.getSExtValue(); int inPortNum = inPortInt.getSExtValue(); outStageSum->nextStageNames.push_back(inStageSum->name); outStageSum->nextStagesByPort[outPortNum].push_back(inStageSum); outStageSum->outPortTypes[outPortNum] = inStageSum->typeNumber; } psum->processLinks(); return true; } // Must pass in definition bool PipeASTVisitor::addStageToPipe(clang::CXXRecordDecl *d, clang::FieldDecl *field) { stageSummary ssum = (*stageMap)[d->getNameAsString()]; ssum.name = field->getNameAsString(); ssum.fullType = field->getType().getAsString(); psum->stages.push_back(ssum); return true; } // Must pass in definition bool PipeASTVisitor::isPikoPipe(clang::CXXRecordDecl *d) { for(clang::CXXRecordDecl::base_class_iterator bbc = d->bases_begin(), ebc = d->bases_end(); bbc != ebc; ++bbc) { if(bbc->getType().getAsString() == "class PikoPipe") { return true; } } return false; } int PipeASTVisitor::getPortNumber(std::string portName) { if(portName == "out0") return 0; else if(portName == "out1") return 1; else if(portName == "out2") return 2; else if(portName == "out3") return 3; else if(portName == "out4") return 4; else return -1; }
24.714912
87
0.670453
piko-dev
1501554ff5b6f85c1379ffba8a4dee83c4c569a2
4,266
cpp
C++
TestSuite/url_unittest.cpp
w20089527/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
1
2019-08-10T20:29:13.000Z
2019-08-10T20:29:13.000Z
TestSuite/url_unittest.cpp
whrool/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
null
null
null
TestSuite/url_unittest.cpp
whrool/Net
ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright(c) 2015 huan.wang // // 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 "stdafx.h" #include "CppUnitTest.h" #include "net/base/url.h" using namespace net::http; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace TestSuite { TEST_CLASS(Url_Test) { public: TEST_METHOD(Test_Parse) { std::string strUrl = "http://www.google.com/?q=abc#frag"; auto url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme() == "http"); Assert::IsTrue(url.GetHost() == "www.google.com"); Assert::IsTrue(url.GetPath() == "/"); Assert::IsTrue(url.GetRawQuery() == "q=abc"); Assert::IsTrue(url.GetFragment() == "frag"); strUrl = "http://www.google.com:8080?q=abc#frag"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme() == "http"); Assert::IsTrue(url.GetHost() == "www.google.com"); Assert::IsTrue(url.GetPath() == "/"); Assert::IsTrue(url.GetPort() == 8080); Assert::IsTrue(url.GetRawQuery() == "q=abc"); Assert::IsTrue(url.GetFragment() == "frag"); strUrl = "file:///usr/home/r.txt"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme() == "file"); Assert::IsTrue(url.GetHost().empty()); Assert::IsTrue(url.GetPath() == "/usr/home/r.txt"); strUrl = ":///usr/home/r.txt"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme().empty()); Assert::IsTrue(url.GetHost().empty()); Assert::IsTrue(url.GetPath().empty()); strUrl = "/usr/home/r.txt"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme().empty()); Assert::IsTrue(url.GetHost().empty()); Assert::IsTrue(url.GetPath() == strUrl); strUrl = "http:/usr/home/r.txt"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme() == "http"); Assert::IsTrue(url.GetHost().empty()); Assert::IsTrue(url.GetPath().empty()); strUrl = "//www.google.com/search?q=r"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme().empty()); Assert::IsTrue(url.GetHost() == "www.google.com"); Assert::IsTrue(url.GetPath() == "/search"); Assert::IsTrue(url.GetRawQuery() == "q=r"); strUrl = "mailto:hello@gmail.com"; url = Url::Parse(strUrl); Assert::IsTrue(url.GetScheme() == "mailto"); Assert::IsTrue(url.GetHost().empty()); Assert::IsTrue(url.GetPath().empty()); Assert::IsTrue(url.GetOpaque() == "hello@gmail.com"); } TEST_METHOD(Test_ResolveReference_ToString) { Url baseUrl = Url::Parse("http://www.google.com/search?q=q"); auto resolveUrl = baseUrl.ResolveReference("../../../hello?q=b#f"); Assert::IsTrue(resolveUrl.ToString() == "http://www.google.com/hello/?q=b#f"); Assert::IsTrue(Url::Parse("mailto:abc@gmail.com").ToString() == "mailto:abc@gmail.com"); } }; }
42.66
129
0.592827
w20089527
1501694fdcde864f56bd759fc7b468560a1c44f2
2,013
cpp
C++
manager/src/CommManager.cpp
FCS-holding/blaze
ed6146219ec47f95ed352c611576edf3f418d803
[ "Apache-2.0" ]
null
null
null
manager/src/CommManager.cpp
FCS-holding/blaze
ed6146219ec47f95ed352c611576edf3f418d803
[ "Apache-2.0" ]
null
null
null
manager/src/CommManager.cpp
FCS-holding/blaze
ed6146219ec47f95ed352c611576edf3f418d803
[ "Apache-2.0" ]
null
null
null
#include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <fcntl.h> #include <fstream> #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <time.h> #ifdef NDEBUG #define LOG_HEADER "CommManager" #endif #include <glog/logging.h> #include "blaze/CommManager.h" #include "blaze/PlatformManager.h" #include "blaze/BlockManager.h" #include "blaze/TaskManager.h" #define MAX_MSGSIZE 4096 namespace blaze { CommManager::CommManager( PlatformManager* _platform, std::string _address, int _port, int _max_threads): ip_address(_address), srv_port(_port), platform_manager(_platform) { // create io_service pointers ios_ptr _ios(new io_service); endpoint_ptr _endpoint(new ip::tcp::endpoint( ip::address::from_string(ip_address), srv_port)); acceptor_ptr _acceptor(new ip::tcp::acceptor(*_ios, *_endpoint)); ios = _ios; endpoint = _endpoint; acceptor = _acceptor; // start io service processing loop io_service::work work(*ios); for (int t=0; t<_max_threads; t++) { comm_threads.create_thread( boost::bind(&io_service::run, ios.get())); } // asynchronously start listening for new connections startAccept(); VLOG(2) << "Listening for new connections at " << ip_address << ":" << srv_port; } CommManager::~CommManager() { ios->stop(); comm_threads.interrupt_all(); comm_threads.join_all(); DVLOG(1) << "Stopped CommManager"; } void CommManager::startAccept() { socket_ptr sock(new ip::tcp::socket(*ios)); acceptor->async_accept(*sock, boost::bind(&CommManager::handleAccept, this, boost::asio::placeholders::error, sock)); } void CommManager::handleAccept( const boost::system::error_code& error, socket_ptr sock) { if (!error) { ios->post(boost::bind(&CommManager::process, this, sock)); startAccept(); } } } // namespace blaze
23.406977
67
0.660705
FCS-holding
1503830f14ffe7593a49ff3447f9cdbc31dd5a60
3,416
cpp
C++
Frameworks/Starboard/DNSService.cpp
crossmob/WinObjC
7bec24671c4c18b81aaf85eff2887438f18a697c
[ "MIT" ]
6,717
2015-08-06T18:04:37.000Z
2019-05-04T12:38:51.000Z
Frameworks/Starboard/DNSService.cpp
Michael-Young48/WinObjC
7bec24671c4c18b81aaf85eff2887438f18a697c
[ "MIT" ]
2,711
2015-08-06T18:41:09.000Z
2019-04-29T12:14:23.000Z
Frameworks/Starboard/DNSService.cpp
Michael-Young48/WinObjC
7bec24671c4c18b81aaf85eff2887438f18a697c
[ "MIT" ]
1,021
2015-08-06T18:08:56.000Z
2019-04-14T06:50:57.000Z
//****************************************************************************** // // Copyright (c) 2016 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 "Starboard.h" #include "dns_sd.h" extern "C" { /** @Status Stub */ void DNSServiceRefDeallocate(DNSServiceRef sdRef) { UNIMPLEMENTED(); } /** @Status Stub */ DNSServiceErrorType DNSServiceSetDispatchQueue(DNSServiceRef service, dispatch_queue_t queue) { UNIMPLEMENTED(); return 0; } /** @Status Stub */ DNSServiceErrorType DNSServiceBrowse(DNSServiceRef* sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, const char* regtype, const char* domain, DNSServiceBrowseReply callBack, void* context) { UNIMPLEMENTED(); return 0; } /** @Status Stub */ DNSServiceErrorType DNSServiceGetAddrInfo(DNSServiceRef* sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceProtocol protocol, const char* hostname, DNSServiceGetAddrInfoReply callBack, void* context) { UNIMPLEMENTED(); return 0; } /** @Status Stub */ DNSServiceErrorType DNSServiceResolve(DNSServiceRef* sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, const char* name, const char* regtype, const char* domain, DNSServiceResolveReply callBack, void* context) { UNIMPLEMENTED(); return 0; } /** @Status Stub */ DNSServiceErrorType DNSServiceRegister(DNSServiceRef* sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, const char* name, const char* regtype, const char* domain, const char* host, uint16_t port, uint16_t txtLen, const void* txtRecord, DNSServiceRegisterReply callBack, void* context) { UNIMPLEMENTED(); return 0; } }
34.505051
95
0.462237
crossmob
1503c4b0cda665eac97f9160dbf3473cf56e5229
14,328
cpp
C++
src/tool/editor_file/editor.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/tool/editor_file/editor.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/tool/editor_file/editor.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
#include "editor.hpp" #include "../../engine/mlib/mlib.hpp" #include "../../version.h" #include <wx/notebook.h> #define L_TEXT_X 3 #define L_TEXT_Y 3 #define E_V1 0x31307645 #define ENTITY_VERSION 0x32307645 #define ENGINE_SFML_VERSION "SFML v2.4.1" BEGIN_EVENT_TABLE(Editor, wxFrame) EVT_BUTTON(ID_BTN_AS_NEW, Editor::as_new) EVT_BUTTON(ID_BTN_AS_LOAD, Editor::as_load) EVT_BUTTON(ID_BTN_AS_SAVE, Editor::as_save) EVT_BUTTON(ID_BTN_AS_SAVEAS, Editor::as_saveas) EVT_BUTTON(ID_BTN_D_NEW, Editor::d_new) EVT_BUTTON(ID_BTN_D_LOAD, Editor::d_load) EVT_BUTTON(ID_BTN_D_SAVE, Editor::d_save) EVT_BUTTON(ID_BTN_D_SAVEAS, Editor::d_saveas) EVT_BUTTON(ID_BTN_DP_LOAD, Editor::dp_load) EVT_BUTTON(ID_BTN_DP_BUILD, Editor::dp_build) EVT_BUTTON(ID_BTN_DP_IMPORT, Editor::dp_import) EVT_BUTTON(ID_BTN_DP_EXPORT, Editor::dp_export) END_EVENT_TABLE() Editor::Editor(const wxString& title) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(400, 500), wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN) { wxFrame::SetIcon(wxIcon(_T("MAINICON"))); Out.setFile("log_file_editor.txt", true); Out.setOutput(false, true); Out = std::string("EG Engine v") + AutoVersion::STATUS + " " + AutoVersion::FULLVERSION_STRING + "\n"; Out = std::string("File Editor Build - ") + ENGINE_SFML_VERSION + "\n"; wxBoxSizer *sizer_vertical = new wxBoxSizer(wxVERTICAL); SetSizer(sizer_vertical); mainsizer = new wxPanel(this); sizer_vertical->Add(mainsizer, 10, wxEXPAND, 0); wxNotebook *tabs = new wxNotebook(mainsizer, -1, wxPoint(0, 0), wxSize(400, 500), wxNB_TOP | wxNB_MULTILINE, _T("TEST")); tabs->AddPage(new wxPanel(tabs), _T("Animated Sprite")); tabs->AddPage(new wxPanel(tabs), _T("Drawable")); tabs->AddPage(new wxPanel(tabs), _T("Build data pack")); tabs->SetSize(GetClientRect()); tabs->Refresh(); wxPanel* current_panel; // animated sprite tab current_panel = (wxPanel*)tabs->GetPage(0); new wxButton(current_panel, ID_BTN_AS_NEW, _T("New"), wxPoint(5,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_AS_LOAD, _T("Load"), wxPoint(60,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_AS_SAVE, _T("Save"), wxPoint(115,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_AS_SAVEAS, _T("Save as"), wxPoint(170,0), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("File"), wxPoint(5+L_TEXT_X,25+L_TEXT_Y)); as_file = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,25), wxSize(330, 23)); new wxStaticText(current_panel, -1, _T("Sprite width"), wxPoint(5+L_TEXT_X,50+L_TEXT_Y)); as_w = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(100,50), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("Sprite height"), wxPoint(155+L_TEXT_X,50+L_TEXT_Y)); as_h = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(250,50), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("Frame count"), wxPoint(5+L_TEXT_X,75+L_TEXT_Y)); as_fc = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(100,75), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("Frame time (ms)"), wxPoint(155+L_TEXT_X,75+L_TEXT_Y)); as_ft = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(250,75), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("Sprite"), wxPoint(5+L_TEXT_X,100+L_TEXT_Y)); as_sprite = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,100), wxSize(180, 23)); // drawable current_panel = (wxPanel*)tabs->GetPage(1); new wxButton(current_panel, ID_BTN_D_NEW, _T("New"), wxPoint(5,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_D_LOAD, _T("Load"), wxPoint(60,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_D_SAVE, _T("Save"), wxPoint(115,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_D_SAVEAS, _T("Save as"), wxPoint(170,0), wxSize(50, 23)); new wxStaticText(current_panel, -1, _T("File"), wxPoint(5+L_TEXT_X,25+L_TEXT_Y)); d_file = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,25), wxSize(330, 23)); new wxStaticText(current_panel, -1, _T("String"), wxPoint(5+L_TEXT_X,50+L_TEXT_Y)); d_draw = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,50), wxSize(150, 23)); new wxStaticText(current_panel, -1, _T("Type"), wxPoint(5+L_TEXT_X,75+L_TEXT_Y)); d_type = new wxChoice(current_panel, -1, wxPoint(50,75), wxSize(150, 23)); d_type->Freeze(); d_type->Append(_T("Undefined")); d_type->Append(_T("RichText")); d_type->Append(_T("sf::Sprite")); d_type->Append(_T("Animated Sprite")); d_type->Append(_T("sf::RectangleShape")); d_type->Append(_T("sf::CircleShape")); d_type->Append(_T("sf::Text")); d_type->Append(_T("GameText")); d_type->Thaw(); d_type->SetSelection(0); // data pack current_panel = (wxPanel*)tabs->GetPage(2); new wxButton(current_panel, ID_BTN_DP_LOAD, _T("Load folder"), wxPoint(0,0), wxSize(100, 23)); new wxButton(current_panel, ID_BTN_DP_BUILD, _T("Build list"), wxPoint(105,0), wxSize(100, 23)); new wxButton(current_panel, ID_BTN_DP_IMPORT, _T("Import"), wxPoint(210,0), wxSize(50, 23)); new wxButton(current_panel, ID_BTN_DP_EXPORT, _T("Export"), wxPoint(265,0), wxSize(50, 23)); dp_folder = new wxStaticText(current_panel, -1, _T(""), wxPoint(L_TEXT_X,25+L_TEXT_Y)); dp_list = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(5, 50), wxSize(375, 375), wxTE_MULTILINE); mainsizer->Show(); } Editor::~Editor() { } void Editor::as_new(wxCommandEvent &event) { if(wxMessageBox(_T("Current data will be cleared. Continue ?"), _T("Confirm"), wxNO) == wxNO) return; as_file->SetValue(_T("")); as_w->SetValue(_T("0")); as_h->SetValue(_T("0")); as_fc->SetValue(_T("0")); as_ft->SetValue(_T("0")); as_sprite->SetValue(_T("")); } void Editor::as_load(wxCommandEvent &event) { wxFileDialog openFileDialog(this, _("Load animated sprite"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST); if(openFileDialog.ShowModal() == wxID_CANCEL) return; std::string path = std::string(openFileDialog.GetPath().mb_str()); std::ifstream f(path.c_str(), std::ios::in | std::ios::binary); if(!f) { wxMessageBox(_T("Load failed")); return; } char c; int32_t tmp32; std::string str; do { if(!f.good()) { wxMessageBox(_T("Load failed")); return; } f.read(&c, 1); if(c != 0x00) str += c; }while(c != 0x00); as_sprite->SetValue(wxString(str.c_str(), wxConvUTF8)); f.read((char*)&tmp32, 4); as_w->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8)); f.read((char*)&tmp32, 4); as_h->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8)); f.read((char*)&tmp32, 4); as_fc->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8)); f.read((char*)&tmp32, 4); as_ft->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8)); as_file->SetValue(wxString(path.c_str(), wxConvUTF8)); } void Editor::as_save(wxCommandEvent &event) { if(!as_stdsave(std::string(as_file->GetValue().mb_str()))) wxMessageBox(_T("Save failed")); else wxMessageBox(_T("Save success")); } void Editor::as_saveas(wxCommandEvent &event) { wxFileDialog saveFileDialog(this, _T("Save animated sprite"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; // the user changed idea... if(!as_stdsave(std::string(saveFileDialog.GetPath().mb_str()))) { wxMessageBox(_T("Save failed")); } else { wxMessageBox(_T("Save success")); as_file->SetValue(saveFileDialog.GetPath()); } } bool Editor::as_stdsave(std::string path) { std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); if(!f) return false; char c; int32_t tmp32; std::string str = std::string(as_sprite->GetValue().mb_str()); for(size_t i = 0; i < str.size(); ++i) f.write(&(str[i]), 1); c = 0; f.write(&c, 1); str = std::string(as_w->GetValue().mb_str()); if(!mlib::isNumber(str)) tmp32 = 0; else tmp32 = mlib::str2long(str) % 0x100000000; f.write((char*)&tmp32, 4); str = std::string(as_h->GetValue().mb_str()); if(!mlib::isNumber(str)) tmp32 = 0; else tmp32 = mlib::str2long(str) % 0x100000000; f.write((char*)&tmp32, 4); str = std::string(as_fc->GetValue().mb_str()); if(!mlib::isNumber(str)) tmp32 = 0; else tmp32 = mlib::str2long(str) % 0x100000000; f.write((char*)&tmp32, 4); str = std::string(as_ft->GetValue().mb_str()); if(!mlib::isNumber(str)) tmp32 = 0; else tmp32 = mlib::str2long(str) % 0x100000000; f.write((char*)&tmp32, 4); return true; } void Editor::d_new(wxCommandEvent &event) { if(wxMessageBox(_T("Current data will be cleared. Continue ?"), _T("Confirm"), wxNO) == wxNO) return; d_file->SetValue(_T("")); d_draw->SetValue(_T("")); d_type->SetSelection(0); } void Editor::d_load(wxCommandEvent &event) { wxFileDialog openFileDialog(this, _("Load drawable"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST); if(openFileDialog.ShowModal() == wxID_CANCEL) return; std::string path = std::string(openFileDialog.GetPath().mb_str()); std::ifstream f(path.c_str(), std::ios::in | std::ios::binary); if(!f) { wxMessageBox(_T("Load failed")); return; } char c; std::string str; f.read(&c, 1); d_type->SetSelection(c); do { if(!f.good()) { wxMessageBox(_T("Load failed")); return; } f.read(&c, 1); if(c != 0x00) str += c; }while(c != 0x00); d_draw->SetValue(wxString(str.c_str(), wxConvUTF8)); d_file->SetValue(openFileDialog.GetPath()); } void Editor::d_save(wxCommandEvent &event) { if(!d_stdsave(std::string(d_file->GetValue().mb_str()))) wxMessageBox(_T("Save failed")); else wxMessageBox(_T("Save success")); } void Editor::d_saveas(wxCommandEvent &event) { wxFileDialog saveFileDialog(this, _T("Save drawable"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; // the user changed idea... if(!d_stdsave(std::string(saveFileDialog.GetPath().mb_str()))) { wxMessageBox(_T("Save failed")); } else { wxMessageBox(_T("Save success")); d_file->SetValue(saveFileDialog.GetPath()); } } bool Editor::d_stdsave(std::string path) { std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); if(!f) return false; char c; std::string str; c = d_type->GetSelection(); f.write(&c, 1); str = std::string(d_draw->GetValue().mb_str()); for(size_t i = 0; i < str.size(); ++i) f.write(&(str[i]), 1); c = 0; f.write(&c, 1); return true; } void Editor::dp_load(wxCommandEvent &event) { wxDirDialog dlg(NULL, _T("Choose the base directory"), wxGetCwd(), wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dlg.ShowModal() == wxID_CANCEL) return; size_t size = dlg.GetPath().size()+1; dp_folder->SetLabel(dlg.GetPath()); wxArrayString array; wxDir::GetAllFiles(dlg.GetPath(), &array, _T(""), wxDIR_FILES|wxDIR_DIRS); dp_list->Freeze(); dp_list->Clear(); for(size_t i = 0; i < array.size(); ++i) { array[i] = array[i].substr(size, array[i].size()-size); for(size_t j = 0; j < array[i].size(); ++j) if(array[i][j] == '\\') array[i][j] = '/'; dp_list->AppendText(array[i]); if(i < array.size() - 1) dp_list->AppendText(_T("\n")); } dp_list->Thaw(); } void Editor::dp_build(wxCommandEvent &event) { wxString cwd = wxGetCwd(); wxSetWorkingDirectory(dp_folder->GetLabel()); wxString tmp = dp_list->GetValue(); wxString out; for(size_t i = 0; i < tmp.size(); ++i) { if(tmp[i] != '\n') out += tmp[i]; else out += _T(" "); } wxString command = _T("\"") + cwd + _T("\\pack_builder.exe\" \"") + cwd + _T("\\data.pack\" ") + out; long errCount = wxExecute(command, wxEXEC_SYNC); wxSetWorkingDirectory(cwd); Out = std::string(command.mb_str()) + "\n"; wxMessageBox(wxString(std::string("Done.\nError count: " + mlib::long2str(errCount)).c_str(), wxConvUTF8)); } void Editor::dp_import(wxCommandEvent &event) { wxFileDialog openFileDialog(this, _("Import file list"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST); if(openFileDialog.ShowModal() == wxID_CANCEL) return; std::string path = std::string(openFileDialog.GetPath().mb_str()); std::ifstream f(path.c_str(), std::ios::in | std::ios::binary); if(!f) return; char c; wxString tmp; do { f.read(&c, 1); if(c != '\n' && f.good()) tmp += c; }while(c != '\n' && f.good()); dp_folder->SetLabel(tmp); tmp.clear(); dp_list->Freeze(); dp_list->Clear(); while(f.good()) { f.read(&c, 1); if(f.good()) { if(c == '\n') { dp_list->AppendText(tmp); dp_list->AppendText(_T("\n")); tmp.clear(); } else tmp += c; } } if(!tmp.empty()) dp_list->AppendText(tmp); dp_list->Thaw(); wxMessageBox(_T("List imported")); } void Editor::dp_export(wxCommandEvent &event) { wxFileDialog saveFileDialog(this, _T("Export file list"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; std::string path = std::string(saveFileDialog.GetPath().mb_str()); std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); if(!f) return; std::string tmp; tmp = std::string(dp_folder->GetLabel().mb_str()); for(size_t i = 0; i < tmp.size(); ++i) f.write(&tmp[i], 1); f.write("\n", 1); tmp = std::string(dp_list->GetValue().mb_str()); for(size_t i = 0; i < tmp.size(); ++i) f.write(&tmp[i], 1); wxMessageBox(_T("List exported")); }
33.633803
166
0.624023
FoFabien
1503f04180268d2c13ac772c8efadb559c2d434a
4,225
cpp
C++
apps/ScreenSaver/ScreenSaver Example v2/ofxScreenSaver/ofxScreenSaverApp.cpp
local-projects/openframeworks_osx_64
430bdd0df27e803ed29078480093f5836053f5fa
[ "MIT" ]
null
null
null
apps/ScreenSaver/ScreenSaver Example v2/ofxScreenSaver/ofxScreenSaverApp.cpp
local-projects/openframeworks_osx_64
430bdd0df27e803ed29078480093f5836053f5fa
[ "MIT" ]
null
null
null
apps/ScreenSaver/ScreenSaver Example v2/ofxScreenSaver/ofxScreenSaverApp.cpp
local-projects/openframeworks_osx_64
430bdd0df27e803ed29078480093f5836053f5fa
[ "MIT" ]
null
null
null
// ofxScreenSaverApp.cpp // ofxScreenSaver // // Created by Nick Hardeman on 1/24/14. // // #include "ofxScreenSaverApp.h" #include "ofxScreenSaverWindow.h" #include "ofAppRunner.h" #include "ofTypes.h" #include "ofUtils.h" #include "testApp.h" #include "ofURLFileLoader.h" #include "Poco/Net/SSLManager.h" #include "ofTrueTypeFont.h" //-------------------------------------------------------------- ofxScreenSaverApp::ofxScreenSaverApp() { bSetup = false; tApp = NULL; windowPtr = NULL; } //-------------------------------------------------------------- ofxScreenSaverApp::~ofxScreenSaverApp() { bSetup = false; ofNotifyExit(); } //-------------------------------------------------------------- void ofxScreenSaverApp::setDataPath( const char* aPath ) { string npath = aPath; npath += "/data/"; ofSetDataPathRoot( npath ); } //-------------------------------------------------------------- void ofxScreenSaverApp::setupOpenGL( int w, int h, bool bPreview) {//, NSOpenGLContext *inGlContext ) { if(!bSetup) { NSLog(@"***** ofxScreenSaverApp :: setupOpenGL *****"); // if( !ofGetWindowPtr() ) { windowPtr = new ofxScreenSaverWindow(); // windowPtr->openGLContext = inGlContext; ofWindowMode twindowmode = bPreview ? OF_WINDOW : OF_FULLSCREEN; ofSetupOpenGL( windowPtr, w, h, twindowmode ); // } } bSetup = true; } //-------------------------------------------------------------- void ofxScreenSaverApp::runApp() { if(bSetup) { if(windowPtr) { windowPtr->initializeWindow(); } // ofSeedRandom(); ofResetElapsedTimeCounter(); if(windowPtr) { tApp = new testApp(); windowPtr->runAppViaInfiniteLoop(tApp); } // ofRunApp( new testApp() ); } } //-------------------------------------------------------------- void ofxScreenSaverApp::update() { if(bSetup) { // NSLog(@"ofxScreenSaverApp :: update"); if(windowPtr != NULL) { ofNotifyUpdate(); if(tApp) { tApp->update(); } } } } //-------------------------------------------------------------- void ofxScreenSaverApp::display() { if(bSetup) { // NSLog(@"ofxScreenSaverApp :: display : "); if(windowPtr) { windowPtr->display(); } } } void ofStopURLLoader(); //-------------------------------------------------------------- void ofxScreenSaverApp::exit_cb() { // if(bSetup) { if( tApp ){ tApp->exit(); delete tApp; tApp = NULL; } // ofExitCallback(); // ofExit(); // windowPtr.reset(); // ofRemoveAllURLRequests(); // ofStopURLLoader(); // Poco::Net::SSLManager::instance().shutdown(); // try to close quicktime, for non-linux systems: #if defined(OF_VIDEO_CAPTURE_QUICKTIME) || defined(OF_VIDEO_PLAYER_QUICKTIME) // closeQuicktime(); #endif //------------------------ // try to close freeImage: // ofCloseFreeImage(); //------------------------ // try to close free type: // ofTrueTypeFont::finishLibraries(); if( windowPtr ){ delete windowPtr; windowPtr = NULL; } // } bSetup = false; } //-------------------------------------------------------------- void ofxScreenSaverApp::keyDown_cb( int key ) { if(bSetup) { ofNotifyKeyPressed( key ); if(tApp) { tApp->keyPressed(key); } } } //-------------------------------------------------------------- void ofxScreenSaverApp::keyUp_cb( int key ) { if(bSetup) { ofNotifyKeyReleased( key ); if(tApp) { tApp->keyReleased(key); } } } //-------------------------------------------------------------- void ofxScreenSaverApp::windowResized( float w, float h ) { if(bSetup) { if(windowPtr) { windowPtr->setWindowShape(w, h); } // ofNotifyWindowResized( w, h ); } }
24.281609
103
0.446154
local-projects
1505e76b5dd4ce74fd263a39acda730a92acb2c5
2,341
cpp
C++
Codeforces/1472/g.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
14
2019-08-14T00:43:10.000Z
2021-12-16T05:43:31.000Z
Codeforces/1472/g.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
null
null
null
Codeforces/1472/g.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
6
2020-12-30T03:30:17.000Z
2022-03-11T03:40:02.000Z
/* Solution: O(N + M) BFS bash. One bfs to find distances from capital. Another bfs from each node to find nodes able to be reached without action 2 Another bfs after taking action 2 once. */ #include <bits/stdc++.h> using namespace std; int N, M; vector<int> graph[200000], rgraph[200000]; int dist[200000], vis[200000]; bool vis1[200000], vis2[200000], vis3[200000]; int ans[200000]; void bfs3(int x, int d){ queue<int> q; q.push(x); while(!q.empty()){ int id = q.front(); q.pop(); if(vis3[id]) continue; vis3[id] = true; ans[id] = min(ans[id], d); for(int i : rgraph[id]){ if(dist[i] >= dist[id]) continue; q.push(i); } } } void bfs2(int x, int d){ queue<int> q; q.push(x); while(!q.empty()){ int id = q.front(); q.pop(); if(vis2[id]) continue; vis2[id] = true; ans[id] = min(ans[id], d); for(int i : rgraph[id]){ if(dist[i] >= dist[id]){ bfs3(i, d); }else{ q.push(i); } } } } void bfs1(){ queue<pair<int, int>> q; q.push({0, 0}); while(!q.empty()){ int id = q.front().first, d = q.front().second; q.pop(); if(vis1[id]) continue; vis1[id] = true; bfs2(id, d); for(int i : graph[id]){ q.push({i, d+1}); } } } int32_t main(){ int T; cin >> T; while(T--){ cin >> N >> M; for(int i = 0; i < N; i++){ vis[i] = vis1[i] = vis2[i] = vis3[i] = false; ans[i] = 1e9; graph[i].clear(); rgraph[i].clear(); } for(int i = 0; i < M; i++){ int u, v; cin >> u >> v; graph[u-1].push_back(v-1); rgraph[v-1].push_back(u-1); } queue<pair<int, int>> q; q.push({0, 0}); while(!q.empty()){ int id = q.front().first, d = q.front().second; q.pop(); if(vis[id]) continue; vis[id] = true; dist[id] = d; for(int i : graph[id]){ q.push({i, d+1}); } } bfs1(); for(int i = 0; i < N; i++){ cout << ans[i] << " "; } cout << endl; } }
22.95098
76
0.425459
eyangch
15064781235ed302c0e33dcf2ba76978824be282
3,528
cc
C++
bin/ledger/storage/fake/fake_journal_delegate.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
1
2018-02-05T23:33:32.000Z
2018-02-05T23:33:32.000Z
bin/ledger/storage/fake/fake_journal_delegate.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
null
null
null
bin/ledger/storage/fake/fake_journal_delegate.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
null
null
null
// 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 "peridot/bin/ledger/storage/fake/fake_journal_delegate.h" #include <utility> #include "lib/fxl/random/rand.h" #include "peridot/bin/ledger/storage/fake/fake_commit.h" #include "peridot/bin/ledger/storage/public/constants.h" namespace storage { namespace fake { namespace { storage::CommitId RandomCommitId() { std::string result; result.resize(kCommitIdSize); fxl::RandBytes(&result[0], kCommitIdSize); return result; } } // namespace FakeJournalDelegate::FakeJournalDelegate(CommitId parent_id, bool autocommit, uint64_t generation = 0) : autocommit_(autocommit), id_(RandomCommitId()), parent_id_(std::move(parent_id)), generation_(generation) {} FakeJournalDelegate::FakeJournalDelegate(CommitId parent_id, CommitId other_id, bool autocommit, uint64_t generation = 0) : autocommit_(autocommit), id_(RandomCommitId()), parent_id_(std::move(parent_id)), other_id_(std::move(other_id)), generation_(generation) {} FakeJournalDelegate::~FakeJournalDelegate() {} Status FakeJournalDelegate::SetValue(convert::ExtendedStringView key, ObjectIdentifier value, KeyPriority priority) { if (is_committed_ || is_rolled_back_) { return Status::ILLEGAL_STATE; } Get(key).value = value; Get(key).priority = priority; return Status::OK; } Status FakeJournalDelegate::Delete(convert::ExtendedStringView key) { if (is_committed_ || is_rolled_back_) { return Status::ILLEGAL_STATE; } Get(key).deleted = true; return Status::OK; } void FakeJournalDelegate::Commit( std::function<void(Status, std::unique_ptr<const storage::Commit>)> callback) { if (is_committed_ || is_rolled_back_) { callback(Status::ILLEGAL_STATE, nullptr); return; } commit_callback_ = std::move(callback); if (autocommit_) { ResolvePendingCommit(Status::OK); } } bool FakeJournalDelegate::IsCommitted() const { return is_committed_; } Status FakeJournalDelegate::Rollback() { if (is_committed_ || is_rolled_back_) { return Status::ILLEGAL_STATE; } is_rolled_back_ = true; return Status::OK; } bool FakeJournalDelegate::IsRolledBack() const { return is_rolled_back_; } std::vector<CommitIdView> FakeJournalDelegate::GetParentIds() const { if (other_id_.empty()) { return {parent_id_}; } return {parent_id_, other_id_}; } bool FakeJournalDelegate::IsPendingCommit() { return static_cast<bool>(commit_callback_); } void FakeJournalDelegate::ResolvePendingCommit(Status /*status*/) { is_committed_ = true; auto callback = std::move(commit_callback_); commit_callback_ = nullptr; callback(Status::OK, std::make_unique<const FakeCommit>(this)); } const std:: map<std::string, FakeJournalDelegate::Entry, convert::StringViewComparator>& FakeJournalDelegate::GetData() const { return data_; } FakeJournalDelegate::Entry& FakeJournalDelegate::Get( convert::ExtendedStringView key) { auto it = data_.find(key); if (it != data_.end()) return it->second; return data_[key.ToString()]; } } // namespace fake } // namespace storage
27.138462
80
0.671202
Acidburn0zzz
1507186a0e1250e9514b50221437c101d51109cd
3,069
hh
C++
RAVL2/SourceTools/CxxDoc/Parser.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/SourceTools/CxxDoc/Parser.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/SourceTools/CxxDoc/Parser.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of CxxDoc, The RAVL C++ Documentation tool // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU General // Public License (GPL). See the gpl.licence file for details or // see http://www.gnu.org/copyleft/gpl.html // file-header-ends-here #ifndef RAVLCXXDOC_PARSER_HEADER #define RAVLCXXDOC_PARSER_HEADER 1 /////////////////////////////////////////////////////////// //! rcsid="$Id: Parser.hh 5240 2005-12-06 17:16:50Z plugger $" //! file="Ravl/SourceTools/CxxDoc/Parser.hh" //! userlevel=Normal //! docentry="Ravl.API.Source Tools.CxxDoc.Internal" //! lib=RavlCxxDoc //! author="Charles Galambos" //! date="06/12/1999" #include "Ravl/String.hh" #include "Ravl/OS/Filename.hh" #include "Ravl/RefCounter.hh" #include "Ravl/CxxDoc/Object.hh" #include "Ravl/CxxDoc/CxxScope.hh" class FlexLexer; namespace RavlCxxDocN { using namespace RavlN; #if RAVL_VISUALCPP_NAMESPACE_BUG using RavlN::RCBodyC; using RavlN::FilenameC; using RavlN::RCHandleC; #endif //! userlevel=Develop //: C++ File Parser class ParserBodyC : public RCBodyC { public: ParserBodyC(); //: Constructor. ~ParserBodyC(); //: Destructor. bool Parse(const FilenameC &fn); //: Parse a file. bool ParseTree(const FilenameC &fn); //: Parse a directory. int NextToken(); //: Get the next token; int LineNo(); //: Get current lineno const FilenameC &CurrentFilename() const { return curFilename; } //: Get current filename. void Dump(ostream &out); //: Dump database to 'out' ObjectListC &Data() { return data; } //: Access parsed data. bool Resolve(); //: Resolve references in input data. bool SetRootFilename(const StringC &filename) { rootFilename = filename; return true; } //: Set the root filename. protected: bool ParseOuter(); //: Do top level parse. FlexLexer *lex; // Ptr because its really an external class. FilenameC curFilename; FilenameC rootFilename; // Directory where the search started. ScopeC data; }; //! userlevel=Normal //: C++ File Parser class ParserC : public RCHandleC<ParserBodyC> { public: ParserC() {} //: Default constructor. explicit ParserC(bool) : RCHandleC<ParserBodyC>(*new ParserBodyC()) {} //: Constructor. bool Parse(const FilenameC &fn) { return Body().Parse(fn); } //: Parse a file. bool ParseTree(const FilenameC &fn) { return Body().ParseTree(fn); } //: Parse a directory. void Dump(ostream &out) { Body().Dump(out); } //: Dump database to 'out' ObjectListC &Data() { return Body().Data(); } //: Access parsed data. bool Resolve() { return Body().Resolve(); } //: Resolve references in input data. bool SetRootFilename(const StringC &filename) { return Body().SetRootFilename(filename); } //: Set root filename. }; } #endif
22.566176
69
0.62333
isuhao
1509db1e1ae5ea5bcc9111b295734a2cb8ce4779
1,242
hpp
C++
includes/Dataset.hpp
arghyatiger/HighPerformanceCNN
166701ae53885199c4f06c97e127cba688cbe1c3
[ "MIT" ]
null
null
null
includes/Dataset.hpp
arghyatiger/HighPerformanceCNN
166701ae53885199c4f06c97e127cba688cbe1c3
[ "MIT" ]
null
null
null
includes/Dataset.hpp
arghyatiger/HighPerformanceCNN
166701ae53885199c4f06c97e127cba688cbe1c3
[ "MIT" ]
null
null
null
#pragma once #include <Layer.hpp> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> class DataSet : public Layer { public: explicit DataSet(std::string data_path, bool shuffle = false); //constructor void reset(); //setting train indexes to zero void forward(int batch_size, bool is_train); //get new batch and push it to model bool has_next(bool is_train); //check is there are more batches left int get_height() { return this->height; } int get_width() { return this->width; } Container* get_label() { return this->output_label.get(); } private: unsigned int reverse_int(unsigned int i); // big endian void read_images(std::string file_name, std::vector<std::vector<float>>& output); //read dataset file and store images in output void read_labels(std::string file_name, std::vector<unsigned char>& output); //read dataset file and store labels in output std::vector<std::vector<float>> train_data; std::vector<unsigned char> train_label; int train_data_index; std::vector<std::vector<float>> test_data; std::vector<unsigned char> test_label; int test_data_index; int height; int width; bool shuffle; std::unique_ptr<Container> output_label; };
30.292683
130
0.728663
arghyatiger
150bc8341f423db902b170fbbeae552438b65b85
8,010
cpp
C++
src/lunar-master/precess2.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
1
2019-03-11T14:46:04.000Z
2019-03-11T14:46:04.000Z
lib/net/src/nrun/astro/precess2.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
null
null
null
lib/net/src/nrun/astro/precess2.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
1
2019-10-12T03:23:41.000Z
2019-10-12T03:23:41.000Z
/* precess2.cpp: (deprecated version of) functions for computing Earth precession; see precess.cpp for current version, and 'changes.txt' for info on why this is deprecated Copyright (C) 2010, Project Pluto This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <math.h> #include <string.h> #include <stdio.h> #include "watdefs.h" #include "afuncs.h" #include "lunar.h" /* for obliquity( ) prototype */ #define PI 3.1415926535897932384626433832795028841971693993751058209749445923 /* setup_precession fills a 3x3 orthonormal matrix for precessing positions FROM */ /* year t1 TO year t2, where t1 and t2 are Julian YEARS. */ int DLL_FUNC setup_precession( double DLLPTR *matrix, double t1, double t2) { double zeta, z, theta, czeta, cz, ctheta, szeta, sz, stheta; double ka, kb; static double t1_old = -PI, t2_old; static double curr_matrix[9]; int going_backward = 0; if( fabs( t1 - t2) < 1.e-5) /* dates sensibly equal; spare the tedium */ { /* of doing pointless math */ set_identity_matrix( matrix); return( 0); } /* Ideally, precessing from t1 to t2 back to t1 should get your */ /* original point. To ensure that this happens, we handle only */ /* the case t2 > t1; otherwise, we swap the times and invert */ /* the resulting matrix. */ /* The reason is that the following precession formula uses */ /* cubic polynomials to approximate zeta, theta, and z. If */ /* you feed it (t2, t1), it does _not_ create a matrix that is */ /* the exact inverse of (t1, t2); there is some accumulated */ /* error. Doing it this way avoids having that show. Also, */ /* there is a performance advantage: if you _do_ call (t1, t2), */ /* then (t2, t1), it's faster to invert the previous result */ /* than it would be to do all the math. */ if( t1 < t2) { double temp = t1; t1 = t2; t2 = temp; going_backward = 1; } /* It's pretty common to precess a few zillion data points. So */ /* it helps to cache the most recently computed precession matrix */ /* so that repeated calls don't result in repeated computation. */ if( t1 == t1_old && t2 == t2_old) { FMEMCPY( matrix, curr_matrix, 9 * sizeof( double)); if( going_backward) invert_orthonormal_matrix( matrix); return( 0); } t1_old = t1; t2_old = t2; t2 = (t2 - t1) / 100.; t1 = (t1 - 2000.) / 100.; ka = 2306.2181 + 1.39656 * t1 - .000139 * t1 * t1; kb = 2004.3109 - 0.85330 * t1 - .000217 * t1 * t1; zeta = t2 * (ka + t2 * ( .30188 - .000345 * t1 + .017998 * t2)); z = t2 * (ka + t2 * (1.09468 + .000066 * t1 + .018203 * t2)); theta = t2 * (kb + t2 * (-.42665 - .000217 * t1 - .041833 * t2)); theta *= (PI / 180.) / 3600.; z *= (PI / 180.) / 3600.; zeta *= (PI / 180.) / 3600.; czeta = cos( zeta); szeta = sin( zeta); cz = cos( z); sz = sin( z); ctheta = cos( theta); stheta = sin( theta); *matrix++ = czeta * ctheta * cz - szeta * sz; *matrix++ = -szeta * ctheta * cz - czeta * sz; *matrix++ = -stheta * cz; *matrix++ = czeta * ctheta * sz + szeta * cz; *matrix++ = -szeta * ctheta * sz + czeta * cz; *matrix++ = -stheta * sz; *matrix++ = czeta * stheta; *matrix++ = -szeta * stheta; *matrix++ = ctheta; matrix -= 9; FMEMCPY( curr_matrix, matrix, 9 * sizeof( double)); if( going_backward) invert_orthonormal_matrix( matrix); return( 0); } static const double sin_obliq_2000 = 0.397777155931913701597179975942380896684; static const double cos_obliq_2000 = 0.917482062069181825744000384639406458043; void DLL_FUNC equatorial_to_ecliptic( double *vect) { double temp; temp = vect[2] * cos_obliq_2000 - vect[1] * sin_obliq_2000; vect[1] = vect[1] * cos_obliq_2000 + vect[2] * sin_obliq_2000; vect[2] = temp; } void DLL_FUNC ecliptic_to_equatorial( double *vect) { double temp; temp = vect[2] * cos_obliq_2000 + vect[1] * sin_obliq_2000; vect[1] = vect[1] * cos_obliq_2000 - vect[2] * sin_obliq_2000; vect[2] = temp; } int DLL_FUNC precess_vector( const double DLLPTR *matrix, const double DLLPTR *v1, double DLLPTR *v2) { int i = 3; while( i--) { *v2++ = matrix[0] * v1[0] + matrix[1] * v1[1] + matrix[2] * v1[2]; matrix += 3; } return( 0); } int DLL_FUNC deprecess_vector( const double DLLPTR *matrix, const double DLLPTR *v1, double DLLPTR *v2) { int i = 3; while( i--) { *v2++ = matrix[0] * v1[0] + matrix[3] * v1[1] + matrix[6] * v1[2]; matrix++; } return( 0); } int DLL_FUNC precess_ra_dec( const double DLLPTR *matrix, double DLLPTR *p_out, const double DLLPTR *p_in, int backward) { double v1[3], v2[3]; const double old_ra = p_in[0]; v1[0] = cos( p_in[0]) * cos( p_in[1]); v1[1] = sin( p_in[0]) * cos( p_in[1]); v1[2] = sin( p_in[1]); if( backward) deprecess_vector( matrix, v1, v2); else precess_vector( matrix, v1, v2); if( v2[1] || v2[0]) p_out[0] = atan2( v2[1], v2[0]); else p_out[0] = 0.; p_out[1] = asine( v2[2]); while( p_out[0] - old_ra > PI) p_out[0] -= PI * 2.; while( p_out[0] - old_ra <-PI) p_out[0] += PI * 2.; return( 0); } /* setup_ecliptic_precession fills a 3x3 orthonormal matrix for precessing */ /* positions _in ecliptic coordinates_ FROM year t1 TO year t2, where t1 */ /* and t2 are Julian YEARS... much as setup_precession( ) does for RA/dec */ /* 30 May 2002: change 'obliquity#' to '-obliquity#' to fix a bug reported */ /* by Jordi Mas, probably in place since the code was written. */ int DLL_FUNC setup_ecliptic_precession( double DLLPTR *matrix, const double t1, const double t2) { const double obliquity1 = mean_obliquity( (t1 - 2000.) / 100.); const double obliquity2 = mean_obliquity( (t2 - 2000.) / 100.); setup_precession( matrix, t1, t2); pre_spin_matrix( matrix + 1, matrix + 2, -obliquity1); spin_matrix( matrix + 3, matrix + 6, -obliquity2); return( 0); } #ifdef TEST_MAIN #include <stdio.h> #include <stdlib.h> int main( const int argc, const char **argv) { double t1, t2, matrix[9]; double p[2]; int i; t1 = atof( argv[1]); t2 = atof( argv[2]); if( argc > 3) { p[0] = atof( argv[3]) * PI / 180.; p[1] = atof( argv[4]) * PI / 180.; } if( argc < 6) setup_precession( matrix, t1, t2); else setup_ecliptic_precession( matrix, t1, t2); for( i = 0; i < 9; i++) printf( "%15.11lf%s", matrix[i], (i % 3 == 2) ? "\n" : " "); if( argc > 3) { precess_ra_dec( matrix, p, p, 0); printf( "%lf %lf\n", p[0] * 180. / PI, p[1] * 180. / PI); precess_ra_dec( matrix, p, p, 1); printf( "%lf %lf\n", p[0] * 180. / PI, p[1] * 180. / PI); } } #endif
32.693878
83
0.576404
TehSnappy
150f91c9bdd785d55e82bf1dec95e6a732972e20
377
cpp
C++
DataStructures/Graphs/Union_Find.cpp
allenli873/USACO_Materials
62540bf22268619283863e624d06b2588961e0a4
[ "MIT" ]
2
2020-05-30T22:24:43.000Z
2020-05-30T23:35:15.000Z
DataStructures/Graphs/Union_Find.cpp
allenli873/USACO_Materials
62540bf22268619283863e624d06b2588961e0a4
[ "MIT" ]
null
null
null
DataStructures/Graphs/Union_Find.cpp
allenli873/USACO_Materials
62540bf22268619283863e624d06b2588961e0a4
[ "MIT" ]
null
null
null
template<int SZ> struct DSU { int par[SZ], ranks[SZ]; DSU() { iota(par, par + SZ, 0); } int find(int curr) { return par[curr] == curr ? curr : (par[curr] = find(par[curr])); } void unite(int n1, int n2) { int f1 = find(n1); int f2 = find(n2); if(ranks[f1] > ranks[f2]) { par[f2] = f1; ranks[f1]++; } else { par[f1] = f2; ranks[f2]++; } } }
15.708333
66
0.517241
allenli873
15153f5d2d66a6fc55c18c6c04aeb3a3eb38afe4
621
cpp
C++
C++ Programs/square_root_using_binary_search.cpp
manvitha1726/RTU-DigitalLibrary
e2dbf042bcebaa52613fa925dfdbe1f72dc13bcd
[ "MIT" ]
32
2020-10-06T09:45:10.000Z
2021-12-23T02:15:42.000Z
C++ Programs/square_root_using_binary_search.cpp
GayatriDS/RTU-DigitalLibrary
6565798f40896371210dc547aa61eb112046de8d
[ "MIT" ]
55
2020-10-05T06:21:13.000Z
2021-09-11T18:06:50.000Z
C++ Programs/square_root_using_binary_search.cpp
Tausif121/RTU-DigitalLibrary
b0ad54356158ba92c476472241b5b118fb624bf4
[ "MIT" ]
248
2020-10-05T06:21:19.000Z
2021-10-03T08:29:23.000Z
#include<bits/stdc++.h> using namespace std; float square_root(int num,int p) { int s=0; int e=num; float ans=-1; while(s<=e) { int mid=s+e>>1; // (s+e)/2 if(mid*mid==num) { return mid; } else if(mid*mid>=num) { e=mid-1; } else { //as 7*7 is vey close to 50 s=mid+1; ans=mid; } } //for floating part //brute force float inc=0.1; for(int i=1;i<=p;i++) { while(ans*ans<=num) { ans=ans+inc; } //when this blows up ans=ans-inc;//comeback 1 step inc/=10; } return ans; } int main() { int num,p; cin>>num; cin>>p; cout<<square_root(num,p)<<endl; return 0; }
14.113636
39
0.557166
manvitha1726
15190683b6207230f0df6041ffdcfaf3ecfb50af
1,109
cpp
C++
CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Managers/Pool/Payload/CsPayload_PooledObjectImpl.h" #include "Containers/CsInterfaceMap.h" const FName NCsPooledObject::NPayload::FImpl::Name = FName("NCsPooledObject::NPayload::FImpl"); namespace NCsPooledObject { namespace NPayload { FImpl::FImpl() : // ICsGetInterfaceMap InterfaceMap(nullptr), // IPayload bAllocated(false), UpdateType(NCsPooledObject::EUpdate::Manager), Instigator(nullptr), Owner(nullptr), Parent(nullptr), Time(), PreserveChangesFromDefaultMask(0) { // ICsGetInterfaceMap InterfaceMap = new FCsInterfaceMap(); InterfaceMap->SetRoot<FImpl>(this); InterfaceMap->Add<IPayload>(static_cast<IPayload*>(this)); } FImpl::~FImpl() { // ICsGetInterfaceMap delete InterfaceMap; } // IPayload #pragma region void FImpl::Reset() { // IPayload bAllocated = false; UpdateType = NCsPooledObject::EUpdate::Manager; Instigator = nullptr; Owner = nullptr; Parent = nullptr; Time.Reset(); } #pragma endregion IPayload } }
20.163636
95
0.699729
closedsum
151deaa252ded8f32e97a3a98dcf327dcbb26263
3,763
cpp
C++
vlcdemo/vlc/vlc.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
3,095
2019-10-11T03:00:33.000Z
2022-03-31T08:15:13.000Z
vlcdemo/vlc/vlc.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
28
2019-11-12T07:24:06.000Z
2022-02-28T02:04:48.000Z
vlcdemo/vlc/vlc.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
1,023
2019-10-09T12:54:07.000Z
2022-03-30T04:02:07.000Z
#include "vlc.h" VlcThread::VlcThread(QObject *parent) : QThread(parent) { setObjectName("VlcThread"); stopped = false; isPlay = false; url = "rtsp://192.168.1.200:554/1"; vlcInst = NULL; vlcMedia = NULL; vlcPlayer = NULL; static bool isInit = false; if (!isInit) { isInit = true; qDebug() << TIMEMS << "init vlc lib ok" << " version:" << libvlc_get_version(); } } void VlcThread::run() { while (!stopped) { msleep(1); } //线程结束后释放资源 free(); stopped = false; isPlay = false; //qDebug() << TIMEMS << "stop vlc1 thread"; } void VlcThread::setUrl(const QString &url) { this->url = url; } void VlcThread::setOption(const QString &option) { if (vlcMedia != NULL) { QByteArray data = option.toUtf8(); const char *arg = data.constData(); libvlc_media_add_option(vlcMedia, arg); } } bool VlcThread::init() { const char *tempArg = ""; const char *vlc_args[9] = {"-I", "dummy", "--no-osd", "--no-stats", "--ignore-config", "--no-video-on-top", "--no-video-title-show", "--no-snapshot-preview", tempArg}; vlcInst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (vlcInst == NULL) { return false; } vlcMedia = libvlc_media_new_location(vlcInst, url.toUtf8().constData()); vlcPlayer = libvlc_media_player_new_from_media(vlcMedia); if (vlcPlayer == NULL) { return false; } //设置播放句柄 VlcWidget *w = (VlcWidget *)this->parent(); #if defined(Q_OS_WIN) libvlc_media_player_set_hwnd(vlcPlayer, (void *)w->winId()); #elif defined(Q_OS_LINUX) libvlc_media_player_set_xwindow(vlcPlayer, w->winId()); #elif defined(Q_OS_MAC) libvlc_media_player_set_nsobject(vlcPlayer, (void *)w->winId()); #endif //设置硬件加速 none auto any d3d11va dxva2 setOption(QString(":avcodec-hw=%1").arg("none")); //设置通信协议 tcp udp setOption(QString(":rtsp-%1").arg("tcp")); //设置缓存时间 默认500毫秒 setOption(QString(":network-caching=%1").arg(300)); libvlc_media_player_play(vlcPlayer); //qDebug() << TIMEMS << "init vlc finsh"; return true; } void VlcThread::play() { isPlay = true; this->init(); } void VlcThread::pause() { if (vlcPlayer != NULL) { libvlc_media_player_pause(vlcPlayer); } } void VlcThread::next() { if (vlcPlayer != NULL) { libvlc_media_player_pause(vlcPlayer); } } void VlcThread::free() { if (vlcInst != NULL) { libvlc_release(vlcInst); vlcInst = NULL; } if (vlcMedia != NULL) { libvlc_media_release(vlcMedia); vlcMedia = NULL; } if (vlcPlayer != NULL) { libvlc_media_player_release(vlcPlayer); vlcPlayer = NULL; } //qDebug() << TIMEMS << "close vlc ok"; } void VlcThread::stop() { stopped = true; } //实时视频显示窗体类 VlcWidget::VlcWidget(QWidget *parent) : QWidget(parent) { thread = new VlcThread(this); } VlcWidget::~VlcWidget() { close(); } void VlcWidget::setUrl(const QString &url) { thread->setUrl(url); } void VlcWidget::open() { //qDebug() << TIMEMS << "open video" << objectName(); clear(); thread->play(); thread->start(); } void VlcWidget::pause() { thread->pause(); } void VlcWidget::next() { thread->next(); } void VlcWidget::close() { //qDebug() << TIMEMS << "close video" << objectName(); if (thread->isRunning()) { thread->stop(); thread->quit(); thread->wait(3000); } QTimer::singleShot(5, this, SLOT(clear())); } void VlcWidget::restart() { //qDebug() << TIMEMS << "restart video" << objectName(); close(); QTimer::singleShot(10, this, SLOT(open())); } void VlcWidget::clear() { update(); }
19.805263
171
0.597661
liyuzhao
151f3dd67175a7f64d3fbc91bb474512ea823b11
457
cpp
C++
chapter_05/BitLevelOperations.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
chapter_05/BitLevelOperations.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
31
2021-05-14T03:37:24.000Z
2022-03-13T17:38:32.000Z
chapter_05/BitLevelOperations.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
// Exercise 5.46 - Computer Architecture: Bit-level operations // I am not sure of this solution it is not mine I need to understand this program. #include <iostream> int main() { std::cout << "Enter an integer: "; int value, mask = 1, temp, bit; std::cin >> value; std::cout << "The bits are "; for (int i = 15; i >= 0; i--) { temp = value >> i; bit = temp & mask; std::cout << bit; } return 0; }
21.761905
83
0.553611
Kevin-Oudai
151f6553975810ceb7a1cebbc794e9528eaeaac5
418
cpp
C++
Competitive Programming/leetcode/Number-of-Good-Pairs.cpp
JcsnP/My-Playground
683600bd32ee7050bbe2cfca8eaf96eb1cdf039c
[ "Unlicense" ]
2
2020-12-31T09:30:57.000Z
2021-03-15T05:04:18.000Z
Competitive Programming/leetcode/Number-of-Good-Pairs.cpp
JcsnP/My-Playground
683600bd32ee7050bbe2cfca8eaf96eb1cdf039c
[ "Unlicense" ]
null
null
null
Competitive Programming/leetcode/Number-of-Good-Pairs.cpp
JcsnP/My-Playground
683600bd32ee7050bbe2cfca8eaf96eb1cdf039c
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int numIdenticalPairs(vector<int>& nums){ unsigned int pairs = 0; for(unsigned int i = 0; i < nums.size(); i++){ for(unsigned int j = 0; j < nums.size(); j++){ if(nums[i] == nums[j] and i < j){ ++pairs; } } } return pairs; } int main(){ vector<int> nums = {1,2,3,1,1,3}; //call function cout << numIdenticalPairs(nums); }
19
50
0.552632
JcsnP
152263c52ba441d91db240eae1b01e0beb96f69a
8,424
cpp
C++
pxr/usd/lib/usdSkel/bindingAPI.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
6
2018-08-26T13:27:22.000Z
2021-08-14T23:57:38.000Z
pxr/usd/lib/usdSkel/bindingAPI.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
pxr/usd/lib/usdSkel/bindingAPI.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
4
2018-06-14T18:14:59.000Z
2021-09-13T22:20:50.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdSkel/bindingAPI.h" #include "pxr/usd/usd/schemaRegistry.h" #include "pxr/usd/usd/typed.h" #include "pxr/usd/usd/tokens.h" #include "pxr/usd/sdf/types.h" #include "pxr/usd/sdf/assetPath.h" PXR_NAMESPACE_OPEN_SCOPE // Register the schema with the TfType system. TF_REGISTRY_FUNCTION(TfType) { TfType::Define<UsdSkelBindingAPI, TfType::Bases< UsdAPISchemaBase > >(); } TF_DEFINE_PRIVATE_TOKENS( _schemaTokens, (BindingAPI) ); /* virtual */ UsdSkelBindingAPI::~UsdSkelBindingAPI() { } /* static */ UsdSkelBindingAPI UsdSkelBindingAPI::Get(const UsdStagePtr &stage, const SdfPath &path) { if (!stage) { TF_CODING_ERROR("Invalid stage"); return UsdSkelBindingAPI(); } return UsdSkelBindingAPI(stage->GetPrimAtPath(path)); } /*virtual*/ bool UsdSkelBindingAPI::_IsAppliedAPISchema() const { return true; } /* static */ UsdSkelBindingAPI UsdSkelBindingAPI::Apply(const UsdPrim &prim) { return UsdAPISchemaBase::_ApplyAPISchema<UsdSkelBindingAPI>( prim, _schemaTokens->BindingAPI); } /* static */ const TfType & UsdSkelBindingAPI::_GetStaticTfType() { static TfType tfType = TfType::Find<UsdSkelBindingAPI>(); return tfType; } /* static */ bool UsdSkelBindingAPI::_IsTypedSchema() { static bool isTyped = _GetStaticTfType().IsA<UsdTyped>(); return isTyped; } /* virtual */ const TfType & UsdSkelBindingAPI::_GetTfType() const { return _GetStaticTfType(); } UsdAttribute UsdSkelBindingAPI::GetGeomBindTransformAttr() const { return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelGeomBindTransform); } UsdAttribute UsdSkelBindingAPI::CreateGeomBindTransformAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelGeomBindTransform, SdfValueTypeNames->Matrix4d, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute UsdSkelBindingAPI::GetJointsAttr() const { return GetPrim().GetAttribute(UsdSkelTokens->skelJoints); } UsdAttribute UsdSkelBindingAPI::CreateJointsAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdSkelTokens->skelJoints, SdfValueTypeNames->TokenArray, /* custom = */ false, SdfVariabilityUniform, defaultValue, writeSparsely); } UsdAttribute UsdSkelBindingAPI::GetJointIndicesAttr() const { return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelJointIndices); } UsdAttribute UsdSkelBindingAPI::CreateJointIndicesAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelJointIndices, SdfValueTypeNames->IntArray, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute UsdSkelBindingAPI::GetJointWeightsAttr() const { return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelJointWeights); } UsdAttribute UsdSkelBindingAPI::CreateJointWeightsAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelJointWeights, SdfValueTypeNames->FloatArray, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdRelationship UsdSkelBindingAPI::GetAnimationSourceRel() const { return GetPrim().GetRelationship(UsdSkelTokens->skelAnimationSource); } UsdRelationship UsdSkelBindingAPI::CreateAnimationSourceRel() const { return GetPrim().CreateRelationship(UsdSkelTokens->skelAnimationSource, /* custom = */ false); } UsdRelationship UsdSkelBindingAPI::GetSkeletonRel() const { return GetPrim().GetRelationship(UsdSkelTokens->skelSkeleton); } UsdRelationship UsdSkelBindingAPI::CreateSkeletonRel() const { return GetPrim().CreateRelationship(UsdSkelTokens->skelSkeleton, /* custom = */ false); } namespace { static inline TfTokenVector _ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right) { TfTokenVector result; result.reserve(left.size() + right.size()); result.insert(result.end(), left.begin(), left.end()); result.insert(result.end(), right.begin(), right.end()); return result; } } /*static*/ const TfTokenVector& UsdSkelBindingAPI::GetSchemaAttributeNames(bool includeInherited) { static TfTokenVector localNames = { UsdSkelTokens->primvarsSkelGeomBindTransform, UsdSkelTokens->skelJoints, UsdSkelTokens->primvarsSkelJointIndices, UsdSkelTokens->primvarsSkelJointWeights, }; static TfTokenVector allNames = _ConcatenateAttributeNames( UsdAPISchemaBase::GetSchemaAttributeNames(true), localNames); if (includeInherited) return allNames; else return localNames; } PXR_NAMESPACE_CLOSE_SCOPE // ===================================================================== // // Feel free to add custom code below this line. It will be preserved by // the code generator. // // Just remember to wrap code in the appropriate delimiters: // 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'. // ===================================================================== // // --(BEGIN CUSTOM CODE)-- #include "pxr/usd/usdGeom/imageable.h" #include "pxr/usd/usdGeom/tokens.h" #include "pxr/usd/usdSkel/utils.h" PXR_NAMESPACE_OPEN_SCOPE UsdGeomPrimvar UsdSkelBindingAPI::GetJointIndicesPrimvar() const { return UsdGeomPrimvar(GetJointIndicesAttr()); } UsdGeomPrimvar UsdSkelBindingAPI::CreateJointIndicesPrimvar(bool constant, int elementSize) const { return UsdGeomImageable(GetPrim()).CreatePrimvar( UsdSkelTokens->primvarsSkelJointIndices, SdfValueTypeNames->IntArray, constant ? UsdGeomTokens->constant : UsdGeomTokens->vertex, elementSize); } UsdGeomPrimvar UsdSkelBindingAPI::GetJointWeightsPrimvar() const { return UsdGeomPrimvar(GetJointWeightsAttr()); } UsdGeomPrimvar UsdSkelBindingAPI::CreateJointWeightsPrimvar(bool constant, int elementSize) const { return UsdGeomImageable(GetPrim()).CreatePrimvar( UsdSkelTokens->primvarsSkelJointWeights, SdfValueTypeNames->FloatArray, constant ? UsdGeomTokens->constant : UsdGeomTokens->vertex, elementSize); } bool UsdSkelBindingAPI::SetRigidJointInfluence(int jointIndex, float weight) const { UsdGeomPrimvar jointIndicesPv = CreateJointIndicesPrimvar(/*constant*/ true, /*elementSize*/ 1); UsdGeomPrimvar jointWeightsPv = CreateJointWeightsPrimvar(/*constant*/ true, /*elementSize*/ 1); VtIntArray indices(1); indices[0] = jointIndex; VtFloatArray weights(1); weights[0] = weight; return jointIndicesPv.Set(indices) && jointWeightsPv.Set(weights); } PXR_NAMESPACE_CLOSE_SCOPE
27.529412
101
0.688746
navefx
1523647b42aa57408cd2e1f5c83e3244f1c9a8d5
1,701
cpp
C++
Algo-1/week1/1-Vector/main.cpp
pepincho/Python101-and-Algo1-Courses
7cf38d26d5be5ffc1a37477ae6375a99906df9e2
[ "MIT" ]
2
2016-10-11T14:09:05.000Z
2017-01-20T19:30:34.000Z
Algo-1/week1/3-Stack/main.cpp
pepincho/HackBulgaria
7cf38d26d5be5ffc1a37477ae6375a99906df9e2
[ "MIT" ]
null
null
null
Algo-1/week1/3-Stack/main.cpp
pepincho/HackBulgaria
7cf38d26d5be5ffc1a37477ae6375a99906df9e2
[ "MIT" ]
null
null
null
#include <iostream> #include "Vector.h" #include "Queue.h" #include "Stack.h" #include <time.h> int main() { clock_t beg = clock(); Vector pesho; pesho.add(5); pesho.add(2); pesho.add(8); pesho.add(16); pesho.insert(1, 10); pesho.add(33); pesho.printVector(); pesho.insert(2, 10); std::cout << "pesho at(2): " << pesho.get(2) << std::endl; pesho.remove(2); pesho.printVector(); pesho.pop(); pesho.printVector(); //for (int i = 0; i < 60000; i++) { // pesho.insert(0, 9); //} //clock_t end = clock(); //std::cout << double(end - beg) / CLOCKS_PER_SEC << std::endl; pesho.printVector(); std::cout << "size of the Vector: " << pesho.getSize() << std::endl; std::cout << "capacity of the Vector: " << pesho.getCapacity() << std::endl; std::cout << "----------------------------------------" << std::endl; Queue pencho; pencho.push(1); pencho.push(3); pencho.push(5); pencho.push(7); int firstElement = pencho.pop(); std::cout << "firstElement: " << firstElement << std::endl; firstElement = pencho.peek(); std::cout << "firstElement: " << firstElement << std::endl; std::cout << "size of the Queue: " << pencho.getSize() << std::endl; pencho.printQueue(); std::cout << "----------------------------------------" << std::endl; Stack pepi; pepi.push(1); pepi.push(3); pepi.push(5); pepi.push(7); firstElement = pepi.pop(); std::cout << "firstElement: " << firstElement << std::endl; firstElement = pepi.peek(); std::cout << "firstElement: " << firstElement << std::endl; std::cout << "size of the Queue: " << pepi.getSize() << std::endl; pepi.printQueue(); std::cout << "----------------------------------------" << std::endl; return 0; }
22.381579
77
0.563786
pepincho
1526cf54858f8c6ff963783c1a303c91e54e44a7
653
hpp
C++
cpp/include/core/https/HttpsClient.hpp
nawbar23/fleetmgr
e5f93877fa373841845941dacf37cfcd4364f69c
[ "MIT" ]
null
null
null
cpp/include/core/https/HttpsClient.hpp
nawbar23/fleetmgr
e5f93877fa373841845941dacf37cfcd4364f69c
[ "MIT" ]
null
null
null
cpp/include/core/https/HttpsClient.hpp
nawbar23/fleetmgr
e5f93877fa373841845941dacf37cfcd4364f69c
[ "MIT" ]
null
null
null
#ifndef FM_CORE_HTTPS_HTTPSCLIENT_HPP #define FM_CORE_HTTPS_HTTPSCLIENT_HPP #include <string> namespace fm { namespace core { namespace https { /** * Created by: Bartosz Nawrot * Date: 2018-11-27 * Description: */ class HttpsClient { public: enum Method { POST, PUT, GET, DELETE, }; HttpsClient(const std::string&, const int, const std::string&); std::string execute(const std::string&, const Method, const std::string&); protected: const std::string host; const int port; const std::string apiKey; }; } // https } // core } // fm #endif // FM_CORE_HTTPS_IHTTPSCLIENT_HPP
13.604167
78
0.644717
nawbar23
1530acbd09e58deb3f6305bdb938900452df6334
528
hpp
C++
examples/02Physics/LevelEnd.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/LevelEnd.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/LevelEnd.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
#ifndef FIRESTORM_LEVELEND_HPP #define FIRESTORM_LEVELEND_HPP #include "scene/SceneNode.hpp" #include <memory> namespace fs::scene { class LevelEnd : public SceneNode { public: LevelEnd() = default; ~LevelEnd() override = default; void create(io::InputManager& inputManager, physics::PhysicsManager& physicsManager, const core::Vector2f& point1, const core::Vector2f& point2); void destroy() override; }; typedef std::unique_ptr<LevelEnd> LevelEndPtr; } #endif //FIRESTORM_LEVELEND_HPP
18.206897
118
0.725379
Galhad
15322fdd0929ad0f55e4421424f3146d31247b4c
4,211
cpp
C++
modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Kharunova Alina #include <gtest/gtest.h> #include "./algorithm_of_strongin.h" #include <gtest-mpi-listener.hpp> TEST(Parallel_Operations_MPI, parallel_sum_in_10_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 10, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 10, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } TEST(Parallel_Operations_MPI, parallel_sum_in_100_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 100, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 100, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } TEST(Parallel_Operations_MPI, parallel_sum_in_1000_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 1000, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 1000, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } TEST(Parallel_Operations_MPI, parallel_sum_in_500_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 500, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 500, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } TEST(Parallel_Operations_MPI, parallel_sum_in_474_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 474, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 474, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } TEST(Parallel_Operations_MPI, parallel_sum_in_50_elements_matrix) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double start, end, timeLin, timeParal; if (rank == 0) { start = MPI_Wtime(); linAlgorithm(1, 50, 0.01); end = MPI_Wtime(); timeLin = end - start; std::cout << "Linear " << timeLin << std::endl; start = MPI_Wtime(); } paralAlgorithm(1, 50, 0.01); if (rank == 0) { end = MPI_Wtime(); timeParal = end - start; std::cout << "Paral " << timeParal << std::endl; std::cout << "Effective " << timeLin / timeParal << std::endl; } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
28.452703
76
0.625742
Gurgen-Arm
15343d244e983291fce531f0643c5f70262e8831
571
hpp
C++
upgrade/boot_loader/VerifierRsa.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
54
2019-04-02T14:42:54.000Z
2022-03-20T23:02:19.000Z
upgrade/boot_loader/VerifierRsa.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
32
2019-03-26T06:57:29.000Z
2022-03-25T00:04:44.000Z
upgrade/boot_loader/VerifierRsa.hpp
oguzcanphilips/embeddedinfralib
f1b083d61a34d123d34ab7cd51267377aa2f7855
[ "Unlicense" ]
20
2019-03-25T15:49:49.000Z
2022-03-20T23:02:22.000Z
#ifndef UPGRADE_VERIFIER_RSA_HPP #define UPGRADE_VERIFIER_RSA_HPP #include "upgrade/boot_loader/Verifier.hpp" namespace application { class VerifierRsa : public Verifier { public: VerifierRsa(infra::ConstByteRange publicKeyN, infra::ConstByteRange publicKeyE); virtual bool IsValid(hal::SynchronousFlash& flash, const hal::SynchronousFlash::Range& signature, const hal::SynchronousFlash::Range& data) const override; private: infra::ConstByteRange publicKeyN; infra::ConstByteRange publicKeyE; }; } #endif
24.826087
163
0.730298
oguzcanphilips
15361ff688031e211c11b637af0b229804760345
2,494
cpp
C++
src/Services/FunctionManagementService.cpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
src/Services/FunctionManagementService.cpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
src/Services/FunctionManagementService.cpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
#include "ECSS_Configuration.hpp" #ifdef SERVICE_FUNCTION #include "Services/FunctionManagementService.hpp" void FunctionManagementService::call(Message& msg) { msg.resetRead(); ErrorHandler::assertRequest(msg.packetType == Message::TC, msg, ErrorHandler::AcceptanceErrorType::UnacceptableMessage); ErrorHandler::assertRequest(msg.messageType == FunctionManagementService::MessageType::PerformFunction, msg, ErrorHandler::AcceptanceErrorType::UnacceptableMessage); ErrorHandler::assertRequest(msg.serviceType == FunctionManagementService::ServiceType, msg, ErrorHandler::AcceptanceErrorType::UnacceptableMessage); uint8_t funcName[ECSSFunctionNameLength] = { 0 }; // the function's name uint8_t funcArgs[ECSSFunctionMaxArgLength] = { 0 }; // arguments for the function msg.readString(funcName, ECSSFunctionNameLength); msg.readString(funcArgs, ECSSFunctionMaxArgLength); if (msg.dataSize > (ECSSFunctionNameLength + ECSSFunctionMaxArgLength)) { ErrorHandler::reportError(msg, ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError); // report failed // start of execution as requested by the standard return; } // locate the appropriate function pointer String<ECSSFunctionNameLength> name(funcName); FunctionMap::iterator iter = funcPtrIndex.find(name); void (*selected)(String<ECSSFunctionMaxArgLength>); if (iter != funcPtrIndex.end()) { selected = *iter->second; } else { ErrorHandler::reportError(msg, ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError); return; } // execute the function if there are no obvious flaws (defined in the standard, pg.158) selected(funcArgs); } void FunctionManagementService::include(String<ECSSFunctionNameLength> funcName, void (* ptr)(String<ECSSFunctionMaxArgLength>)) { if (not funcPtrIndex.full()) { // CAUTION: etl::map won't check by itself if it's full // before attempting to insert a key-value pair, causing segmentation faults. Check first! funcName.append(ECSSFunctionNameLength - funcName.length(), 0); funcPtrIndex.insert(std::make_pair(funcName, ptr)); } else { ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType::MapFull); } } void FunctionManagementService::execute(Message& message) { switch (message.messageType) { case PerformFunction: call(message); // TC[8,1] break; default: ErrorHandler::reportInternalError(ErrorHandler::OtherMessageType); break; } } #endif
37.223881
112
0.761427
ACubeSAT
1539fab1fc1668eed8ad73910cf93a87afee1161
2,238
cpp
C++
tests/ModLoaderTests.cpp
Zemurin/commonItems
cda7c217c7b3433b61a17cd05ce8d3893b711bf7
[ "MIT" ]
7
2018-12-22T03:59:34.000Z
2021-06-10T22:42:37.000Z
tests/ModLoaderTests.cpp
IhateTrains/commonItems
759705dc41ff1595db9786d0a9facc0b336888c3
[ "MIT" ]
45
2018-12-04T04:51:20.000Z
2021-08-12T12:20:56.000Z
tests/ModLoaderTests.cpp
IhateTrains/commonItems
759705dc41ff1595db9786d0a9facc0b336888c3
[ "MIT" ]
15
2019-01-09T05:59:48.000Z
2020-08-27T09:08:09.000Z
#include "../ModLoader/ModLoader.h" #include "../OSCompatibilityLayer.h" #include "gtest/gtest.h" #include <gmock/gmock-matchers.h> using testing::UnorderedElementsAre; TEST(ModLoaderTests, ModsCanBeLocatedUnpackedAndUpdated) { Mods incomingMods; // this is what comes from the save incomingMods.emplace_back(Mod("Some mod", "mod/themod.mod")); // mod's in fact named "The Mod" in the file. commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); ASSERT_THAT(mods, UnorderedElementsAre(Mod("The Mod", "TestFiles/mod/themod/"))); EXPECT_THAT(mods[0].dependencies, UnorderedElementsAre("Packed Mod", "Missing Mod")); } TEST(ModLoaderTests, BrokenMissingAndNonexistentModsAreDiscarded) { Mods incomingMods; incomingMods.emplace_back(Mod("", "mod/themod.mod")); // no name given incomingMods.emplace_back(Mod("Broken mod", "mod/brokenmod.mod")); // no path incomingMods.emplace_back(Mod("Missing mod", "mod/missingmod.mod")); // missing directory incomingMods.emplace_back(Mod("Nonexistent mod", "mod/nonexistentmod.mod")); // doesn't exist. commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("The Mod", "TestFiles/mod/themod/"))); } TEST(ModLoaderTests, CompressedModsCanBeUnpacked) { Mods incomingMods; incomingMods.emplace_back(Mod("some packed mod", "mod/packedmod.mod")); commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("Packed Mod", "mods/packedmod/"))); EXPECT_TRUE(commonItems::DoesFolderExist("mods/packedmod/")); } TEST(ModLoaderTests, BrokenCompressedModsAreNotSkippedEvenThoughTheyShouldBe) { Mods incomingMods; incomingMods.emplace_back(Mod("broken packed mod", "mod/brokenpacked.mod")); commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("Broken Packed Mod", "mods/brokenpacked/"))); EXPECT_TRUE(commonItems::DoesFolderExist("mods/brokenpacked/")); }
37.3
108
0.758266
Zemurin
153a61e9019d7b15d28d88d3922dd9ac261ebd05
6,529
hpp
C++
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
140
2020-01-16T19:04:33.000Z
2022-03-10T02:54:01.000Z
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
4
2021-02-28T12:02:46.000Z
2022-02-14T01:41:57.000Z
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
38
2020-01-16T01:48:08.000Z
2022-03-12T16:52:20.000Z
// Copyright (c) 2020 Can Boluk // 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 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. // #pragma once #include <string_view> #include <stdlib.h> #include <cstring> #include "../img_common.hpp" #pragma pack(push, COFF_STRUCT_PACKING) namespace coff { // String table. // union string_table_t { uint32_t size; char raw_data[ VAR_LEN ]; // Resolves a string given the offset. // const char* begin() const { return size > 4 ? &raw_data[ 0 ] : nullptr; } const char* end() const { return size > 4 ? &raw_data[ size ] : nullptr; } std::string_view resolve( size_t offset ) const { // Fail if invalid offset. // if ( offset < 4 ) return {}; // Search for the null terminator, return if found. // const char* start = begin() + offset; const char* lim = end(); for ( const char* it = start; it < lim; it++ ) if ( !*it ) return { start, ( size_t ) ( it - start ) }; // Invalid string. // return {}; } }; // External reference to string table. // struct string_t { union { char short_name[ LEN_SHORT_STR ]; // Name as inlined string. struct { uint32_t is_short; // If non-zero, name is inline'd into short_name, else has a long name. uint32_t long_name_offset; // Offset into string table. }; }; // Convert to string view given an optional string table. // std::string_view to_string( const string_table_t* tbl = nullptr ) const { if ( tbl && !is_short ) return tbl->resolve( long_name_offset ); size_t len = 0; while ( len != LEN_SHORT_STR && short_name[ len ] ) len++; return { short_name, len }; } // Array lookup, only available for short strings. // char& operator[]( size_t n ) { return const_cast<char&>( to_string()[ n ] ); } const char& operator[]( size_t n ) const { return to_string()[ n ]; } // Basic comparison primitive. // bool equals( const char* str, const string_table_t* tbl = nullptr ) const { return to_string( tbl ) == str; } // Short string comparison primitive. // template<size_t N> requires( N <= ( LEN_SHORT_STR + 1 ) ) bool equals_s( const char( &str )[ N ] ) const { // Compare with against empty string. // if constexpr ( N == 1 ) return ( !is_short && !long_name_offset ) || ( is_short && !short_name[ 0 ] ); // Can skip is short check since if string is not null, is short will be overwritten. // if constexpr ( N == ( LEN_SHORT_STR + 1 ) ) return !memcmp( short_name, str, LEN_SHORT_STR ); else return !memcmp( short_name, str, N ); } }; // Same as above but archive convention, used for section names. // struct scn_string_t { char short_name[ LEN_SHORT_STR ]; // Convert to string view given an optional string table. // std::string_view to_string( const string_table_t* tbl = nullptr ) const { if ( tbl && short_name[ 0 ] == '/' ) { char* end = ( char* ) std::end( short_name ); return tbl->resolve( strtoll( short_name + 1, &end, 10 ) ); } size_t len = 0; while ( len != LEN_SHORT_STR && short_name[ len ] ) len++; return { short_name, len }; } // Array lookup, only available for short strings. // char& operator[]( size_t n ) { return const_cast<char&>( to_string()[ n ] ); } const char& operator[]( size_t n ) const { return to_string()[ n ]; } // Basic comparison primitive. // bool equals( const char* str, const string_table_t* tbl = nullptr ) const { return to_string( tbl ) == str; } // Short string comparison primitive. // template<size_t N> requires( N <= ( LEN_SHORT_STR + 1 ) ) bool equals_s( const char( &str )[ N ] ) const { // Compare with against empty string. // if constexpr ( N == 1 ) return !short_name[ 0 ]; // Can skip is short check since if string is not null, is short will be overwritten. // if constexpr ( N == ( LEN_SHORT_STR + 1 ) ) return !memcmp( short_name, str, LEN_SHORT_STR ); else return !memcmp( short_name, str, N ); } }; }; #pragma pack(pop)
38.405882
134
0.559657
archercreat
153e7c40f2bc9bfd7b3574a1fb809f1b9ef5da28
3,750
hpp
C++
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_ARCH_X86_AVX2_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED #define BOOST_SIMD_ARCH_X86_AVX2_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints16_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi16(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::avx_> , bs::pack_<bd::ints32_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm256_sllv_epi32(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi32(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::sse_> , bs::pack_<bd::ints32_<A0>, bs::sse_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm_sllv_epi32(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::avx_> , bs::pack_<bd::ints64_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm256_sllv_epi64(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi64(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::sse_> , bs::pack_<bd::ints64_<A0>, bs::sse_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm_sllv_epi64(a0, a1); } }; } } } #endif
33.482143
100
0.461333
SylvainCorlay
153f99ecd798218b9cb5ddf6ca547d6d87587629
2,400
cpp
C++
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
#include "CaffeFaceDetector.h" #include <Common/CommonClasses.h> CaffeFaceDetector::CaffeFaceDetector() { capacity = MAX_TARGETS_COUNT; inputSize = cv::Size(300, 300); inputMean = cv::Scalar(104.0, 177.0, 123.0); inputName = "data"; outputName = "detection_out"; const cv::String trackerConfiguration = "Assets/model/caffe/deploy.prototxt"; const cv::String trackerBinary = "Assets/model/caffe/res10_300x300_ssd_iter_140000_fp16.caffemodel"; trackingNet = cv::dnn::readNetFromCaffe(trackerConfiguration, trackerBinary); //trackingNet.setPreferableBackend(cv::dnn::DNN_BACKEND_HALIDE); //trackingNet.setPreferableTarget(cv::dnn::DNN_TARGET_OPENCL); } CaffeFaceDetector::~CaffeFaceDetector() { } void CaffeFaceDetector::start() {} void CaffeFaceDetector::stop() {} void CaffeFaceDetector::setRefFrame(cv::Mat frame) {} cv::Mat CaffeFaceDetector::preProcess(cv::Mat frame) { if (frame.channels() == 4) { cv::Mat gray(frame.rows, frame.cols, CV_8UC3); cvtColor(frame, gray, cv::COLOR_BGRA2BGR); return gray; } return frame; } std::vector<cv::Rect> CaffeFaceDetector::scan(cv::Mat frame) { cv::Mat resizeFrame; std::vector<cv::Rect> results; if (!trackingNet.empty()) { cv::resize(frame, resizeFrame, inputSize); cv::Mat inputBlob = cv::dnn::blobFromImage(frame, activescale, inputSize, inputMean, inputSwapRB, inputCrop); trackingNet.setInput(inputBlob, inputName); cv::Mat detection = trackingNet.forward(outputName); cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>()); for (int i = 0; i < detectionMat.rows; i++) { float confidence = detectionMat.at<float>(i, 2); if (confidence > CONFIDENCE_THRESHOLD) { int xLeftBottom = static_cast<int>(detectionMat.at<float>(i, 3) * frame.cols); int yLeftBottom = static_cast<int>(detectionMat.at<float>(i, 4) * frame.rows); int xRightTop = static_cast<int>(detectionMat.at<float>(i, 5) * frame.cols); int yRightTop = static_cast<int>(detectionMat.at<float>(i, 6) * frame.rows); cv::Rect object((int)xLeftBottom, (int)yLeftBottom, (int)(xRightTop - xLeftBottom), (int)(yRightTop - yLeftBottom)); results.push_back(object); } } } return results; } void CaffeFaceDetector::getPoints(std::array<cv::Point2f, TARGET_DETAIL_MODIFIER> &points) { } void CaffeFaceDetector::scale(double newscale) { activescale = newscale; }
27.272727
111
0.722917
KanSmith
1540132a3a38811421655f7b946b35a07fbe798b
118,611
cpp
C++
jtransc-rt/resources/cpp/Base.cpp
renesugar/jtransc
9a562bf3f855c16cbea8c8c2e2ca4f3665d8626a
[ "Apache-2.0" ]
null
null
null
jtransc-rt/resources/cpp/Base.cpp
renesugar/jtransc
9a562bf3f855c16cbea8c8c2e2ca4f3665d8626a
[ "Apache-2.0" ]
null
null
null
jtransc-rt/resources/cpp/Base.cpp
renesugar/jtransc
9a562bf3f855c16cbea8c8c2e2ca4f3665d8626a
[ "Apache-2.0" ]
null
null
null
#ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define _CRT_SECURE_NO_DEPRECATE #include <windows.h> #endif #ifdef _WIN32 #define _JTRANSC_UNIX_LIKE_ 0 #define _JTRANSC_WINDOWS_ 1 #elif __APPLE__ #define _JTRANSC_UNIX_LIKE_ 1 #define _JTRANSC_WINDOWS_ 0 #elif __linux__ #define _JTRANSC_UNIX_LIKE_ 1 #define _JTRANSC_WINDOWS_ 0 #elif __unix__ #define _JTRANSC_UNIX_LIKE_ 1 #define _JTRANSC_WINDOWS_ 0 #elif defined(_POSIX_VERSION) #define _JTRANSC_UNIX_LIKE_ 1 #define _JTRANSC_WINDOWS_ 0 #else # error "Unknown compiler" #endif #define jlong_to_ptr(a) ((void *)(uintptr_t)(a)) #define ptr_to_jlong(a) ((jlong)(uintptr_t)(a)) #include <memory> #include <vector> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cmath> //#include <clocale> #include <csignal> //#include <chrono> #include <thread> #include <mutex> #include "jni.h" #if _JTRANSC_UNIX_LIKE_ #include <dlfcn.h> #endif {% for include in CPP_INCLUDES %} #include <{{ include }}> {% end %} //#ifndef USE_PORTABLE_GC //#define USE_PORTABLE_GC //#endif #ifdef USE_PORTABLE_GC # include "GC_portable.cpp" #else # include "GC_boehm.cpp" #endif //#define DO_NOT_USE_GC // For debugging purposes (to detect crashes related to GC) #ifdef DO_NOT_USE_GC void* JT_MALLOC(std::size_t sz) { void* out = malloc(sz); memset(out, 0, sz); return out; } void* JT_MALLOC_ATOMIC(std::size_t sz) { return malloc(sz); } #else void* JT_MALLOC(std::size_t sz) { return GC_MALLOC(sz); } void* JT_MALLOC_ATOMIC(std::size_t sz) { return GC_MALLOC_ATOMIC(sz); } #endif struct gc { void* operator new(std::size_t sz) { //std::printf("global op new called, size = %zu\n",sz); return JT_MALLOC(sz); } }; #ifdef _WIN32 #ifdef _WIN64 const char *JT_OS = "Windows 64"; #else const char *JT_OS = "Windows 32"; #endif #elif __APPLE__ #include "TargetConditionals.h" #if TARGET_IPHONE_SIMULATOR const char *JT_OS = "iOS Simulator"; #elif TARGET_OS_IPHONE const char *JT_OS = "iOS Device"; #elif TARGET_OS_MAC const char *JT_OS = "MacOSX"; #else const char *JT_OS = "Apple Unknown"; #endif #elif __linux__ const char *JT_OS = "Linux"; #elif __unix__ const char *JT_OS = "Unix"; #elif defined(_POSIX_VERSION) const char *JT_OS = "Posix"; #else const char *JT_OS = "Unknown"; #endif extern "C" { #include <stdio.h> #include <wchar.h> #include <string.h> #ifndef _WIN32 #include <sys/stat.h> #include <unistd.h> #endif #include <math.h> #include <stdlib.h> #include <stdint.h> } #undef min #undef max #if defined(S_IFREG) && !defined(_S_IFREG) #define _S_IFREG S_IFREG #define _S_IFDIR S_IFDIR #endif typedef float float32_t; typedef double float64_t; typedef int8_t JT_BOOL; // HEADERS + INCLUDES {{ HEADER }} int TRACE_INDENT = 0; typedef struct { int32_t x, y; } Int32x2; typedef struct { float32_t x, y, z, w; } Float32x4; typedef struct { Float32x4 x, y, z, w; } Float32x4x4; inline Int32x2 Int32x2_i(int32_t x, int32_t y) { return {x, y}; } inline Float32x4 Float32x4_i() { return {0, 0, 0, 0}; } inline Float32x4 Float32x4_i(float x, float y, float z, float w) { return {x, y, z, w}; } inline Float32x4x4 Float32x4x4_i() { return { Float32x4_i(), Float32x4_i(), Float32x4_i(), Float32x4_i() }; } inline Float32x4x4 Float32x4x4_i(Float32x4 x, Float32x4 y, Float32x4 z, Float32x4 w) { return { x, y, z, w }; } inline Float32x4 operator-(const Float32x4& l) { return {-l.x, -l.y, -l.z, -l.w}; }; inline Float32x4 operator+(const Float32x4& l, const Float32x4& r) { return {l.x+r.x, l.y+r.y, l.z+r.z, l.w+r.w}; }; inline Float32x4 operator-(const Float32x4& l, const Float32x4& r) { return {l.x-r.x, l.y-r.y, l.z-r.z, l.w-r.w}; }; inline Float32x4 operator*(const Float32x4& l, const Float32x4& r) { return {l.x*r.x, l.y*r.y, l.z*r.z, l.w*r.w}; }; inline Float32x4 operator/(const Float32x4& l, const Float32x4& r) { return {l.x/r.x, l.y/r.y, l.z/r.z, l.w/r.w}; }; inline Float32x4 operator*(const Float32x4& l, float r) { return {l.x*r, l.y*r, l.z*r, l.w*r}; }; inline float sum(const Float32x4& l) { return l.x + l.y + l.z + l.w; }; inline Float32x4 abs(const Float32x4& l) { return { std::fabs(l.x), std::fabs(l.y), std::fabs(l.z), std::fabs(l.w)}; }; inline Float32x4 min(const Float32x4& l, const Float32x4& r){ return { std::fmin(l.x, r.x), std::fmin(l.y, r.y), std::fmin(l.z, r.z), std::fmin(l.w, r.w)}; }; inline Float32x4 max(const Float32x4& l, const Float32x4& r){ return { std::fmax(l.x, r.x), std::fmax(l.y, r.y), std::fmax(l.z, r.z), std::fmax(l.w, r.w)}; }; struct CLASS_TRACE { public: const char* text; static void print_indent() { for (int n = 0; n < TRACE_INDENT; n++) putchar(' '); }; CLASS_TRACE(const char* text) : text(text) { print_indent(); printf("Enter: %s\n", text); TRACE_INDENT++; }; ~CLASS_TRACE() { #ifdef TRACING_JUST_ENTER TRACE_INDENT--; #else TRACE_INDENT--; print_indent(); printf("Exit: %s\n", text); #endif }; }; #if TRACING #define TRACE_REGISTER(location) std::shared_ptr<CLASS_TRACE> __CLASS_TRACE(new CLASS_TRACE(location)); #else #define TRACE_REGISTER(location) ; #endif // For referencing pointers {{ CLASS_REFERENCES }} //typedef std::shared_ptr<java_lang_Object> SOBJ; //typedef std::weak_ptr<java_lang_Object> WOBJ; typedef java_lang_Object* JAVA_OBJECT; // generateTypeTableHeader() {{ TYPE_TABLE_HEADERS }} #define GET_OBJECT(type, obj) (dynamic_cast<type*>(obj)) #define GET_OBJECT2(ptype, obj) (dynamic_cast<type>(obj)) #define GET_OBJECT_NPE(type, obj) GET_OBJECT(type, N::ensureNpe(obj)) #ifdef DEBUG #define CHECK_NPE 1 #else #define CHECK_NPE 0 #endif {{ ARRAY_TYPES }} struct N; // Headers struct Env { JNIEnv jni; // }; //template<typename T> p_java_lang_Object CC_GET_OBJECT(T t) { // if (t == nullptr) return nullptr; // return t->__toObj(); //} //template<typename T> void* CC_GET_VOID(T t) { // if (t == nullptr) return nullptr; // return t->__toVoid(); //} /* template <typename TTo> TTo CC_CHECK_CAST1(void* i, int typeId, const char *from, const char *to) { //printf("N::CHECK_CAST(%p, %s -> %s)\n", i, from, to); if (i == nullptr) return nullptr; if (!N::is(i, typeId)) return nullptr; TTo res = static_cast<TTo>(i); if (res == nullptr) { throw {% CONSTRUCTOR java.lang.ClassCastException:(Ljava/lang/String;)V %}(N::str("Class cast error")); } return res; } */ //template <typename TTo> TTo CC_CHECK_CAST2(p_java_lang_Object i, const char *from, const char *to) { // //printf("N::CHECK_CAST(%p, %s -> %s)\n", i, from, to); // if (i == nullptr) return nullptr; // TTo res = dynamic_cast<TTo>(i); // if (res == nullptr) { // throw {% CONSTRUCTOR java.lang.ClassCastException:(Ljava/lang/String;)V %}(N::str("Class cast error")); // } // return res; //} struct N { public: static Env env; static int64_t NAN_LONG; static double NAN_DOUBLE; static double INFINITY_DOUBLE; static int32_t NAN_INT; static float NAN_FLOAT; static float INFINITY_FLOAT; static const int32_t MIN_INT32 = (int32_t)0x80000000; static const int32_t MAX_INT32 = (int32_t)0x7FFFFFFF; static const int64_t MIN_INT64 = (int64_t)0x8000000000000000; static const int64_t MAX_INT64 = (int64_t)0x7FFFFFFFFFFFFFFF; static JAVA_OBJECT resolveClass(std::wstring str); inline static int64_t lnew(int32_t high, int32_t low); static JT_BOOL is(JAVA_OBJECT obj, int32_t type); template<typename T> inline static bool is(T* obj, int32_t type) { return is((JAVA_OBJECT)obj, type); } static JT_BOOL isArray(JAVA_OBJECT obj); static JT_BOOL isArray(JAVA_OBJECT obj, std::wstring desc); static JT_BOOL isUnknown(std::shared_ptr<{% CLASS java.lang.Object %}> obj, const char *error); static int cmp(double a, double b); static int cmpl(double a, double b); static int cmpg(double a, double b); inline static int32_t ishl(int32_t a, int32_t b); inline static int32_t ishr(int32_t a, int32_t b); inline static int32_t iushr(int32_t a, int32_t b); inline static int64_t bswap64(int64_t a); inline static int32_t bswap32(int32_t a); inline static int16_t bswap16(int16_t a); inline static int32_t ishl_cst(int32_t a, int32_t b); inline static int32_t ishr_cst(int32_t a, int32_t b); inline static int32_t iushr_cst(int32_t a, int32_t b); inline static int32_t idiv (int32_t a, int32_t b); inline static int32_t irem (int32_t a, int32_t b); inline static int64_t lcmp (int64_t a, int64_t b); inline static int64_t ladd (int64_t a, int64_t b); inline static int64_t lsub (int64_t a, int64_t b); inline static int64_t lmul (int64_t a, int64_t b); inline static int64_t ldiv (int64_t a, int64_t b); inline static int64_t lrem (int64_t a, int64_t b); inline static int64_t land (int64_t a, int64_t b); inline static int64_t lor (int64_t a, int64_t b); inline static int64_t lxor (int64_t a, int64_t b); inline static int64_t lshl (int64_t a, int b); inline static int64_t lshr (int64_t a, int b); inline static int64_t lushr(int64_t a, int b); inline static int64_t lshl_cst (int64_t a, int b); inline static int64_t lshr_cst (int64_t a, int b); inline static int64_t lushr_cst(int64_t a, int b); inline static int32_t z2i(int32_t v); inline static float j2f(int64_t v); inline static double j2d(int64_t v); inline static int64_t i2j(int32_t v); inline static int32_t j2i(int64_t v); inline static int64_t f2j(float v); inline static int64_t d2j(double v); inline static int32_t f2i(float v); inline static int32_t d2i(double v); static void log(std::wstring str); static void log(JAVA_OBJECT str); {% if ENABLE_TYPING %} static p_java_lang_String str(const char *str); static p_java_lang_String str(const wchar_t *str, int32_t len); static p_java_lang_String str(std::wstring str); static p_java_lang_String str(std::string str); static p_JA_L strArray(int32_t count, wchar_t **strs); static p_JA_L strArray(std::vector<std::wstring> strs); static p_JA_L strArray(std::vector<std::string> strs); static p_JA_L strEmptyArray(); {% else %} static JAVA_OBJECT str(const char *str); static JAVA_OBJECT str(const wchar_t *str, int32_t len); static JAVA_OBJECT str(std::wstring str); static JAVA_OBJECT str(std::string str); static JAVA_OBJECT strArray(int32_t count, wchar_t **strs); static JAVA_OBJECT strArray(std::vector<std::wstring> strs); static JAVA_OBJECT strArray(std::vector<std::string> strs); static JAVA_OBJECT strEmptyArray(); {% end %} static std::wstring istr2(JAVA_OBJECT obj); static std::string istr3(JAVA_OBJECT obj); static JAVA_OBJECT dummyMethodClass(); static void throwNpe(const wchar_t *position); template<typename T> static T ensureNpe(T obj, const wchar_t *position); static void throwNpe(); template<typename T> static T ensureNpe(T obj); static std::vector<JAVA_OBJECT> getVectorOrEmpty(JAVA_OBJECT array); template<typename T> static p_java_lang_Object CC_GET_OBJ(T t); template<typename TTo, typename TFrom> TTo static CC_CHECK_CLASS(TFrom i, int32_t typeId); template<typename T> T static CC_CHECK_UNTYPED(T i, int32_t typeId); template<typename TTo, typename TFrom> TTo static CC_CHECK_INTERFACE(TFrom i, int32_t typeId); template<typename TTo, typename TFrom> TTo static CC_CHECK_GENERIC(TFrom i); static int32_t strLen(JAVA_OBJECT obj); static uint16_t strCharAt(JAVA_OBJECT obj, int32_t n); static int32_t identityHashCode(JAVA_OBJECT obj); static void writeChars(JAVA_OBJECT str, char *out, int32_t len); static JAVA_OBJECT unboxVoid(JAVA_OBJECT obj); static JT_BOOL unboxBool(JAVA_OBJECT obj); static int8_t unboxByte(JAVA_OBJECT obj); static int16_t unboxShort(JAVA_OBJECT obj); static uint16_t unboxChar(JAVA_OBJECT obj); static int32_t unboxInt(JAVA_OBJECT obj); static int64_t unboxLong(JAVA_OBJECT obj); static float unboxFloat(JAVA_OBJECT obj); static double unboxDouble(JAVA_OBJECT obj); static JAVA_OBJECT boxVoid(void); static JAVA_OBJECT boxVoid(JAVA_OBJECT v); static JAVA_OBJECT boxBool(JT_BOOL v); static JAVA_OBJECT boxByte(int8_t v); static JAVA_OBJECT boxShort(int16_t v); static JAVA_OBJECT boxChar(uint16_t v); static JAVA_OBJECT boxInt(int32_t v); static JAVA_OBJECT boxLong(int64_t v); static JAVA_OBJECT boxFloat(float v); static JAVA_OBJECT boxDouble(double v); static double getTime(); static int64_t nanoTime(); static void startup(); static void initStringPool(); static JAVA_OBJECT newBoolArray(); static JAVA_OBJECT newByteArray(); static JAVA_OBJECT newShortArray(); static JAVA_OBJECT newCharArray(); static JAVA_OBJECT newIntArray(); static JAVA_OBJECT newLongArray(); static JAVA_OBJECT newFloatArray(); static JAVA_OBJECT newDoubleArray(); static JNIEnv* getJniEnv(); static void monitorEnter(JAVA_OBJECT obj); static void monitorExit(JAVA_OBJECT obj); }; /* Used for synchronized methods.*/ class SynchronizedMethodLocker{ JAVA_OBJECT obj; public: SynchronizedMethodLocker(JAVA_OBJECT obj){ this->obj=obj; N::monitorEnter(obj); } ~SynchronizedMethodLocker(){ N::monitorExit(this->obj); } }; struct DYN { public: static void* openDynamicLib(const char*); static void closeDynamicLib(void*); static void* findDynamicSymbol(void*, const char*); static void* jtvmResolveNative(JAVA_OBJECT, const char*, const char*, void**); static void* jtvmResolveNativeMethodImpl(const char*, const char*, JAVA_OBJECT, void**); }; // Strings {{ STRINGS }} /// ARRAY_HEADERS {{ ARRAY_HEADERS_PRE }} struct JA_0 : public java_lang_Object { public: void *_data; int32_t length; int8_t elementSize; std::wstring desc; JA_0(JT_BOOL pointers, void* data, int32_t len, int8_t esize, std::wstring d) : length(len), elementSize(esize), desc(d) { this->__JT__CLASS_ID = 1; this->_data = data; } JA_0(JT_BOOL pointers, int32_t len, int8_t esize, std::wstring d) : JA_0(pointers, alloc(pointers, len, esize), len, esize, d) { } static void* alloc(JT_BOOL pointers, int32_t len, int8_t esize) { void * result = nullptr; int64_t bytesSize = esize * (len + 1); if (pointers) { result = (void*)JT_MALLOC(bytesSize); // this malloc already clears memory, so it is pointless doing this again } else { result = (void*)JT_MALLOC_ATOMIC(bytesSize); ::memset(result, 0, bytesSize); } return result; } ~JA_0() { /*::free(_data);*/ } void *getOffsetPtr(int32_t offset) { return (void*)&(((int8_t *)_data)[offset * elementSize]); } void *getStartPtr() { return getOffsetPtr(0); } int64_t bytesLength() { return length * elementSize; } static void copy(JA_0* src, int32_t srcpos, JA_0* dst, int32_t dstpos, int32_t len) { ::memmove(dst->getOffsetPtr(dstpos), src->getOffsetPtr(srcpos), len * src->elementSize); } //JAVA_OBJECT toBoolArray(); //JAVA_OBJECT toByteArray(); //JAVA_OBJECT toCharArray(); //JAVA_OBJECT toShortArray(); //JAVA_OBJECT toIntArray(); //JAVA_OBJECT toLongArray(); //JAVA_OBJECT toFloatArray(); //JAVA_OBJECT toDoubleArray(); }; template <class T> struct JA_Base : JA_0 { JA_Base(JT_BOOL pointers, int32_t size, std::wstring desc) : JA_0(pointers, size, sizeof(T), desc) { }; JA_Base(JT_BOOL pointers, void* data, int32_t size, std::wstring desc) : JA_0(pointers, data, size, sizeof(T), desc) { }; /* * Checks that the offset is in the bounds. * Returns true when offset is in bounds, false otherwise. */ static inline JT_BOOL isInBounds(int32_t offset, int32_t length) { return ((uint32_t)offset <= (uint32_t)length); }; /* * Checks that the offset is in the bounds. * Throws exception on failure. */ static void checkBoundsThrowing(int32_t offset, int32_t length) { if(((uint32_t)offset <= (uint32_t)length)){ // In bounds } else { __throwArrayOutOfBounds(offset, length); } }; static void __throwArrayOutOfBounds(int32_t offset, int32_t length){ std::wstringstream os; os << L"Out of bounds offset: " << offset << L" length: " << length; throw os.str(); } T *getStartPtr() { return (T *)_data; } #ifdef CHECK_ARRAYS void fastSet(int32_t offset, T v) { if(isInBounds(offset, length)) ((T*)(this->_data))[offset] = v; else __throwArrayOutOfBounds(offset, length); }; T fastGet(int32_t offset) { if(isInBounds(offset, length)) return ((T*)(this->_data))[offset]; else __throwArrayOutOfBounds(offset, length); } #else void fastSet(int32_t offset, T v) { ((T*)(this->_data))[offset] = v; }; T fastGet(int32_t offset) { return ((T*)(this->_data))[offset]; } #endif JA_Base<T> *init(int32_t offset, T v) { ((T*)(this->_data))[offset] = v; return this; }; void set(int32_t offset, T v) { checkBoundsThrowing(offset, length); fastSet(offset, v); }; T get(int32_t offset) { checkBoundsThrowing(offset, length); return fastGet(offset); }; void fill(int32_t from, int32_t to, T v) { constexpr int32_t typesize = sizeof(T); checkBoundsThrowing(from, length); checkBoundsThrowing(to - 1, length); if ((typesize == 8) && (sizeof(void*) == 4)) { // constexpr (we are on 32-bits but this is a 64-bit size). Let's optimize this since some compilers don't do this for us. int32_t* data = (int32_t*)this->_data; int32_t from32 = from * 2; int32_t to32 = to * 2; int32_t* src = (int32_t *)&v; int32_t v1 = src[0]; int32_t v2 = src[1]; int32_t n = from32; while (n < to32) { data[n++] = v1; data[n++] = v2; } } else { T* data = (T*)this->_data; for (int32_t n = from; n < to; n++) data[n] = v; } }; JA_Base<T> *setArray(int32_t start, int32_t size, const T *arrays) { for (int32_t n = 0; n < size; n++) this->set(start + n, arrays[n]); return this; }; }; struct JA_B : JA_Base<int8_t> { JA_B(int32_t size, std::wstring desc = L"[B") : JA_Base(false, size, desc) { }; JA_B(void* data, int32_t size, std::wstring desc = L"[B") : JA_Base(false, data, size, desc) { }; void fill(int32_t from, int32_t to, int8_t v) { checkBoundsThrowing(from, length); checkBoundsThrowing(to - 1, length); ::memset((void *)(&((int8_t *)this->_data)[from]), v, (to - from)); } static JA_B* fromArray(std::wstring desc, std::vector<int8_t> array) { auto len = (int32_t)array.size(); auto out = new JA_B(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_Z : public JA_B { JA_Z(int32_t size, std::wstring desc = L"[Z") : JA_B(size, desc) { }; JA_Z(void* data, int32_t size, std::wstring desc = L"[Z") : JA_B(data, size, desc) { }; static JA_Z* fromArray(std::wstring desc, std::vector<int8_t> array) { auto len = (int32_t)array.size(); auto out = new JA_Z(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_S : JA_Base<int16_t> { JA_S(int32_t size, std::wstring desc = L"[S") : JA_Base(false, size, desc) { }; JA_S(void* data, int32_t size, std::wstring desc = L"[S") : JA_Base(false, data, size, desc) { }; static JA_S* fromArray(std::wstring desc, std::vector<int16_t> array) { auto len = (int32_t)array.size(); auto out = new JA_S(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_C : JA_Base<uint16_t> { JA_C(int32_t size, std::wstring desc = L"[C") : JA_Base(false, size, desc) { }; JA_C(void* data, int32_t size, std::wstring desc = L"[C") : JA_Base(false, data, size, desc) { }; static JA_C* fromArray(std::wstring desc, std::vector<uint16_t> array) { auto len = (int32_t)array.size(); auto out = new JA_C(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_I : JA_Base<int32_t> { JA_I(int32_t size, std::wstring desc = L"[I") : JA_Base(false, size, desc) { }; JA_I(void* data, int32_t size, std::wstring desc = L"[I") : JA_Base(false, data, size, desc) { }; // @TODO: Try to move to JA_Base static JA_I *fromVector(int32_t *data, int32_t count) { return (JA_I * )(new JA_I(count))->setArray(0, count, (const int32_t *)data); }; static JA_I *fromArgValues() { return (JA_I * )(new JA_I(0)); }; static JA_I *fromArgValues(int32_t a0) { return (JA_I * )(new JA_I(1))->init(0, a0); }; static JA_I *fromArgValues(int32_t a0, int32_t a1) { return (JA_I * )(new JA_I(2))->init(0, a0)->init(1, a1); }; static JA_I *fromArgValues(int32_t a0, int32_t a1, int32_t a2) { return (JA_I * )(new JA_I(3))->init(0, a0)->init(1, a1)->init(2, a2); }; static JA_I *fromArgValues(int32_t a0, int32_t a1, int32_t a2, int32_t a3) { return (JA_I * )(new JA_I(4))->init(0, a0)->init(1, a1)->init(2, a2)->init(3, a3); }; static JA_I* fromArray(std::wstring desc, std::vector<int32_t> array) { auto len = (int32_t)array.size(); auto out = new JA_I(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_J : JA_Base<int64_t> { JA_J(int32_t size, std::wstring desc = L"[J") : JA_Base(false, size, desc) { }; JA_J(void* data, int32_t size, std::wstring desc = L"[J") : JA_Base(false, data, size, desc) { }; static JA_J* fromArray(std::wstring desc, std::vector<int64_t> array) { auto len = (int32_t)array.size(); auto out = new JA_J(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_F : JA_Base<float> { JA_F(int32_t size, std::wstring desc = L"[F") : JA_Base(false, size, desc) { }; JA_F(void* data, int32_t size, std::wstring desc = L"[F") : JA_Base(false, data, size, desc) { }; static JA_F* fromArray(std::wstring desc, std::vector<float> array) { auto len = (int32_t)array.size(); auto out = new JA_F(len); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_D : JA_Base<double> { JA_D(int32_t size, std::wstring desc = L"[D") : JA_Base(false, size, desc) { }; JA_D(void* data, int32_t size, std::wstring desc = L"[D") : JA_Base(false, data, size, desc) { }; static JA_D* fromArray(std::wstring desc, std::vector<double> array) { auto len = (int32_t)array.size(); auto out = new JA_D(len); for (int n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; struct JA_L : JA_Base<JAVA_OBJECT> { JA_L(int32_t size, std::wstring desc) : JA_Base(true, size, desc) { }; JA_L(void* data, int32_t size, std::wstring desc) : JA_Base(true, data, size, desc) { }; std::vector<JAVA_OBJECT> getVector() { int32_t len = this->length; std::vector<JAVA_OBJECT> out(len); for (int32_t n = 0; n < len; n++) out[n] = this->fastGet(n); return out; } static JA_0* createMultiSure(std::wstring desc, std::vector<int32_t> sizes) { if (sizes.size() == 0) throw L"Multiarray with zero sizes"; int32_t size = sizes[0]; if (sizes.size() == 1) { if (desc == std::wstring(L"[Z")) return new JA_Z(size); if (desc == std::wstring(L"[B")) return new JA_B(size); if (desc == std::wstring(L"[S")) return new JA_S(size); if (desc == std::wstring(L"[C")) return new JA_C(size); if (desc == std::wstring(L"[I")) return new JA_I(size); if (desc == std::wstring(L"[J")) return new JA_J(size); if (desc == std::wstring(L"[F")) return new JA_F(size); if (desc == std::wstring(L"[D")) return new JA_D(size); throw L"Invalid multiarray"; } // std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector); auto out = new JA_L(size, desc); auto subdesc = desc.substr(1); auto subsizes = std::vector<int32_t>(sizes.begin() + 1, sizes.end()); for (int32_t n = 0; n < size; n++) { out->set(n, createMultiSure(subdesc, subsizes)); } return out; } static JA_L* fromArray(std::wstring desc, std::vector<JAVA_OBJECT> array) { auto len = (int32_t)array.size(); auto out = new JA_L(len, desc); for (int32_t n = 0; n < len; n++) out->fastSet(n, array[n]); return out; } }; //JAVA_OBJECT JA_0::toBoolArray () { return new JA_Z((void *)getStartPtr(), bytesLength() / 1); }; //JAVA_OBJECT JA_0::toByteArray () { return new JA_B((void *)getStartPtr(), bytesLength() / 1); }; //JAVA_OBJECT JA_0::toCharArray () { return new JA_C((void *)getStartPtr(), bytesLength() / 2); }; //JAVA_OBJECT JA_0::toShortArray () { return new JA_S((void *)getStartPtr(), bytesLength() / 2); }; //JAVA_OBJECT JA_0::toIntArray () { return new JA_I((void *)getStartPtr(), bytesLength() / 4); }; //JAVA_OBJECT JA_0::toLongArray () { return new JA_J((void *)getStartPtr(), bytesLength() / 8); }; //JAVA_OBJECT JA_0::toFloatArray () { return new JA_F((void *)getStartPtr(), bytesLength() / 4); }; //JAVA_OBJECT JA_0::toDoubleArray() { return new JA_D((void *)getStartPtr(), bytesLength() / 8); }; {{ ARRAY_HEADERS_POST }} // Classes IMPLS {{ CLASSES_IMPL }} // Map of c++ constructors // Used for contructing an object without calling the *java constructor* {{ CPP_CTOR_MAP }} // N IMPLS JAVA_OBJECT N::resolveClass(std::wstring str) { return {% SMETHOD java.lang.Class:forName0 %}(N::str(str)); }; int64_t N::lnew(int32_t high, int32_t low) { return (((int64_t)high) << 32) | (((int64_t)low) << 0); }; JT_BOOL N::is(JAVA_OBJECT obj, int32_t type) { if (obj == nullptr) return false; const TYPE_INFO type_info = TYPE_TABLE::TABLE[obj->__JT__CLASS_ID]; const size_t size = type_info.size; const int32_t* subtypes = type_info.subtypes; for (size_t i = 0; i < size; i++){ if (subtypes[i] == type) return true; } return false; }; JT_BOOL N::isArray(JAVA_OBJECT obj) { return GET_OBJECT(JA_0, obj) != nullptr; }; JT_BOOL N::isArray(JAVA_OBJECT obj, std::wstring desc) { JA_0* ptr = GET_OBJECT(JA_0, obj); JT_BOOL result = (ptr != nullptr) && (ptr->desc == desc); if (!result) { if (desc.substr(0, 2) == L"[L") { return GET_OBJECT(JA_L, obj) != nullptr; } } return result; }; JT_BOOL N::isUnknown(std::shared_ptr<{% CLASS java.lang.Object %}> obj, const char * error) { throw error; }; int N::cmp(double a, double b) { return (a < b) ? (-1) : ((a > b) ? (+1) : 0); }; int N::cmpl(double a, double b) { return (std::isnan(a) || std::isnan(b)) ? (-1) : N::cmp(a, b); }; int N::cmpg(double a, double b) { return (std::isnan(a) || std::isnan(b)) ? (+1) : N::cmp(a, b); }; int64_t N::NAN_LONG = 0x7FF8000000000000L; double N::NAN_DOUBLE = *(double*)&(N::NAN_LONG); int32_t N::NAN_INT = 0x7FC00000; float N::NAN_FLOAT = *(float*)&(N::NAN_INT); double N::INFINITY_DOUBLE = (double)INFINITY; float N::INFINITY_FLOAT = (float)INFINITY; int FIXSHIFT(int r) { if (r < 0) { return (32 - ((-r) & 0x1F)) & 0x1F; } else { return r & 0x1F; } } int32_t N::ishl(int32_t a, int32_t b) { return (a << FIXSHIFT(b)); } int32_t N::ishr(int32_t a, int32_t b) { return (a >> FIXSHIFT(b)); } int32_t N::iushr(int32_t a, int32_t b) { return (int32_t)(((uint32_t)a) >> FIXSHIFT(b)); } int32_t N::ishl_cst(int32_t a, int32_t b) { return (a << b); } int32_t N::ishr_cst(int32_t a, int32_t b) { return (a >> b); } int32_t N::iushr_cst(int32_t a, int32_t b) { return (int32_t)(((uint32_t)a) >> b); } int32_t N::idiv(int32_t a, int32_t b) { if (a == 0) return 0; if (b == 0) return 0; // CRASH if (a == N::MIN_INT32 && b == -1) { // CRASH TOO //printf("aaaaaaaaaaaaaaa\n"); fflush(stdout); return N::MIN_INT32; // CRASH TOO? } return a / b; } int32_t N::irem(int32_t a, int32_t b) { if (a == 0) return 0; if (b == 0) return 0; // CRASH if (a == N::MIN_INT32 && b == -1) { // CRASH TOO return 0; // CRASH TOO? } return a % b; } //INT_ADD_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a + b would overflow in [min,max] integer arithmetic. See above for restrictions. //INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a - b would overflow in [min,max] integer arithmetic. See above for restrictions. //INT_NEGATE_RANGE_OVERFLOW (a, min, max) //Yield 1 if -a would overflow in [min,max] integer arithmetic. See above for restrictions. //INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a * b would overflow in [min,max] integer arithmetic. See above for restrictions. //INT_DIVIDE_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a / b would overflow in [min,max] integer arithmetic. See above for restrictions. Division overflow can happen on two’s complement hosts when dividing the most negative integer by -1. This macro does not check for division by zero. //INT_REMAINDER_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a % b would overflow in [min,max] integer arithmetic. See above for restrictions. Remainder overflow can happen on two’s complement hosts when dividing the most negative integer by -1; although the mathematical result is always 0, in practice some implementations trap, so this counts as an overflow. This macro does not check for division by zero. //INT_LEFT_SHIFT_RANGE_OVERFLOW (a, b, min, max) //Yield 1 if a << b would overflow in [min,max] integer arithmetic. See above for restrictions. Here, min and max are for a only, and b need not be of the same type as the other arguments. The C standard says that behavior is undefined for shifts unless 0≤b<w where w is a’s word width, and that when a is negative then a << b has undefined behavior, but this macro does not check these other restrictions. int64_t N::lcmp (int64_t a, int64_t b) { return (a < b) ? -1 : ((a > b) ? +1 : 0); } int64_t N::ladd (int64_t a, int64_t b) { return a + b; } int64_t N::lsub (int64_t a, int64_t b) { return a - b; } int64_t N::lmul (int64_t a, int64_t b) { return a * b; } int64_t N::ldiv (int64_t a, int64_t b) { if (a == 0) return 0; if (b == 0) return 0; //printf("ldiv::: %lld %lld\n", a, N::MIN_INT64); if (a == N::MIN_INT64 && b == -1) { //printf("aaaaaaaaaaaaaaaaaa\n"); //-9223372036854775808/-1 return N::MIN_INT64; } return a / b; } int64_t N::lrem (int64_t a, int64_t b) { if (a == 0) return 0; if (b == 0) return 0; if (a == N::MIN_INT64 && b == -1) return 0; return a % b; } int64_t N::land (int64_t a, int64_t b) { return a & b; } int64_t N::lor (int64_t a, int64_t b) { return a | b; } int64_t N::lxor (int64_t a, int64_t b) { return a ^ b; } int LFIXSHIFT(int r) { if (r < 0) { return (64 - ((-r) & 0x3F)) & 0x3F; } else { return r & 0x3F; } } int64_t N::lshl(int64_t a, int b) { return (a << LFIXSHIFT(b)); } int64_t N::lshr(int64_t a, int b) { return (a >> LFIXSHIFT(b)); } int64_t N::lushr(int64_t a, int b) { return (int64_t)(((uint64_t)a) >> LFIXSHIFT(b)); } int64_t N::lshl_cst(int64_t a, int b) { return (a << b); } int64_t N::lshr_cst(int64_t a, int b) { return (a >> b); } int64_t N::lushr_cst(int64_t a, int b) { return (int64_t)(((uint64_t)a) >> b); } int32_t N::z2i(int32_t v) { return (v != 0) ? 1 : 0; } int64_t N::i2j(int32_t v) { return (int64_t)v; } float N::j2f(int64_t v) { return (float)v; } double N::j2d(int64_t v) { return (double)v; } int32_t N::j2i(int64_t v) { return (int32_t)v; } int64_t N::f2j(float v) { if (std::isfinite(v)) { return (int64_t)v; } else { if (std::isnan(v)) { return 0; } else if (v >= 0) { return MAX_INT64; } else { return MIN_INT64; } } } int64_t N::d2j(double v) { if (std::isfinite(v)) { return (int64_t)v; } else { if (std::isnan(v)) { return 0; } else if (v >= 0) { return MAX_INT64; } else { return MIN_INT64; } } } // TODO: templatize d2i and f2i to write just once int32_t N::d2i(double v) { if (std::isfinite(v)) { return (int32_t)v; } else { if (std::isnan(v)) { return 0; } else if (v >= 0) { return MAX_INT32; } else { return MIN_INT32; } } } int32_t N::f2i(float v) { if (std::isfinite(v)) { return (int32_t)v; } else { if (std::isnan(v)) { return 0; } else if (v >= 0) { return MAX_INT32; } else { return MIN_INT32; } } } //SOBJ N::strLiteral(wchar_t *ptr, int len) { // SOBJ out(new {% CLASS java.lang.String %}()); // return out.get()->sptr(); //} {% if ENABLE_TYPING %}p_java_lang_String{% else %}JAVA_OBJECT{% end %} N::str(const wchar_t *str, int32_t len) { p_java_lang_String out = new {% CLASS java.lang.String %}(); JAVA_OBJECT _out = (JAVA_OBJECT)out; p_JA_C array = new JA_C(len); p_JA_C arrayobj = array; uint16_t *ptr = (uint16_t *)array->getStartPtr(); if (sizeof(wchar_t) == sizeof(uint16_t)) { ::memcpy((void *)ptr, (void *)str, len * sizeof(uint16_t)); } else { for (int32_t n = 0; n < len; n++) ptr[n] = (uint16_t)str[n]; } out->{% FIELD java.lang.String:value %} = arrayobj; //GET_OBJECT({% CLASS java.lang.String %}, out)->M_java_lang_String__init____CII_V(array, 0, len); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; }; {% if ENABLE_TYPING %}p_java_lang_String{% else %}JAVA_OBJECT{% end %} N::str(std::wstring str) { int32_t len = str.length(); p_java_lang_String out(new {% CLASS java.lang.String %}()); JAVA_OBJECT _out = (JAVA_OBJECT)out; p_JA_C array = new JA_C(len); p_JA_C arrayobj = array; uint16_t *ptr = (uint16_t *)array->getStartPtr(); for (int32_t n = 0; n < len; n++) ptr[n] = (uint16_t)str[n]; out->{% FIELD java.lang.String:value %} = arrayobj; //GET_OBJECT({% CLASS java.lang.String %}, out)->M_java_lang_String__init____CII_V(array, 0, len); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; }; {% if ENABLE_TYPING %}p_java_lang_String{% else %}JAVA_OBJECT{% end %} N::str(std::string s) { //if (s == nullptr) return SOBJ(nullptr); std::wstring ws(s.begin(), s.end()); return N::str(ws); }; {% if ENABLE_TYPING %}p_java_lang_String{% else %}JAVA_OBJECT{% end %} N::str(const char *s) { if (s == nullptr) return nullptr; int32_t len = strlen(s); p_java_lang_String out(new {% CLASS java.lang.String %}()); JAVA_OBJECT _out = (JAVA_OBJECT)out; p_JA_C array = new JA_C(len); p_JA_C arrayobj = array; uint16_t *ptr = (uint16_t *)array->getStartPtr(); //::memcpy((void *)ptr, (void *)str, len * sizeof(uint16_t)); for (int32_t n = 0; n < len; n++) ptr[n] = (uint16_t)s[n]; out->{% FIELD java.lang.String:value %} = arrayobj; //GET_OBJECT({% CLASS java.lang.String %}, out)->M_java_lang_String__init____CII_V(array, 0, len); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; }; {% if ENABLE_TYPING %}p_JA_L{% else %}JAVA_OBJECT{% end %} N::strArray(int32_t count, wchar_t **strs) { p_JA_L out = new JA_L(count, L"[java/lang/String;"); JAVA_OBJECT _out = (JAVA_OBJECT)out; for (int32_t n = 0; n < count; n++) out->set(n, N::str(std::wstring(strs[n]))); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; } {% if ENABLE_TYPING %}p_JA_L{% else %}JAVA_OBJECT{% end %} N::strArray(std::vector<std::wstring> strs) { int32_t len = strs.size(); p_JA_L out = new JA_L(len, L"[java/lang/String;"); JAVA_OBJECT _out = (JAVA_OBJECT)out; for (int32_t n = 0; n < len; n++) out->set(n, N::str(strs[n])); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; } {% if ENABLE_TYPING %}p_JA_L{% else %}JAVA_OBJECT{% end %} N::strArray(std::vector<std::string> strs) { int32_t len = strs.size(); p_JA_L out = new JA_L(len, L"[Ljava/lang/String;"); JAVA_OBJECT _out = (JAVA_OBJECT)out; for (int32_t n = 0; n < len; n++) out->set(n, N::str(strs[n])); return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; } {% if ENABLE_TYPING %}p_JA_L{% else %}JAVA_OBJECT{% end %} N::strEmptyArray() { p_JA_L out = new JA_L(0, L"Ljava/lang/String;"); JAVA_OBJECT _out = (JAVA_OBJECT)out; return {% if ENABLE_TYPING %}out{% else %}_out{% end %}; } std::wstring N::istr2(JAVA_OBJECT obj) { int32_t len = N::strLen(obj); std::wstring s; s.reserve(len); for (int32_t n = 0; n < len; n++) s.push_back(N::strCharAt(obj, n)); return s; } std::string N::istr3(JAVA_OBJECT obj) { int32_t len = N::strLen(obj); std::string s; s.reserve(len); for (int32_t n = 0; n < len; n++) s.push_back(N::strCharAt(obj, n)); return s; } int32_t N::strLen(JAVA_OBJECT obj) { auto str = GET_OBJECT({% CLASS java.lang.String %}, obj); return str->{% METHOD java.lang.String:length %}(); } uint16_t N::strCharAt(JAVA_OBJECT obj, int32_t n) { auto str = GET_OBJECT({% CLASS java.lang.String %}, obj); return str->{% METHOD java.lang.String:charAt %}(n); } void N::log(std::wstring str) { std::wcout << str << L"\n"; fflush(stdout); } void N::log(JAVA_OBJECT obj) { N::log(N::istr2(obj)); } JAVA_OBJECT N::dummyMethodClass() { throw "Not supported java8 method references"; return nullptr; } void N::throwNpe(const wchar_t* position) { TRACE_REGISTER("N::throwNpe()"); std::wcout << L"N::throwNpe():" << std::wstring(position) << L"\n"; throw {% CONSTRUCTOR java.lang.NullPointerException:()V %}(); } template<typename T> T N::ensureNpe(T obj, const wchar_t* position) { #ifdef CHECK_NPE if (obj == nullptr) N::throwNpe(position); #endif return obj; } void N::throwNpe() { N::throwNpe(L"unknown"); } template<typename T> T N::ensureNpe(T obj) { #ifdef CHECK_NPE if (obj == nullptr) N::throwNpe(); #endif return obj; } int32_t N::identityHashCode(JAVA_OBJECT obj) { return (int32_t)(size_t)(void *)(obj); } //TODO signature of *out? void N::writeChars(JAVA_OBJECT str, char *out, int32_t maxlen) { int32_t len = std::min(N::strLen(str), maxlen - 1); for (int32_t n = 0; n < len; n++) { out[n] = N::strCharAt(str, n); } out[len] = 0; } void __throwCLASSCAST() { throw {% CONSTRUCTOR java.lang.ClassCastException:(Ljava/lang/String;)V %}(N::str(L"Class cast error")); } template<typename T> p_java_lang_Object N::CC_GET_OBJ(T t) { if (t == nullptr) return nullptr; return t->__getObj(); } template<typename TTo, typename TFrom> TTo N::CC_CHECK_CLASS(TFrom i, int32_t typeId) { if (i == nullptr) return nullptr; if (!N::is(i, typeId)) __throwCLASSCAST(); TTo result = dynamic_cast<TTo>(i); if (result == nullptr) __throwCLASSCAST(); return result; } template<typename T> T N::CC_CHECK_UNTYPED(T i, int32_t typeId) { if (i == nullptr) return nullptr; if (!N::is(i, typeId)) __throwCLASSCAST(); return i; } template<typename TTo, typename TFrom> TTo N::CC_CHECK_INTERFACE(TFrom i, int32_t typeId) { if (i == nullptr) return nullptr; if (!N::is(i, typeId)) __throwCLASSCAST(); TTo result = static_cast<TTo>(i->__getInterface(typeId)); if (result == nullptr) __throwCLASSCAST(); return result; } template<typename TTo, typename TFrom> TTo N::CC_CHECK_GENERIC(TFrom i) { if (i == nullptr) return nullptr; TTo result = dynamic_cast<TTo>(i); if (result == nullptr) __throwCLASSCAST(); return result; } #ifndef __has_builtin #define __has_builtin(x) 0 #endif // https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c // https://msdn.microsoft.com/es-es/library/b0084kay.aspx #ifdef _MSC_VER #include <intrin.h> #define JT_HAS_INTRINSIC_BSWAP64 #define JT_HAS_INTRINSIC_BSWAP32 #define JT_HAS_INTRINSIC_BSWAP16 // Unification #define __builtin_bswap16 _byteswap_ushort #define __builtin_bswap32 _byteswap_ulong #define __builtin_bswap64 _byteswap_uint64 #else #if defined(__GNUC__) || __has_builtin(__builtin_bswap64) #define JT_HAS_INTRINSIC_BSWAP64 #endif #if defined(__GNUC__) || __has_builtin(__builtin_bswap32) #define JT_HAS_INTRINSIC_BSWAP32 #endif #if defined(__GNUC__) || __has_builtin(__builtin_bswap16) #define JT_HAS_INTRINSIC_BSWAP16 #endif #endif int16_t N::bswap16(int16_t a) { #ifdef JT_HAS_INTRINSIC_BSWAP16 return __builtin_bswap16(a); #else return ((a & 0xff) << 8) | ((a & 0xff00) >> 8); #endif } int32_t N::bswap32(int32_t a) { #ifdef JT_HAS_INTRINSIC_BSWAP32 return __builtin_bswap32(a); #else return (a & 0x000000ff) << 24 | (a & 0x0000ff00) << 8 | (a & 0x00ff0000) >> 8 | (a & 0xff000000) >> 24; #endif } // https://linux.die.net/man/3/htobe64 int64_t N::bswap64(int64_t a) { #ifdef JT_HAS_INTRINSIC_BSWAP64 return __builtin_bswap64(a); #else return ((a << 56) & 0xff00000000000000UL) | ((a << 40) & 0x00ff000000000000UL) | ((a << 24) & 0x0000ff0000000000UL) | ((a << 8) & 0x000000ff00000000UL) | ((a >> 8) & 0x00000000ff000000UL) | ((a >> 24) & 0x0000000000ff0000UL) | ((a >> 40) & 0x000000000000ff00UL) | ((a >> 56) & 0x00000000000000ffUL) ; #endif } JAVA_OBJECT N::unboxVoid(JAVA_OBJECT obj) { return (JAVA_OBJECT)nullptr; } JT_BOOL N::unboxBool(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Boolean %}, obj)->{% SMETHOD java.lang.Boolean:booleanValue %}(); } int8_t N::unboxByte(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Byte %}, obj)->{% SMETHOD java.lang.Byte:byteValue %}(); } int16_t N::unboxShort(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Short %}, obj)->{% SMETHOD java.lang.Short:shortValue %}(); } uint16_t N::unboxChar(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Character %}, obj)->{% SMETHOD java.lang.Character:charValue %}(); } int32_t N::unboxInt(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Integer %}, obj)->{% SMETHOD java.lang.Integer:intValue %}(); } int64_t N::unboxLong(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Long %}, obj)->{% SMETHOD java.lang.Long:longValue %}(); } float N::unboxFloat(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Float %}, obj)->{% SMETHOD java.lang.Float:floatValue %}(); } double N::unboxDouble(JAVA_OBJECT obj) { return GET_OBJECT({% CLASS java.lang.Double %}, obj)->{% SMETHOD java.lang.Double:doubleValue %}(); } JAVA_OBJECT N::boxVoid(void) { return (JAVA_OBJECT)nullptr; } JAVA_OBJECT N::boxVoid(JAVA_OBJECT v) { return (JAVA_OBJECT)nullptr; } JAVA_OBJECT N::boxBool(JT_BOOL v) { return {% SMETHOD java.lang.Boolean:valueOf:(Z)Ljava/lang/Boolean; %}(v); } JAVA_OBJECT N::boxByte(int8_t v) { return {% SMETHOD java.lang.Byte:valueOf:(B)Ljava/lang/Byte; %}(v); } JAVA_OBJECT N::boxShort(int16_t v) { return {% SMETHOD java.lang.Short:valueOf:(S)Ljava/lang/Short; %}(v); } JAVA_OBJECT N::boxChar(uint16_t v) { return {% SMETHOD java.lang.Character:valueOf:(C)Ljava/lang/Character; %}(v); } JAVA_OBJECT N::boxInt(int32_t v) { return {% SMETHOD java.lang.Integer:valueOf:(I)Ljava/lang/Integer; %}(v); } JAVA_OBJECT N::boxLong(int64_t v) { return {% SMETHOD java.lang.Long:valueOf:(J)Ljava/lang/Long; %}(v); } JAVA_OBJECT N::boxFloat(float v) { return {% SMETHOD java.lang.Float:valueOf:(F)Ljava/lang/Float; %}(v); } JAVA_OBJECT N::boxDouble(double v) { return {% SMETHOD java.lang.Double:valueOf:(D)Ljava/lang/Double; %}(v); } //SOBJ JA_0::{% METHOD java.lang.Object:getClass %}() { return {% SMETHOD java.lang.Class:forName0 %}(N::str(desc)); } std::vector<JAVA_OBJECT> N::getVectorOrEmpty(JAVA_OBJECT obj) { auto array = GET_OBJECT(JA_L, obj); if (array == nullptr) return std::vector<JAVA_OBJECT>(0); return array->getVector(); }; #include <chrono> double N::getTime() { using namespace std::chrono; milliseconds ms = duration_cast<milliseconds>( system_clock::now().time_since_epoch() ); return (double)(int64_t)ms.count(); }; int64_t N::nanoTime() { using namespace std::chrono; auto time = duration_cast<nanoseconds>( high_resolution_clock::now().time_since_epoch() ); return (int64_t)time.count(); }; void N::monitorEnter(JAVA_OBJECT obj) { if (obj == nullptr) return; //std::wcout << L"N::monitorEnter[1]\n"; obj->mtx.lock(); //std::wcout << L"N::monitorEnter[2]\n"; } void N::monitorExit(JAVA_OBJECT obj){ if (obj == nullptr) return; //std::wcout << L"N::monitorExit[1]\n"; obj->mtx.unlock(); //std::wcout << L"N::monitorExit[2]\n"; } void SIGSEGV_handler(int signal) { std::wcout << L"invalid memory access (segmentation fault)\n"; throw L"invalid memory access (segmentation fault)"; }; void SIGFPE_handler(int signal) { std::wcout << L"erroneous arithmetic operation such as divide by zero\n"; throw L"erroneous arithmetic operation such as divide by zero"; }; //SIGTERM termination request, sent to the program //SIGSEGV invalid memory access (segmentation fault) //SIGINT external interrupt, usually initiated by the user //SIGILL invalid program image, such as invalid instruction //SIGABRT abnormal termination condition, as is e.g. initiated by std::abort() //SIGFPE erroneous arithmetic operation such as divide by zero void* DYN::openDynamicLib(const char* libraryName){ #if _JTRANSC_WINDOWS_ return LoadLibrary(libraryName); #elif _JTRANSC_UNIX_LIKE_ return dlopen(libraryName, RTLD_LAZY | RTLD_LOCAL); #else # error "Dynamic loading unsupported on this target" #endif } void DYN::closeDynamicLib(void* handle){ #if _JTRANSC_WINDOWS_ FreeLibrary((HMODULE)handle); #elif _JTRANSC_UNIX_LIKE_ dlclose(handle); #else # error "Dynamic loading unsupported on this target" #endif } void* DYN::findDynamicSymbol(void* handle, const char* symbolToSearch){ #if _JTRANSC_WINDOWS_ void* symbol = GetProcAddress((HMODULE)handle, symbolToSearch); //TODO error handling, etc. return symbol; #elif _JTRANSC_UNIX_LIKE_ dlerror(); //Clear all old errors void* symbol = dlsym(handle, symbolToSearch); if(symbol){ return symbol; } else { const char* error = dlerror(); if(error){ return NULL; //throw error; } else { return NULL; //throw (std::string("Unknown error while trying to resolve ") + std::string(symbolToSearch) + std::string(" or the symbol refers to a null pointer!")).c_str(); } } #else # error "Dynamic loading unsupported on this target" #endif } void* DYN::jtvmResolveNative(JAVA_OBJECT clazz, const char* shortMangledName, const char* longMangledName, void** ptr){ if(*ptr != NULL) { return *ptr; } else { auto classLoader = GET_OBJECT({% CLASS java.lang.Class %}, clazz)->{% METHOD java.lang.Class:getClassLoader %}(); *ptr = jtvmResolveNativeMethodImpl(shortMangledName, longMangledName, classLoader, ptr); } if(*ptr == NULL){ throw "Couldn't find native symbol"; } return *ptr; } void* DYN::jtvmResolveNativeMethodImpl(const char* shortMangledName, const char* longMangledName, JAVA_OBJECT classLoader, void** ptr){ JAVA_OBJECT nativeLibsRaw = GET_OBJECT({% CLASS java.lang.ClassLoader %}, classLoader)->{% METHOD java.lang.ClassLoader:getNativeLibs %}(); auto nativeLibs = GET_OBJECT({% CLASS java.util.ArrayList %}, nativeLibsRaw); jint size = nativeLibs->{% METHOD java.util.ArrayList:size %}(); for(jint i = 0; i < size; i++){ auto nativeLib = GET_OBJECT({% CLASS java.lang.ClassLoader$NativeLib %}, nativeLibs->{% METHOD java.util.ArrayList:get %}(i)); auto handle = jlong_to_ptr(nativeLib->{% FIELD java.lang.ClassLoader$NativeLib:handle %}); void* symbol = DYN::findDynamicSymbol(handle, shortMangledName); if(symbol){ return symbol; } else { symbol = DYN::findDynamicSymbol(handle, longMangledName); if(symbol) { return symbol; } else { return NULL; } } } return nullptr; } jmethodID JNICALL FromReflectedMethod(JNIEnv *env, jobject method){ return (jmethodID)method; // TODO check requirements and other stuff } jfieldID JNICALL FromReflectedField(JNIEnv *env, jobject field){ return (jfieldID)field; // TODO check requirements and other stuff } jobject JNICALL ToReflectedMethod(JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic){ return (jobject)methodID; // TODO check requirements and other stuff } jclass JNICALL GetSuperclass(JNIEnv *env, jclass clazz){ return (jclass)GET_OBJECT({% CLASS java.lang.Class %}, (JAVA_OBJECT)clazz)->{% METHOD java.lang.Class:getSuperclass%}(); } jboolean JNICALL IsAssignableFrom(JNIEnv *env, jclass clazz1, jclass clazz2){ return GET_OBJECT({% CLASS java.lang.Class %}, (JAVA_OBJECT)clazz2)->{% METHOD java.lang.Class:isAssignableFrom %}(GET_OBJECT({% CLASS java.lang.Class %}, (JAVA_OBJECT)clazz1)); } jobject JNICALL ToReflectedField(JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic){ return (jobject)fieldID; // TODO check requirements and other stuff } jint JNICALL PushLocalFrame(JNIEnv* env, jint cap) { return 0; } jobject JNICALL PopLocalFrame(JNIEnv* env, jobject res) { return res; } jint JNICALL EnsureLocalCapacity(JNIEnv* env, jint capacity) { return 0; } static JA_L* jvalueToJavaArray(int32_t count, {% CLASS java.lang.reflect.MethodConstructor %}* ctor, const jvalue *args){ JA_L* array = new JA_L(count, L"[Ljava.lang.Object;"); const char* s = N::istr3(ctor->{% FIELD java.lang.reflect.MethodConstructor:jniSignature%}).c_str(); for( int32_t i = 0; i < count; i++){ switch (s[i]) { case 'B': array->fastSet(i, N::boxByte(args[i].b)); break; case 'Z': array->fastSet(i, N::boxBool(args[i].z)); break; case 'S': array->fastSet(i, N::boxShort(args[i].s)); break; case 'C': array->fastSet(i, N::boxChar(args[i].c)); break; case 'I': array->fastSet(i, N::boxInt(args[i].i)); break; case 'J': array->fastSet(i, N::boxLong(args[i].j)); break; case 'F': array->fastSet(i, N::boxFloat(args[i].f)); break; case 'D': array->fastSet(i, N::boxDouble(args[i].d)); break; case '[': array->fastSet(i, (JAVA_OBJECT)args[i].l); break; case 'L': array->fastSet(i, (JAVA_OBJECT)args[i].l); break; } } return array; } static JA_L* va_listToJavaArray(int32_t count, {% CLASS java.lang.reflect.MethodConstructor %}* ctor, va_list args){ JA_L* array = new JA_L(count, L"[Ljava.lang.Object;"); const char* s = N::istr3(ctor->{% FIELD java.lang.reflect.MethodConstructor:jniSignature%}).c_str(); for( int32_t i = 0; i < count; i++){ switch (s[i]) { case 'B': array->fastSet(i, N::boxByte((jbyte)va_arg(args, jint))); break; case 'Z': array->fastSet(i, N::boxBool((jboolean)va_arg(args, jint))); break; case 'S': array->fastSet(i, N::boxShort((jshort)va_arg(args, jint))); break; case 'C': array->fastSet(i, N::boxChar((jchar)va_arg(args, jint))); break; case 'I': array->fastSet(i, N::boxInt(va_arg(args, jint))); break; case 'J': array->fastSet(i, N::boxLong(va_arg(args, jlong))); break; case 'F': array->fastSet(i, N::boxFloat((float)va_arg(args, jdouble))); break; case 'D': array->fastSet(i, N::boxDouble(va_arg(args, jdouble))); break; case '[': array->fastSet(i, (JAVA_OBJECT)va_arg(args, jobject)); break; case 'L': array->fastSet(i, (JAVA_OBJECT)va_arg(args, jobject)); break; } } return array; } JAVA_OBJECT jtvmNewObjectA(JAVA_OBJECT clazz, JAVA_OBJECT method, const jvalue *args) { {% CLASS java.lang.reflect.Constructor %}* ctor = GET_OBJECT({% CLASS java.lang.reflect.Constructor %}, method); int32_t parameterCount = ctor->{% METHOD java.lang.reflect.Constructor:getParameterCount %}(); return ctor->{% METHOD java.lang.reflect.Constructor:newInstance %}(jvalueToJavaArray(parameterCount, ctor, args)); } JAVA_OBJECT jtvmNewObjectV(JAVA_OBJECT clazz, JAVA_OBJECT method, va_list args) { {% CLASS java.lang.reflect.Constructor %}* ctor = GET_OBJECT({% CLASS java.lang.reflect.Constructor %}, method); int32_t parameterCount = ctor->{% METHOD java.lang.reflect.Constructor:getParameterCount %}(); return ctor->{% METHOD java.lang.reflect.Constructor:newInstance %}(va_listToJavaArray(parameterCount, ctor, args)); } jobject JNICALL NewObjectV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { return (jobject) jtvmNewObjectV((JAVA_OBJECT) clazz, (JAVA_OBJECT) methodID, args); } jobject JNICALL NewObjectA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { return (jobject) jtvmNewObjectA((JAVA_OBJECT) clazz, (JAVA_OBJECT) methodID, args); } jobject JNICALL NewObject(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jobject o = NewObjectV(env, clazz, methodID, args); va_end(args); return o; } jobject JNICALL AllocObject(JNIEnv *env, jclass clazz){ int32_t classId = GET_OBJECT({% CLASS java.lang.Class %}, (JAVA_OBJECT)clazz)->{% FIELD java.lang.Class:id %}; return (jobject)CTOR_TABLE[classId](); } inline static jboolean isMethodStatic(jmethodID method_){ JAVA_OBJECT method = (JAVA_OBJECT)method_; jboolean result = GET_OBJECT({% CLASS java.lang.reflect.MethodConstructor %}, method)->{% METHOD java.lang.reflect.MethodConstructor:isStatic %}(); return result; } JAVA_OBJECT jtvmGetMethodForClass(JNIEnv *env, JAVA_OBJECT clazz, const char *name, const char *sig){ if(strcmp(sig, "<init>") == 0){ // for ctors // TODO check correctness etc. JAVA_OBJECT ctor_ = GET_OBJECT({% CLASS java.lang.Class %}, clazz)->{% METHOD java.lang.Class:getDeclaredConstructorBySig %}(N::str(sig)); auto ctor = GET_OBJECT({% CLASS java.lang.reflect.Method %}, ctor_); if(ctor){ return ctor; } } else { // for methods // TODO check correctness etc. JAVA_OBJECT method_ = GET_OBJECT({% CLASS java.lang.Class %}, clazz)->{% METHOD java.lang.Class:getDeclaredMethodBySig %}(N::str(name), N::str(sig)); auto method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, method_); if(method){ return method; } } return nullptr; } jmethodID jtvmGetInstanceMethod(JNIEnv *env, JAVA_OBJECT clazz_, const char *name, const char *sig){ auto clazz = GET_OBJECT({% CLASS java.lang.Class %}, clazz_); if(strcmp(sig, "<init>") == 0 || strcmp(sig, "<clinit>") == 0 ){ // ctors and static initializers are not inherited, so only check this class and not the superclass jmethodID method = (jmethodID)jtvmGetMethodForClass(env, reinterpret_cast<JAVA_OBJECT>(clazz), name, sig); if(method && !isMethodStatic(method)) return method; //TODO throw exception? } java_lang_Class* c = NULL; for (c = clazz; c != NULL; c = GET_OBJECT({% CLASS java.lang.Class %}, GET_OBJECT({% CLASS java.lang.Class %}, c)->{% METHOD java.lang.Class:getSuperclass %}())) { jmethodID method = (jmethodID)jtvmGetMethodForClass(env, clazz, name, sig); if(method && !isMethodStatic(method)) return method; //TODO throw exception? } return NULL; } jmethodID JNICALL GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig){ // TODO force init of clazz if not already initialised return jtvmGetInstanceMethod(env, reinterpret_cast<JAVA_OBJECT>(clazz), name, sig); } /** * Returns a methddID based on the obj. That's necessary because the methodID may not always be the exact right. * This is needed for the virtual dispatch routines. **/ static inline jmethodID getRealMethod(JNIEnv* env, jobject obj, jmethodID methodID){ JAVA_OBJECT clazz = ((JAVA_OBJECT)obj)->{% METHOD java.lang.Object:getClass %}(); auto method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT) methodID); JAVA_OBJECT containingClazz = method->{% FIELD java.lang.reflect.MethodConstructor:clazz %}; if(method->{% METHOD java.lang.reflect.MethodConstructor:isPrivate %}() || clazz->{% METHOD java.lang.Class:equals %}(containingClazz)){ return methodID; } else { const char* name = N::istr3(method->{% FIELD java.lang.reflect.MethodConstructor:name %}).c_str(); const char* sig = N::istr3(method->{% FIELD java.lang.reflect.MethodConstructor:signature %}).c_str(); return GetMethodID(env, GetSuperclass(env, (jclass)clazz), name, sig); } } jobject jtvmCallObjectInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return (jobject)method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args)); } jobject jtvmCallObjectInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return (jobject)method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args)); } jobject JNICALL CallObjectMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallObjectInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jobject JNICALL CallObjectMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallObjectInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jobject JNICALL CallObjectMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jobject o = CallObjectMethodV(env, obj, methodID, args); va_end(args); return o; } jboolean jtvmCallBooleanInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxBool(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jboolean jtvmCallBooleanInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxBool(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jboolean JNICALL CallBooleanMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallBooleanInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jboolean JNICALL CallBooleanMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallBooleanInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jboolean JNICALL CallBooleanMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jboolean b = CallBooleanMethodV(env, obj, methodID, args); va_end(args); return b; } jbyte jtvmCallByteInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxByte(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jbyte jtvmCallByteInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxByte(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jbyte JNICALL CallByteMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallByteInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jbyte JNICALL CallByteMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallByteInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jbyte JNICALL CallByteMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jbyte b = CallByteMethodV(env, obj, methodID, args); va_end(args); return b; } jchar jtvmCallCharInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxChar(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jchar jtvmCallCharInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxChar(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jchar JNICALL CallCharMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallCharInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jchar JNICALL CallCharMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallCharInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jchar JNICALL CallCharMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jchar c = CallCharMethodV(env, obj, methodID, args); va_end(args); return c; } jshort jtvmCallShortInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxShort(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jshort jtvmCallShortInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxShort(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jshort JNICALL CallShortMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallShortInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jshort JNICALL CallShortMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallShortInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jshort JNICALL CallShortMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jshort s = CallShortMethodV(env, obj, methodID, args); va_end(args); return s; } jint jtvmCallIntInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxInt(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jint jtvmCallIntInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxInt(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jint JNICALL CallIntMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallIntInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jint JNICALL CallIntMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallIntInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jint JNICALL CallIntMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jint i = CallIntMethodV(env, obj, methodID, args); va_end(args); return i; } jlong jtvmCallLongInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxLong(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jlong jtvmCallLongInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxLong(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jlong JNICALL CallLongMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallLongInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jlong JNICALL CallLongMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallLongInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jlong JNICALL CallLongMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jlong l = CallLongMethodV(env, obj, methodID, args); va_end(args); return l; } jfloat jtvmCallFloatInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxFloat(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jfloat jtvmCallFloatInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxFloat(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jfloat JNICALL CallFloatMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallFloatInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jfloat JNICALL CallFloatMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallFloatInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jfloat JNICALL CallFloatMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jfloat f = CallFloatMethodV(env, obj, methodID, args); va_end(args); return f; } jdouble jtvmCallDoubleInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxDouble(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args))); } jdouble jtvmCallDoubleInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxDouble(method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args))); } jdouble JNICALL CallDoubleMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { return jtvmCallDoubleInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } jdouble JNICALL CallDoubleMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { return jtvmCallDoubleInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } jdouble JNICALL CallDoubleMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jdouble d = CallDoubleMethodV(env, obj, methodID, args); va_end(args); return d; } void jtvmCallVoidInstanceMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args){ {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, va_listToJavaArray(parameterCount, method, args)); } void jtvmCallVoidInstanceMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); method->{% METHOD java.lang.reflect.Method:invoke %}((JAVA_OBJECT)obj, jvalueToJavaArray(parameterCount, method, args)); } void JNICALL CallVoidMethodV(JNIEnv* env, jobject obj, jmethodID methodID, va_list args) { jtvmCallVoidInstanceMethodV(env, obj, getRealMethod(env, obj, methodID), args); } void JNICALL CallVoidMethodA(JNIEnv* env, jobject obj, jmethodID methodID, const jvalue* args) { jtvmCallVoidInstanceMethodA(env, obj, getRealMethod(env, obj, methodID), args); } void JNICALL CallVoidMethod(JNIEnv* env, jobject obj, jmethodID methodID, ...) { va_list args; va_start(args, methodID); CallVoidMethodV(env, obj, methodID, args); va_end(args); } // jobject JNICALL CallNonvirtualObjectMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallObjectInstanceMethodV(env, obj, methodID, args); } jobject JNICALL CallNonvirtualObjectMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallObjectInstanceMethodA(env, obj, methodID, args); } jobject JNICALL CallNonvirtualObjectMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jobject o = CallNonvirtualObjectMethodV(env, obj, clazz, methodID, args); va_end(args); return o; } jboolean JNICALL CallNonvirtualBooleanMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallBooleanInstanceMethodV(env, obj, methodID, args); } jboolean JNICALL CallNonvirtualBooleanMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallBooleanInstanceMethodA(env, obj, methodID, args); } jboolean JNICALL CallNonvirtualBooleanMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jboolean b = CallNonvirtualBooleanMethodV(env, obj, clazz, methodID, args); va_end(args); return b; } jbyte JNICALL CallNonvirtualByteMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallByteInstanceMethodV(env, obj, methodID, args); } jbyte JNICALL CallNonvirtualByteMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallByteInstanceMethodA(env, obj, methodID, args); } jbyte JNICALL CallNonvirtualByteMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jbyte b = CallNonvirtualByteMethodV(env, obj, clazz, methodID, args); va_end(args); return b; } jchar JNICALL CallNonvirtualCharMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallCharInstanceMethodV(env, obj, methodID, args); } jchar JNICALL CallNonvirtualCharMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallCharInstanceMethodA(env, obj, methodID, args); } jchar JNICALL CallNonvirtualCharMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jchar c = CallNonvirtualCharMethodV(env, obj, clazz, methodID, args); va_end(args); return c; } jshort JNICALL CallNonvirtualShortMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallShortInstanceMethodV(env, obj, methodID, args); } jshort JNICALL CallNonvirtualShortMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallShortInstanceMethodA(env, obj, methodID, args); } jshort JNICALL CallNonvirtualShortMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jshort s = CallNonvirtualShortMethodV(env, obj, clazz, methodID, args); va_end(args); return s; } jint JNICALL CallNonvirtualIntMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallIntInstanceMethodV(env, obj, methodID, args); } jint JNICALL CallNonvirtualIntMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallIntInstanceMethodA(env, obj, methodID, args); } jint JNICALL CallNonvirtualIntMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jint i = CallNonvirtualIntMethodV(env, obj, clazz, methodID, args); va_end(args); return i; } jlong JNICALL CallNonvirtualLongMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallLongInstanceMethodV(env, obj, methodID, args); } jlong JNICALL CallNonvirtualLongMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallLongInstanceMethodA(env, obj, methodID, args); } jlong JNICALL CallNonvirtualLongMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jlong l = CallNonvirtualLongMethodV(env, obj, clazz, methodID, args); va_end(args); return l; } jfloat JNICALL CallNonvirtualFloatMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallFloatInstanceMethodV(env, obj, methodID, args); } jfloat JNICALL CallNonvirtualFloatMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallFloatInstanceMethodA(env, obj, methodID, args); } jfloat JNICALL CallNonvirtualFloatMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jfloat f = CallNonvirtualFloatMethodV(env, obj, clazz, methodID, args); va_end(args); return f; } jdouble JNICALL CallNonvirtualDoubleMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { return jtvmCallDoubleInstanceMethodV(env, obj, methodID, args); } jdouble JNICALL CallNonvirtualDoubleMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { return jtvmCallDoubleInstanceMethodA(env, obj, methodID, args); } jdouble JNICALL CallNonvirtualDoubleMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jdouble d = CallNonvirtualDoubleMethodV(env, obj, clazz, methodID, args); va_end(args); return d; } void JNICALL CallNonvirtualVoidMethodV(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, va_list args) { jtvmCallVoidInstanceMethodV(env, obj, methodID, args); } void JNICALL CallNonvirtualVoidMethodA(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, const jvalue* args) { jtvmCallVoidInstanceMethodA(env, obj, methodID, args); } void JNICALL CallNonvirtualVoidMethod(JNIEnv* env, jobject obj, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); CallNonvirtualVoidMethodV(env, obj, clazz, methodID, args); va_end(args); } jfieldID jtvmGetFieldID({% CLASS java.lang.Class %}* clazz, JAVA_OBJECT name, JAVA_OBJECT sig){ auto field_ = clazz->{% METHOD java.lang.Class:getField %}(name); auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, field_); if(field){ JAVA_OBJECT signature = field->{% FIELD java.lang.reflect.Field:signature %}; if(signature->{% METHOD java.lang.String:equals %}(sig)){ if(field->{% METHOD java.lang.reflect.Field:isStatic %}()){ return (jfieldID)field; } else { return NULL; } } } return (jfieldID)field; } jfieldID JNICALL GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig){ return jtvmGetFieldID(GET_OBJECT({% CLASS java.lang.Class %}, (JAVA_OBJECT)clazz), N::str(name), N::str(sig)); } jobject JNICALL GetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return (jobject) field->{% METHOD java.lang.reflect.Field:get %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jboolean JNICALL GetBooleanField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getBoolean %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jbyte JNICALL GetByteField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getByte %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jchar JNICALL GetCharField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getChar %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jshort JNICALL GetShortField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getShort %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jint JNICALL GetIntField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getInt %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jlong JNICALL GetLongField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getLong %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jfloat JNICALL GetFloatField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getFloat %}(reinterpret_cast<JAVA_OBJECT>(obj)); } jdouble JNICALL GetDoubleField(JNIEnv *env, jobject obj, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getDouble %}(reinterpret_cast<JAVA_OBJECT>(obj)); } void JNICALL SetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID, jobject value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:set %}(reinterpret_cast<JAVA_OBJECT>(obj), reinterpret_cast<JAVA_OBJECT>(value)); } void JNICALL SetBooleanField(JNIEnv *env, jobject obj, jfieldID fieldID, jboolean value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setBoolean %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetByteField(JNIEnv *env, jobject obj, jfieldID fieldID, jbyte value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setByte %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetCharField(JNIEnv *env, jobject obj, jfieldID fieldID, jchar value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setChar %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetShortField(JNIEnv *env, jobject obj, jfieldID fieldID, jshort value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setShort %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetIntField(JNIEnv *env, jobject obj, jfieldID fieldID, jint value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setInt %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetLongField(JNIEnv *env, jobject obj, jfieldID fieldID, jlong value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setLong %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetFloatField(JNIEnv *env, jobject obj, jfieldID fieldID, jfloat value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setFloat %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } void JNICALL SetDoubleField(JNIEnv *env, jobject obj, jfieldID fieldID, jdouble value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setDouble %}(reinterpret_cast<JAVA_OBJECT>(obj), value); } jobject JNICALL CallStaticObjectMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return (jobject)method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args)); } jmethodID JNICALL GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig){ return (jmethodID)jtvmGetMethodForClass(env, (JAVA_OBJECT)clazz, name, sig); // TODO verify jni specs } jobject JNICALL CallStaticObjectMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return (jobject)method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args)); } jobject JNICALL CallStaticObjectMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jobject o = CallStaticObjectMethodV(env, clazz, methodID, args); va_end(args); return o; } jboolean JNICALL CallStaticBooleanMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxBool(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jboolean JNICALL CallStaticBooleanMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxBool(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jboolean JNICALL CallStaticBooleanMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jboolean b = CallStaticBooleanMethodV(env, clazz, methodID, args); va_end(args); return b; } jbyte JNICALL CallStaticByteMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxByte(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jbyte JNICALL CallStaticByteMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxByte(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jbyte JNICALL CallStaticByteMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jbyte b = CallStaticByteMethodV(env, clazz, methodID, args); va_end(args); return b; } jchar JNICALL CallStaticCharMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxChar(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jchar JNICALL CallStaticCharMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxChar(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jchar JNICALL CallStaticCharMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jchar c = CallStaticCharMethodV(env, clazz, methodID, args); va_end(args); return c; } jshort JNICALL CallStaticShortMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxShort(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jshort JNICALL CallStaticShortMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxShort(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jshort JNICALL CallStaticShortMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jshort s = CallStaticShortMethodV(env, clazz, methodID, args); va_end(args); return s; } jint JNICALL CallStaticIntMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxInt(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jint JNICALL CallStaticIntMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxInt(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jint JNICALL CallStaticIntMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jint i = CallStaticIntMethodV(env, clazz, methodID, args); va_end(args); return i; } jlong JNICALL CallStaticLongMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxLong(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jlong JNICALL CallStaticLongMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxLong(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jlong JNICALL CallStaticLongMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jlong l = CallStaticLongMethodV(env, clazz, methodID, args); va_end(args); return l; } jfloat JNICALL CallStaticFloatMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxFloat(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jfloat JNICALL CallStaticFloatMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxFloat(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jfloat JNICALL CallStaticFloatMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jfloat f = CallStaticFloatMethodV(env, clazz, methodID, args); va_end(args); return f; } jdouble JNICALL CallStaticDoubleMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxDouble(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args))); } jdouble JNICALL CallStaticDoubleMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); return N::unboxDouble(method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args))); } jdouble JNICALL CallStaticDoubleMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); jdouble d = CallStaticDoubleMethodV(env, clazz, methodID, args); va_end(args); return d; } void JNICALL CallStaticVoidMethodV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, va_listToJavaArray(parameterCount, method, args)); } void JNICALL CallStaticVoidMethodA(JNIEnv* env, jclass clazz, jmethodID methodID, const jvalue* args) { {% CLASS java.lang.reflect.Method %}* method = GET_OBJECT({% CLASS java.lang.reflect.Method %}, (JAVA_OBJECT)methodID); int32_t parameterCount = method->{% METHOD java.lang.reflect.MethodConstructor:getParameterCount %}(); method->{% METHOD java.lang.reflect.Method:invoke %}(NULL, jvalueToJavaArray(parameterCount, method, args)); } void JNICALL CallStaticVoidMethod(JNIEnv* env, jclass clazz, jmethodID methodID, ...) { va_list args; va_start(args, methodID); CallStaticVoidMethodV(env, clazz, methodID, args); va_end(args); } jfieldID jtvmGetStaticFieldID(JNIEnv *env, JAVA_OBJECT clazz, const char *name, const char *sig){ JAVA_OBJECT field_ = GET_OBJECT({% CLASS java.lang.Class %}, clazz)->{% METHOD java.lang.Class:getDeclaredField %}(N::str(name)); auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, field_); if(field){ JAVA_OBJECT signature = field->{% FIELD java.lang.reflect.Field:signature %}; if(strcmp(N::istr3(signature).c_str(), sig) == 0){ if(field->{% METHOD java.lang.reflect.Field:isStatic %}()){ return (jfieldID)field; } } } return nullptr; } jfieldID JNICALL GetStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig){ // TODO force init of clazz if not already initialised return jtvmGetStaticFieldID(env, reinterpret_cast<JAVA_OBJECT>(clazz), name, sig); } jobject JNICALL GetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return (jobject) field->{% METHOD java.lang.reflect.Field:get %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jboolean JNICALL GetStaticBooleanField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getBoolean %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jbyte JNICALL GetStaticByteField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getByte %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jchar JNICALL GetStaticCharField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getChar %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jshort JNICALL GetStaticShortField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getShort %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jint JNICALL GetStaticIntField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getInt %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jlong JNICALL GetStaticLongField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getLong %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jfloat JNICALL GetStaticFloatField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getFloat %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } jdouble JNICALL GetStaticDoubleField(JNIEnv *env, jclass clazz, jfieldID fieldID){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (JAVA_OBJECT)fieldID); return field->{% METHOD java.lang.reflect.Field:getDouble %}(reinterpret_cast<JAVA_OBJECT>(clazz)); } void JNICALL SetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:set %}(reinterpret_cast<JAVA_OBJECT>(clazz), reinterpret_cast<JAVA_OBJECT>(value)); } void JNICALL SetStaticBooleanField(JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setBoolean %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticByteField(JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setByte %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticCharField(JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setChar %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticShortField(JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setShort %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticIntField(JNIEnv *env, jclass clazz, jfieldID fieldID, jint value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setInt %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticLongField(JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setLong %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticFloatField(JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setFloat %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } void JNICALL SetStaticDoubleField(JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value){ auto field = GET_OBJECT({% CLASS java.lang.reflect.Field %}, (reinterpret_cast<JAVA_OBJECT>(fieldID))); field->{% METHOD java.lang.reflect.Field:setDouble %}(reinterpret_cast<JAVA_OBJECT>(clazz), value); } JAVA_OBJECT jtvmNewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity){ JA_B* byteArray = new JA_B(address, (jint)capacity); return {% CONSTRUCTOR java.nio.ByteBuffer:([BZ)V %}(byteArray, (int8_t)true); } jobject JNICALL NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity){ return (jobject) jtvmNewDirectByteBuffer(env, address, capacity); } void* jtvmGetDirectBufferAddress(JNIEnv* env, JAVA_OBJECT buf){ auto buffer = GET_OBJECT({% CLASS java.nio.ByteBuffer %}, buf); //TODO check that this is a direct buffer return GET_OBJECT(JA_B, buffer->{% FIELD java.nio.ByteBuffer:backingArray %})->_data; } void* JNICALL GetDirectBufferAddress(JNIEnv* env, jobject buf){ return jtvmGetDirectBufferAddress(env, (JAVA_OBJECT) buf); } jlong jtvmGetDirectBufferCapacity(JNIEnv* env, JAVA_OBJECT buf){ auto buffer = GET_OBJECT({% CLASS java.nio.ByteBuffer %}, buf); return GET_OBJECT(JA_B, buffer->{% FIELD java.nio.ByteBuffer:backingArray %})->length; } jlong JNICALL GetDirectBufferCapacity(JNIEnv* env, jobject buf){ return jtvmGetDirectBufferCapacity(env, (JAVA_OBJECT) buf); } jsize jtvmGetArrayLength(JNIEnv* env, jarray array){ return ((JA_0*)array)->length; } jsize JNICALL GetArrayLength(JNIEnv* env, jarray array){ return jtvmGetArrayLength(env, array); } jobjectArray JNICALL NewObjectArray(JNIEnv *env, jsize length, jclass elementClass, jobject initialElement){ JA_L* array = new JA_L(length, L"[Ljava/lang/Object"); // TODO fix me! for(int32_t i = 0; i < length; i++){ array->fastSet(i, (JAVA_OBJECT)initialElement); } return (jobjectArray)array; } jobject JNICALL GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index){ JA_L* arr = (JA_L*)array; return (jobject)arr->fastGet(index); // TODO indexoutofbounds check } void JNICALL SetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index, jobject value){ JA_L* arr = (JA_L*)array; arr->fastSet(index, (JAVA_OBJECT)value); // TODO indexoutofbounds check } void* jtvmGetUniversalArrayElements(JNIEnv *env, JA_0* array, jboolean *isCopy){ if(isCopy) *isCopy = false; return array->_data; } jboolean* JNICALL GetBooleanArrayElements(JNIEnv *env, jbooleanArray array, jboolean *isCopy){ return (jboolean*) jtvmGetUniversalArrayElements(env, (JA_Z*) array, isCopy); } jbyte* JNICALL GetByteArrayElements(JNIEnv *env, jbyteArray array, jboolean *isCopy){ return (jbyte*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jchar* JNICALL GetCharArrayElements(JNIEnv *env, jcharArray array, jboolean *isCopy){ return (jchar*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jshort* JNICALL GetShortArrayElements(JNIEnv *env, jshortArray array, jboolean *isCopy){ return (jshort*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jint* JNICALL GetIntArrayElements(JNIEnv *env, jintArray array, jboolean *isCopy){ return (jint*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jlong* JNICALL GetLongArrayElements(JNIEnv *env, jlongArray array, jboolean *isCopy){ return (jlong*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jfloat* JNICALL GetFloatArrayElements(JNIEnv *env, jfloatArray array, jboolean *isCopy){ return (jfloat*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } jdouble* JNICALL GetDoubleArrayElements(JNIEnv *env, jdoubleArray array, jboolean *isCopy){ return (jdouble*) jtvmGetUniversalArrayElements(env, (JA_0*) array, isCopy); } void JNICALL ReleaseBooleanArrayElements(JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode){ } void JNICALL ReleaseByteArrayElements(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode){ } void JNICALL ReleaseCharArrayElements(JNIEnv *env, jcharArray array, jchar *elems, jint mode){ } void JNICALL ReleaseShortArrayElements(JNIEnv *env, jshortArray array, jshort *elems, jint mode){ } void JNICALL ReleaseIntArrayElements(JNIEnv *env, jintArray array, jint *elems, jint mode){ } void JNICALL ReleaseLongArrayElements(JNIEnv *env, jlongArray array, jlong *elems, jint mode){ } void JNICALL ReleaseFloatArrayElements(JNIEnv *env, jfloatArray array, jfloat *elems, jint mode){ } void JNICALL ReleaseDoubleArrayElements(JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode){ } static jboolean checkBounds(JNIEnv* env, JA_0* array, jint start, jint len){ jsize arrayLength = array->length; jsize end = start + arrayLength; if(start < 0 || len < 0 || end > arrayLength){ //jtvmThrowException(); return false; } return true; } void JNICALL GetBooleanArrayRegion(JNIEnv *env, jbooleanArray array, jsize start, jsize len, jboolean *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jboolean* )((JA_Z*) array)->_data) + start, sizeof(jboolean) * len); } void JNICALL GetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jbyte* )((JA_B*) array)->_data) + start, sizeof(jbyte) * len); } void JNICALL GetCharArrayRegion(JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jchar* )((JA_C*) array)->_data) + start, sizeof(jchar) * len); } void JNICALL GetShortArrayRegion(JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jshort* )((JA_S*) array)->_data) + start, sizeof(jshort) * len); } void JNICALL GetIntArrayRegion(JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jint* )((JA_I*) array)->_data) + start, sizeof(jint) * len); } void JNICALL GetLongArrayRegion(JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jlong* )((JA_J*) array)->_data) + start, sizeof(jlong) * len); } void JNICALL GetFloatArrayRegion(JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jfloat* )((JA_F*) array)->_data) + start, sizeof(jfloat) * len); } void JNICALL GetDoubleArrayRegion(JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(buf, ((jdouble* )((JA_D*) array)->_data) + start, sizeof(jdouble) * len); } void JNICALL SetBooleanArrayRegion(JNIEnv *env, jbooleanArray array, jsize start, jsize len, const jboolean *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jboolean* )((JA_Z*) array)->_data) + start, buf, sizeof(jboolean) * len); } void JNICALL SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jbyte* )((JA_B*) array)->_data) + start, buf, sizeof(jbyte) * len); } void JNICALL SetCharArrayRegion(JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jchar* )((JA_C*) array)->_data) + start, buf, sizeof(jchar) * len); } void JNICALL SetShortArrayRegion(JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jshort* )((JA_S*) array)->_data) + start, buf, sizeof(jshort) * len); } void JNICALL SetIntArrayRegion(JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jint* )((JA_I*) array)->_data) + start, buf, sizeof(jint) * len); } void JNICALL SetLongArrayRegion(JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jlong* )((JA_J*) array)->_data) + start, buf, sizeof(jlong) * len); } void JNICALL SetFloatArrayRegion(JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jfloat* )((JA_F*) array)->_data) + start, buf, sizeof(jfloat) * len); } void JNICALL SetDoubleArrayRegion(JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf){ if(!checkBounds(env, (JA_0*) array, start, len)) return; memcpy(((jdouble* )((JA_D*) array)->_data) + start, buf, sizeof(jdouble) * len); } void* JNICALL GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy){ if(isCopy) *isCopy = false; return ((JA_0*) array)->_data; } void JNICALL ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode){ } JA_Z* jtvmNewBooleanArray(JNIEnv* env, jsize length){ JA_Z* out = new JA_Z(length); return out; } jbooleanArray JNICALL NewBooleanArray(JNIEnv* env, jsize length){ return (jbooleanArray) jtvmNewBooleanArray(env, length); } JA_B* jtvmNewByteArray(JNIEnv* env, jsize length){ JA_B* out = new JA_B(length); return out; } jbyteArray JNICALL NewByteArray(JNIEnv* env, jsize length){ return (jbyteArray) jtvmNewByteArray(env, length); } JA_C* jtvmNewCharArray(JNIEnv* env, jsize length){ JA_C* out = new JA_C(length); return out; } jcharArray JNICALL NewCharArray(JNIEnv* env, jsize length){ return (jcharArray) jtvmNewCharArray(env, length); } JA_S* jtvmNewShortArray(JNIEnv* env, jsize length){ JA_S* out = new JA_S(length); return out; } jshortArray JNICALL NewShortArray(JNIEnv* env, jsize length){ return (jshortArray) jtvmNewShortArray(env, length); } JA_I* jtvmNewIntArray(JNIEnv* env, jsize length){ JA_I* out = new JA_I(length); return out; } jintArray JNICALL NewIntArray(JNIEnv* env, jsize length){ return (jintArray) jtvmNewIntArray(env, length); } JA_J* jtvmNewLongArray(JNIEnv* env, jsize length){ JA_J* out = new JA_J(length); return out; } jlongArray JNICALL NewLongArray(JNIEnv* env, jsize length){ return (jlongArray) jtvmNewLongArray(env, length); } JA_F* jtvmNewFloatArray(JNIEnv* env, jsize length){ JA_F* out = new JA_F(length); return out; } jfloatArray JNICALL NewFloatArray(JNIEnv* env, jsize length){ return (jfloatArray) jtvmNewFloatArray(env, length); } JA_D* jtvmNewDoubleArray(JNIEnv* env, jsize length){ JA_D* out = new JA_D(length); return out; } jdoubleArray JNICALL NewDoubleArray(JNIEnv* env, jsize length){ return (jdoubleArray) jtvmNewDoubleArray(env, length); } JNIEnv* N::getJniEnv(){ return &N::env.jni; } jint JNICALL GetVersion(JNIEnv* env){ return JNI_VERSION_1_6; } jclass JNICALL DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize bufLen){ throw "Unsupported Operation"; // TODO add proper exception return NULL; } JAVA_OBJECT jtvmFindClass(JNIEnv* env, const char *name){ return N::resolveClass(N::istr2(N::str(name))); // FIXME horribly inefficient // FIXME semantics are probably wrong } jclass JNICALL FindClass(JNIEnv* env, const char *name){ return (jclass) jtvmFindClass(env, name); } JAVA_OBJECT jtvmGetObjectClass(JNIEnv *env, JAVA_OBJECT obj){ return obj->{% METHOD java.lang.Object:getClass %}(); } jclass JNICALL GetObjectClass(JNIEnv *env, jobject obj){ return (jclass) jtvmGetObjectClass(env, (JAVA_OBJECT) obj); } bool jtvmIsInstanceOf(JNIEnv *env, JAVA_OBJECT obj, JAVA_OBJECT clazz){ return N::is(obj, GET_OBJECT_NPE({% CLASS java.lang.Class %}, clazz)->{% FIELD java.lang.Class:id %}); // FIXME verification and stuff... } jboolean JNICALL IsInstanceOf(JNIEnv *env, jobject obj, jclass clazz){ return jtvmIsInstanceOf(env, (JAVA_OBJECT) obj, (JAVA_OBJECT) clazz); } const struct JNINativeInterface_ jni = { nullptr, nullptr, nullptr, nullptr, &GetVersion, &DefineClass, &FindClass, &FromReflectedMethod, &FromReflectedField, &ToReflectedMethod, &GetSuperclass, &IsAssignableFrom, &ToReflectedField, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &PushLocalFrame, &PopLocalFrame, nullptr, nullptr, nullptr, nullptr, nullptr, &EnsureLocalCapacity, &AllocObject, &NewObject, &NewObjectV, &NewObjectA, &GetObjectClass, &IsInstanceOf, &GetMethodID, &CallObjectMethod, &CallObjectMethodV, &CallObjectMethodA, &CallBooleanMethod, &CallBooleanMethodV, &CallBooleanMethodA, &CallByteMethod, &CallByteMethodV, &CallByteMethodA, &CallCharMethod, &CallCharMethodV, &CallCharMethodA, &CallShortMethod, &CallShortMethodV, &CallShortMethodA, &CallIntMethod, &CallIntMethodV, &CallIntMethodA, &CallLongMethod, &CallLongMethodV, &CallLongMethodA, &CallFloatMethod, &CallFloatMethodV, &CallFloatMethodA, &CallDoubleMethod, &CallDoubleMethodV, &CallDoubleMethodA, &CallVoidMethod, &CallVoidMethodV, &CallVoidMethodA, &CallNonvirtualObjectMethod, &CallNonvirtualObjectMethodV, &CallNonvirtualObjectMethodA, &CallNonvirtualBooleanMethod, &CallNonvirtualBooleanMethodV, &CallNonvirtualBooleanMethodA, &CallNonvirtualByteMethod, &CallNonvirtualByteMethodV, &CallNonvirtualByteMethodA, &CallNonvirtualCharMethod, &CallNonvirtualCharMethodV, &CallNonvirtualCharMethodA, &CallNonvirtualShortMethod, &CallNonvirtualShortMethodV, &CallNonvirtualShortMethodA, &CallNonvirtualIntMethod, &CallNonvirtualIntMethodV, &CallNonvirtualIntMethodA, &CallNonvirtualLongMethod, &CallNonvirtualLongMethodV, &CallNonvirtualLongMethodA, &CallNonvirtualFloatMethod, &CallNonvirtualFloatMethodV, &CallNonvirtualFloatMethodA, &CallNonvirtualDoubleMethod, &CallNonvirtualDoubleMethodV, &CallNonvirtualDoubleMethodA, &CallNonvirtualVoidMethod, &CallNonvirtualVoidMethodV, &CallNonvirtualVoidMethodA, &GetFieldID, &GetObjectField, &GetBooleanField, &GetByteField, &GetCharField, &GetShortField, &GetIntField, &GetLongField, &GetFloatField, &GetDoubleField, &SetObjectField, &SetBooleanField, &SetByteField, &SetCharField, &SetShortField, &SetIntField, &SetLongField, &SetFloatField, &SetDoubleField, &GetStaticMethodID, &CallStaticObjectMethod, &CallStaticObjectMethodV, &CallStaticObjectMethodA, &CallStaticBooleanMethod, &CallStaticBooleanMethodV, &CallStaticBooleanMethodA, &CallStaticByteMethod, &CallStaticByteMethodV, &CallStaticByteMethodA, &CallStaticCharMethod, &CallStaticCharMethodV, &CallStaticCharMethodA, &CallStaticShortMethod, &CallStaticShortMethodV, &CallStaticShortMethodA, &CallStaticIntMethod, &CallStaticIntMethodV, &CallStaticIntMethodA, &CallStaticLongMethod, &CallStaticLongMethodV, &CallStaticLongMethodA, &CallStaticFloatMethod, &CallStaticFloatMethodV, &CallStaticFloatMethodA, &CallStaticDoubleMethod, &CallStaticDoubleMethodV, &CallStaticDoubleMethodA, &CallStaticVoidMethod, &CallStaticVoidMethodV, &CallStaticVoidMethodA, &GetStaticFieldID, &GetStaticObjectField, &GetStaticBooleanField, &GetStaticByteField, &GetStaticCharField, &GetStaticShortField, &GetStaticIntField, &GetStaticLongField, &GetStaticFloatField, &GetStaticDoubleField, &SetStaticObjectField, &SetStaticBooleanField, &SetStaticByteField, &SetStaticCharField, &SetStaticShortField, &SetStaticIntField, &SetStaticLongField, &SetStaticFloatField, &SetStaticDoubleField, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &GetArrayLength, &NewObjectArray, &GetObjectArrayElement, &SetObjectArrayElement, &NewBooleanArray, &NewByteArray, &NewCharArray, &NewShortArray, &NewIntArray, &NewLongArray, &NewFloatArray, &NewDoubleArray, &GetBooleanArrayElements, &GetByteArrayElements, &GetCharArrayElements, &GetShortArrayElements, &GetIntArrayElements, &GetLongArrayElements, &GetFloatArrayElements, &GetDoubleArrayElements, &ReleaseBooleanArrayElements, &ReleaseByteArrayElements, &ReleaseCharArrayElements, &ReleaseShortArrayElements, &ReleaseIntArrayElements, &ReleaseLongArrayElements, &ReleaseFloatArrayElements, &ReleaseDoubleArrayElements, &GetBooleanArrayRegion, &GetByteArrayRegion, &GetCharArrayRegion, &GetShortArrayRegion, &GetIntArrayRegion, &GetLongArrayRegion, &GetFloatArrayRegion, &GetDoubleArrayRegion, &SetBooleanArrayRegion, &SetByteArrayRegion, &SetCharArrayRegion, &SetShortArrayRegion, &SetIntArrayRegion, &SetLongArrayRegion, &SetFloatArrayRegion, &SetDoubleArrayRegion, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &GetPrimitiveArrayCritical, &ReleasePrimitiveArrayCritical, nullptr, nullptr, nullptr, nullptr, nullptr, &NewDirectByteBuffer, &GetDirectBufferAddress, &GetDirectBufferCapacity, nullptr }; Env N::env; void N::startup() { /* GC_set_no_dls(0); GC_set_dont_precollect(1); */ //GC_set_all_interior_pointers(0); GC_init_main_thread(); /* GC_clear_roots(); GC_add_roots(&STRINGS_START, &STRINGS_END); {% for ptr in CPP_GLOBAL_POINTERS %} GC_ADD_ROOT_SINGLE({{ ptr }}); {% end %} */ //GC_set_finalize_on_demand(0); //std::setlocale(LC_COLLATE, "en_US.UTF-8"); //std::setlocale(LC_CTYPE, "en_US.UTF-8"); N::env.jni.functions = &jni; setvbuf(stdout, nullptr, _IONBF, 0); setvbuf(stderr, nullptr, _IONBF, 0); std::signal(SIGSEGV, SIGSEGV_handler); std::signal(SIGFPE, SIGFPE_handler); N::initStringPool(); }; // Type Table Footer {{ TYPE_TABLE_FOOTER }} // Main {{ MAIN }}
38.114075
406
0.713652
renesugar
1543882b2a28c40a8b2f7f37d65e700e15b4e2ee
2,979
hpp
C++
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
#ifndef Visitable_hpp #define Visitable_hpp #include <functional> #include <typeinfo> // ---------------------------------------------------------------------------- // VisitableBase // ---------------------------------------------------------------------------- template<typename VisitorType, typename SignatureType> class VisitableBase; template<typename VisitorType, typename ReturnType, typename... ParameterTypes> class VisitableBase<VisitorType, ReturnType( ParameterTypes... )> { public: virtual ~VisitableBase() = default; virtual std::type_info const & typeInfo() const = 0; virtual ReturnType accept( VisitorType & visitor, ParameterTypes... parameters ) const = 0; }; // class VisitableBase<VisitorType, ReturnType (ParameterTypes...)> // ---------------------------------------------------------------------------- // Visitable // ---------------------------------------------------------------------------- template<typename VisiteeType, typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> class Visitable; template<typename VisiteeType, typename VisitorType, typename ReturnType, typename... ParameterTypes> class Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )> : public VisitableBase<VisitorType, ReturnType( ParameterTypes... )> { public: Visitable( VisiteeType const & visitee ); std::type_info const & typeInfo() const override; ReturnType accept( VisitorType & visitor, ParameterTypes... parameters ) const override; private: VisiteeType mVisitee; }; // class Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )> template<typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> using VisitableUPtr = std::unique_ptr<VisitableBase<VisitorType, SignatureType>>; template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableUPtr<VisitorType, SignatureType> makeUniqueVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename VisiteeType> VisitableUPtr<VisitorType, typename VisitorType::SignatureType> makeUniqueVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> using VisitableSPtr = std::shared_ptr<VisitableBase<VisitorType, SignatureType>>; template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableSPtr<VisitorType, SignatureType> makeSharedVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename VisiteeType> VisitableSPtr<VisitorType, typename VisitorType::SignatureType> makeSharedVisitable( VisiteeType const & visitee ); #include <visitor/Visitable.tpp> #endif // Visitable_hpp
35.464286
83
0.65089
cesiumsolutions
1543a351fa8dec3493095c95e01a4b6449ff059e
1,117
cc
C++
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
null
null
null
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
3
2020-05-06T18:22:40.000Z
2020-05-26T14:00:23.000Z
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
4
2021-02-11T10:44:29.000Z
2021-06-17T10:50:23.000Z
// @(#)lib/base:$Id$ // Author: Rafal Lalik 18/11/2017 /************************************************************************* * Copyright (C) 2017-2018, Rafał Lalik. * * All rights reserved. * * * * For the licensing terms see $SiFiSYS/LICENSE. * * For the list of contributors see $SiFiSYS/README/CREDITS. * *************************************************************************/ #include "SPar.h" /** * \class SPar \ingroup lib_base SPar is an abstract class to hold container and geometry parameters. It must be derivated and pure virtual members defined. The parameters are parsed from text file in SDatabase and stored in the SParContainer. The getParam() method reads content of the SParContainer and fills variables inside the SPar object. The putParam method allows to update parameters in the container and write to param file. \sa SFibersCalibratorPar \sa SFibersDigitizerPar \sa SFibersGeomPar */
36.032258
76
0.52641
SiFi-CC
154892726a064aa98f1dd9781fcd606859ade052
573
cpp
C++
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; void printLine (int star, int space)//function not returning any result is void { for (int i = 0; i < space; i++) { cout<<" "<<" "; } for (int i = 0; i < star; i++) { cout<<"*"<<" "; } cout<<endl; } int main() { int lines = 0; do { cout<<"Enter the number of lines (5-15): "; cin>>lines; } while (lines < 5 || lines > 15); for (int i = lines; i > 0; i--) { printLine(i, lines - i);//the smaller i the bigger lines-i } return 0; }
18.483871
79
0.481675
slaveya-nusheva
1549cbcd24f93a67ce4a96896a56c07c39ce7a62
318
cpp
C++
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
class Solution { public: char findTheDifference(string s, string t) { int res = 0; for (char c : s) { int ch = c - 'a'; res ^= ch; } for (char c : t) { int ch = c - 'a'; res ^= ch; } return (char)(res + 'a'); } };
19.875
48
0.367925
Alex-Amber
154d9907057df14a6add70a2e8b3a3d5a92ee4b9
3,311
cpp
C++
src/OpenGL/VertexBuffer.cpp
neuromancer/Phantasma
9552d3b43ab5ffe235f69d6d9d4e921b715464f3
[ "MIT" ]
13
2015-06-09T21:35:16.000Z
2021-08-18T14:14:43.000Z
src/OpenGL/VertexBuffer.cpp
neuromancer/Phantasma
9552d3b43ab5ffe235f69d6d9d4e921b715464f3
[ "MIT" ]
null
null
null
src/OpenGL/VertexBuffer.cpp
neuromancer/Phantasma
9552d3b43ab5ffe235f69d6d9d4e921b715464f3
[ "MIT" ]
7
2017-09-28T20:18:41.000Z
2021-03-16T11:55:45.000Z
// // VertexArray.cpp // Phantasma // // Created by Thomas Harte on 22/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "VertexBuffer.h" #include <map> VertexBuffer *VertexBuffer::boundBuffer; VertexBuffer::VertexBuffer() { // create a vector to write new values to and seed our stride as 0 stride = 0; // the first write index will be zero writeIndex = 0; // we've also so far uploaded nothing uploadedLength = 0; // flag the buffer as not yet generated buffer = 0; } VertexBuffer::~VertexBuffer() { // cleanup is: returning the OpenGL object, deleting all the attributes if(buffer) glDeleteBuffers(1, &buffer); for(std::vector <VertexAttribute *>::size_type index = 0; index < attributes.size(); index++) delete attributes[index]; // we might as well clear up boundBuffer if it's pointed to us — // that pointer is never dereferenced but a subsequent VertexBuffer // might get this address if(boundBuffer == this) boundBuffer = nullptr; } void VertexBuffer::bind() { // make sure this buffer is allocated and bound bool needsBinding = false; if(boundBuffer != this) { boundBuffer = this; needsBinding = true; if(!buffer) glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); } // make sure we've uploaded the latest data; if we've gained anything // new then add it to the pile if(uploadedLength != targetPool.size()) { if(!uploadedLength) { glBufferData(GL_ARRAY_BUFFER, (GLsizei)targetPool.size(), &targetPool[0], GL_STATIC_DRAW); } else { glBufferSubData(GL_ARRAY_BUFFER, (GLsizei)uploadedLength, (GLsizei)(targetPool.size() - uploadedLength), &targetPool[uploadedLength]); } uploadedLength = targetPool.size(); // use this opportunity to release temporary storage for(std::vector <VertexAttribute *>::size_type index = 0; index < attributes.size(); index++) attributes[index]->deleteTemporaryStorage(); } // make sure all attributes are bound if(needsBinding) { for(std::vector <VertexAttribute *>::size_type index = 0; index < attributes.size(); index++) attributes[index]->bindWithStride(stride); } } void VertexBuffer::addAttribute(GLuint index, GLint size, GLenum type, GLboolean normalised) { // allocate an attribute, add it to our list; we can figure out its start offset // from our current idea of stride VertexAttribute *newAttribute = new VertexAttribute(index, size, type, normalised, &targetPool, (std::vector<uint8_t>::size_type)stride); attributes.push_back(newAttribute); // stride is the sum of all attribute values, so update it now stride += newAttribute->sizeOfValue(); // also store the new attribute for lookup by index attributesByIndex[index] = newAttribute; } VertexAttribute *VertexBuffer::attributeForIndex(GLuint index) { // trivial, really, just pass the thing along return attributesByIndex[index]; } size_t VertexBuffer::commitVertex() { // store the current index for return and increment it for next time size_t returnIndex = writeIndex; writeIndex++; // make sure all attributes write their values in the correct sequence for(std::vector <VertexAttribute *>::size_type index = 0; index < attributes.size(); index++) attributes[index]->commitValue(); // return the index we just wrote to return returnIndex; }
27.591667
138
0.728179
neuromancer
154de9e98f0aa68c49a924d63034fe984444059e
960
cxx
C++
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
#include <memory> #include <QApplication> #include <QSurfaceFormat> #include <QVTKOpenGLStereoWidget.h> #include "DmwKernel.hxx" #include "DmwApplication.hxx" using std::make_unique; DmwApplication::DmwApplication(int argc, char ** argv) : qApplication(nullptr) { // TODO: Move everything from constructor to `exec()` method. Constructor should stay empty. // Taken from VTK example "vtk/Examples/Gui/Qt/SimpleView" // needed to ensure appropriate OpenGL context is created for VTK rendering. // ! This call must be done before construction of QApplication (see docs of QSurfaceFormat::setDefaultFormat()) QSurfaceFormat::setDefaultFormat(QVTKOpenGLStereoWidget::defaultFormat()); qApplication = make_unique<QApplication>(argc, argv); } DmwApplication::~DmwApplication() noexcept { // Nothing to do yet } int DmwApplication::exec() { DmwKernel kernel; kernel.showMainWindow(); return qApplication->exec(); }
25.263158
116
0.739583
DmitrySemikin
15520df3796e4a0361494a452b28788498a03910
193,984
cpp
C++
src/Cmfd.cpp
AI-Pranto/OpenMOC
7f6ce4797aec20ddd916981a56a4ba54ffda9a06
[ "MIT" ]
1
2021-02-14T12:43:30.000Z
2021-02-14T12:43:30.000Z
src/Cmfd.cpp
AI-Pranto/OpenMOC
7f6ce4797aec20ddd916981a56a4ba54ffda9a06
[ "MIT" ]
null
null
null
src/Cmfd.cpp
AI-Pranto/OpenMOC
7f6ce4797aec20ddd916981a56a4ba54ffda9a06
[ "MIT" ]
1
2020-10-25T06:08:50.000Z
2020-10-25T06:08:50.000Z
#include "Cmfd.h" /** * @brief Constructor initializes boundaries and variables that describe * the CMFD object. * @details The constructor initializes the many variables that describe * the CMFD mesh and are used to solve the nonlinear diffusion * acceleration problem. */ Cmfd::Cmfd() { /* Initialize Geometry and Mesh-related attribute */ _quadrature = NULL; _geometry = NULL; _materials = NULL; /* Communication structs */ _convergence_data = NULL; _domain_communicator = NULL; /* Global variables used in solving CMFD problem */ _source_convergence_threshold = 1E-5; _num_x = 1; _num_y = 1; _num_z = 1; _local_num_x = 1; _local_num_y = 1; _local_num_z = 1; _width_x = 0.; _width_y = 0.; _width_z = 0.; _cell_width_x = 0.; _cell_width_y = 0.; _cell_width_z = 0.; _num_unbounded_iterations = 0; _flux_update_on = true; _centroid_update_on = false; _use_axial_interpolation = 0; _flux_limiting = true; _balance_sigma_t = false; _k_nearest = 1; _SOR_factor = 1.5; _num_FSRs = 0; #ifndef THREED _SOLVE_3D = false; #endif _total_tally_size = 0; _tallies_allocated = false; _domain_communicator_allocated = false; _linear_source = false; _check_neutron_balance = false; _old_dif_surf_valid = false; _non_uniform = false; _widths_adjusted_for_domains = false; /* Energy group and polar angle problem parameters */ _num_moc_groups = 0; _num_cmfd_groups = 0; _num_backup_groups = 1; _num_polar = 0; _num_azim = 0; /* Set matrices and arrays to NULL */ _A = NULL; _M = NULL; _moc_iteration = 0; _k_eff = 1.0; _relaxation_factor = 0.7; _old_flux = NULL; _new_flux = NULL; _old_dif_surf_corr = NULL; _old_source = NULL; _new_source = NULL; _flux_moments = NULL; _group_indices = NULL; _group_indices_map = NULL; _user_group_indices = false; _surface_currents = NULL; _starting_currents = NULL; _net_currents = NULL; _full_surface_currents = NULL; _cell_locks = NULL; _volumes = NULL; _lattice = NULL; _azim_spacings = NULL; _polar_spacings = NULL; _backup_cmfd = NULL; _cmfd_group_to_backup_group = NULL; _backup_group_structure.resize(0); /* Initialize boundaries to be reflective */ _boundaries = new boundaryType[6]; _boundaries[SURFACE_X_MIN] = REFLECTIVE; _boundaries[SURFACE_X_MAX] = REFLECTIVE; _boundaries[SURFACE_Y_MIN] = REFLECTIVE; _boundaries[SURFACE_Y_MAX] = REFLECTIVE; _boundaries[SURFACE_Z_MIN] = REFLECTIVE; _boundaries[SURFACE_Z_MAX] = REFLECTIVE; /* Initialize CMFD timer */ _timer = new Timer(); } /** * @brief Destructor deletes arrays of A and M row insertion arrays. */ Cmfd::~Cmfd() { if (_cell_locks != NULL) delete [] _cell_locks; if (_boundaries != NULL) delete [] _boundaries; if (_group_indices != NULL) delete [] _group_indices; if (_group_indices_map != NULL) delete [] _group_indices_map; /* Delete the Matrix and Vector objects */ if (_M != NULL) delete _M; if (_A != NULL) delete _A; if (_old_source != NULL) delete _old_source; if (_new_source != NULL) delete _new_source; if (_old_flux != NULL) delete _old_flux; if (_new_flux != NULL) delete _new_flux; if (_surface_currents != NULL) delete _surface_currents; if (_starting_currents != NULL) delete _starting_currents; if (_net_currents != NULL) delete _net_currents; if (_full_surface_currents != NULL) delete _full_surface_currents; if (_old_dif_surf_corr != NULL) delete _old_dif_surf_corr; if (_volumes != NULL) delete _volumes; if (_azim_spacings != NULL) delete [] _azim_spacings; if (_polar_spacings != NULL) { for (int a=0; a < _num_azim / 4; a++) delete [] _polar_spacings[a]; delete [] _polar_spacings; } /* Delete CMFD materials array */ if (_materials != NULL) { for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) delete _materials[i]; delete [] _materials; } /* Delete the CMFD lattice */ if (_lattice != NULL) delete _lattice; /* Clear the _cell_fsrs vector of vectors */ std::vector< std::vector<long> >::iterator iter1; for (iter1 = _cell_fsrs.begin(); iter1 != _cell_fsrs.end(); ++iter1) iter1->clear(); _cell_fsrs.clear(); /* Clear the _k_nearest_stencils map of vectors */ std::map<long, std::vector< std::pair<int, double> > >::iterator iter2; for (iter2 = _k_nearest_stencils.begin(); iter2 != _k_nearest_stencils.end(); ++iter2) iter2->second.clear(); _k_nearest_stencils.clear(); /* Delete tally information */ if (_tallies_allocated) { delete [] _tally_memory; delete [] _reaction_tally; delete [] _volume_tally; delete [] _diffusion_tally; } #ifdef MPIx /* De-allocate domain communicator */ if (_domain_communicator != NULL) { if (_domain_communicator_allocated) { for (int rb=0; rb<2; rb++) { for (int f=0; f < NUM_FACES; f++) { delete [] _domain_communicator->indexes[rb][f]; delete [] _domain_communicator->domains[rb][f]; delete [] _domain_communicator->coupling_coeffs[rb][f]; delete [] _domain_communicator->fluxes[rb][f]; } delete [] _domain_communicator->num_connections[rb]; delete [] _domain_communicator->indexes[rb]; delete [] _domain_communicator->domains[rb]; delete [] _domain_communicator->coupling_coeffs[rb]; delete [] _domain_communicator->fluxes[rb]; } delete [] _domain_communicator->num_connections; delete [] _domain_communicator->indexes; delete [] _domain_communicator->domains; delete [] _domain_communicator->fluxes; delete [] _domain_communicator->coupling_coeffs; delete _domain_communicator; delete [] _inter_domain_data; for (int s=0; s < NUM_FACES; s++) { delete [] _boundary_volumes[s]; delete [] _boundary_reaction[s]; delete [] _boundary_diffusion[s]; delete [] _old_boundary_flux[s]; delete [] _boundary_surface_currents[s]; } delete [] _boundary_volumes; delete [] _boundary_reaction; delete [] _boundary_diffusion; delete [] _old_boundary_flux; delete [] _boundary_surface_currents; } } #endif for (long r=0; r < _axial_interpolants.size(); r++) delete [] _axial_interpolants.at(r); if (_backup_cmfd != NULL) delete _backup_cmfd; delete _timer; } /** * @brief Set the number of Mesh cells in a row. * @param num_x number of Mesh cells in a row */ void Cmfd::setNumX(int num_x) { if (num_x < 1) log_printf(ERROR, "The number of lattice cells in the x direction " "must be > 0. Input value: %i", num_x); _num_x = num_x; if (!_widths_adjusted_for_domains) { _local_num_x = _num_x; if (_domain_communicator != NULL) _local_num_x = _num_x / _domain_communicator->_num_domains_x; } } /** * @brief Set the number of Mesh cells in a column. * @param num_y number of Mesh cells in a column */ void Cmfd::setNumY(int num_y) { if (num_y < 1) log_printf(ERROR, "The number of lattice cells in the y direction " "must be > 0. Input value: %i", num_y); _num_y = num_y; if (!_widths_adjusted_for_domains) { _local_num_y = _num_y; if (_domain_communicator != NULL) _local_num_y = _num_y / _domain_communicator->_num_domains_y; } } /** * @brief Set the number of Mesh cells in the z-direction. * @param num_z number of Mesh cells in the z direction */ void Cmfd::setNumZ(int num_z) { if (num_z < 1) log_printf(ERROR, "The number of lattice cells in the z direction " "must be > 0. Input value: %i", num_z); _num_z = num_z; if (!_widths_adjusted_for_domains) { _local_num_z = _num_z; if (_domain_communicator != NULL) _local_num_z = _num_z / _domain_communicator->_num_domains_z; } } /** * @brief Get the number of Mesh cells in a row. * @return number of Mesh cells in a row */ int Cmfd::getNumX() { return _num_x; } /** * @brief Get the number of Mesh cells in a column * @return number of Mesh cells in a column */ int Cmfd::getNumY() { return _num_y; } /** * @brief Get the number of Mesh cells in the z-direction * @return number of Mesh cells in the z-direction */ int Cmfd::getNumZ() { return _num_z; } /** * @brief Get the Vector of surface currents. * @return pointer to a vector containing the surface currents */ Vector* Cmfd::getLocalCurrents() { return _surface_currents; } /** * @brief Get the array of surface currents on the boundaries. * @return 3D array containing the boundary surface currents */ CMFD_PRECISION*** Cmfd::getBoundarySurfaceCurrents() { return _boundary_surface_currents; } /** * @brief Set Mesh width in the x-direction * @param width Physical width of Mesh in the x-direction */ void Cmfd::setWidthX(double width) { _width_x = width; } /** * @brief Set Mesh width in the y-direction * @param width Physical width of Mesh in the y-direction */ void Cmfd::setWidthY(double width) { _width_y = width; } /** * @brief Set Mesh width in the z-direction * @param width Physical width of Mesh in the z-direction */ void Cmfd::setWidthZ(double width) { _width_z = width; } #ifdef MPIx /** * @brief Set the number of domains in each direction. * @param num_x number of domains in the X direction * @param num_y number of domains in the Y direction * @param num_z number of domains in the Z direction */ void Cmfd::setNumDomains(int num_x, int num_y, int num_z) { if (_domain_communicator == NULL) { _domain_communicator = new DomainCommunicator; _domain_communicator->_MPI_cart = _geometry->getMPICart(); } _domain_communicator->_num_domains_x = num_x; _domain_communicator->_num_domains_y = num_y; _domain_communicator->_num_domains_z = num_z; _accumulate_lmx.resize(num_x + 1, 0); _accumulate_lmy.resize(num_y + 1, 0); _accumulate_lmz.resize(num_z + 1, 0); std::vector<std::pair<int, double> > divisions_missing_x; std::vector<std::pair<int, double> > divisions_missing_y; std::vector<std::pair<int, double> > divisions_missing_z; /* Find the position of domain decomposition interfaces among the non-uniform CMFD mesh cell boundaries, in the X direction */ int j, j_prev; for (int i=0; i<num_x; i++) { double coord = (i + 1) * _width_x / num_x; for (j=1; j<_num_x+1; j++) { /* Keep track of index in mesh before domain boundary */ if (_accumulate_x[j] < coord) j_prev = j; /* Exit loop if division is found */ if (fabs(coord - _accumulate_x[j]) < FLT_EPSILON) { _accumulate_lmx[i+1] = j; break; } } if (j == _num_x+1) divisions_missing_x.push_back(std::make_pair(j_prev, coord)); } /* Find the position of domain decomposition interfaces among the non-uniform CMFD mesh cell boundaries, in the Y direction */ for (int i=0; i<num_y; i++) { double coord = (i + 1) * _width_y / num_y; for (j=1; j<_num_y+1; j++) { /* Keep track of index in mesh before domain boundary */ if (_accumulate_y[j] < coord) j_prev = j; /* Exit loop if division is found */ if (fabs(coord - _accumulate_y[j]) < FLT_EPSILON) { _accumulate_lmy[i+1] = j; break; } } if (j == _num_y+1) divisions_missing_y.push_back(std::make_pair(j_prev, coord)); } /* Find the position of domain decomposition interfaces among the non-uniform CMFD mesh cell boundaries, in the Z direction */ for (int i=0; i<num_z; i++) { double coord = (i + 1) * _width_z / num_z; for (j=1; j<_num_z+1; j++) { /* Keep track of index in mesh before domain boundary */ if (_accumulate_z[j] < coord) j_prev = j; /* Exit loop if division is found */ if (fabs(coord - _accumulate_z[j]) < FLT_EPSILON) { _accumulate_lmz[i+1] = j; break; } } if (j == _num_z+1) divisions_missing_z.push_back(std::make_pair(j_prev, coord)); } /* Output the missing subdivisions */ std::string div_miss_x = ""; std::string div_miss_y = ""; std::string div_miss_z = ""; std::vector<std::pair<int, double> >::iterator iter; for (iter = divisions_missing_x.begin(); iter != divisions_missing_x.end(); ++iter) { div_miss_x += std::to_string(iter->second); if (iter != std::prev(divisions_missing_x.end())) div_miss_x += ", "; } for (iter = divisions_missing_y.begin(); iter != divisions_missing_y.end(); ++iter) { div_miss_y += std::to_string(iter->second); if (iter != std::prev(divisions_missing_y.end())) div_miss_y += ", "; } for (iter = divisions_missing_z.begin(); iter != divisions_missing_z.end(); ++iter) { div_miss_z += std::to_string(iter->second); if (iter != std::prev(divisions_missing_z.end())) div_miss_z += ", "; } if (divisions_missing_x.size() > 0) log_printf(WARNING_ONCE, "Domain boundaries [%s] are not in CMFD X-mesh", div_miss_x.c_str()); if (divisions_missing_y.size() > 0) log_printf(WARNING_ONCE, "Domain boundaries [%s] are not in CMFD Y-mesh", div_miss_y.c_str()); if (divisions_missing_z.size() > 0) log_printf(WARNING_ONCE, "Domain boundaries [%s] are not in CMFD Z-mesh", div_miss_z.c_str()); /* Modify the CMFD mesh, in order to have divisions at domain boundaries, but also to avoid small CMFD cells */ std::string added_cells_x = ""; std::string modified_cells_x = ""; int cells_added = 0; for (iter = divisions_missing_x.begin(); iter != divisions_missing_x.end(); ++iter) { j_prev = iter->first; double cmfd_cell_width = _accumulate_x[j_prev+1] - _accumulate_x[j_prev]; double coord = iter->second; /* If the new CMFD cells are about to be very small, move the CMFD cell boundaries instead, to the closest one */ double delta_below = coord - _accumulate_x[j_prev]; double delta_above = _accumulate_x[j_prev+1] - coord; if (delta_below < 0.1 * cmfd_cell_width || delta_above < 0.1 * cmfd_cell_width) { modified_cells_x += (std::to_string(coord) + " "); if (delta_below < delta_above) { _cell_widths_x[j_prev + cells_added - 1] += delta_below; _cell_widths_x[j_prev + cells_added] -= delta_below; } else { _cell_widths_x[j_prev + cells_added] -= delta_above; _cell_widths_x[j_prev + cells_added + 1] += delta_above; //FIXME Capture j_prev+1 overflow } } /* Else, add a new subdivision to the CMFD mesh */ else { _cell_widths_x[j_prev + cells_added] = delta_below; _cell_widths_x.insert(_cell_widths_x.begin() + j_prev + cells_added + 1, delta_above); added_cells_x += (std::to_string(coord) + " "); cells_added++; } } if (added_cells_x.compare("") != 0) log_printf(WARNING_ONCE, "New CMFD cells created for domain decomposition " "boundaries in the X direction at [%s] cm.", added_cells_x.c_str()); if (modified_cells_x.compare("") != 0) log_printf(WARNING_ONCE, "CMFD mesh cell widths adjusted to fit " "domain decomposition boundaries in the X direction " "at [%s] cm.", modified_cells_x.c_str()); /* Y-direction */ std::string added_cells_y = ""; std::string modified_cells_y = ""; cells_added = 0; for (iter = divisions_missing_y.begin(); iter != divisions_missing_y.end(); ++iter) { j_prev = iter->first; double cmfd_cell_width = _accumulate_y[j_prev+1] - _accumulate_y[j_prev]; double coord = iter->second; /* If the new CMFD cells are about to be very small, move the CMFD cell boundaries instead, to the closest one */ double delta_below = coord - _accumulate_y[j_prev]; double delta_above = _accumulate_y[j_prev+1] - coord; if (delta_below < 0.1 * cmfd_cell_width || delta_above < 0.1 * cmfd_cell_width) { modified_cells_y += (std::to_string(coord) + " "); if (delta_below < delta_above) { _cell_widths_y[j_prev + cells_added - 1] += delta_below; _cell_widths_y[j_prev + cells_added] -= delta_below; } else { _cell_widths_y[j_prev + cells_added] -= delta_above; _cell_widths_y[j_prev + cells_added + 1] += delta_above; //FIXME Capture j_prev+1 overflow } } /* Else, add a new subdivision to the CMFD mesh */ else { _cell_widths_y[j_prev + cells_added] = delta_below; _cell_widths_y.insert(_cell_widths_y.begin() + j_prev + cells_added + 1, delta_above); added_cells_y += (std::to_string(coord) + " "); cells_added++; } } if (added_cells_y.compare("") != 0) log_printf(WARNING_ONCE, "New CMFD cells created for domain decomposition " "boundaries in the Y direction at [%s] cm.", added_cells_y.c_str()); if (modified_cells_y.compare("") != 0) log_printf(WARNING_ONCE, "CMFD mesh cell widths adjusted to fit " "domain decomposition boundaries in the Y direction " "at [%s] cm.", modified_cells_y.c_str()); /* Z-direction */ std::string added_cells_z = ""; std::string modified_cells_z = ""; cells_added = 0; for (iter = divisions_missing_z.begin(); iter != divisions_missing_z.end(); ++iter) { j_prev = iter->first; double cmfd_cell_width = _accumulate_z[j_prev+1] - _accumulate_z[j_prev]; double coord = iter->second; /* If the new CMFD cells are about to be very small, move the CMFD cell boundaries instead, to the closest one */ double delta_below = coord - _accumulate_z[j_prev]; double delta_above = _accumulate_z[j_prev+1] - coord; if (delta_below < 0.1 * cmfd_cell_width || delta_above < 0.1 * cmfd_cell_width) { modified_cells_z += (std::to_string(coord) + " "); if (delta_below < delta_above) { _cell_widths_z[j_prev + cells_added - 1] += delta_below; _cell_widths_z[j_prev + cells_added] -= delta_below; } else { _cell_widths_z[j_prev + cells_added] -= delta_above; _cell_widths_z[j_prev + cells_added + 1] += delta_above; //FIXME Capture j_prev+1 overflow } } /* Else, add a new subdivision to the CMFD mesh */ else { _cell_widths_z[j_prev + cells_added] = delta_below; _cell_widths_z.insert(_cell_widths_z.begin() + j_prev + cells_added + 1, delta_above); added_cells_z += (std::to_string(coord) + " "); cells_added++; } } if (added_cells_z.compare("") != 0) log_printf(WARNING_ONCE, "New CMFD cells created for domain decomposition " "boundaries in the Z direction at [%s] cm.", added_cells_z.c_str()); if (modified_cells_z.compare("") != 0) log_printf(WARNING_ONCE, "CMFD mesh cell widths adjusted to fit " "domain decomposition boundaries in the Z direction " "at [%s] cm.", modified_cells_z.c_str()); /* Re-initialize lattice since widths have been modified */ if (divisions_missing_x.size() > 0 || divisions_missing_y.size() > 0 || divisions_missing_z.size() > 0) { _non_uniform = true; Point offset; offset.setXYZ(_lattice->getOffset()->getXYZ()); initializeLattice(&offset); /* Re-run routine to obtain _accumulate_lmxyz arrays */ if (!_widths_adjusted_for_domains) { _widths_adjusted_for_domains = true; setNumDomains(num_x, num_y, num_z); } else log_printf(ERROR, "Mesh adjustment to domain decomposition boundaries " "failed. Manually add the domain boundaries in a non-" "uniform CMFD mesh."); } } /** * @brief Set the indexes of the domain among the global lattice of domains. */ void Cmfd::setDomainIndexes(int idx_x, int idx_y, int idx_z) { if (_domain_communicator == NULL) { _domain_communicator = new DomainCommunicator; _domain_communicator->_MPI_cart = _geometry->getMPICart(); } _domain_communicator->_domain_idx_x = idx_x; _domain_communicator->_domain_idx_y = idx_y; _domain_communicator->_domain_idx_z = idx_z; _local_num_x = _accumulate_lmx[idx_x + 1] - _accumulate_lmx[idx_x]; _local_num_y = _accumulate_lmy[idx_y + 1] - _accumulate_lmy[idx_y]; _local_num_z = _accumulate_lmz[idx_z + 1] - _accumulate_lmz[idx_z]; } #endif /** * @brief Collapse cross-sections and fluxes for each CMFD cell by * energy condensing and volume averaging cross sections from * the MOC sweep. * @details This method performs a cell-wise energy condensation and flux-volume * average of the cross sections of the fine, unstructured FSR mesh. * The cross sections are condensed such that all reaction rates and * the neutron production rate from fission are conserved. It is * important to note that the volume averaging is performed before * energy condensation in order to properly collapse the diffusion * coefficients. */ void Cmfd::collapseXS() { log_printf(INFO, "Collapsing cross-sections onto CMFD mesh..."); /* Record net currents over cells if neutron balance of sigma-t requested */ if (_balance_sigma_t) recordNetCurrents(); /* Check to see that CMFD tallies have been allocated */ if (!_tallies_allocated) log_printf(ERROR, "Tallies need to be allocated before collapsing " "cross-sections"); /* Split vertex and edge currents to side surfaces */ splitVertexCurrents(); #ifdef MPIx if (_geometry->isDomainDecomposed()) communicateSplits(false); #endif splitEdgeCurrents(); #ifdef MPIx if (_geometry->isDomainDecomposed()) communicateSplits(true); #endif /* Report number of negative currents */ long num_negative_currents = _surface_currents->getNumNegativeValues(); int total_negative_CMFD_current_domains = (num_negative_currents > 0); #ifdef MPIx if (_domain_communicator != NULL) { long temp_sum_neg = num_negative_currents; MPI_Allreduce(&temp_sum_neg, &num_negative_currents, 1, MPI_LONG, MPI_SUM, _domain_communicator->_MPI_cart); int temp_sum_dom = total_negative_CMFD_current_domains; MPI_Allreduce(&temp_sum_dom, &total_negative_CMFD_current_domains, 1, MPI_INT, MPI_SUM, _domain_communicator->_MPI_cart); } #endif if (_SOLVE_3D && num_negative_currents > 0) log_printf(WARNING_ONCE, "Negative CMFD currents in %ld surfaces-groups in" " %d domains.", num_negative_currents, total_negative_CMFD_current_domains); #pragma omp parallel { /* Initialize variables for FSR properties */ FP_PRECISION volume, flux; FP_PRECISION tot, nu_fis, chi; FP_PRECISION* scat; /* Allocate arrays for tallies on the stack */ double scat_tally[_num_cmfd_groups]; double chi_tally[_num_cmfd_groups]; /* Pointers to material objects */ Material* fsr_material; Material* cell_material; /* Loop over CMFD cells */ #pragma omp for for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { std::vector<long>::iterator iter; cell_material = _materials[i]; /* Zero group-wise fission terms */ double neutron_production_tally = 0.0; for (int e = 0; e < _num_cmfd_groups; e++) chi_tally[e] = 0.0; /* Loop over FSRs in CMFD cell */ for (iter = _cell_fsrs.at(i).begin(); iter != _cell_fsrs.at(i).end(); ++iter) { fsr_material = _FSR_materials[*iter]; volume = _FSR_volumes[*iter]; /* Calculate total neutron production in the FSR */ double neutron_production = 0.0; for (int h = 0; h < _num_moc_groups; h++) neutron_production += fsr_material->getNuSigmaFByGroup(h+1) * _FSR_fluxes[(*iter)*_num_moc_groups+h] * volume; /* Calculate contribution to all CMFD groups */ for (int e=0; e < _num_cmfd_groups; e++) { chi = 0; for (int h = _group_indices[e]; h < _group_indices[e + 1]; h++) chi += fsr_material->getChiByGroup(h+1); chi_tally[e] += chi * neutron_production; } /* Add to total neutron production within the CMFD cell */ neutron_production_tally += neutron_production; } /* Set chi */ if (fabs(neutron_production_tally) > 0) { /* Calculate group-wise fission contributions */ for (int e=0; e < _num_cmfd_groups; e++) cell_material->setChiByGroup(chi_tally[e] / neutron_production_tally, e + 1); } else { /* Calculate group-wise chi to zero */ for (int e=0; e < _num_cmfd_groups; e++) cell_material->setChiByGroup(0.0, e + 1); } /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Zero tallies for this group */ double nu_fission_tally = 0.0; double total_tally = 0.0; _diffusion_tally[i][e] = 0.0; _reaction_tally[i][e] = 0.0; _volume_tally[i][e] = 0.0; /* Zero each group-to-group scattering tally */ for (int g = 0; g < _num_cmfd_groups; g++) scat_tally[g] = 0.0; /* Loop over MOC energy groups within this CMFD coarse group */ for (int h = _group_indices[e]; h < _group_indices[e+1]; h++) { /* Reset volume tally for this MOC group */ _volume_tally[i][e] = 0.0; double rxn_tally_group = 0.0; double trans_tally_group = 0.0; /* Loop over FSRs in CMFD cell */ for (iter = _cell_fsrs.at(i).begin(); iter != _cell_fsrs.at(i).end(); ++iter) { /* Gets FSR volume, material, and cross sections */ fsr_material = _FSR_materials[*iter]; volume = _FSR_volumes[*iter]; scat = fsr_material->getSigmaS(); flux = _FSR_fluxes[(*iter)*_num_moc_groups+h]; tot = fsr_material->getSigmaTByGroup(h+1); nu_fis = fsr_material->getNuSigmaFByGroup(h+1); /* Increment tallies for this group */ total_tally += tot * flux * volume; nu_fission_tally += nu_fis * flux * volume; _reaction_tally[i][e] += flux * volume; _volume_tally[i][e] += volume; /* Increment diffusion MOC group-wise tallies */ rxn_tally_group += flux * volume; trans_tally_group += tot * flux * volume; /* Scattering tallies */ for (int g = 0; g < _num_moc_groups; g++) { scat_tally[getCmfdGroup(g)] += scat[g*_num_moc_groups+h] * flux * volume; } } /* Condense diffusion coefficient (with homogenized transport XS) */ if (fabs(trans_tally_group) > fabs(rxn_tally_group) * FLT_EPSILON) { CMFD_PRECISION flux_avg_sigma_t = trans_tally_group / rxn_tally_group; _diffusion_tally[i][e] += rxn_tally_group / (3.0 * flux_avg_sigma_t); } } /* Save cross-sections to material */ double rxn_tally = _reaction_tally[i][e]; if (rxn_tally <= 0) { int cell = getGlobalCMFDCell(i); int x = (cell % (_num_x * _num_y)) % _num_x; int y = (cell % (_num_x * _num_y)) / _num_x; int z = cell / (_num_x * _num_y); log_printf(WARNING, "Negative or zero reaction tally calculated in " "CMFD cell %d [%d %d %d] in CMFD group %d : %e", cell, x, y, z, e + 1, rxn_tally); /* Set all cross sections to be 1 */ rxn_tally = ZERO_SIGMA_T; _reaction_tally[i][e] = ZERO_SIGMA_T; _diffusion_tally[i][e] = ZERO_SIGMA_T; total_tally = ZERO_SIGMA_T; if (nu_fission_tally != 0) nu_fission_tally = ZERO_SIGMA_T; /* Avoid excessive downscatter */ for (int g = 0; g < _num_cmfd_groups; g++) scat_tally[g] = 0; } cell_material->setSigmaTByGroup(total_tally / rxn_tally, e + 1); cell_material->setNuSigmaFByGroup(nu_fission_tally / rxn_tally, e + 1); /* Set scattering xs */ for (int g = 0; g < _num_cmfd_groups; g++) { cell_material->setSigmaSByGroup(scat_tally[g] / rxn_tally, e + 1, g + 1); } } } } #ifdef MPIx if (_geometry->isDomainDecomposed()) { if (_domain_communicator != NULL) { /* Start recording MPI communication time */ _timer->startTimer(); /* Do the Ghost cell exchange */ ghostCellExchange(); /* Tally the MPI communication time */ _timer->stopTimer(); _timer->recordSplit("CMFD MPI communication time"); } } #endif /* Calculate (local) old fluxes and set volumes */ #pragma omp parallel for for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Load tallies at this cell and energy group */ double vol_tally = _volume_tally[i][e]; double rxn_tally = _reaction_tally[i][e]; _old_flux->setValue(i, e, rxn_tally / vol_tally); /* Set the Mesh cell properties with the tallies */ _volumes->setValue(i, 0, vol_tally); } } /* Loop over boundary CMFD cells and set cross sections */ if (_geometry->isDomainDecomposed()) { #pragma omp parallel for for (int s=0; s < NUM_FACES; s++) { /* Loop over all CMFD cells on the current surface */ std::map<int, int>::iterator it; for (it=_boundary_index_map.at(s).begin(); it != _boundary_index_map.at(s).end(); ++it) { int idx = it->second; /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Load tallies at this cell and energy group */ double vol_tally = _boundary_volumes[s][idx][0]; double rxn_tally = _boundary_reaction[s][idx][e]; _old_boundary_flux[s][idx][e] = rxn_tally / vol_tally; } } } } /* Output max CMFD cell optical thickness for stability concerns */ float max_tau = -1; for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { int global_cmfd_cell = getGlobalCMFDCell(i); CMFD_PRECISION delta_x = getPerpendicularSurfaceWidth(0, global_cmfd_cell); CMFD_PRECISION delta_y = getPerpendicularSurfaceWidth(1, global_cmfd_cell); CMFD_PRECISION delta_z = -1; if (_SOLVE_3D) delta_z = getPerpendicularSurfaceWidth(2, global_cmfd_cell); max_tau = std::max(max_tau, float(_materials[i]->getMaxSigmaT() * std::max(delta_x, std::max(delta_y, delta_z)))); } float global_max_tau = max_tau; #ifdef MPIx if (_domain_communicator != NULL) MPI_Allreduce(&global_max_tau, &max_tau, 1, MPI_FLOAT, MPI_MAX, _domain_communicator->_MPI_cart); #endif if (_moc_iteration == 0) log_printf(INFO_ONCE, "Max CMFD optical thickness in all domains %.2e", global_max_tau); } /** * @brief Computes the diffusion coefficient for a given CMFD cell and CMFD * energy group. * @details This method computes the diffusion coefficient for a CMFD cell and * CMFD energy group by spatially collapsing the total/transport xs * in each FSR contained within the CMFD cell and then energy * collapsing the diffusion coefficient (\f$1 / (3 * \Sigma_t)\f$) for * all MOC groups in the given CMFD energy group. * @param cmfd_cell A CMFD cell * @param group A CMFD energy group * @return The diffusion coefficient */ CMFD_PRECISION Cmfd::getDiffusionCoefficient(int cmfd_cell, int group) { return _diffusion_tally[cmfd_cell][group] / _reaction_tally[cmfd_cell][group]; } /** * @brief Compute the surface diffusion coefficient for a given CMFD cell, * cell surface, and group. * @details This method uses finite differencing to compute the surface * diffusion coefficient (\f$ \hat{D} \f$) or surface diffusion * coefficient correction (\f$ \tilde{D} \f$) for a given CMFD cell, * cell surface, and CMFD energy group. If the MOC iteration is zero, * (\f$ \tilde{D} \f$) is returned as zero. Since (\f$ \hat{D} \f$) and * (\f$ \tilde{D} \f$) are dependent on each other, they must be * computed together. * @param cmfd_cell A CMFD cell * @param surface A surface of the CMFD cell * @param group A CMFD energy group * @param dif_surf the surface diffusion coefficient \f$ \hat{D} \f$ * @param dif_surf_corr the correction diffusion coefficient \f$ \tilde{D} \f$ */ void Cmfd::getSurfaceDiffusionCoefficient(int cmfd_cell, int surface, int group, CMFD_PRECISION& dif_surf, CMFD_PRECISION& dif_surf_corr) { FP_PRECISION current, current_out, current_in; CMFD_PRECISION flux_next; /* Get diffusivity and flux for Mesh cell */ CMFD_PRECISION dif_coef = getDiffusionCoefficient(cmfd_cell, group); int global_cmfd_cell = getGlobalCMFDCell(cmfd_cell); int global_cmfd_cell_next = getCellNext(global_cmfd_cell, surface); CMFD_PRECISION flux = _old_flux->getValue(cmfd_cell, group); CMFD_PRECISION delta_interface = getSurfaceWidth(surface, global_cmfd_cell); CMFD_PRECISION delta = getPerpendicularSurfaceWidth(surface, global_cmfd_cell); CMFD_PRECISION delta_next = 0.0; if (global_cmfd_cell_next != -1) delta_next = getPerpendicularSurfaceWidth(surface, global_cmfd_cell_next); int sense = getSense(surface); /* Correct the diffusion coefficient with Larsen's effective diffusion * coefficient correction factor */ if (!_linear_source) dif_coef *= computeLarsensEDCFactor(dif_coef, delta); /* If surface is on a boundary with REFLECTIVE or VACUUM BCs, choose * appropriate BC */ if (global_cmfd_cell_next == -1) { /* REFLECTIVE BC */ if (_boundaries[surface] == REFLECTIVE) { dif_surf = 0.0; dif_surf_corr = 0.0; } /* VACUUM BC */ else if (_boundaries[surface] == VACUUM) { /* Compute the surface-averaged current leaving the cell */ current_out = sense * _surface_currents->getValue (cmfd_cell, surface*_num_cmfd_groups + group) / delta_interface; /* Set the surface diffusion coefficient and MOC correction */ dif_surf = 2 * dif_coef / delta / (1 + 4 * dif_coef / delta); dif_surf_corr = (sense * dif_surf * flux - current_out) / flux; } } /* If surface is an interface or PERIODIC BC, use finite differencing */ else { /* Get the surface index for the surface in the neighboring cell */ int surface_next = (surface + NUM_FACES / 2) % NUM_FACES; /* Get the outward current on surface */ current_out = _surface_currents->getValue (cmfd_cell, surface*_num_cmfd_groups + group); /* Set diffusion coefficient and flux for the neighboring cell */ int cmfd_cell_next = getLocalCMFDCell(global_cmfd_cell_next); CMFD_PRECISION dif_coef_next; if (cmfd_cell_next == -1) { /* Get the currents in cells touching this boundary */ CMFD_PRECISION** boundary_currents = _boundary_surface_currents[surface]; int idx = _boundary_index_map.at(surface)[global_cmfd_cell_next]; dif_coef_next = _boundary_diffusion[surface][idx][group] / _boundary_reaction[surface][idx][group]; flux_next = _old_boundary_flux[surface][idx][group]; /* Get the inward current on the surface */ current_in = boundary_currents[idx][surface_next*_num_cmfd_groups+group]; } else { dif_coef_next = getDiffusionCoefficient(cmfd_cell_next, group); flux_next = _old_flux->getValue(cmfd_cell_next, group); /* Get the inward current on the surface */ current_in = _surface_currents->getValue (cmfd_cell_next, surface_next*_num_cmfd_groups + group); } /* Correct the diffusion coefficient with Larsen's effective diffusion * coefficient correction factor */ if (!_linear_source) dif_coef_next *= computeLarsensEDCFactor(dif_coef_next, delta_next); /* Compute the surface diffusion coefficient */ dif_surf = 2.0 * dif_coef * dif_coef_next / (delta_next * dif_coef + delta * dif_coef_next); /* Compute the surface-averaged net current across the surface */ current = sense * (current_out - current_in) / delta_interface; /* Compute the surface diffusion coefficient correction */ dif_surf_corr = -(sense * dif_surf * (flux_next - flux) + current) / (flux_next + flux); /* Flux limiting condition */ if (_flux_limiting && _moc_iteration > 0) { double ratio = dif_surf_corr / dif_surf; if (std::abs(ratio) > 1.0) { if (sense * current > 0.0) dif_surf = std::abs(current / (2.0*flux)); else dif_surf = std::abs(current / (2.0*flux_next)); dif_surf_corr = -(sense * dif_surf * (flux_next - flux) + current) / (flux_next + flux); /* Make sure diffusion coefficient is larger than the corrected one, to floating point precision */ dif_surf = std::max(dif_surf, std::abs(dif_surf_corr)); } } } /* Weight the old and new corrected diffusion coefficients by the relaxation factor */ if (_old_dif_surf_valid) { CMFD_PRECISION old_dif_surf_corr = _old_dif_surf_corr->getValue (cmfd_cell, surface*_num_cmfd_groups+group); dif_surf_corr = _relaxation_factor * dif_surf_corr + (1.0 - _relaxation_factor) * old_dif_surf_corr; } /* If it is the first MOC iteration, solve the straight diffusion problem * with no MOC correction */ if (_moc_iteration == 0 && !_check_neutron_balance) dif_surf_corr = 0.0; } /** * @brief Solve the nonlinear diffusion acceleration problem to accelerate the * convergence of the MOC problem. * @details This method uses the information from the last MOC transport sweep * and solves a simplified nonlinear diffusion problem. The diffusion * problem is tightly converged and the solution is used to update the * the solution of the MOC problem. * @param moc_iteration MOC iteration number * @return The dominant eigenvalue of the nonlinear diffusion problem */ double Cmfd::computeKeff(int moc_iteration) { log_printf(INFO, "Running diffusion solver..."); /* Start recording total CMFD time */ _timer->startTimer(); /* Save MOC iteration number */ _moc_iteration = moc_iteration; /* Create matrix and vector objects */ if (_A == NULL) { log_printf(ERROR, "Unable to compute k-eff in CMFD since the CMFD " "linear algebra matrices and arrays have not been created."); } /* Start recording XS collapse time */ _timer->startTimer(); /* Copy surface currents if neutron balance check requested */ if (_check_neutron_balance) copyFullSurfaceCurrents(); /* Collapse the cross sections onto the CMFD mesh */ collapseXS(); /* Tally the XS collapse time */ _timer->stopTimer(); _timer->recordSplit("Total collapse time"); /* Construct matrices and record time */ _timer->startTimer(); constructMatrices(); _timer->stopTimer(); _timer->recordSplit("Matrix construction time"); /* Check neutron balance if requested */ if (_check_neutron_balance) checkNeutronBalance(false, false); /* Copy old flux to new flux to use collapsed flux as a starting guess */ _old_flux->copyTo(_new_flux); /* Start recording CMFD solve time */ _timer->startTimer(); /* Solve the eigenvalue problem */ double k_eff = eigenvalueSolve(_A, _M, _new_flux, _k_eff, _source_convergence_threshold, _SOR_factor, _convergence_data, _domain_communicator); /* Try to use a few-group solver to remedy convergence issues */ bool reduced_group_solution = false; if (fabs(k_eff + 1) < FLT_EPSILON && _num_cmfd_groups > _num_backup_groups) { log_printf(NORMAL, "Switching to a %d group CMFD solver on this iteration", _num_backup_groups); if (_backup_cmfd == NULL) initializeBackupCmfdSolver(); copyCurrentsToBackup(); k_eff = _backup_cmfd->computeKeff(moc_iteration); reduced_group_solution = true; } /* Tally the CMFD solver time */ _timer->stopTimer(); _timer->recordSplit("Total solver time"); /* Check for a legitimate solve */ if (fabs(k_eff + 1) > FLT_EPSILON) _k_eff = k_eff; else return _k_eff; /* Do not prolong if the few-group solution was used */ if (reduced_group_solution) { log_printf(NORMAL, "The %d group CMFD solver was successful", _num_backup_groups); return _k_eff; } /* Rescale the old and new flux */ rescaleFlux(); /* Update the MOC flux */ _timer->startTimer(); if (_flux_update_on) updateMOCFlux(); /* Tally the update and total CMFD time */ _timer->stopTimer(); _timer->recordSplit("Total MOC flux update time"); _timer->stopTimer(); _timer->recordSplit("Total CMFD time"); /* If debugging, print CMFD prolongation factors */ if (get_log_level() == DEBUG) printProlongationFactors(); return _k_eff; } /** * @brief Rescale the initial and converged flux arrays. * @details The diffusion problem is a generalized eigenvalue problem and * therefore the solution is independent of flux level. This method * rescales the input flux and converged flux to both have an average * fission source of 1.0 in each group in each cell. */ void Cmfd::rescaleFlux() { /* Rescale the new and old flux to have an avg source of 1.0 */ matrixMultiplication(_M, _new_flux, _new_source); matrixMultiplication(_M, _old_flux, _old_source); double new_source_sum = _new_source->getSum(); double old_source_sum = _old_source->getSum(); #ifdef MPIx if (_domain_communicator != NULL) { double temp_sum_new = new_source_sum; MPI_Allreduce(&temp_sum_new, &new_source_sum, 1, MPI_DOUBLE, MPI_SUM, _domain_communicator->_MPI_cart); double temp_sum_old = old_source_sum; MPI_Allreduce(&temp_sum_old, &old_source_sum, 1, MPI_DOUBLE, MPI_SUM, _domain_communicator->_MPI_cart); } #endif _new_flux->scaleByValue(1.0 / new_source_sum); _old_flux->scaleByValue(1.0 / old_source_sum); /* Check for negative fluxes in CMFD flux */ long num_negative_fluxes = _new_flux->getNumNegativeValues(); int total_negative_CMFD_flux_domains = (num_negative_fluxes > 0); #ifdef MPIx if (_domain_communicator != NULL) { long temp_sum_neg = num_negative_fluxes; MPI_Allreduce(&temp_sum_neg, &num_negative_fluxes, 1, MPI_LONG, MPI_SUM, _domain_communicator->_MPI_cart); int temp_sum_dom = total_negative_CMFD_flux_domains; MPI_Allreduce(&temp_sum_dom, &total_negative_CMFD_flux_domains, 1, MPI_INT, MPI_SUM, _domain_communicator->_MPI_cart); } #endif if (num_negative_fluxes > 0) log_printf(WARNING_ONCE, "Negative CMFD fluxes in %ld cells on %d domains.", num_negative_fluxes, total_negative_CMFD_flux_domains); } /** * @brief Construct the loss + streaming matrix (A) and the fission gain * matrix (M) in preparation for solving the eigenvalue problem. * @details This method loops over all mesh cells and energy groups and * accumulates the iteraction and streaming terms into their * appropriate positions in the loss + streaming matrix and * fission gain matrix. */ void Cmfd::constructMatrices() { log_printf(INFO, "Constructing matrices..."); /* Zero _A and _M matrices */ _A->clear(); _M->clear(); /* Zero the number of connections */ if (_domain_communicator != NULL) { int num_boundary_cells = 2 * (_local_num_x * _local_num_z + _local_num_y * _local_num_z + _local_num_x * _local_num_y); for (int c=0; c<2; c++) { for (int ncg=0; ncg < num_boundary_cells * _num_cmfd_groups; ncg++) { _domain_communicator->num_connections[c][ncg] = 0; } } } #pragma omp parallel { FP_PRECISION value, volume, delta; CMFD_PRECISION dif_surf, dif_surf_corr; int sense; Material* material; int x_start = 0; int y_start = 0; int z_start = 0; int x_end = _num_x; int y_end = _num_y; int z_end = _num_z; if (_geometry->isDomainDecomposed()) { if (_domain_communicator != NULL) { x_start = _accumulate_lmx[_domain_communicator->_domain_idx_x]; x_end = x_start + _local_num_x; y_start = _accumulate_lmy[_domain_communicator->_domain_idx_y]; y_end = y_start + _local_num_y; z_start = _accumulate_lmz[_domain_communicator->_domain_idx_z]; z_end = z_start + _local_num_z; } } /* Loop over cells */ #pragma omp for for (int i = 0; i < _local_num_x*_local_num_y*_local_num_z; i++) { int global_ind = getGlobalCMFDCell(i); int color = getCellColor(global_ind); material = _materials[i]; volume = _volumes->getValue(i, 0); /* Find neighboring cells on other domains */ int domain_surface_index = -1; int neighbor_cells[NUM_FACES]; if (_geometry->isDomainDecomposed() && _domain_communicator != NULL) { bool on_surface = false; for (int s = 0; s < NUM_FACES; s++) { neighbor_cells[s] = -1; if (getCellNext(i, s, false, false) == -1) { neighbor_cells[s] = getCellNext(i, s, false, true); if (neighbor_cells[s] != -1) on_surface = true; } } /* If the cell is on a surface, find the index into the comm buffers */ if (on_surface) domain_surface_index = _domain_communicator->mapLocalToSurface[i]; } /* Loop over groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Net removal term */ value = material->getSigmaTByGroup(e+1) * volume; _A->incrementValue(i, e, i, e, value); /* Re-compute diagonal if neutron re-balance requested */ if (_balance_sigma_t) { enforceBalanceOnDiagonal(i, e); } /* Scattering gain from all groups */ for (int g = 0; g < _num_cmfd_groups; g++) { value = - material->getSigmaSByGroup(g+1, e+1) * volume; if (std::abs(value) > FLT_EPSILON) _A->incrementValue(i, g, i, e, value); } /* Streaming to neighboring cells */ for (int s = 0; s < NUM_FACES; s++) { sense = getSense(s); delta = getSurfaceWidth(s, global_ind); /* Set transport term on diagonal */ getSurfaceDiffusionCoefficient(i, s, e, dif_surf, dif_surf_corr); /* Record the corrected diffusion coefficient */ _old_dif_surf_corr->setValue(i, s*_num_cmfd_groups+e, dif_surf_corr); /* Set the diagonal term */ value = (dif_surf - sense * dif_surf_corr) * delta; _A->incrementValue(i, e, i, e, value); /* Set the off diagonal term */ if (getCellNext(i, s, false, false) != -1) { value = - (dif_surf + sense * dif_surf_corr) * delta; _A->incrementValue(getCellNext(i, s, false, false), e, i, e, value); } /* Check for cell in neighboring domain if applicable */ else if (_geometry->isDomainDecomposed()) { if (_domain_communicator != NULL) { if (neighbor_cells[s] != -1) { int neighbor_cell = neighbor_cells[s]; int row = domain_surface_index * _num_cmfd_groups + e; //FIXME Make num_connections, indexes and domains array not // group dependent int idx = _domain_communicator->num_connections[color][row]; value = - (dif_surf + sense * dif_surf_corr) * delta; _domain_communicator->indexes[color][row][idx] = neighbor_cell; _domain_communicator->domains[color][row][idx] = s; _domain_communicator->coupling_coeffs[color][row][idx] = value; _domain_communicator->num_connections[color][row]++; } } } } /* Fission source term */ for (int g = 0; g < _num_cmfd_groups; g++) { value = material->getChiByGroup(e+1) * material->getNuSigmaFByGroup(g+1) * volume; if (std::abs(value) > FLT_EPSILON) _M->incrementValue(i, g, i, e, value); } } } } /* Mark correction diffusion coefficient as valid for relaxation purposes */ _old_dif_surf_valid = true; log_printf(INFO, "Done constructing matrices..."); } /** * @brief Update the MOC flux in each FSR. * @details This method uses the condensed flux from the last MOC transport * sweep and the converged flux from the eigenvalue problem to * update the MOC flux in each FSR. */ void Cmfd::updateMOCFlux() { log_printf(INFO, "Updating MOC flux..."); /* Set max prolongation factor */ if (_convergence_data != NULL) _convergence_data->pf = 1.0; /* Loop over mesh cells */ #pragma omp parallel for for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { CMFD_PRECISION thread_max_update_ratio = 1; std::vector<long>::iterator iter; /* Loop over CMFD groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Loop over FRSs in mesh cell */ for (iter = _cell_fsrs.at(i).begin(); iter != _cell_fsrs.at(i).end(); ++iter) { /* Get the update ratio */ CMFD_PRECISION update_ratio = getUpdateRatio(i, e, *iter); /* Limit the update ratio for stability purposes. For very low flux regions, update ratio may be left unrestricted a few iterations*/ if (_moc_iteration > _num_unbounded_iterations) if (update_ratio > 20.0) update_ratio = 20.0; else if (update_ratio < 0.05) update_ratio = 0.05; /* Save max update ratio among fsrs and groups in a cell */ if (_convergence_data != NULL) if (std::abs(log(update_ratio)) > std::abs(log(thread_max_update_ratio))) thread_max_update_ratio = update_ratio; for (int h = _group_indices[e]; h < _group_indices[e + 1]; h++) { /* Update FSR flux using ratio of old and new CMFD flux */ _FSR_fluxes[*iter*_num_moc_groups + h] *= update_ratio; /* Update flux moments if they were set */ if (_linear_source) { _flux_moments[(*iter)*3*_num_moc_groups + h] *= update_ratio; _flux_moments[(*iter)*3*_num_moc_groups + _num_moc_groups + h] *= update_ratio; _flux_moments[(*iter)*3*_num_moc_groups + 2*_num_moc_groups + h] *= update_ratio; } log_printf(DEBUG, "Updating flux in FSR: %d, cell: %d, MOC group: " "%d, CMFD group: %d, ratio: %f", *iter ,i, h, e, update_ratio); } } } /* Save maximum update ratio among CMFD cells, for output purposes */ if (_convergence_data != NULL) { #pragma omp critical { if (std::abs(log(thread_max_update_ratio)) > std::abs(log(_convergence_data->pf))) _convergence_data->pf = thread_max_update_ratio; } } } /* Compare maximum update ratios between domains and keep the maximum */ #ifdef MPIx if (_domain_communicator != NULL && _convergence_data != NULL) { double max_pf = _convergence_data->pf; MPI_Allreduce(&max_pf, &_convergence_data->pf, 1, MPI_DOUBLE, MPI_MAX, _domain_communicator->_MPI_cart); } #endif } /** * @brief Compute Larsen's effective diffusion coefficient correction factor. * @details By conserving reaction and leakage rates within cells, CMFD * guarantees preservation of area-averaged scalar fluxes and net * surface currents from the MOC fixed source iteration if the CMFD * equations can be converged. However, when the MOC mesh cell size * becomes significantly larger than the neutron mean free path in that * cell, the step characteristics no longer preserve the linear * infinite medium solution to the transport equation. While the * surface diffusion coefficient correction term in CMFD is guaranteed * to preserve reaction rates and surface net currents for any choice * of diffusion coefficient, convergence (and convergence rate) of the * nonlinear iteration acceleration of CMFD is affected by the choice * of diffusion coefficient. All flat source methods, when applied for * thick optical meshes, artificially distribute neutrons in space. * This is the reason that Larsen's effective diffusion coefficient is * useful in ensuring that the CMFD acceleration equations have a * diffusion coefficient (on the flux gradient term) that is * consistent, not with the physical transport problem, but with the * transport problem that is being accelerated by the CMFD equations. * Larsen's effective diffusion coefficient is precisely this term in * the one-dimensional limit. The following publications provide * further background on how this term is derived and used: * * [1] E. Larsen, "Infinite Medium Solutions to the transport * equation, Sn discretization schemes, and the diffusion * approximation", M&C 2001. * [2] S. Shaner, "Transient Method of Characteristics via the * Adiabatic, Theta, and Multigrid Amplitude Function Methods", * Masters Thesis, MIT 2014. * @param dif_coef Diffusion coefficient before applying correction factor * @param delta Width of the cell in the direction of interest * @return The diffusion coefficient correction factor */ CMFD_PRECISION Cmfd::computeLarsensEDCFactor(CMFD_PRECISION dif_coef, CMFD_PRECISION delta) { /* Initialize variables */ CMFD_PRECISION alpha, mu, expon; double rho = 0.0; /* Loop over azimuthal angles */ for (int a=0; a < _num_azim/2; a++) { CMFD_PRECISION wa = _quadrature->getAzimWeight(a); /* Loop over polar angles */ for (int p = 0; p < _num_polar/2; p++) { mu = sqrt(1.0 - pow(_quadrature->getSinTheta(a,p), 2)); expon = exp(-delta / (3 * dif_coef * mu)); alpha = (1 + expon) / (1 - expon) - 2 * (3 * dif_coef * mu) / delta; rho += 2.0 * mu * _quadrature->getPolarWeight(a,p) * wa * alpha; } } /* Compute the correction factor */ CMFD_PRECISION correction = 1.0 + delta * rho / (2 * dif_coef); return correction; } /** * @brief Set the FSR materials array pointer. * @param FSR_materials pointer to FSR_materials array */ void Cmfd::setFSRMaterials(Material** FSR_materials) { _FSR_materials = FSR_materials; } /** * @brief Set the pointer to the array of FSR_volumes. * @param FSR_volumes array of FSR volumes */ void Cmfd::setFSRVolumes(FP_PRECISION* FSR_volumes) { _FSR_volumes = FSR_volumes; } /** * @brief Set pointer to FSR flux array. * @param scalar_flux pointer to FSR flux array */ void Cmfd::setFSRFluxes(FP_PRECISION* scalar_flux) { _FSR_fluxes = scalar_flux; } /** * @brief Set pointer to FSR source array. * @param sources pointer to FSR source array */ void Cmfd::setFSRSources(FP_PRECISION* sources) { _FSR_sources = sources; } /** * @brief Set pointer to source region flux moments array. * @param flux_moments pointer to source region flux moments array */ void Cmfd::setFluxMoments(FP_PRECISION* flux_moments) { _flux_moments = flux_moments; _linear_source = true; } /** * @brief Set successive over-relaxation relaxation factor. * @param SOR_factor over-relaxation factor */ void Cmfd::setSORRelaxationFactor(double SOR_factor) { if (SOR_factor <= 0.0 || SOR_factor >= 2.0) log_printf(ERROR, "The successive over-relaxation relaxation factor " "must be > 0 and < 2. Input value: %i", SOR_factor); _SOR_factor = SOR_factor; } /** * @brief Set the CMFD relaxation factor applied to diffusion coefficients. * @param relaxation_factor CMFD relaxation factor */ void Cmfd::setCMFDRelaxationFactor(double relaxation_factor) { if (relaxation_factor <= 0.0 || relaxation_factor > 1.0) log_printf(ERROR, "The CMFD relaxation factor must be greater than 0 and " "less than or equal to 1. Input value: %6.4f", relaxation_factor); _relaxation_factor = relaxation_factor; } /** * @brief Forces CMFD to check neutron balance on every solve. */ void Cmfd::checkBalance() { _check_neutron_balance = true; } /** * @brief Get the number of coarse CMFD energy groups. * @return the number of CMFD energy groups */ int Cmfd::getNumCmfdGroups() { return _num_cmfd_groups; } /** * @brief Set a coarse energy group structure for CMFD. * @details CMFD does not necessarily need to have the same energy group * structure as the MOC problem. This function can be used to set * a sparse energy group structure to speed up the CMFD solve. An * example of how this may be called from Python to use a coarse * 2-group CMFD structure atop a fine 7-group MOC structure is * illustrated below: * * @code * cmfd.setGroupStructure([[1,2,3], [4,5,6,7]]) * @endcode * * @param group_indices A nested vector of MOC-to-CMFD group mapping */ void Cmfd::setGroupStructure(std::vector< std::vector<int> > group_indices) { _user_group_indices = true; /* Delete old group indices array if it exists */ if (_group_indices != NULL) delete [] _group_indices; /* Allocate memory for new group indices */ _num_cmfd_groups = group_indices.size(); _group_indices = new int[_num_cmfd_groups+1]; /* Initialize first group index to 0 */ int last_moc_group = 0; /* Set MOC group bounds for rest of CMFD energy groups */ for (int i=0; i < _num_cmfd_groups; i++) { for (int j=0; j < group_indices[i].size(); j++) { if (group_indices[i][j] != last_moc_group + 1) log_printf(ERROR, "The CMFD coarse group indices are not " "monotonically increasing"); last_moc_group = group_indices[i][j]; } _group_indices[i] = group_indices[i][0] - 1; log_printf(DEBUG, "CMFD group indices %d: %d", i, _group_indices[i]); } /* Set the last group index */ _group_indices[_num_cmfd_groups] = group_indices[_num_cmfd_groups-1].back(); log_printf(DEBUG, "CMFD group indices %d: %d", _num_cmfd_groups, _group_indices[_num_cmfd_groups]); } /** * @brief Initialize the CMFD materials. */ void Cmfd::initializeMaterials() { Material* material; /* Delete old CMFD surface currents vector if it exists */ if (_materials != NULL){ for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) delete _materials[i]; delete [] _materials; } /* Compute and log size in memory of Material array */ double size = (double) (_num_cmfd_groups + 4) * _num_cmfd_groups * _local_num_x * _local_num_y * _local_num_z * sizeof(FP_PRECISION) / (double) 1e6; log_printf(NORMAL, "CMFD material storage per domain = %6.2f MB", size); try { _materials = new Material*[_local_num_x*_local_num_y*_local_num_z]; for (int z = 0; z < _local_num_z; z++) { for (int y = 0; y < _local_num_y; y++) { for (int x = 0; x < _local_num_x; x++) { int ind = z*_local_num_x*_local_num_y + y*_local_num_x + x; material = new Material(ind); material->setNumEnergyGroups(_num_cmfd_groups); _materials[ind] = material; } } } } catch(std::exception &e) { log_printf(ERROR, "Could not allocate memory for the Mesh cell materials. " "Backtrace:%s", e.what()); } } /** * @brief Initializes CMFD surface currents Vector prior to first MOC iteration. */ void Cmfd::initializeCurrents() { /* Delete old CMFD surface currents vector if it exists */ if (_surface_currents != NULL) delete _surface_currents; float size = _num_cmfd_groups * (NUM_FACES + 2 * _balance_sigma_t) * _local_num_x * _local_num_y * _local_num_z * sizeof(CMFD_PRECISION) / float(1e6); log_printf(INFO_ONCE, "CMFD surface current storage per domain = %6.2f MB", size); /* Allocate memory for the CMFD Mesh surface and corner currents Vectors */ _surface_currents = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, _num_cmfd_groups * NUM_FACES); if (_balance_sigma_t) { /* Allocate memory for the actual starting currents on boundary CMFD cells */ _starting_currents = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, _num_cmfd_groups); /* Allocate memory for the net currents of all CMFD cells */ _net_currents = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, _num_cmfd_groups); } } /** * @brief Initializes the vector of vectors that links CMFD cells with FSRs. * @details This method is called by the geometry once the CMFD mesh has been * initialized by the geometry. This method allocates a vector for * each CMFD cell that is used to store the FSR ids contained within * that cell. */ void Cmfd::initializeCellMap() { /* Allocate memory for mesh cell FSR vectors */ for (int z = 0; z < _local_num_z; z++) { for (int y = 0; y < _local_num_y; y++) { for (int x = 0; x < _local_num_x; x++) _cell_fsrs.push_back(std::vector<long>()); } } } /** * @brief Allocates memory for the CMFD tallies. * @details This method is called by the CMFD initialization routine, and * allocates memory for the diffusion, reaction and volume tallies for * every CMFD cells. */ void Cmfd::allocateTallies() { if (_num_x*_num_y*_num_z == 0) log_printf(ERROR, "Zero cells in CMFD mesh. Please set CMFD mesh before " "initializing CMFD tallies."); if (_num_cmfd_groups == 0) log_printf(ERROR, "Zero CMFD groups. Please set CMFD group structure " "before initializing CMFD tallies."); /* Determine tally sizes */ int num_cells = _num_x * _num_y * _num_z; int local_num_cells = _local_num_x * _local_num_y * _local_num_z; int tally_size = local_num_cells * _num_cmfd_groups; _total_tally_size = 3 * tally_size; _tally_memory = new CMFD_PRECISION[_total_tally_size]; CMFD_PRECISION** all_tallies[3]; for (int t=0; t < 3; t++) { all_tallies[t] = new CMFD_PRECISION*[local_num_cells]; for (int i=0; i < local_num_cells; i++) { int idx = i * _num_cmfd_groups + t * tally_size; all_tallies[t][i] = &_tally_memory[idx]; } } log_printf(INFO_ONCE, "CMFD tally storage per domain = %6.2f MB", (_total_tally_size * sizeof(CMFD_PRECISION) + 3 * local_num_cells * sizeof(CMFD_PRECISION*)) / float(1e6)); /* Assign tallies to allocated data */ _diffusion_tally = all_tallies[0]; _reaction_tally = all_tallies[1]; _volume_tally = all_tallies[2]; _tallies_allocated = true; } /** * @brief Initialize and set array that links the MOC energy groups to the * CMFD energy groups. * @details This method initializes the _group_indices_map, which is a 1D array * of length _num_moc_groups that maps the MOC energy groups to CMFD * energy groups. The indices into _group_indices_map are the MOC * energy groups and the values are the CMFD energy groups. */ void Cmfd::initializeGroupMap() { /* Setup one-to-one fine-to-coarse group map if not specified by user */ if (!_user_group_indices) { _num_cmfd_groups = _num_moc_groups; /* Delete old group indices array if it exists */ if (_group_indices != NULL) delete [] _group_indices; /* Allocate memory for new group indices */ _group_indices = new int[_num_cmfd_groups+1]; /* Populate a 1-to-1 mapping from MOC to CMFD groups */ for (int i = 0; i <= _num_cmfd_groups; i++) { _group_indices[i] = i; } } else { if (_num_moc_groups != _group_indices[_num_cmfd_groups]) log_printf(ERROR, "The CMFD coarse group mapping is specified for " "%d groups, but the MOC problem contains %d groups", _group_indices[_num_cmfd_groups], _num_moc_groups); } /* Delete old group indices map if it exists */ if (_group_indices_map != NULL) delete [] _group_indices_map; /* Allocate memory for new group indices map */ _group_indices_map = new int[_num_moc_groups]; /* Create group indices map */ for (int e = 0; e < _num_cmfd_groups; e++) { for (int h = _group_indices[e]; h < _group_indices[e + 1]; h++) { _group_indices_map[h] = e; } } } /** * @brief Find the CMFD surface that a LocalCoords object lies on. * @details If the coords is not on a surface, -1 is returned. Otherwise, * the surface ID is returned. * @param cell the CMFD cell ID that the local coords is in. * @param coords the coords being evaluated. * @return The surface ID. */ int Cmfd::findCmfdSurface(int cell, LocalCoords* coords) { Point* point = coords->getHighestLevel()->getPoint(); /* If domain decomposition, compute the global CMFD cell ID */ if (_geometry->isDomainDecomposed()) cell = getGlobalCMFDCell(cell); return _lattice->getLatticeSurface(cell, point); } /** * @brief Find the CMFD cell that a LocalCoords object is in. * @param coords the coords being evaluated. * @return The CMFD cell ID. */ int Cmfd::findCmfdCell(LocalCoords* coords) { Point* point = coords->getHighestLevel()->getPoint(); int global_cmfd_cell = _lattice->getLatticeCell(point); /* If domain decomposition, compute the local CMFD cell ID*/ if (_geometry->isDomainDecomposed()) { int local_cmfd_cell = getLocalCMFDCell(global_cmfd_cell); return local_cmfd_cell; } else /* Without decomposition, global and local CMFD cell ID are equal.*/ return global_cmfd_cell; } /** * @brief The structure of the Lattice to be used as the CMFD mesh. * @param num_x The number of cells in the x direction. * @param num_y The number of cells in the y direction. * @param num_z The number of cells in the z direction. */ void Cmfd::setLatticeStructure(int num_x, int num_y, int num_z) { setNumX(num_x); setNumY(num_y); setNumZ(num_z); } /** * @brief Returns the Lattice object used as the CMFD mesh. * @return A pointer to a Lattice object. */ Lattice* Cmfd::getLattice() { return _lattice; } /** * @brief Add an FSR ID to a vector that contains all the FSR IDs * contained within a CMFD mesh cell. * @param cmfd_cell the CMFD cell ID. * @param fsr_id the FSR ID. */ void Cmfd::addFSRToCell(int cmfd_cell, long fsr_id) { _cell_fsrs.at(cmfd_cell).push_back(fsr_id); } /** * @brief Set the number of MOC energy groups. * @param num_groups number of MOC energy groups */ void Cmfd::setNumMOCGroups(int num_groups) { _num_moc_groups = num_groups; } /** * @brief Get the number of MOC energy groups. * @return the number of MOC energy groups */ int Cmfd::getNumMOCGroups() { return _num_moc_groups; } /** * @brief Get the number of CMFD cells. * @return the number of CMFD cells */ int Cmfd::getNumCells() { return _num_x * _num_y * _num_z; } /** * @brief set the number of FSRs. * @param num_fsrs the number of FSRs */ void Cmfd::setNumFSRs(long num_fsrs) { _num_FSRs = num_fsrs; } /** * @brief Split the currents of the Mesh cell vertices to the adjacent faces and * edges. * @details This method takes the currents tallied across the vertices of a CMFD * cell and splits them evenly across the adjacent faces and edges. In * order to transport the current through to the diagonal cell, the * current is also tallied on the edges of the adjacent cells. * Essentially, the tracks that cross through vertices are split into * three one-third-weight tracks as shown in the illustration below. * Face crossings are denoted as "o" and edge crossings are denoted as * "e". As shown, each partial-weight track first crosses a face and * then crosses through an edge to get into an adjacent cell. After all * partial-weight tracks reach the diagonal cell, they are recombined * into one full-weight track. Note tracks are not physically split * into partial-weight tracks for ray tracing; rather tracks cross * through the vertices and the current through each vertex is tallied. * * . . . * . \| . * | / . . . * | / . . \ * | e . . * | / . . * . e/ . * x -------------------.-+---------e----------- * o o /| . * . . / | . * . . / | . * \ | / o| * . /. | * . \ ./ | * . . y z * . * */ void Cmfd::splitVertexCurrents() { log_printf(INFO, "Splitting CMFD vertex currents..."); int ncg = _num_cmfd_groups; int nf = NUM_FACES; int ne = NUM_EDGES; int ns = NUM_SURFACES; #pragma omp parallel { FP_PRECISION current; std::vector<int> surfaces; std::vector<int>::iterator iter; std::map<int, CMFD_PRECISION>::iterator it; int cell, surface; #pragma omp for for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) { int global_id = getGlobalCMFDCell(i); for (int v = NUM_FACES + NUM_EDGES; v < NUM_SURFACES; v++) { /* Check if this surface is contained in the map */ int ind = i * NUM_SURFACES * ncg + v * ncg; it = _edge_corner_currents.find(ind); if (it == _edge_corner_currents.end()) continue; getVertexSplitSurfaces(global_id, v, &surfaces); //TODO Optimize since dont want to look for cells at every group for (int g=0; g < ncg; g++) { /* Divide vertex current by 3 since we will split to 3 surfaces, * which propagate through 3 edges */ current = _edge_corner_currents[ind+g] / 3; /* Increment current for faces and edges adjacent to this vertex */ for (iter = surfaces.begin(); iter != surfaces.end(); ++iter) { cell = (*iter) / ns; surface = (*iter) % ns; /* Look for the CMFD cell on-domain */ int local_cell = getLocalCMFDCell(cell); if (local_cell != -1) { /* Add face contributions */ if (surface < NUM_FACES) { _surface_currents->incrementValue(local_cell, surface * ncg + g, current); } /* Add edges contributions */ else { /* Map is accessed directly at new index, if the key doesn't exist, the default constructor is called, initializing at 0. */ int new_ind = (local_cell * NUM_SURFACES + surface) * ncg + g; /* Add the contribution */ omp_set_lock(&_edge_corner_lock); _edge_corner_currents[new_ind] += current; omp_unset_lock(&_edge_corner_lock); } } /* Look for the CMFD cell off-domain */ else { /* Look for the boundary containing the cell */ for (int s=0; s < NUM_FACES; s++) { std::map<int, int>::iterator it = _boundary_index_map.at(s).find(cell); if (it != _boundary_index_map.at(s).end()) { int idx = it->second; /* Add the current to the off-domain split currents cell */ // Comment out this line to check for MOC neutron balance omp_set_lock(&_edge_corner_lock); _off_domain_split_currents[s][idx][surface * ncg + g] += current; omp_unset_lock(&_edge_corner_lock); break; } } } } _edge_corner_currents[ind+g] = 0.0; } } } } } /** * @brief Split the currents of the Mesh cell edges to the adjacent faces. * @details This method takes the currents tallied across the edges (or corners) * of a CMFD cell and splits them evenly across the adjacent surfaces * (locations 1 and 2). In order to transport the current through to * the diagonal cell, the current is also tallied on the surfaces of * the adjacent cells (locations 3 and 4). Essentially, the tracks that * cross through edges are split into two half-weight tracks as shown * in the illustration below: * * | / * | __/_ * |/ / * 3 / / * /| / 4 * ------------------/-+-/------------------ * 1 / |/ * / / 2 * /___/| * / | * / | * */ void Cmfd::splitEdgeCurrents() { log_printf(INFO, "Splitting CMFD edge currents..."); int ncg = _num_cmfd_groups; int nf = NUM_FACES; int ne = NUM_EDGES; int ns = NUM_SURFACES; #pragma omp parallel { FP_PRECISION current; std::vector<int> surfaces; std::vector<int>::iterator iter; std::map<int, CMFD_PRECISION>::iterator it; int cell, surface; #pragma omp for for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) { int global_id = getGlobalCMFDCell(i); for (int e = NUM_FACES; e < NUM_FACES + NUM_EDGES; e++) { /* Check if this surface is contained in the map */ int ind = i * NUM_SURFACES * ncg + e * ncg; it = _edge_corner_currents.find(ind); if (it == _edge_corner_currents.end()) continue; getEdgeSplitSurfaces(global_id, e, &surfaces); //TODO Optimize since dont want to look for cells at every group for (int g=0; g < ncg; g++) { /* Divide edge current by 2 since we will split to 2 surfaces, * which propagate through 2 surfaces */ current = _edge_corner_currents[ind+g] / 2; /* Increment current for faces and edges adjacent to this vertex */ for (iter = surfaces.begin(); iter != surfaces.end(); ++iter) { cell = (*iter) / ns; surface = (*iter) % ns; /* Look for the CMFD cell on-domain */ int local_cell = getLocalCMFDCell(cell); if (local_cell != -1) { _surface_currents->incrementValue(local_cell, surface * ncg + g, current); } /* Look for the CMFD cell off-domain */ else { /* Look for the boundary containing the cell */ for (int s=0; s < NUM_FACES; s++) { std::map<int, int>::iterator it = _boundary_index_map.at(s).find(cell); if (it != _boundary_index_map.at(s).end()) { int idx = it->second; /* Add the current to the off-domain split currents cell */ // Comment out this line to check for MOC neutron balance omp_set_lock(&_edge_corner_lock); _off_domain_split_currents[s][idx][surface * ncg + g] += current; omp_unset_lock(&_edge_corner_lock); break; } } } } _edge_corner_currents[ind+g] = 0.0; } } } } } /** * @brief Get the faces and edges to split the currents of the Mesh cell * vertices. * @details The process by which the current of tracks passing through vertices * is split is described in the comment for * Cmfd::splitVertexCurrents(). This method takes in the cell and * vertex that is being split as well as a std::vector used to store * the IDs of surfaces that are crossed by the partial-weight tracks. * This method properly accounts for crossings on the geometry * boundaries by applying the corresponding boundary conditions to * split the currents. * @param cell The CMFD cell ID that the vertex is in. * @param vertex The vertex that the track crosses through. * @param surfaces A std::vector that is populated with the IDs of surfaces that * are crossed by partial-weight tracks. */ void Cmfd::getVertexSplitSurfaces(int cell, int vertex, std::vector<int>* surfaces) { surfaces->clear(); int x = (cell % (_num_x * _num_y)) % _num_x; int y = (cell % (_num_x * _num_y)) / _num_x; int z = cell / (_num_x * _num_y); int ns = NUM_SURFACES; int cell_indexes[3] = {x,y,z}; int cell_limits[3] = {_num_x, _num_y, _num_z}; int direction[3]; convertSurfaceToDirection(vertex, direction); /* Get the partial surfaces composing the edge split */ int remainder_surfaces[3]; int partial_surfaces[3]; for (int i=0; i < 3; i++) { int remainder_direction[3]; int partial_direction[3]; for (int j=0; j < 3; j++) { if (i == j) { remainder_direction[j] = 0; partial_direction[j] = direction[j]; } else { remainder_direction[j] = direction[j]; partial_direction[j] = 0; } } remainder_surfaces[i] = convertDirectionToSurface(remainder_direction); partial_surfaces[i] = convertDirectionToSurface(partial_direction); } /* Treat all partial surfaces */ for (int i=0; i < 3; i++) { int remainder_surface = remainder_surfaces[i]; int partial_surface = partial_surfaces[i]; surfaces->push_back(cell * ns + partial_surface); /* Tally current on neighboring cell or appropriate boundary */ int cell_next = getCellNext(cell, partial_surface); if ((cell_indexes[i] == 0 && direction[i] == -1) || (cell_indexes[i] == cell_limits[i] - 1 && direction[i] == +1)) { if (_boundaries[partial_surface] == REFLECTIVE) surfaces->push_back(cell * ns + remainder_surface); //NOTE Comment out this line to check MOC neutron balance else if (_boundaries[partial_surface] == PERIODIC) surfaces->push_back(cell_next * ns + remainder_surface); } else surfaces->push_back(cell_next * ns + remainder_surface); } } /** * @brief Get the faces to split the currents of the Mesh cell edges. * @details The process by which the current of tracks passing through edges * is split is described in the comment for Cmfd::splitEdgeCurrents(). * This method takes in the cell and edge that is being split as well * as a std::vector used to store the IDs of surfaces that are crossed * by the partial-weight tracks. This method properly accounts for * crossings on the geometry boundaries by applying the corresponding * boundary conditions to split the currents. * @param cell The CMFD cell ID that the edge is in. * @param edge The edge that the track crosses through. * @param surfaces A std::vector that is populated with the IDs of surfaces that * are crossed by partial-weight tracks. */ void Cmfd::getEdgeSplitSurfaces(int cell, int edge, std::vector<int>* surfaces) { surfaces->clear(); int x = (cell % (_num_x * _num_y)) % _num_x; int y = (cell % (_num_x * _num_y)) / _num_x; int z = cell / (_num_x * _num_y); int ns = NUM_SURFACES; int cell_indexes[3] = {x,y,z}; int cell_limits[3] = {_num_x, _num_y, _num_z}; int direction[3]; convertSurfaceToDirection(edge, direction); /* Get the partial surfaces composing the edge split */ int partial_surfaces[2]; int opposite_surfaces[2]; int ind = 0; for (int i=0; i < 3; i++) { if (direction[i] != 0) { int partial_direction[3] = {0,0,0}; partial_direction[i] = direction[i]; partial_surfaces[ind] = convertDirectionToSurface(partial_direction); ind++; } } /* Treat all partial surfaces */ ind = 0; for (int i=0; i < 3; i++) { if (direction[i] != 0) { int partial_surface = partial_surfaces[ind]; int other_surface = partial_surfaces[1-ind]; surfaces->push_back(cell * ns + partial_surface); /* Tally current on neighboring cell or appropriate boundary */ int cell_next = getCellNext(cell, partial_surface); if ((cell_indexes[i] == 0 && direction[i] == -1) || (cell_indexes[i] == cell_limits[i] - 1 && direction[i] == +1)) { if (_boundaries[partial_surface] == REFLECTIVE) surfaces->push_back(cell * ns + other_surface); //NOTE Comment out this line to check MOC neutron balance else if (_boundaries[partial_surface] == PERIODIC) surfaces->push_back(cell_next * ns + other_surface); } else surfaces->push_back(cell_next * ns + other_surface); ind++; } } } /** * @brief Get the ID of the Mesh cell next to given Mesh cell. * @param cell index of the current CMFD cell * @param surface_id id of the surface between the current cell and the next * @param global work at the global (all domains together) level * @param neighbor give cell in neighboring domain * @return neighboring CMFD cell ID */ int Cmfd::getCellNext(int cell, int surface_id, bool global, bool neighbor) { int cell_next = -1; int x, y, z; int nx, ny, nz; int x_global, y_global, z_global; if (global || _domain_communicator == NULL) { x_global = (cell % (_num_x * _num_y)) % _num_x; y_global = (cell % (_num_x * _num_y)) / _num_x; z_global = cell / (_num_x * _num_y); x = x_global; y = y_global; z = z_global; nx = _num_x; ny = _num_y; nz = _num_z; } else { x = (cell % (_local_num_x * _local_num_y)) % _local_num_x; y = (cell % (_local_num_x * _local_num_y)) / _local_num_x; z = cell / (_local_num_x * _local_num_y); x_global = x + _accumulate_lmx[_domain_communicator->_domain_idx_x]; y_global = y + _accumulate_lmy[_domain_communicator->_domain_idx_y]; z_global = z + _accumulate_lmz[_domain_communicator->_domain_idx_z]; nx = _local_num_x; ny = _local_num_y; nz = _local_num_z; } /* Find the cell on the other side of the surface */ if (surface_id == SURFACE_X_MIN) { if (x != 0) cell_next = cell - 1; else if (neighbor && !global && x_global != 0) cell_next = z * _local_num_y + y; else if (_boundaries[SURFACE_X_MIN] == PERIODIC) cell_next = cell + (_num_x-1); } else if (surface_id == SURFACE_Y_MIN) { if (y != 0) cell_next = cell - nx; else if (neighbor && !global && y_global != 0) cell_next = z * _local_num_x + x; else if (_boundaries[SURFACE_Y_MIN] == PERIODIC) cell_next = cell + _num_x*(_num_y-1); } else if (surface_id == SURFACE_Z_MIN) { if (z != 0) cell_next = cell - nx*ny; else if (neighbor && !global && z_global != 0) cell_next = y * _local_num_x + x; else if (_boundaries[SURFACE_Z_MIN] == PERIODIC) cell_next = cell + _num_x*_num_y*(_num_z-1); } else if (surface_id == SURFACE_X_MAX) { if (x != nx - 1) cell_next = cell + 1; else if (neighbor && !global && x_global != _num_x - 1) cell_next = z * _local_num_y + y; else if (_boundaries[SURFACE_X_MAX] == PERIODIC) cell_next = cell - (_num_x-1); } else if (surface_id == SURFACE_Y_MAX) { if (y != ny - 1) cell_next = cell + nx; else if (neighbor && !global && y_global != _num_y - 1) cell_next = z * _local_num_x + x; else if (_boundaries[SURFACE_Y_MAX] == PERIODIC) cell_next = cell - _num_x*(_num_y-1); } else if (surface_id == SURFACE_Z_MAX) { if (z != nz - 1) cell_next = cell + nx*ny; else if (neighbor && !global && z_global != _num_z - 1) cell_next = y * _local_num_x + x; else if (_boundaries[SURFACE_Z_MAX] == PERIODIC) cell_next = cell - _num_x*_num_y*(_num_z-1); } return cell_next; } /** * @brief Set the CMFD boundary type for a given surface. * @details The CMFD boundary is assumed to be rectangular with the * surfaces identified by constants in the constants.h file. * @param side The CMFD surface UID. * @param boundary The boundaryType of the surface. */ void Cmfd::setBoundary(int side, boundaryType boundary) { _boundaries[side] = boundary; } /** * @brief Get the boundaryType for one side of the CMFD mesh. * @param side the CMFD mesh surface ID. * @return the boundaryType for the surface. */ int Cmfd::getBoundary(int side) { return _boundaries[side]; } /** * @brief Return the CMFD cell ID that a FSR lies in. * @details Note that a CMFD cell is not an actual Cell object; rather, a CMFD * cell is just a way of describing each of the rectangular regions * that make up a CMFD lattice. CMFD cells are numbered with 0 in the * lower left corner and monotonically increasing from left to right, * from bottom to top. For example, the indices for a 4 x 4 lattice * are: * 12 13 14 15 * 8 9 10 11 * 4 5 6 7 * 0 1 2 3 * @param fsr_id the FSR ID. * @return The CMFD cell ID. Return -1 if cell is not found. */ int Cmfd::convertFSRIdToCmfdCell(long fsr_id) { std::vector<long>::iterator iter; for (int cell_id=0; cell_id < _local_num_x*_local_num_y*_local_num_z; cell_id++) { for (iter = _cell_fsrs.at(cell_id).begin(); iter != _cell_fsrs.at(cell_id).end(); ++iter) { if (*iter == fsr_id) return cell_id; } } return -1; } /** * @brief Return the CMFD cell ID that a FSR lies in. * @param global_fsr_id The global FSR ID. * @return The CMFD cell ID. */ int Cmfd::convertGlobalFSRIdToCmfdCell(long global_fsr_id) { /* Determine the domain and local FSR ID */ int cmfd_cell = -1; if (!_geometry->isDomainDecomposed()) { cmfd_cell = convertFSRIdToCmfdCell(global_fsr_id); } #ifdef MPIx else { long fsr_id; int domain; _geometry->getLocalFSRId(global_fsr_id, fsr_id, domain); /* Get the FSR centroid in the correct domain */ int rank; MPI_Comm comm = _geometry->getMPICart(); MPI_Comm_rank(comm, &rank); int temp_cmfd_cell = 0; if (rank == domain) temp_cmfd_cell = convertFSRIdToCmfdCell(fsr_id); /* Broadcast the temp_cmfd_cell */ MPI_Allreduce(&temp_cmfd_cell, &cmfd_cell, 1, MPI_INT, MPI_SUM, comm); } #endif return cmfd_cell; } /** * @brief Return a pointer to the vector of vectors that contains * the FSRs that lie in each cell. * @return Vector of vectors containing FSR IDs in each cell. */ std::vector< std::vector<long> >* Cmfd::getCellFSRs() { return &_cell_fsrs; } /** * @brief Set the vector of vectors that contains the FSRs that lie in each * cell. * @param cell_fsrs vector of vectors containing FSR IDs in each cell. */ void Cmfd::setCellFSRs(std::vector< std::vector<long> >* cell_fsrs) { if (!_cell_fsrs.empty()) { std::vector< std::vector<long> >::iterator iter; for (iter = _cell_fsrs.begin(); iter != _cell_fsrs.end(); ++iter) iter->clear(); _cell_fsrs.clear(); } _cell_fsrs = *cell_fsrs; } /** * @brief Set flag indicating whether to update the MOC flux. * @param flux_update_on Flag saying whether to update MOC flux. */ void Cmfd::setFluxUpdateOn(bool flux_update_on) { _flux_update_on = flux_update_on; } /** * @brief Sets the a ConvergenceData object to record diagnostics. * @details The ConvergenceData object records the number of fission source * and flux iterations for the CMFD solver as well as the maximum * magnitude prolongation factor * @param convergence_data The convergence data object */ void Cmfd::setConvergenceData(ConvergenceData* convergence_data) { _convergence_data = convergence_data; } /** * @brief Set the flag indicating whether to use quadratic axial interpolation * for update ratios. * @param interpolate flag meaning No interpolation(0), FSR axially averaged value(1) or centroid z-coordinate evaluated value(2) */ void Cmfd::useAxialInterpolation(int interpolate) { if (interpolate<0 || interpolate>2) log_printf(ERROR, "interpolate can only has value 0, 1, or 2, respectively" " meaning No interpolation, FSR axially averaged value or" " centroid z-coordinate evaluated value"); if (interpolate==1 || interpolate==2) log_printf(WARNING_ONCE, "Axial interpolation CMFD prolongation may only" " be effective when all the FSRs are axially homogeneous"); _use_axial_interpolation = interpolate; } /** * @brief Turns on the flux limiting condition. * @details If the CMFD correction diffusion coefficient is larger than the * diffusion coefficient, recompute the diffusion coefficient as the * ratio of current to twice the flux, and re-compute a correction * diffusion coefficient. * @param flux_limiting whether to turn on the flux limiting condition */ void Cmfd::useFluxLimiting(bool flux_limiting) { _flux_limiting = flux_limiting; } /** * @brief Modifies the diagonal element to be consistent with the MOC solve * @details This function re-computes a new total cross-section x volume that * maintains consistency with the MOC solution. Generally, this will * not change the diagonal element at all since CMFD should be * consistent with MOC. However, if negative fluxes are corrected to * zero after the MOC transport sweep, there will be an inconsistency. * This function modifies sigma-t so that there is consistency with * the altered solution. * @param cmfd_cell The cmfd cell of the element to adjust * @param group The cmfd group of the element to adjust */ void Cmfd::enforceBalanceOnDiagonal(int cmfd_cell, int group) { /* Initialize tallies */ Material* material = _materials[cmfd_cell]; double cmfd_volume = _volumes->getValue(cmfd_cell, 0); /* Loop over FSRs in CMFD cell to tally the total neutron source */ double moc_source = 0.0; for (int j = 0; j < _cell_fsrs.at(cmfd_cell).size(); j++) { long fsr_id = _cell_fsrs.at(cmfd_cell).at(j); FP_PRECISION volume = _FSR_volumes[fsr_id]; /* Loop over MOC energy groups within this CMFD coarse group */ for (int h = _group_indices[group]; h < _group_indices[group+1]; h++) moc_source += 4 * M_PI * volume * _FSR_sources[fsr_id * _num_moc_groups + h]; } if (fabs(moc_source) < FLUX_EPSILON) moc_source = FLUX_EPSILON; /* Compute updated value */ double flux = _old_flux->getValue(cmfd_cell, group); CMFD_PRECISION net_current = _net_currents->getValue(cmfd_cell, group); CMFD_PRECISION updated_value = (moc_source - net_current) / flux; if (updated_value < 0.0) log_printf(ERROR, "Negative Total XS of %6.4f computed in CMFD rebalance", updated_value); /* Update the diagonal element */ _A->setValue(cmfd_cell, group, cmfd_cell, group, updated_value); } /** * @brief Rebalances the total cross section to be consistent with the MOC * solution on every sweep. * @param balance_sigma_t Wheter to compute the rebalanced total cross-section */ void Cmfd::rebalanceSigmaT(bool balance_sigma_t) { _balance_sigma_t = balance_sigma_t; } /** * @brief Returns a flag indicating whether the sigma-t rebalance is on. * @return A flag indicating whether the rebalance is on */ bool Cmfd::isSigmaTRebalanceOn() { return _balance_sigma_t; } /** * @brief Get flag indicating whether to update the MOC flux. * @return Flag saying whether to update MOC flux */ bool Cmfd::isFluxUpdateOn() { return _flux_update_on; } /** * @brief Set flag indicating whether to use FSR centroids to update * the MOC flux. * @param centroid_update_on Flag saying whether to use centroids to * update MOC flux */ void Cmfd::setCentroidUpdateOn(bool centroid_update_on) { _centroid_update_on = centroid_update_on; } /** * @brief Get flag indicating whether to use FSR centroids to update * the MOC flux. * @return Flag saying whether to use centroids to update MOC flux */ bool Cmfd::isCentroidUpdateOn() { return _centroid_update_on; } /** * @brief Sets the threshold for CMFD source convergence (>0). * @param source_thresh the threshold for source convergence */ void Cmfd::setSourceConvergenceThreshold(double source_thresh) { if (source_thresh <= 0.0) log_printf(ERROR, "Unable to set the CMFD source convergence threshold to" " %f since the threshold must be positive.", source_thresh); _source_convergence_threshold = source_thresh; } /** * @brief Sets the Quadrature object in use by the MOC Solver. * @param quadrature a Quadrature object pointer from the Solver */ void Cmfd::setQuadrature(Quadrature* quadrature) { _quadrature = quadrature; _num_polar = quadrature->getNumPolarAngles(); _num_azim = quadrature->getNumAzimAngles(); } /** * @brief Generate the k-nearest neighbor CMFD cell stencil for each FSR. * @details This method finds the k-nearest CMFD cell stencil for each FSR * and saves the stencil, ordered from the closest-to-furthest * CMFD cell, in the _k_nearest_stencils map. The stencil of cells * surrounding the current cell is defined as: * * 6 7 8 * 3 4 5 * 0 1 2 * * where 4 is the given CMFD cell. If the cell is on the edge or corner * of the geometry and there are less than k nearest neighbor cells, * k is reduced to the number of neighbor cells for that instance. */ void Cmfd::generateKNearestStencils() { std::vector< std::pair<int, double> >::iterator stencil_iter; std::vector<long>::iterator fsr_iter; Point* centroid; long fsr_id; if (_centroid_update_on){ /* Number of cells in stencil */ int num_cells_in_stencil = 9; /* Loop over mesh cells */ for (int i = 0; i < _local_num_x*_local_num_y*_local_num_z; i++) { int global_ind = getGlobalCMFDCell(i); /* Loop over FRSs in mesh cell */ for (fsr_iter = _cell_fsrs.at(i).begin(); fsr_iter != _cell_fsrs.at(i).end(); ++fsr_iter) { fsr_id = *fsr_iter; /* Get centroid */ centroid = _geometry->getFSRCentroid(fsr_id); /* Create new stencil */ _k_nearest_stencils[fsr_id] = std::vector< std::pair<int, double> >(); /* Get distance to all cells that touch current cell */ for (int j=0; j < num_cells_in_stencil; j++) _k_nearest_stencils[fsr_id] .push_back(std::make_pair<int, double> (int(j), getDistanceToCentroid(centroid, global_ind, i, j))); /* Sort the distances */ std::sort(_k_nearest_stencils[fsr_id].begin(), _k_nearest_stencils[fsr_id].end(), stencilCompare); /* Remove ghost cells that are outside the geometry boundaries */ stencil_iter = _k_nearest_stencils[fsr_id].begin(); while (stencil_iter != _k_nearest_stencils[fsr_id].end()) { if (stencil_iter->second > FLT_INFINITY) stencil_iter = _k_nearest_stencils[fsr_id].erase(stencil_iter); else ++stencil_iter; } /* Resize stencil to be of size <= _k_nearest */ _k_nearest_stencils[fsr_id].resize (std::min(_k_nearest, int(_k_nearest_stencils[fsr_id].size()))); } } /* Precompute (1.0 - cell distance / total distance) of each FSR centroid to * its k-nearest CMFD cells */ double total_distance; for (long i=0; i < _num_FSRs; i++) { total_distance = 1.e-10; /* Compute the total distance of each FSR centroid to its k-nearest CMFD * cells */ for (stencil_iter = _k_nearest_stencils[i].begin(); stencil_iter < _k_nearest_stencils[i].end(); ++stencil_iter) total_distance += stencil_iter->second; /* Reset the second stencil value to * (1.0 - cell_distance / total_distance) */ for (stencil_iter = _k_nearest_stencils[i].begin(); stencil_iter < _k_nearest_stencils[i].end(); ++stencil_iter) stencil_iter->second = 1.0 - stencil_iter->second / total_distance; } } /* Compute axial quadratic interpolation values if requested */ if (_use_axial_interpolation && _local_num_z >= 3) { /* Initialize axial quadratic interpolant values */ _axial_interpolants.resize(_num_FSRs); for (long r=0; r < _num_FSRs; r++) { _axial_interpolants.at(r) = new double[3](); } log_printf(INFO_ONCE, "CMFD axial interpolation storage per domain = %6.2f" " MB", _num_FSRs * 3 * sizeof(double) / float(1e6)); /* Loop over mesh cells */ for (int i = 0; i < _local_num_x*_local_num_y*_local_num_z; i++) { /* Starting z number of CMFD mesh in this domain */ int z_start = 0; if (_domain_communicator != NULL) z_start = _accumulate_lmz[_domain_communicator->_domain_idx_z]; /* Calculate the CMFD cell z-coordinate */ int z_ind = i / (_local_num_x * _local_num_y); /* The heights of neighboring three CMFD meshes for quadratic fit */ double h0, h1, h2; /* The z coordinate of the mesh center of the middle-CMFD cell */ double z_cmfd; if (z_ind == 0) { h0 = _cell_widths_z[z_start + z_ind]; h1 = _cell_widths_z[z_start + z_ind + 1]; h2 = _cell_widths_z[z_start + z_ind + 2]; z_cmfd = _accumulate_z[z_start + z_ind+1] + h1/2. + _lattice->getMinZ(); } else if (z_ind == _local_num_z - 1) { h0 = _cell_widths_z[z_start + z_ind - 2]; h1 = _cell_widths_z[z_start + z_ind - 1]; h2 = _cell_widths_z[z_start + z_ind]; z_cmfd = _accumulate_z[z_start + z_ind-1] + h1/2. + _lattice->getMinZ(); } else { h0 = _cell_widths_z[z_start + z_ind - 1]; h1 = _cell_widths_z[z_start + z_ind]; h2 = _cell_widths_z[z_start + z_ind + 1]; z_cmfd = _accumulate_z[z_start + z_ind] + h1/2. + _lattice->getMinZ(); } /* Start and end relative z-coordinate of an FSR */ double zs, ze; /* Loop over FRSs in mesh cell */ int num_fissionable_FSRs = 0; for (fsr_iter = _cell_fsrs.at(i).begin(); fsr_iter != _cell_fsrs.at(i).end(); ++fsr_iter) { /* Get centroid and calculate relative z-coordinate */ fsr_id = *fsr_iter; Point* centroid = _geometry->getFSRCentroid(fsr_id); Point* feature_point = _geometry->getFSRPoint(fsr_id); double zc = (centroid->getZ() - z_cmfd) / h1; zs = (feature_point->getZ() - z_cmfd) / h1; ze = 2*zc - zs; /* Calculate components for quadratic interpolation of the FSR axially averaged value */ if (_use_axial_interpolation ==1) { _axial_interpolants.at(fsr_id)[0] = (h1*(h1+h1*zc*4.0+h2*zc*8.0- h1*(zc*zc)*1.6E1-h1*(zs*zs)*4.0+h1*zc*zs*8.0)*(-1.0/4.0)) /((h0+h1)*(h0+h1+h2)); _axial_interpolants.at(fsr_id)[1] = (h1+h2-h1*zc*2.0)/(h1+h2)+(h1*(h1+ h1*zc*4.0+h2*zc*8.0-h1*(zc*zc)*1.6E1-h1*(zs*zs)*4.0+h1*zc*zs*8.0)* (1.0/4.0))/(h2*(h0+h1))-((h1*h1)*(h1+h1*zc*4.0+h2*zc*8.0-h1*(zc*zc)* 1.6E1-h1*(zs*zs)*4.0+h1*zc*zs*8.0)*(1.0/4.0))/(h2*(h1+h2)*(h0+h1+h2)); _axial_interpolants.at(fsr_id)[2] = (h1*(-h1+h0*zc*8.0+h1*zc*4.0+ h1*(zc*zc)*1.6E1+h1*(zs*zs)*4.0-h1*zc*zs*8.0)*(1.0/4.0)) /((h1+h2)*(h0+h1+h2)); log_printf(DEBUG, "CMFD-ID: %d, FSR-ID: %ld, c0= %10.6f, c1= %10.6f," " c2= %10.6f", i, fsr_id, _axial_interpolants.at(fsr_id)[0], _axial_interpolants.at(fsr_id)[1], _axial_interpolants.at(fsr_id)[2]); } /* Calculate components for quadratic interpolation of the centroid z-coordinate evaluated value. */ else if (_use_axial_interpolation == 2) { _axial_interpolants.at(fsr_id)[0] = -(h1*(h1+h1*zc*4.0+h2*zc*8.0-h1* (zc*zc)*1.2E1))/((h0*4.0+h1*4.0)*(h0+h1+h2)); _axial_interpolants.at(fsr_id)[1] = (-zc*(h0*(h1*h1)*1.2E1+(h0*h0)*h1* 8.0-h1*(h2*h2)*8.0-(h1*h1)*h2*1.2E1)+h0*(h1*h1)*9.0+(h0*h0)*h1*4.0+h0* (h2*h2)*4.0+(h0*h0)*h2*4.0+h1*(h2*h2)*4.0+(h1*h1)*h2*9.0+(h1*h1*h1)*6.0 -(zc*zc)*(h0*(h1*h1)*1.2E1+(h1*h1)*h2*1.2E1+(h1*h1*h1)*2.4E1)+h0*h1*h2 *1.2E1)/((h1+h2)*(h0*4.0+h1*4.0)*(h0+h1+h2)); _axial_interpolants.at(fsr_id)[2] = (h1*(-h1+h0*zc*8.0+h1*zc*4.0+h1* (zc*zc)*1.2E1))/((h1*4.0+h2*4.0)*(h0+h1+h2)); log_printf(DEBUG, "CMFD-ID: %d, FSR-ID: %ld, c0= %10.6f, c1= %10.6f," " c2= %10.6f", i, fsr_id, _axial_interpolants.at(fsr_id)[0], _axial_interpolants.at(fsr_id)[1], _axial_interpolants.at(fsr_id)[2]); } /* Calculate components for quadratic interpolation of the centroid z-coordinate evaluted value. For uniform CMFD */ /*_axial_interpolants.at(fsr_id)[0] = zc * zc/2.0 - zc/2.0 - 1.0/24.0; _axial_interpolants.at(fsr_id)[1] = -zc * zc + 26.0/24.0; _axial_interpolants.at(fsr_id)[2] = zc * zc/2.0 + zc/2.0 - 1.0/24.0;*/ /* Set zero axial prolongation for cells with no fissionable material */ if (_FSR_materials[fsr_id]->isFissionable()) num_fissionable_FSRs++; } } } } /** * @brief Get the ID of the Mesh cell given a stencil ID and Mesh cell ID. * @details The stencil of cells surrounding the current cell is defined as: * * 6 7 8 * 3 4 5 * 0 1 2 * * @param cell_id Current Mesh cell ID * @param stencil_id CMFD cell stencil ID * @return Neighboring CMFD cell ID */ int Cmfd::getCellByStencil(int cell_id, int stencil_id) { int cell_next_id = -1; int x = (cell_id % (_local_num_x * _local_num_y)) % _local_num_x; int y = (cell_id % (_local_num_x * _local_num_y)) / _local_num_x; if (stencil_id == 0) { if (x != 0 && y != 0) cell_next_id = cell_id - _local_num_x - 1; } else if (stencil_id == 1) { if (y != 0) cell_next_id = cell_id - _local_num_x; else if (_boundaries[SURFACE_Y_MIN] == PERIODIC) cell_next_id = cell_id + _local_num_x * (_local_num_y - 1); } else if (stencil_id == 2) { if (x != _local_num_x - 1 && y != 0) cell_next_id = cell_id - _local_num_x + 1; } else if (stencil_id == 3) { if (x != 0) cell_next_id = cell_id - 1; else if (_boundaries[SURFACE_X_MIN] == PERIODIC) cell_next_id = cell_id + (_local_num_x - 1); } else if (stencil_id == 4) { cell_next_id = cell_id; } else if (stencil_id == 5) { if (x != _local_num_x - 1) cell_next_id = cell_id + 1; else if (_boundaries[SURFACE_X_MAX] == PERIODIC) cell_next_id = cell_id - (_local_num_x - 1); } else if (stencil_id == 6) { if (x != 0 && y != _local_num_y - 1) cell_next_id = cell_id + _local_num_x - 1; } else if (stencil_id == 7) { if (y != _local_num_y - 1) cell_next_id = cell_id + _local_num_x; else if (_boundaries[SURFACE_Y_MAX] == PERIODIC) cell_next_id = cell_id - _local_num_x * (_local_num_y - 1); } else if (stencil_id == 8) { if (x != _local_num_x - 1 && y != _local_num_y - 1) cell_next_id = cell_id + _local_num_x + 1; } return cell_next_id; } /** * @brief Get the ratio used to update the FSR flux after converging CMFD. * @details This method takes in a CMFD cell, a MOC energy group, and a FSR * and returns the ratio used to update the FSR flux. There are two * methods that can be used to update the flux, conventional and * k-nearest centroid updating. The k-nearest centroid updating uses * the k-nearest cells (with k between 1 and 9) of the current CMFD * cell and the 8 neighboring CMFD cells. The stencil of cells * surrounding the current cell is defined as: * * 6 7 8 * 3 4 5 * 0 1 2 * * where 4 is the given CMFD cell. If the cell is on the edge or corner * of the geometry and there are less than k nearest neighbor cells, * k is reduced to the number of neighbor cells for that instance. * @param cell_id The CMFD cell ID containing the FSR. * @param group The CMFD energy group being updated. * @param fsr The fsr being updated. * @return the ratio used to update the FSR flux. */ CMFD_PRECISION Cmfd::getUpdateRatio(int cell_id, int group, long fsr) { CMFD_PRECISION ratio = 0.0; std::vector< std::pair<int, double> >::iterator iter; int cell_next_id; if (_centroid_update_on) { /* Compute the ratio for all the surrounding cells */ for (iter = _k_nearest_stencils[fsr].begin(); iter != _k_nearest_stencils[fsr].end(); ++iter) { if (iter->first != 4) { cell_next_id = getCellByStencil(cell_id, iter->first);//cell_id is Local itself here. ratio += iter->second * getFluxRatio(cell_next_id, group, fsr); } } /* INTERNAL */ if (_k_nearest_stencils[fsr].size() == 1) ratio += getFluxRatio(cell_id, group, fsr); else { ratio += _k_nearest_stencils[fsr][0].second * getFluxRatio(cell_id, group, fsr); ratio /= (_k_nearest_stencils[fsr].size() - 1); } } else ratio = getFluxRatio(cell_id, group, fsr); return ratio; } /** * @brief Retrieves the ratio of pre- and post- CMFD solve fluxes * @details The CMFD flux ratio is returned for the given FSR. A quadratic * axial interpolant is used to estimate the value at the FSR. * @param cell_id The CMFD cell ID containing the FSR. * @param group The CMFD energy group being updated. * @param fsr The fsr being updated. * @return the ratio of CMFD fluxes */ CMFD_PRECISION Cmfd::getFluxRatio(int cell_id, int group, long fsr) { double ratio = 1.0; if (_use_axial_interpolation && _local_num_z >= 3) { /* Get pre-computed interpolation ratios */ double* interpolants = _axial_interpolants.at(fsr); int z_ind = cell_id / (_local_num_x * _local_num_y); int cell_mid = cell_id; /* Shift up or down one cell if at top/bottom, interpolants corrects for the shift in cells */ if (z_ind == 0) cell_mid += _local_num_x * _local_num_y; else if (z_ind == _local_num_z - 1) cell_mid -= _local_num_x * _local_num_y; /* Get cell index above and below current CMFD cell */ int cell_prev = cell_mid - _local_num_x * _local_num_y; int cell_next = cell_mid + _local_num_x * _local_num_y; /* Get new and old fluxes in bottom/mid/top cells */ double old_flux_prev = _old_flux->getValue(cell_prev, group); double new_flux_prev = _new_flux->getValue(cell_prev, group); double old_flux_next = _old_flux->getValue(cell_next, group); double new_flux_next = _new_flux->getValue(cell_next, group); double old_flux_mid = _old_flux->getValue(cell_mid, group); double new_flux_mid = _new_flux->getValue(cell_mid, group); double old_flux = interpolants[0] * old_flux_prev + interpolants[1] * old_flux_mid + interpolants[2] * old_flux_next; double new_flux = interpolants[0] * new_flux_prev + interpolants[1] * new_flux_mid + interpolants[2] * new_flux_next; if (fabs(old_flux) > FLUX_EPSILON) ratio = new_flux / old_flux; /* Fallback: using the cell average flux ratio */ if (ratio < 0) { if (fabs(_old_flux->getValue(cell_id, group)) > FLUX_EPSILON) ratio = _new_flux->getValue(cell_id, group) / _old_flux->getValue(cell_id, group); else ratio = 0.0; } return ratio; } else { if (fabs(_old_flux->getValue(cell_id, group)) > FLUX_EPSILON) return _new_flux->getValue(cell_id, group) / _old_flux->getValue(cell_id, group); else return 0.0; } } /** * @brief Get the distances from an FSR centroid to a given CMFD cell. * @details This method takes in a FSR centroid, a CMFD cell, and a stencil index * to a cell located in the 9-point stencil encompassing the CMFD * cell an all its possible neighbors. The CMFD cell stencil is: * * 6 7 8 * 3 4 5 * 0 1 2 * * where 4 is the given CMFD cell. If a CMFD edge or corner cells is * given and the stencil indexed cell lies outside the geometry, the * maximum allowable double value is returned. * @param centroid The numerical centroid an FSR in the cell. * @param cell_id The global CMFD cell containing the FSR. * @param local_cell_id The local CMFD id of the cell containing the fsr * @param stencil_index The index of the cell in the stencil that we want to * get the distance from. * @return the distance from the CMFD cell centroid to the FSR centroid. */ double Cmfd::getDistanceToCentroid(Point* centroid, int cell_id, int local_cell_id, int stencil_index) { int x = (cell_id % (_num_x * _num_y)) % _num_x; int y = (cell_id % (_num_x * _num_y)) / _num_x; int xl = (local_cell_id % (_local_num_x * _local_num_y)) % _local_num_x; int yl = (local_cell_id % (_local_num_x * _local_num_y)) / _local_num_x; double dist_x, dist_y; bool found = false; double centroid_x = centroid->getX(); double centroid_y = centroid->getY(); /* The center of geometry is not always at (0,0,0), then relative coordinates should be used. */ double dx = centroid_x - _lattice->getMinX(); double dy = centroid_y - _lattice->getMinY(); /* LOWER LEFT CORNER */ if (xl > 0 && yl > 0 && stencil_index == 0) { dist_x = pow(dx - (_accumulate_x[x-1]+_cell_widths_x[x-1]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y-1]+_cell_widths_y[y-1]/2), 2.0); found = true; } /* BOTTOM SIDE */ else if (yl > 0 && stencil_index == 1) { dist_x = pow(dx - (_accumulate_x[x ]+_cell_widths_x[x ]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y-1]+_cell_widths_y[y-1]/2), 2.0); found = true; } /* LOWER RIGHT CORNER */ else if (xl < _local_num_x - 1 && yl > 0 && stencil_index == 2) { dist_x = pow(dx - (_accumulate_x[x+1]+_cell_widths_x[x+1]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y-1]+_cell_widths_y[y-1]/2), 2.0); found = true; } /* LEFT SIDE */ else if (xl > 0 && stencil_index == 3) { dist_x = pow(dx - (_accumulate_x[x-1]+_cell_widths_x[x-1]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y ]+_cell_widths_y[y ]/2), 2.0); found = true; } /* CURRENT */ else if (stencil_index == 4) { dist_x = pow(dx - (_accumulate_x[x ]+_cell_widths_x[x ]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y ]+_cell_widths_y[y ]/2), 2.0); found = true; } /* RIGHT SIDE */ else if (xl < _local_num_x - 1 && stencil_index == 5) { dist_x = pow(dx - (_accumulate_x[x+1]+_cell_widths_x[x+1]/2 ), 2.0); dist_y = pow(dy - (_accumulate_y[y ]+_cell_widths_y[y ]/2 ), 2.0); found = true; } /* UPPER LEFT CORNER */ else if (xl > 0 && yl < _local_num_y - 1 && stencil_index == 6) { dist_x = pow(dx - (_accumulate_x[x-1]+_cell_widths_x[x-1]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y+1]+_cell_widths_y[y+1]/2), 2.0); found = true; } /* TOP SIDE */ else if (yl < _local_num_y - 1 && stencil_index == 7) { dist_x = pow(dx - (_accumulate_x[x ]+_cell_widths_x[x ]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y+1]+_cell_widths_y[y+1]/2), 2.0); found = true; } /* UPPER RIGHT CORNER */ else if (xl < _local_num_x - 1 && yl < _local_num_y - 1 && stencil_index == 8) { dist_x = pow(dx - (_accumulate_x[x+1]+_cell_widths_x[x+1]/2), 2.0); dist_y = pow(dy - (_accumulate_y[y+1]+_cell_widths_y[y+1]/2), 2.0); found = true; } if (found) return pow(dist_x + dist_y, 0.5); else return std::numeric_limits<double>::max(); } /** * @brief Set a pointer to the Geometry. * @param geometry A pointer to a Geometry object. */ void Cmfd::setGeometry(Geometry* geometry) { _geometry = geometry; } /** * @brief Set the number of iterations where the CMFD update ratios are not * bounded. * @param unbounded number of iterations without bounds on CMFD update ratios */ void Cmfd::setNumUnboundedIterations(int unbounded_iterations) { _num_unbounded_iterations = unbounded_iterations; } /** * @brief Set a number of k-nearest neighbor cells to use in updating * the FSR flux. * @param k_nearest The number of nearest neighbor CMFD cells. */ void Cmfd::setKNearest(int k_nearest) { if (k_nearest < 1 || k_nearest > 9) log_printf(ERROR, "Unable to set CMFD k-nearest to %i. k-nearest " "must be between 1 and 9.", k_nearest); else _k_nearest = k_nearest; /* Enables use of centroids for K-nearest */ _centroid_update_on = true; } /** * @brief Zero the surface currents for each mesh cell and energy group. */ void Cmfd::zeroCurrents() { _surface_currents->clear(); if (_balance_sigma_t) { _starting_currents->clear(); _net_currents->clear(); } /* Clear boundary currents */ #ifdef MPIx if (_geometry->isDomainDecomposed()) { #pragma omp parallel for for (int s=0; s < NUM_FACES; s++) { /* Loop over all CMFD cells on the current surface */ std::map<int, int>::iterator it; for (it=_boundary_index_map.at(s).begin(); it != _boundary_index_map.at(s).end(); ++it) { int idx = it->second; /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Loop over cell faces */ for (int f=0; f < NUM_FACES; f++) _boundary_surface_currents[s][idx][f*_num_cmfd_groups+e] = 0.0; /* Loop over all cell faces and edges */ for (int fe=0; fe < NUM_FACES + NUM_EDGES; fe++) { _off_domain_split_currents[s][idx][fe*_num_cmfd_groups+e] = 0.0; _received_split_currents[s][idx][fe*_num_cmfd_groups+e] = 0.0; } } } } } #endif } /** * @brief Initialize the Matrix and Vector objects, k-nearest stencils, the * CMFD cell currents and MOC materials. */ void Cmfd::initialize() { /* Delete old Matrix and Vector objects if they exist */ if (_A != NULL) delete _A; if (_M != NULL) delete _M; if (_old_source != NULL) delete _old_source; if (_new_source != NULL) delete _new_source; if (_old_flux != NULL) delete _old_flux; if (_new_flux != NULL) delete _new_flux; if (_old_dif_surf_corr != NULL) delete _old_dif_surf_corr; if (_volumes != NULL) delete _volumes; if (_cell_locks != NULL) delete [] _cell_locks; /* Calculate the number of elements */ int num_cells = _local_num_x * _local_num_y * _local_num_z; int ncg = _num_cmfd_groups; try { /* Allocate array of OpenMP locks for each CMFD cell */ _cell_locks = new omp_lock_t[num_cells]; /* Loop over all cells to initialize OpenMP locks */ #pragma omp parallel for schedule(guided) for (int r=0; r < num_cells; r++) omp_init_lock(&_cell_locks[r]); omp_init_lock(&_edge_corner_lock); /* Compute and log size in memory of CMFD matrices */ int num_rows = _num_cmfd_groups * _local_num_x * _local_num_y * _local_num_z * 2; // A matrix is duplicated as list of list and CSR form (allocated before // each transport iteration's CMFD solve) int num_non_zero_coeffs = 6 + 20 * _num_cmfd_groups / 70; // 20 is estimated number of non-zero scatters per group for 70g structure double size = (double) (num_rows) * num_non_zero_coeffs * sizeof(CMFD_PRECISION) / (double) 1e6; log_printf(NORMAL, "CMFD A matrix est. storage per domain = %6.2f MB", size); /* Allocate memory for matrix and vector objects */ _M = new Matrix(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _A = new Matrix(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _old_source = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _new_source = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _old_flux = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _new_flux = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, ncg); _old_dif_surf_corr = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, NUM_FACES * ncg); _old_dif_surf_corr->setAll(0.0); _volumes = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, 1); log_printf(INFO_ONCE, "CMFD flux, source and diffusion coefficient storage" " = %6.2f MB", num_cells * ((4 + NUM_FACES) * ncg * sizeof(CMFD_PRECISION) + sizeof(omp_lock_t)) / float(1e6)); /* Initialize k-nearest stencils, currents, flux, materials and tallies */ generateKNearestStencils(); initializeCurrents(); initializeMaterials(); allocateTallies(); #ifdef MPIx /* Initialize domain communicator */ if (_domain_communicator != NULL) { _domain_communicator->stop = false; int offset = _accumulate_lmx[_domain_communicator->_domain_idx_x] + _accumulate_lmy[_domain_communicator->_domain_idx_y] + _accumulate_lmz[_domain_communicator->_domain_idx_z]; _domain_communicator->_offset = offset; _domain_communicator->_local_num_x = _local_num_x; _domain_communicator->_local_num_y = _local_num_y; _domain_communicator->_local_num_z = _local_num_z; _domain_communicator->num_groups = ncg; int dir_sizes[3] = {num_cells / _local_num_x, num_cells / _local_num_y, num_cells / _local_num_z}; /* Count total number of cells at all faces of the domain */ int num_per_side[3] = {_local_num_y * _local_num_z, _local_num_x * _local_num_z, _local_num_x * _local_num_y}; int num_boundary_cells = 0; for (int s=0; s < NUM_FACES; s++) num_boundary_cells += num_per_side[s % 3]; float size = 2 * num_boundary_cells * ncg * (1 + 2 * NUM_FACES) * sizeof(int) + (2 * NUM_FACES * 2 * ncg * num_boundary_cells + 2 * num_boundary_cells * ncg * NUM_FACES + NUM_FACES * 4 * ncg * num_boundary_cells) * sizeof(CMFD_PRECISION); log_printf(INFO_ONCE, "CMFD domain communicator size per domain = %6.2f " "MB", size / 1e6); /* Allocate arrays to contain information about the domain's neighbors */ _domain_communicator->num_connections = new int*[2]; _domain_communicator->indexes = new int**[2]; _domain_communicator->domains = new int**[2]; /* Arrays to contain data to communicate to/receive from other domains */ _domain_communicator->fluxes = new CMFD_PRECISION**[2]; _domain_communicator->coupling_coeffs = new CMFD_PRECISION**[2]; _domain_communicator->buffer = new CMFD_PRECISION*[NUM_FACES]; for (int rb=0; rb<2; rb++) { _domain_communicator->num_connections[rb] = new int[num_boundary_cells*ncg]; _domain_communicator->indexes[rb] = new int*[num_boundary_cells*ncg]; _domain_communicator->domains[rb] = new int*[num_boundary_cells*ncg]; _domain_communicator->fluxes[rb] = new CMFD_PRECISION*[NUM_FACES]; _domain_communicator->coupling_coeffs[rb] = new CMFD_PRECISION*[num_boundary_cells*ncg]; for (int coord=0; coord < 3; coord++) { for (int d=0; d < 2; d++) { int surf = coord + 3 * d; _domain_communicator->fluxes[rb][surf] = new CMFD_PRECISION[dir_sizes[coord]*ncg]; _domain_communicator->buffer[surf] = new CMFD_PRECISION[2*dir_sizes[coord]*ncg]; } } for (int nsc=0; nsc < num_boundary_cells * ncg; nsc++) { _domain_communicator->num_connections[rb][nsc] = 0; _domain_communicator->indexes[rb][nsc] = new int[NUM_FACES]; _domain_communicator->domains[rb][nsc] = new int[NUM_FACES]; _domain_communicator->coupling_coeffs[rb][nsc] = new CMFD_PRECISION[NUM_FACES]; } _domain_communicator_allocated = true; } /* Create map of continuous indexes for the domain's 6 faces : same order as the surfaces (XMIN=0, YMIN=1...) */ int count = 0; for (int iz=0; iz < _local_num_z; iz++) { for (int iy=0; iy < _local_num_y; iy++) { int cell = (iz*_local_num_y + iy)*_local_num_x; _domain_communicator->mapLocalToSurface[cell] = count++; } } for (int iz=0; iz < _local_num_z; iz++) { for (int ix=1; ix < _local_num_x; ix++) { int cell = (iz*_local_num_y)*_local_num_x + ix; _domain_communicator->mapLocalToSurface[cell] = count++; } } for (int iy=1; iy < _local_num_y; iy++) { for (int ix=1; ix < _local_num_x; ix++) { int cell = (iy)*_local_num_x + ix; _domain_communicator->mapLocalToSurface[cell] = count++; } } for (int iz=1; iz < _local_num_z; iz++) { for (int iy=1; iy < _local_num_y; iy++) { int cell = (iz*_local_num_y + iy)*_local_num_x + _local_num_x - 1; _domain_communicator->mapLocalToSurface[cell] = count++; } } for (int iz=1; iz < _local_num_z; iz++) { for (int ix=1; ix < _local_num_x-1; ix++) { int cell = (iz*_local_num_y + _local_num_y - 1)*_local_num_x + ix; _domain_communicator->mapLocalToSurface[cell] = count++; } } for (int iy=1; iy < _local_num_y-1; iy++) { for (int ix=1; ix < _local_num_x-1; ix++) { int cell = ((_local_num_z - 1)*_local_num_y + iy)*_local_num_x + ix; _domain_communicator->mapLocalToSurface[cell] = count++; } } /* Allocate communication buffers for CMFD matrix construction */ int storage_per_cell = ((2 + NUM_FACES) * ncg + 1); int internal = ncg * num_boundary_cells; int comm_data_size = storage_per_cell * num_boundary_cells; //NOTE Rank 0 is at a corner log_printf(INFO_ONCE, "CMFD communication buffers size per domain = " "%6.2f MB", (4 * comm_data_size + internal) * sizeof(CMFD_PRECISION) / float(1e6)); _inter_domain_data = new CMFD_PRECISION[comm_data_size + internal]; _send_domain_data = new CMFD_PRECISION[comm_data_size]; /* Allocate memory for communication of off-domain quantities */ _domain_data_by_surface = new CMFD_PRECISION*[NUM_FACES]; _send_data_by_surface = new CMFD_PRECISION*[NUM_FACES]; _boundary_volumes = new CMFD_PRECISION**[NUM_FACES]; _boundary_reaction = new CMFD_PRECISION**[NUM_FACES]; _boundary_diffusion = new CMFD_PRECISION**[NUM_FACES]; _boundary_surface_currents = new CMFD_PRECISION**[NUM_FACES]; _old_boundary_flux = new CMFD_PRECISION**[NUM_FACES]; int start = 0; int ext = 0; for (int s=0; s < NUM_FACES; s++) { _domain_data_by_surface[s] = &_inter_domain_data[start]; _send_data_by_surface[s] = &_send_domain_data[start]; _boundary_volumes[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _boundary_reaction[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _boundary_diffusion[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _boundary_surface_currents[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _old_boundary_flux[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; for (int idx=0; idx < num_per_side[s % 3]; idx++) { _boundary_volumes[s][idx] = &_inter_domain_data[start]; _boundary_reaction[s][idx] = &_inter_domain_data[start+1]; _boundary_diffusion[s][idx] = &_inter_domain_data[start+ncg+1]; _boundary_surface_currents[s][idx] = &_inter_domain_data[start+2*ncg+1]; _old_boundary_flux[s][idx] = &_inter_domain_data[comm_data_size+ext]; ext += ncg; start += storage_per_cell; } } /* Allocate memory for split current communication */ int ns = NUM_FACES + NUM_EDGES; int vec_size = ns*ncg*sizeof(CMFD_PRECISION); int split_current_size = ncg * ns * num_boundary_cells; _send_split_current_data = new CMFD_PRECISION[split_current_size]; _receive_split_current_data = new CMFD_PRECISION[split_current_size]; //NOTE Rank 0 is at a corner log_printf(INFO_ONCE, "CMFD corner current comm. storage per domain = " "%6.2f MB", 4 * split_current_size * sizeof(CMFD_PRECISION) / float(1e6)); _send_split_currents_array = new CMFD_PRECISION*[NUM_FACES]; _receive_split_currents_array = new CMFD_PRECISION*[NUM_FACES]; _off_domain_split_currents = new CMFD_PRECISION**[NUM_FACES]; _received_split_currents = new CMFD_PRECISION**[NUM_FACES]; start = 0; for (int s=0; s < NUM_FACES; s++) { _send_split_currents_array[s] = &_send_split_current_data[start]; _receive_split_currents_array[s] = &_receive_split_current_data[start]; _off_domain_split_currents[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _received_split_currents[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; for (int idx=0; idx < num_per_side[s % 3]; idx++) { _off_domain_split_currents[s][idx] = &_send_split_current_data[start]; memset(_off_domain_split_currents[s][idx], 0, vec_size); _received_split_currents[s][idx] = &_receive_split_current_data[start]; memset(_received_split_currents[s][idx], 0, vec_size); start += ns*ncg; } } /* Allocate memory for communication of on-domain quantities */ _send_volumes = new CMFD_PRECISION**[NUM_FACES]; _send_reaction = new CMFD_PRECISION**[NUM_FACES]; _send_diffusion = new CMFD_PRECISION**[NUM_FACES]; _send_currents = new CMFD_PRECISION**[NUM_FACES]; start = 0; for (int s=0; s < NUM_FACES; s++) { _send_volumes[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _send_reaction[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _send_diffusion[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; _send_currents[s] = new CMFD_PRECISION*[num_per_side[s % 3]]; for (int idx=0; idx < num_per_side[s % 3]; idx++) { _send_volumes[s][idx] = &_send_domain_data[start]; _send_reaction[s][idx] = &_send_domain_data[start+1]; _send_diffusion[s][idx] = &_send_domain_data[start+ncg+1]; _send_currents[s][idx] = &_send_domain_data[start+2*ncg+1]; start += storage_per_cell; } } /* Calculate the starting and ending indexes of on-domain CMFD cells */ int x_start = _accumulate_lmx[_domain_communicator->_domain_idx_x]; int x_end = x_start + _local_num_x; int y_start = _accumulate_lmy[_domain_communicator->_domain_idx_y]; int y_end = y_start + _local_num_y; int z_start = _accumulate_lmz[_domain_communicator->_domain_idx_z]; int z_end = z_start + _local_num_z; _boundary_index_map.resize(NUM_FACES); /* Map connecting cells on x-surfaces */ int global_ind; for (int y=0; y < _local_num_y; y++) { for (int z=0; z < _local_num_z; z++) { if (x_start > 0) { global_ind = ((z_start + z) * _num_y + y + y_start) * _num_x + x_start - 1; _boundary_index_map.at(SURFACE_X_MIN)[global_ind] = z * _local_num_y + y; } if (x_end < _num_x) { global_ind = ((z_start + z) * _num_y + y + y_start) * _num_x + x_end; _boundary_index_map.at(SURFACE_X_MAX)[global_ind] = z * _local_num_y + y; } } } /* Map connecting cells on y-surfaces */ for (int x=0; x < _local_num_x; x++) { for (int z=0; z < _local_num_z; z++) { if (y_start > 0) { global_ind = ((z_start + z) * _num_y + y_start-1) * _num_x + x + x_start; _boundary_index_map.at(SURFACE_Y_MIN)[global_ind] = z * _local_num_x + x; } if (y_end < _num_y) { global_ind = ((z_start + z) * _num_y + y_end) * _num_x + x + x_start; _boundary_index_map.at(SURFACE_Y_MAX)[global_ind] = z * _local_num_x + x; } } } /* Map connecting cells on z-surfaces */ for (int x=0; x < _local_num_x; x++) { for (int y=0; y < _local_num_y; y++) { if (z_start > 0) { global_ind = ((z_start-1) * _num_y + y + y_start) * _num_x + x + x_start; _boundary_index_map.at(SURFACE_Z_MIN)[global_ind] = y * _local_num_x + x; } if (z_end < _num_z) { global_ind = (z_end * _num_y + y + y_start) * _num_x + x + x_start; _boundary_index_map.at(SURFACE_Z_MAX)[global_ind] = y * _local_num_x + x; } } } } #endif } catch (std::exception &e) { log_printf(ERROR, "Could not allocate memory for the CMFD mesh objects. " "Backtrace:%s", e.what()); } } /** * @brief Initialize the CMFD lattice and compute mesh dimensions, considering * both uniform/non-uniform and 2D/3D cases. * @param offset the offset point of the CMFD Lattice * @param is_2D whether CMFD will be used in a 2D simulation (true) or 3D */ void Cmfd::initializeLattice(Point* offset, bool is_2D) { /* Deal with 2D case, set all widths Z to 1 */ if (is_2D || _width_z > FLT_INFINITY) { _num_z = 1; _local_num_z = 1; _width_z = 1.0; _cell_width_z = 1.0; _cell_widths_z.resize(_num_z); _cell_widths_z[0] = _cell_width_z; setBoundary(SURFACE_Z_MIN, REFLECTIVE); setBoundary(SURFACE_Z_MAX, REFLECTIVE); } /* Handle use of X,Y and Z symmetries */ if (_geometry->getSymmetry(0)) { // Compute current width of CMFD mesh double width_x = 0; for (int i=0; i<_cell_widths_x.size(); i++) width_x = width_x + _cell_widths_x[i]; // If CMFD mesh was meant for full geometry, adapt it if (std::abs(width_x - _width_x * 2) < FLT_EPSILON) { if (_cell_widths_x.size() % 2 == 0) _cell_widths_x.resize(_cell_widths_x.size() / 2); else { _cell_widths_x.resize(_cell_widths_x.size() / 2 + 1); _cell_widths_x[_cell_widths_x.size() - 1] /= 2; } } } if (_geometry->getSymmetry(1)) { // Compute current width of CMFD mesh double width_y = 0; for (int i=0; i<_cell_widths_y.size(); i++) width_y = width_y + _cell_widths_y[i]; // If CMFD mesh was meant for full geometry, adapt it if (std::abs(width_y - _width_y * 2) < FLT_EPSILON) { if (_cell_widths_y.size() % 2 == 0) _cell_widths_y.resize(_cell_widths_y.size() / 2); else { _cell_widths_y.resize(_cell_widths_y.size() / 2 + 1); _cell_widths_y[_cell_widths_y.size() - 1] /= 2; } } } if (_geometry->getSymmetry(2)) { // Compute current width of CMFD mesh double width_z = 0; for (int i=0; i<_cell_widths_z.size(); i++) width_z = width_z + _cell_widths_z[i]; // If CMFD mesh was meant for full geometry, adapt it if (std::abs(width_z - _width_z * 2) < FLT_EPSILON) { if (_cell_widths_z.size() % 2 == 0) _cell_widths_z.resize(_cell_widths_z.size() / 2); else { _cell_widths_z.resize(_cell_widths_z.size() / 2 + 1); _cell_widths_z[_cell_widths_z.size() - 1] /= 2; } } } if (_non_uniform) { setNumX(_cell_widths_x.size()); setNumY(_cell_widths_y.size()); setNumZ(_cell_widths_z.size()); } else { _cell_width_x = _width_x / _num_x; _cell_width_y = _width_y / _num_y; _cell_width_z = _width_z / _num_z; _cell_widths_x.resize(_num_x, _cell_width_x); _cell_widths_y.resize(_num_y, _cell_width_y); _cell_widths_z.resize(_num_z, _cell_width_z); } _accumulate_x.resize(_num_x+1, 0.0); _accumulate_y.resize(_num_y+1, 0.0); _accumulate_z.resize(_num_z+1, 0.0); for (int i=0; i<_num_x; i++) _accumulate_x[i+1] = _accumulate_x[i] + _cell_widths_x[i]; for (int i=0; i<_num_y; i++) _accumulate_y[i+1] = _accumulate_y[i] + _cell_widths_y[i]; for (int i=0; i<_num_z; i++) _accumulate_z[i+1] = _accumulate_z[i] + _cell_widths_z[i]; if (fabs(_width_x - _accumulate_x[_num_x]) > FLT_EPSILON || fabs(_width_y - _accumulate_y[_num_y]) > FLT_EPSILON || fabs(_width_z - _accumulate_z[_num_z]) > FLT_EPSILON) log_printf(ERROR, "The sum of non-uniform mesh widths are not consistent " "with geometry dimensions. width_x = %20.17E, width_y = %20.17E" ", width_z = %20.17E, sum_x = %20.17E, sum_y = %20.17E, sum_z =" " %20.17E, diff_x = %20.17E, diff_y = %20.17E, diff_z = %20.17E" ", FLT_EPSILON = %20.17E", _width_x, _width_y, _width_z, _accumulate_x[_num_x], _accumulate_y[_num_y], _accumulate_z[_num_z], fabs(_width_x - _accumulate_x[_num_x]), fabs(_width_y - _accumulate_y[_num_y]), fabs(_width_z - _accumulate_z[_num_z]), FLT_EPSILON); /* Delete old lattice if it exists */ if (_lattice != NULL) delete _lattice; /* Initialize the lattice */ _lattice = new Lattice(); _lattice->setNumX(_num_x); _lattice->setNumY(_num_y); _lattice->setNumZ(_num_z); if (_non_uniform) _lattice->setWidths(_cell_widths_x, _cell_widths_y, _cell_widths_z); else _lattice->setWidth(_cell_width_x, _cell_width_y, _cell_width_z); _lattice->setOffset(offset->getX(), offset->getY(), offset->getZ()); _lattice->computeSizes(); } /** * @brief Initializes a backup CMFD solver. * @details This backup solver is not necessary to run simulations, but may be * used if the regular solver fails and the user wants to try another * group structure without restarting the simulation. */ void Cmfd::initializeBackupCmfdSolver() { /* Initialize new CMFD object */ _backup_cmfd = new Cmfd(); _backup_cmfd->useAxialInterpolation(_use_axial_interpolation); _backup_cmfd->setLatticeStructure(_num_x, _num_y, _num_z); _backup_cmfd->setKNearest(_k_nearest); _backup_cmfd->setSORRelaxationFactor(_SOR_factor); _backup_cmfd->setCMFDRelaxationFactor(_relaxation_factor); _backup_cmfd->useFluxLimiting(_flux_limiting); /* Set one-group group structure */ if (_backup_group_structure.size() == 0) { std::vector<int> all_groups; for (int e=0; e < _num_moc_groups; e++) all_groups.push_back(e+1); _backup_group_structure.push_back(all_groups); _cmfd_group_to_backup_group = new int[_num_cmfd_groups]; for (int e=0; e < _num_cmfd_groups; e++) _cmfd_group_to_backup_group[e] = 0; } _backup_cmfd->setGroupStructure(_backup_group_structure); /* Set CMFD mesh boundary conditions */ for (int i=0; i < 6; i++) _backup_cmfd->setBoundary(i, _boundaries[i]); /* Set CMFD mesh dimensions */ _backup_cmfd->setWidthX(_width_x); _backup_cmfd->setWidthY(_width_y); _backup_cmfd->setWidthZ(_width_z); /* Initialize CMFD Maps */ _backup_cmfd->initializeCellMap(); /* Initialize the CMFD lattice */ _backup_cmfd->initializeLattice(_lattice->getOffset()); _backup_cmfd->setGeometry(_geometry); #ifdef MPIx if (_domain_communicator != NULL) { _backup_cmfd->setNumDomains(_domain_communicator->_num_domains_x, _domain_communicator->_num_domains_y, _domain_communicator->_num_domains_z); _backup_cmfd->setDomainIndexes(_domain_communicator->_domain_idx_x, _domain_communicator->_domain_idx_y, _domain_communicator->_domain_idx_z); } #endif /* Initialize the backup CMFD solver */ _backup_cmfd->initialize(); /* Initialize the CMFD energy group structure */ _backup_cmfd->setSourceConvergenceThreshold(_source_convergence_threshold); _backup_cmfd->setNumMOCGroups(_num_moc_groups); _backup_cmfd->initializeGroupMap(); /* Give CMFD number of FSRs and FSR property arrays */ _backup_cmfd->setSolve3D(_SOLVE_3D); _backup_cmfd->setNumFSRs(_num_FSRs); _backup_cmfd->setFSRVolumes(_FSR_volumes); _backup_cmfd->setFSRMaterials(_FSR_materials); _backup_cmfd->setFSRFluxes(_FSR_fluxes); _backup_cmfd->setFSRSources(_FSR_sources); _backup_cmfd->setQuadrature(_quadrature); if (_flux_moments != NULL) _backup_cmfd->setFluxMoments(_flux_moments); /* Add FSRs to cells */ _backup_cmfd->setCellFSRs(&_cell_fsrs); /* Initialize the backup CMFD solver */ _backup_cmfd->initialize(); _backup_cmfd->setConvergenceData(_convergence_data); } /** * @brief Copies the current from the regular to the backup CMFD solver. * @details The currents are condensed to the backup solver's energy structure * when transfered as well. */ void Cmfd::copyCurrentsToBackup() { /* Clear currents */ _backup_cmfd->zeroCurrents(); /* Get the number of backup groups */ int nbg = _backup_group_structure.size(); /* Get the local current array */ Vector* backup_currents = _backup_cmfd->getLocalCurrents(); /* Copy on-node surface currents */ #pragma omp parallel for for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) { for (int f=0; f < NUM_FACES; f++) { for (int e=0; e < _num_cmfd_groups; e++) { /* Sum group contributions and add to currents */ int bg = _cmfd_group_to_backup_group[e]; CMFD_PRECISION val = _surface_currents->getValue(i, f * _num_cmfd_groups + e); backup_currents->incrementValue(i, f * nbg + bg, val); } } } #ifdef MPIx /* Copy off-node surface currents */ if (_domain_communicator != NULL) { CMFD_PRECISION*** off_node_currents = _backup_cmfd->getBoundarySurfaceCurrents(); for (int surface=0; surface < NUM_FACES; surface++) { /* Extract arrays on surface */ CMFD_PRECISION** boundary_currents = _boundary_surface_currents[surface]; CMFD_PRECISION** backup_currents = off_node_currents[surface]; /* Loop over all CMFD cells on the current surface */ std::map<int, int>::iterator it; for (it=_boundary_index_map.at(surface).begin(); it != _boundary_index_map.at(surface).end(); ++it) { int idx = it->second; /* Loop over cell faces */ for (int f=0; f < NUM_FACES; f++) { /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { int bg = _cmfd_group_to_backup_group[e]; backup_currents[idx][f*nbg + bg] += boundary_currents[idx][f*_num_cmfd_groups+e]; } } } } } #endif } /** * @brief Returns the width of a given surface * @param surface A surface index, from 0 to NUM_FACES - 1 * @param global_ind global index of a CMFD cell * @return The surface width */ CMFD_PRECISION Cmfd::getSurfaceWidth(int surface, int global_ind) { CMFD_PRECISION width; int ix = global_ind % _num_x; int iy = (global_ind % (_num_x * _num_y)) / _num_x; int iz = global_ind / (_num_x * _num_y); if (surface == SURFACE_X_MIN || surface == SURFACE_X_MAX) return _cell_widths_y[iy] * _cell_widths_z[iz]; else if (surface == SURFACE_Y_MIN || surface == SURFACE_Y_MAX) return _cell_widths_x[ix] * _cell_widths_z[iz]; else return _cell_widths_x[ix] * _cell_widths_y[iy]; } /** * @brief Returns the width of the surface perpendicular to a given surface * @param surface A surface index, from 0 to NUM_FACES - 1 * @param global_ind The CMFD cell global index * @return The perpendicular surface width */ CMFD_PRECISION Cmfd::getPerpendicularSurfaceWidth(int surface, int global_ind) { int ix = global_ind % _num_x; int iy = (global_ind % (_num_x * _num_y)) / _num_x; int iz = global_ind / (_num_x * _num_y); if (surface == SURFACE_X_MIN || surface == SURFACE_X_MAX) return _cell_widths_x[ix]; else if (surface == SURFACE_Y_MIN || surface == SURFACE_Y_MAX) return _cell_widths_y[iy]; else return _cell_widths_z[iz]; } /** * @brief Returns the sense of a given surface * @details The sense of minimum surfaces (e.g. SURFACE_X_MIN) is defined to be * -1 while maximum surfaces (e.g. SURFACE_X_MAX) are defined to have a * sense of +1. This is based on the current exiting a cell from a * minimum surface being in the direction of negative net current and * the current leaving a cell from a maximum surface being in the * direction of positive net current. * @param surface A surface index, from 0 to NUM_FACES - 1 * @return The sense of the surface */ int Cmfd::getSense(int surface) { if (surface == SURFACE_X_MIN || surface == SURFACE_Y_MIN || surface == SURFACE_Z_MIN) return -1; else return 1; } /** * @brief Sets a flag to indicate whether a 2D or 3D problem is being solved. * @param solve_3D A boolean indicate whether a 2D or 3D problem is being * solved. */ void Cmfd::setSolve3D(bool solve_3D) { #ifndef THREED _SOLVE_3D = solve_3D; #endif } /** * @brief Sets the azimuthal spacings. * @param azim_spacings An array of azimuthal spacings for each azimuthal angle. * @param num_azim the number of azimuthal angles. */ void Cmfd::setAzimSpacings(const std::vector<double>& azim_spacings, int num_azim) { if (_azim_spacings != NULL) delete [] _azim_spacings; _azim_spacings = new double[num_azim/4]; for (int a=0; a < num_azim/4; a++) _azim_spacings[a] = double(azim_spacings[a]); } /** * @brief Sets the polar spacings. * @param polar_spacings A 2D array of polar spacings for each azimuthal and * polar angle combination. * @param num_azim the number of azimuthal angles. * @param num_polar the number of polar angles. */ void Cmfd::setPolarSpacings(const std::vector< std::vector<double> >& polar_spacings, int num_azim, int num_polar) { if (_polar_spacings != NULL) { for (int a=0; a < num_azim/4; a++) delete [] _polar_spacings[a]; delete [] _polar_spacings; } _polar_spacings = new double*[num_azim/4]; for (int a=0; a < num_azim/4; a++) _polar_spacings[a] = new double[num_polar/2]; for (int a=0; a < num_azim/4; a++) { for (int p=0; p < num_polar/2; p++) _polar_spacings[a][p] = double(polar_spacings[a][p]); } } /** * @brief Set the value of the k effective for the CMFD solver. This is meant * for research / debugging purposes. * @param k_eff the k_eff value to set. */ void Cmfd::setKeff(double k_eff) { _k_eff = k_eff; } /** * @brief Set the backup CMFD solver's group structure. It is necessarily * coarser than and must align with the regular CMFD group structure. * @param group_indices the indices of the CMFD groups in the MOC groups */ void Cmfd::setBackupGroupStructure(std::vector< std::vector<int> > group_indices) { /* Assign the number of backup energy groups */ _num_backup_groups = group_indices.size(); /* Initialize mappings */ _backup_group_structure = group_indices; _cmfd_group_to_backup_group = new int[_num_cmfd_groups]; for (int e=0; e < _num_cmfd_groups; e++) _cmfd_group_to_backup_group[e] = -1; /* Check that the mapping is valid and assign CMFD groups to backup groups */ int cmfd_group = -1; int moc_group = 0; for (int i=0; i < group_indices.size(); i++) { for (int j=0; j < group_indices.at(i).size(); j++) { if (group_indices.at(i).at(j) != moc_group + 1) { log_printf(ERROR, "Invalid backup group structure: indices must be " "monotonic and include all MOC groups."); } if (moc_group >= _group_indices[cmfd_group+1]) { cmfd_group++; _cmfd_group_to_backup_group[cmfd_group] = i; } if (i != _cmfd_group_to_backup_group[cmfd_group]) log_printf(ERROR, "Invalid backup group structure: indices of backup " "group structure must align with boundaries of CMFD group " "structure."); moc_group++; } } /* Ensure that every CMFD group has a backup group */ for (int e=0; e < _num_cmfd_groups; e++) { if (_cmfd_group_to_backup_group[e] == -1) log_printf(ERROR, "Invalid backup group structure: failed to find " "matching index for CMFD group %d", e); } } /** * @brief A function that prints a summary of the CMFD input parameters. */ void Cmfd::printInputParamsSummary() { if (_flux_update_on) log_printf(NORMAL, "CMFD acceleration: ON"); else log_printf(NORMAL, "CMFD acceleration: OFF (no MOC flux update)"); // Print CMFD relaxation information if (std::abs(_SOR_factor - 1) > FLT_EPSILON) log_printf(NORMAL, "CMFD inner linear solver SOR factor: %f", _SOR_factor); log_printf(NORMAL, "CMFD corrected diffusion coef. relaxation factor: %f", _relaxation_factor); // Print CMFD interpolation techniques if (_centroid_update_on) log_printf(NORMAL, "CMFD K-nearest scheme: %d neighbors", _k_nearest); if (_use_axial_interpolation == 1) log_printf(NORMAL, "CMFD axial interpolation with axially averaged update " "ratios"); else if (_use_axial_interpolation == 2) log_printf(NORMAL, "CMFD axial interpolation with update ratios evaluated " "at centroid Z-coordinate"); // Print other CMFD modifications if (_flux_limiting) log_printf(INFO_ONCE, "CMFD corrected diffusion coef. bounded by " "regular diffusion coef."); if (_balance_sigma_t) log_printf(INFO_ONCE, "CMFD total cross sections adjusted for matching MOC " "reaction rates"); // Print CMFD space and energy mesh information log_printf(NORMAL, "CMFD Mesh: %d x %d x %d", _num_x, _num_y, _num_z); if (_flux_update_on && _num_cmfd_groups != _num_moc_groups) { log_printf(NORMAL, "CMFD Group Structure:"); log_printf(NORMAL, "\t MOC Group \t CMFD Group"); for (int g=0; g < _num_moc_groups; g++) log_printf(NORMAL, "\t %d \t\t %d", g+1, getCmfdGroup(g)+1); } else log_printf(NORMAL, "CMFD and MOC group structures match"); } /** * @brief Report the physical time use by major components of the CMFD solver. */ void Cmfd::printTimerReport() { std::string msg_string; /* Get the total CMFD time */ double tot_time = _timer->getSplit("Total CMFD time"); msg_string = " Total CMFD computation time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), tot_time); /* Get the total XS collapse time */ double xs_collapse_time = _timer->getSplit("Total collapse time"); msg_string = " XS collapse time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), xs_collapse_time); /* Get the total matrix construction time */ double matrix_construction_time = _timer->getSplit("Matrix construction time"); msg_string = " Matrix construction time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), matrix_construction_time); #ifdef MPIx /* Get the MPI communication time */ double comm_time = _timer->getSplit("CMFD MPI communication time"); msg_string = " MPI communication time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), comm_time); #endif /* Get the total solver time */ double solver_time = _timer->getSplit("Total solver time"); msg_string = " Total CMFD solver time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), solver_time); /* Get the total MOC flux update time */ double update_time = _timer->getSplit("Total MOC flux update time"); msg_string = " Total flux update time"; msg_string.resize(53, '.'); log_printf(RESULT, "%s%1.4E sec", msg_string.c_str(), update_time); } /** * @brief Forms a full copy of the surface currents on every surface * @details The copy contains all surface currents including edge and corner * currents explicitly. It is stored in the _full_surface_currents * vector for use in debugging and diagnostics. */ void Cmfd::copyFullSurfaceCurrents() { /* Allocate full surface currents if necessary */ if (_full_surface_currents == NULL) _full_surface_currents = new Vector(_cell_locks, _local_num_x, _local_num_y, _local_num_z, _num_cmfd_groups * NUM_SURFACES); /* Clear the currently saved surface currents */ _full_surface_currents->clear(); /* Copy surface currents from surface faces */ for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) { for (int s=0; s < NUM_FACES; s++) { for (int g=0; g < _num_cmfd_groups; g++) { FP_PRECISION current = _surface_currents->getValue(i, s * _num_cmfd_groups + g); _full_surface_currents->incrementValue(i, s * _num_cmfd_groups + g, current); } } } /* Copy surface currents from edges and corners */ std::map<int, CMFD_PRECISION>::iterator it; for (it = _edge_corner_currents.begin(); it != _edge_corner_currents.end(); ++it) { int key = it->first; int cell = key / (_num_cmfd_groups * NUM_SURFACES); int surf_group = key % (_num_cmfd_groups * NUM_SURFACES); _full_surface_currents->incrementValue(cell, surf_group, it->second); } } /** * @brief Computes the neutron balance over each CMFD cell for both MOC and CMFD * @details This routine can be used once the CMFD matrices have been formed to * compute the neutron balance in the CMFD cell. With regards to MOC, * it loops over all fsrs in the cell to compute all reaction rates * and currents. * //NOTE : Expect a neutron imbalance : - in CMFD if there is CMFD relaxation * - in MOC (and CMFD) if using the newly computed source, which * is not converged with regards to group-to-group scattering * - in MOC at the boundaries, as the incoming currents are not * tallied (except at ite 0, they are null) * - in MOC at the reflective boundaries when tracks hit edges and * corners as the contributions are double tallied (not a bug, only * a problem for this routine, see NOTE for where to modify code) * @param pre_split whether edge currents are not split (default true) * @param moc_balance whether to check the MOC balance over the cell or * compare the MOC and CMFD imbalance (due to group to group scattering) */ void Cmfd::checkNeutronBalance(bool pre_split, bool moc_balance) { /* Print a few warnings on routine limitations (exhaustive in docstring) */ if (_geometry->isDomainDecomposed() && pre_split) log_printf(WARNING_ONCE, "MOC neutron balance is currently not checked " "correctly for domain decomposed geometries."); if (_relaxation_factor != 1.0) log_printf(WARNING_ONCE, "CMFD relaxation factor is not 1.0, expect CMFD " "vs MOC neutron imbalance after iteration 0."); if (moc_balance) log_printf(WARNING_ONCE, "MOC neutron imbalance is expected at the " "boundaries past the first iteration as incoming currents are " "not tallied."); /* Initialize variables */ omp_lock_t* cell_locks = _old_flux->getCellLocks(); int num_rows = _old_flux->getNumRows(); int num_x = _old_flux->getNumX(); int num_y = _old_flux->getNumY(); int num_z = _old_flux->getNumZ(); int num_groups = _old_flux->getNumGroups(); Vector m_phi(cell_locks, num_x, num_y, num_z, num_groups); Vector a_phi(cell_locks, num_x, num_y, num_z, num_groups); /* Compute CMFD balance */ /* Compute neutron production */ matrixMultiplication(_M, _old_flux, &m_phi); /* Compute neutron transfer and loss */ matrixMultiplication(_A, _old_flux, &a_phi); CMFD_PRECISION* a_phi_array = a_phi.getArray(); #ifdef MPIx if (_geometry->isDomainDecomposed()) { int* coupling_sizes = NULL; int** coupling_indexes = NULL; CMFD_PRECISION** coupling_coeffs = NULL; CMFD_PRECISION** coupling_fluxes = NULL; int offset = 0; for (int color=0; color < 2; color++) { getCouplingTerms(_domain_communicator, color, coupling_sizes, coupling_indexes, coupling_coeffs, coupling_fluxes, _old_flux->getArray(), offset); #pragma omp parallel for collapse(2) for (int iz=0; iz < _local_num_z; iz++) { for (int iy=0; iy < _local_num_y; iy++) { for (int ix=(iy+iz+color+offset)%2; ix < _local_num_x; ix+=2) { int cell = (iz*_local_num_y + iy)*_local_num_x + ix; bool on_surface = (iz==0) || (iz==_local_num_z-1) || (iy==0) || (iy==_local_num_y-1) || (ix==0) || (ix==_local_num_x-1); for (int g=0; g < _num_cmfd_groups; g++) { int row = cell * _num_cmfd_groups + g; if (on_surface) { int row_surf = _domain_communicator->mapLocalToSurface[cell]; for (int i = 0; i < coupling_sizes[row_surf]; i++) { int idx = coupling_indexes[row_surf][i] * _num_cmfd_groups + g; int domain = _domain_communicator->domains[color][row_surf][i]; CMFD_PRECISION flux = coupling_fluxes[domain][idx]; a_phi_array[row] += coupling_coeffs[row_surf][i] * flux; } } } } } } } } #endif int num_imbalanced = 0; double max_imbalance = 0.0; double max_imbalance_moc, max_imbalance_cmfd; int max_imbalance_cell = -1; int max_imbalance_grp = -1; /* Compute MOC balance */ /* Loop over CMFD cells */ for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { bool imbalance_reported = false; int x = (i % (_local_num_x * _local_num_y)) % _local_num_x; int y = (i % (_local_num_x * _local_num_y)) / _local_num_x; int z = i / (_local_num_x * _local_num_y); Material* cell_material = _materials[i]; /* Loop over CMFD coarse energy groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Initialize tallies */ double total = 0.0; double in_scattering = 0.0; double fission = 0.0; /* Loop over FSRs in CMFD cell */ for (int j = 0; j < _cell_fsrs.at(i).size(); j++) { long fsr_id = _cell_fsrs.at(i).at(j); Material* fsr_material = _FSR_materials[fsr_id]; FP_PRECISION volume = _FSR_volumes[fsr_id]; FP_PRECISION* scat = fsr_material->getSigmaS(); FP_PRECISION* flux = &_FSR_fluxes[fsr_id*_num_moc_groups]; /* Loop over MOC energy groups within this CMFD coarse group */ double chi = 0.0; for (int h = _group_indices[e]; h < _group_indices[e+1]; h++) chi += fsr_material->getChiByGroup(h+1); /* Use new fluxes to compute the source terms */ if (!moc_balance) { /* Calculate total fission and in-scattering in the FSR */ double tot_fission = 0.0; for (int g = 0; g < _num_moc_groups; g++) { /* Tally total fission */ double nu_fis = fsr_material->getNuSigmaFByGroup(g+1); tot_fission += nu_fis * flux[g] * volume; /* Loop over MOC energy groups within this CMFD coarse group */ for (int h = _group_indices[e]; h < _group_indices[e+1]; h++) in_scattering += scat[h*_num_moc_groups + g] * flux[g] * volume; } /* Calculate fission contribution to this CMFD coarse group */ fission += chi * tot_fission / _k_eff; } /* Use the old MOC source to check neutron balance */ else { in_scattering = 0.0; // for convenience fission += _FSR_sources[fsr_id*_num_moc_groups + e] * volume * FOUR_PI; } /* Calculate total reaction rate in this CMFD coarse group */ for (int h = _group_indices[e]; h < _group_indices[e+1]; h++) { double tot = fsr_material->getSigmaTByGroup(h+1); total += tot * flux[h] * volume; } } /* Calculate net current out of the cell */ double net_current = 0.0; /* Use currents before splitting edges/corners if requested */ if (pre_split) { /* Create arrays of cell indexes and bounds */ int cell_limits[3] = {_local_num_x, _local_num_y, _local_num_z}; int cell_ind[3]; cell_ind[0] = i % _local_num_x; cell_ind[1] = (i / _local_num_x) % _local_num_y; cell_ind[2] = i / (_local_num_x * _local_num_y); /* Tally current from all surfaces including edges and corners */ for (int s=0; s < NUM_SURFACES; s++) { /* Compute index and vector direction */ int idx = s * _num_cmfd_groups + e; int direction[3]; convertSurfaceToDirection(s, direction); /* Compute the next CMFD cell from the cell indexes and direction */ int cmfd_cell_next = 0; int cell_next_ind[3]; for (int d=0; d < 3; d++) cell_next_ind[d] = cell_ind[d] + direction[d]; cmfd_cell_next = cell_next_ind[0] + cell_next_ind[1] * _local_num_x + cell_next_ind[2] * (_local_num_x * _local_num_y); /* Compute the opposite direction vector */ int op_direction[3]; for (int d=0; d < 3; d++) op_direction[d] = -1 * direction[d]; /* Determine if the next CMFD cell is within the bounds */ for (int d=0; d < 3; d++) if (cell_next_ind[d] < 0 || cell_next_ind[d] >= cell_limits[d]) cmfd_cell_next = -1; /* If the cell is outside the bounds, handle boundaries */ if (cmfd_cell_next == -1) { /* Booleans for determining surface boundary type */ bool vacuum = false; bool reflective = false; bool transmit_avail = false; int transmit_direction[3] = {0,0,0}; /* Loop over all directions to handle boundaries */ for (int d=0; d < 3; d++) { if (cell_next_ind[d] < 0 || cell_next_ind[d] >= cell_limits[d]) { /* Form the surface for each direction */ int partial_direction[3] = {0,0,0}; partial_direction[d] = direction[d]; int partial_surface = convertDirectionToSurface(partial_direction); /* Look at the boundary type in this direction */ if (_boundaries[partial_surface] == VACUUM) { vacuum = true; } else if (_boundaries[partial_surface] == REFLECTIVE) { reflective = true; op_direction[d] *= -1; } } /* For non-boundary surfaces, save the direction */ else if (direction[d] != 0) { transmit_avail = true; transmit_direction[d] = direction[d]; } } /* For vacuum boundaries, tally the leakage */ if (vacuum) net_current += _full_surface_currents->getValue(i, idx); /* For reflective boundaries, find the appropriate cell to deliver current if available */ else if (reflective && transmit_avail) { for (int d=0; d < 3; d++) cell_next_ind[d] = cell_ind[d] + transmit_direction[d]; cmfd_cell_next = cell_next_ind[0] + cell_next_ind[1] * _local_num_x + cell_next_ind[2] * (_local_num_x * _local_num_y); } } /* Transmit current to available cells */ if (cmfd_cell_next != -1) { int surface_next = convertDirectionToSurface(op_direction); int idx_next = surface_next * _num_cmfd_groups + e; net_current += _full_surface_currents->getValue(i, idx) - _full_surface_currents->getValue(cmfd_cell_next, idx_next); } } } /* Use post-split edges/corner currents if requested */ else { /* Tally current only over surface faces */ for (int s = 0; s < NUM_FACES; s++) { int idx = s * _num_cmfd_groups + e; int cmfd_cell_next = getCellNext(i, s, false); int surface_next = (s + NUM_FACES / 2) % NUM_FACES; int idx_next = surface_next * _num_cmfd_groups + e; /* Out of domain currents */ if (cmfd_cell_next == -1) { int i_global = getGlobalCMFDCell(i); int global_cmfd_cell_next = getCellNext(i_global, s); /* Currents at the geometry outer boundaries */ if ((global_cmfd_cell_next == -1 && _boundaries[s] == VACUUM) || (moc_balance)) net_current += _surface_currents->getValue(i, idx); //FIXME For moc_balance, this is correct at iteration 0 only /* Currents from other domains */ else if (global_cmfd_cell_next != -1) { int idx_off = _boundary_index_map.at(s)[global_cmfd_cell_next]; net_current += _surface_currents->getValue(i, idx) - _boundary_surface_currents[s][idx_off][surface_next* _num_cmfd_groups+e]; } } /* In-domain currents */ else net_current += _surface_currents->getValue(i, idx) - _surface_currents->getValue(cmfd_cell_next, idx_next); } } /* Compute balance in given cell and group */ double moc_balance = in_scattering + fission - total - net_current; double cmfd_balance = m_phi.getValue(i, e) / _k_eff - a_phi.getValue(i, e); double tmp_imbalance = std::abs(moc_balance); if (!moc_balance) tmp_imbalance = std::abs(moc_balance - cmfd_balance); if (tmp_imbalance > max_imbalance) { max_imbalance = tmp_imbalance; max_imbalance_moc = moc_balance; max_imbalance_cmfd = cmfd_balance; max_imbalance_cell = i; max_imbalance_grp = e; } /* Select appropriate level of numerical tolerance */ //NOTE Track angular fluxes being in single precision, double precision // neutron balance is not expected. #ifdef SINGLE FP_PRECISION tol = 5e-6; #else FP_PRECISION tol = 5e-7; #endif /* Report an abnormal neutron imbalance */ if (tmp_imbalance > tol) { /* Output an imbalance only once for all groups on log level INFO */ if (!imbalance_reported) { num_imbalanced++; log_printf(INFO, "Neutron imbalance in cell (%d, %d, %d) for CMFD " "group %d = MOC %g, CMFD %g, diff %g", x, y, z, e, moc_balance, cmfd_balance, moc_balance - cmfd_balance); } /* Output an imbalance for every group at log level DEBUG */ else log_printf(DEBUG, "Neutron imbalance in cell (%d, %d, %d) for CMFD " "group %d = MOC %g, CMFD %g, diff %g", x, y, z, e, moc_balance, cmfd_balance, moc_balance - cmfd_balance); imbalance_reported = true; } } } /* Output max imbalance in CMFD mesh */ int x = (max_imbalance_cell % (_local_num_x * _local_num_y)) % _local_num_x; int y = (max_imbalance_cell % (_local_num_x * _local_num_y)) / _local_num_x; int z = max_imbalance_cell / (_local_num_x * _local_num_y); if (moc_balance) { log_printf(NODAL, "Maximum neutron imbalance MOC %.2e (CMFD %.2e) at cell " "%i (%d %d %d) and group %d.", max_imbalance_moc, max_imbalance_cmfd, max_imbalance_cell, x, y, z, max_imbalance_grp); log_printf(NODAL, "%d CMFD cells report a MOC neutron imbalance", num_imbalanced); } else { log_printf(NODAL, "Maximum neutron imbalance between MOC and CMFD : %.2e " "(MOC %.2e CMFD %.2e) at cell %i (%d %d %d) and group %d.", max_imbalance_moc - max_imbalance_cmfd, max_imbalance_moc, max_imbalance_cmfd, max_imbalance_cell, x, y, z, max_imbalance_grp); log_printf(NODAL, "%d CMFD cells report a neutron imbalance between MOC " "and CMFD", num_imbalanced); } } /** * @brief Returns the color of a CMFD cell in the red/black SOR solver * @param cmfd_cell The cmfd cell's global ID */ int Cmfd::getCellColor(int cmfd_cell) { int ix = cmfd_cell % _num_x; int iy = (cmfd_cell % (_num_x * _num_y)) / _num_x; int iz = cmfd_cell / (_num_x * _num_y); int color = (ix + iy + iz) % 2; return color; } /** * @brief Packs reaction rates and currents into buffers for communication. * @details Buffer description is found in ghostCellExchange's docstring */ #ifdef MPIx void Cmfd::packBuffers() { int current_idx[6] = {0,0,0,0,0,0}; bool found_surfaces[NUM_FACES]; for (int z=0; z < _local_num_z; z++) { for (int y=0; y < _local_num_y; y++) { for (int x=0; x < _local_num_x; x++) { for (int s=0; s < NUM_FACES; s++) found_surfaces[s] = false; /* Check that cell is at a boundary */ if (x == 0) found_surfaces[SURFACE_X_MIN] = true; if (x == _local_num_x-1) found_surfaces[SURFACE_X_MAX] = true; if (y == 0) found_surfaces[SURFACE_Y_MIN] = true; if (y == _local_num_y-1) found_surfaces[SURFACE_Y_MAX] = true; if (z == 0) found_surfaces[SURFACE_Z_MIN] = true; if (z == _local_num_z-1) found_surfaces[SURFACE_Z_MAX] = true; /* Fill buffers with tallies */ for (int s=0; s < NUM_FACES; s++) { if (found_surfaces[s]) { int idx = current_idx[s]; int cell_id = ((z * _local_num_y) + y) * _local_num_x + x; _send_volumes[s][idx][0] = _volume_tally[cell_id][0]; for (int e=0; e < _num_cmfd_groups; e++) { _send_reaction[s][idx][e] = _reaction_tally[cell_id][e]; _send_diffusion[s][idx][e] = _diffusion_tally[cell_id][e]; for (int f=0; f < NUM_FACES; f++) { _send_currents[s][idx][f*_num_cmfd_groups + e] = _surface_currents->getValue(cell_id, f*_num_cmfd_groups+e); } } current_idx[s]++; } } } } } } /** * @brief Exchanges ghost cell buffers in 3D cartesian (i.e., 6 directions) * @details comm The cartesian MPI domain communicator object that is * configured for the CMFD exchange * send_buffers A 2D array of floating point data. The outer dimension * corresponds to each face of the domain, while the inner dimension * is the serialized buffer corresponding to the number of 2D cells * to exchange times the number of energy groups. * recv_buffers A 2D array of floating point data. The outer dimension * corresponds to each face of the domain, while the inner dimension * is the serialized buffer corresponding to the number of 2D cells to * exchange times the number of energy groups. */ void Cmfd::ghostCellExchange() { packBuffers(); MPI_Request requests[2*NUM_FACES]; MPI_Datatype precision; if (sizeof(CMFD_PRECISION) == 4) precision = MPI_FLOAT; else precision = MPI_DOUBLE; int storage_per_cell = ((2 + NUM_FACES) * _num_cmfd_groups + 1); int sizes[NUM_FACES]; for (int coord=0; coord < 3; coord++) { for (int d=0; d<2; d++) { int dir = 2*d - 1; int surf = coord + 3*d; int op_surf = surf - 3*dir; int source, dest; // Figure out serialized buffer length for this face int size = 0; if (surf == SURFACE_X_MIN) { size = _local_num_y * _local_num_z * storage_per_cell; } else if (surf == SURFACE_X_MAX) { size = _local_num_y * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Y_MIN) { size = _local_num_x * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Y_MAX) { size = _local_num_x * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Z_MIN) { size = _local_num_x * _local_num_y * storage_per_cell; } else if (surf == SURFACE_Z_MAX) { size = _local_num_x * _local_num_y * storage_per_cell; } sizes[surf] = size; /* Get ranks of source and destination domains, using the cartesian structure of the domain decomposition */ MPI_Cart_shift(_domain_communicator->_MPI_cart, coord, dir, &source, &dest); // Post send MPI_Isend(_send_data_by_surface[surf], size, precision, dest, 0, _domain_communicator->_MPI_cart, &requests[2*surf]); // Post receive MPI_Irecv(_domain_data_by_surface[op_surf], size, precision, source, 0, _domain_communicator->_MPI_cart, &requests[2*surf+1]); } } // Block for communication round to complete MPI_Waitall(12, requests, MPI_STATUSES_IGNORE); } /** * @brief Communicate split (at corners and edges) currents (respectively edge * and face currents) to other domains. * @param faces whether the currents are for edges or faces, for unpacking */ void Cmfd::communicateSplits(bool faces) { //TODO: Form into communicateEdgeCurrents and communicateFaceCurrents // 1. communicate edge currents use array of length NUM_EDGES, called after // vertex splits // 2. communicate face currents use array of length NUM_FACES, called after // edge splits // NOTE: only communicate currents that are saved OFF DOMAIN at each step // NOTE: communicateFaceCurrents will use currents formed from vertex splits MPI_Request requests[2*NUM_FACES]; MPI_Datatype precision; if (sizeof(CMFD_PRECISION) == 4) precision = MPI_FLOAT; else precision = MPI_DOUBLE; int storage_per_cell = (NUM_FACES + NUM_EDGES) * _num_cmfd_groups; int sizes[NUM_FACES]; for (int coord=0; coord < 3; coord++) { for (int d=0; d<2; d++) { int dir = 2*d-1; int surf = coord + 3*d; int op_surf = surf - 3*dir; int source, dest; // Figure out serialized buffer length for this face int size = 0; if (surf == SURFACE_X_MIN) { size = _local_num_y * _local_num_z * storage_per_cell; } else if (surf == SURFACE_X_MAX) { size = _local_num_y * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Y_MIN) { size = _local_num_x * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Y_MAX) { size = _local_num_x * _local_num_z * storage_per_cell; } else if (surf == SURFACE_Z_MIN) { size = _local_num_x * _local_num_y * storage_per_cell; } else if (surf == SURFACE_Z_MAX) { size = _local_num_x * _local_num_y * storage_per_cell; } sizes[surf] = size; MPI_Cart_shift(_domain_communicator->_MPI_cart, coord, dir, &source, &dest); // Post send MPI_Isend(_send_split_currents_array[surf], size, precision, dest, 0, _domain_communicator->_MPI_cart, &requests[2*surf]); // Post receive MPI_Irecv(_receive_split_currents_array[op_surf], size, precision, source, 0, _domain_communicator->_MPI_cart, &requests[2*surf+1]); } } // Block for communication round to complete MPI_Waitall(12, requests, MPI_STATUSES_IGNORE); unpackSplitCurrents(faces); } /** * @brief Unpacks communicated split current data * @param faces Whether to split the currents onto surface faces */ void Cmfd::unpackSplitCurrents(bool faces) { int current_idx[6] = {0,0,0,0,0,0}; bool found_surfaces[NUM_FACES]; /* Loop over all CMFD cells */ for (int z=0; z < _local_num_z; z++) { for (int y=0; y < _local_num_y; y++) { for (int x=0; x < _local_num_x; x++) { /* Look for boundaries touching the CMFD cell */ for (int s=0; s < NUM_FACES; s++) found_surfaces[s] = false; if (x == 0) found_surfaces[SURFACE_X_MIN] = true; if (x == _local_num_x-1) found_surfaces[SURFACE_X_MAX] = true; if (y == 0) found_surfaces[SURFACE_Y_MIN] = true; if (y == _local_num_y-1) found_surfaces[SURFACE_Y_MAX] = true; if (z == 0) found_surfaces[SURFACE_Z_MIN] = true; if (z == _local_num_z-1) found_surfaces[SURFACE_Z_MAX] = true; /* Handle all boundaries */ for (int s=0; s < NUM_FACES; s++) { if (found_surfaces[s]) { /* Convert the (x,y,z) indexes to a cell ID and boundary index */ int cell_id = ((z * _local_num_y) + y) * _local_num_x + x; int idx = current_idx[s]; /* Copy the appropriate face or edge information */ if (faces) { /* Treat CMFD cell face currents */ for (int f=0; f < NUM_FACES; f++) { for (int g=0; g < _num_cmfd_groups; g++) { /* Get the face current value */ CMFD_PRECISION value = _received_split_currents[s][idx][f * _num_cmfd_groups + g]; /* Treat nonzero values */ if (fabs(value) > FLUX_EPSILON) _surface_currents->incrementValue(cell_id, f * _num_cmfd_groups + g, value); } } } else { /* Treat CMFD cell edge currents */ for (int e=NUM_FACES; e < NUM_EDGES+NUM_FACES; e++) { int surf_idx = cell_id * NUM_SURFACES * _num_cmfd_groups + e * _num_cmfd_groups; for (int g=0; g < _num_cmfd_groups; g++) { /* Get the edge current value */ CMFD_PRECISION value = _received_split_currents[s][idx][e * _num_cmfd_groups + g]; /* Treat nonzero values */ if (fabs(value) > FLUX_EPSILON) { int new_ind = surf_idx + g; /* Add the contribution */ _edge_corner_currents[new_ind] += value; } } } } /* Increment the boundary index */ current_idx[s]++; } } } } } } #endif /** * @brief Converts a global CMFD cell ID into its local ID * @details Marked for deletion, but still used thoroughly. * @param cmfd_cell The global CMFD cell ID * @return The local CMFD cell ID, -1 if not in the domain. */ int Cmfd::getLocalCMFDCell(int cmfd_cell) { int x_start = 0; int y_start = 0; int z_start = 0; int x_end = _num_x; int y_end = _num_y; int z_end = _num_z; if (_geometry->isDomainDecomposed()) { if (_domain_communicator != NULL) { x_start = _accumulate_lmx[_domain_communicator->_domain_idx_x]; x_end = x_start + _local_num_x; y_start = _accumulate_lmy[_domain_communicator->_domain_idx_y]; y_end = y_start + _local_num_y; z_start = _accumulate_lmz[_domain_communicator->_domain_idx_z]; z_end = z_start + _local_num_z; } } int ix = (cmfd_cell % (_num_x * _num_y)) % _num_x; int iy = (cmfd_cell % (_num_x * _num_y)) / _num_x; int iz = cmfd_cell / (_num_x * _num_y); int local_cmfd_cell; if (ix >= x_start && ix < x_end && iy >= y_start && iy < y_end && iz >= z_start && iz < z_end) local_cmfd_cell = ((iz - z_start) * _local_num_y + iy - y_start) * _local_num_x + ix - x_start; else local_cmfd_cell = -1; return local_cmfd_cell; } /** * @brief Converts a 3 integer vector direction into a surface * @details The direction is a tuplet with each value taking either * +1 (positive directed), 0 (neutral), or -1 (negative directed) * @param direction The integer vector describing the direction * @return The surface associated with traveling the provided direction from * the origin of the cell */ int Cmfd::convertDirectionToSurface(int* direction) { int surface = 0; int num_crossings = std::abs(direction[0]) + std::abs(direction[1]) + std::abs(direction[2]); if (num_crossings == 1) { for (int i=0; i < 3; i++) { int present = std::abs(direction[i]); int fwd = (direction[i] + 1) / 2; surface += present * (3 * fwd + i); } } else if (num_crossings == 2) { surface += NUM_FACES; int ind1 = 0; int ind2 = 0; if (direction[0] == 0) { ind1 = direction[1]; ind2 = direction[2]; surface += 8; } else if (direction[1] == 0) { ind1 = direction[0]; ind2 = direction[2]; surface += 4; } else if (direction[2] == 0) { ind1 = direction[0]; ind2 = direction[1]; } ind1 = (ind1 + 1) / 2; ind2 = (ind2 + 1) / 2; surface += 2 * ind2 + ind1; } else if (num_crossings == 3) { surface += NUM_FACES + NUM_EDGES; int fwd[3]; for (int i=0; i < 3; i++) fwd[i] = (direction[i] + 1) / 2; surface += 4 * fwd[0] + 2 * fwd[1] + fwd[2]; } else { log_printf(ERROR, "Invalid number of surface crossings"); } return surface; } /** * @brief Converts a surface into a 3 integer vector direction * @details The direction is a tuplet with each value taking either * +1 (positive directed), 0 (neutral, or -1 (negative directed) * @param surface The surface of interest * @param direction The integer vector describing the direction */ void Cmfd::convertSurfaceToDirection(int surface, int* direction) { direction[0] = 0; direction[1] = 0; direction[2] = 0; if (surface < NUM_FACES) { int ind = surface % 3; int dir = 2 * (surface/3) - 1; direction[ind] = dir; } else if (surface < NUM_FACES + NUM_EDGES) { surface -= NUM_FACES; int group = surface / 4; int skipped = 2 - group; surface = surface % 4; int ind[2]; ind[0] = surface % 2; ind[1] = (surface - ind[0]) / 2; int n = 0; for (int i=0; i < 3; i++) { if (i != skipped) { direction[i] = 2 * ind[n] - 1; n++; } } } else if (surface < NUM_SURFACES) { surface -= NUM_FACES + NUM_EDGES; direction[0] = 2 * (surface / 4) - 1; direction[1] = 2 * ((surface / 2) % 2) - 1; direction[2] = 2 * (surface % 2) - 1; } else { log_printf(ERROR, "Invalid surface ID %d", surface); } } /** * @brief Returns the surface name associated with the 3 integer vector * direction * @details The direction is a tuplet with each value taking either * +1 (positive directed), 0 (neutral, or -1 (negative directed) * @param direction The integer vector describing the direction * @return A string containing the surface name */ std::string Cmfd::getSurfaceNameFromDirection(int* direction) { std::string str = "SURFACE"; std::string variables = "XYZ"; for (int i=0; i < 3; i++) { if (direction[i] != 0) { str += "_"; str += variables.at(i); if (direction[i] < 0) str += "_MIN"; else str += "_MAX"; } } return str; } /** * @brief Returns the surface name associated with a surface * @param surface The surface of interest * @return A string containing the surface name */ std::string Cmfd::getSurfaceNameFromSurface(int surface) { int direction[3]; convertSurfaceToDirection(surface, direction); return getSurfaceNameFromDirection(direction); } /** * @brief A debugging tool that prints all prolongation factors to file */ void Cmfd::printProlongationFactors() { /* Loop over CMFD groups */ for (int e = 0; e < _num_cmfd_groups; e++) { /* Create arrays for spatial data */ CMFD_PRECISION log_ratios[_num_x * _num_y * _num_z]; for (int i = 0; i < _num_x * _num_y * _num_z; i++) log_ratios[i] = 0.0; for (int i = 0; i < _local_num_x * _local_num_y * _local_num_z; i++) { double old_flux = _old_flux->getValue(i, e); double new_flux = _new_flux->getValue(i, e); int cell_id = getGlobalCMFDCell(i); log_ratios[cell_id] = log(new_flux/old_flux); } #ifdef MPIx if (_geometry->isDomainDecomposed()) { CMFD_PRECISION temp_log_ratios[_num_x * _num_y * _num_z]; /* Select appropriate floating point size for transfer */ MPI_Datatype mpi_precision; if (sizeof(FP_PRECISION) == 4) mpi_precision = MPI_FLOAT; else mpi_precision = MPI_DOUBLE; for (int i = 0; i < _num_x * _num_y * _num_z; i++) temp_log_ratios[i] = log_ratios[i]; MPI_Allreduce(temp_log_ratios, log_ratios, _num_x * _num_y * _num_z, mpi_precision, MPI_SUM, _geometry->getMPICart()); } #endif /* Print prolongation factors distribution to file */ if (_geometry->isRootDomain()) { long long iter = _moc_iteration; long long group = e; std::string fname = "pf_group_"; std::string group_num = std::to_string(group); std::string iter_num = std::to_string(iter); fname += group_num; fname += "_iter_"; fname += iter_num; fname += ".txt"; std::ofstream out(fname); out<< std::setprecision(5); out << "[NORMAL] Spatial distribution of prolongation factors:" << std::endl; for (int z=0; z < _num_z; z++) { out << " -------- z = " << z << " ----------" << std::endl; for (int y=0; y < _num_y; y++) { for (int x=0; x < _num_x; x++) { int ind = (z * _num_y + y) * _num_x + x; out << log_ratios[ind] << " "; } out << std::endl; } } out.close(); } } } /** * @brief This function tallies the current impinging on the domain from * starting fluxes * @details Incoming currents are tallied for use in diagnostics, debugging, * and adjusting sigma-t to enforce consistency with the MOC solution, * if requested * @param point The point where the fluxes enter the geometry * @param delta_x The a small x-nudge in the direction of travel * @param delta_y The a small y-nudge in the direction of travel * @param delta_z The a small z-nudge in the direction of travel * @param track_flux The angular fluxes impinging on the domain * @param weight The weight of the Track */ void Cmfd::tallyStartingCurrent(Point* point, double delta_x, double delta_y, double delta_z, float* track_flux, double weight) { /* Check for non-zero current */ bool non_zero = false; for (int e=0; e < _num_moc_groups; e++) { if (fabs(track_flux[e]) > 0) { non_zero = true; break; } } if (!non_zero) return; /* Create local coordinate */ LocalCoords coords; coords.setUniverse(_geometry->getRootUniverse()); coords.setX(point->getX()); coords.setY(point->getY()); coords.setZ(point->getZ()); /* Find the CMFD cell */ coords.adjustCoords(delta_x, delta_y, delta_z); int cell = findCmfdCell(&coords); coords.adjustCoords(-delta_x, -delta_y, -delta_z); /* Check the CMFD cell */ if (cell == -1) log_printf(ERROR, "Failed to find starting CMFD cell for track start " "point"); int cell_x = cell % _local_num_x; int cell_y = (cell % (_local_num_x * _local_num_y)) / _local_num_x; int cell_z = cell / (_local_num_x * _local_num_y); int bounds[3]; bool singular[3] = {_local_num_x == 1, _local_num_y == 1, _local_num_z == 1}; bounds[0] = -1 * (cell_x == 0) + (cell_x == _local_num_x-1); bounds[1] = -1 * (cell_y == 0) + (cell_y == _local_num_y-1); bounds[2] = -1 * (cell_z == 0) + (cell_z == _local_num_z-1); if ((bounds[0] == 0 && !singular[0]) && (bounds[1] == 0 && !singular[1]) && (bounds[2] == 0 && !singular[2])) log_printf(ERROR, "Track start point not on a boundary CMFD cell. " "Cell = %d (%d, %d, %d) from Track: (%3.2f, %3.2f, %3.2f) " "adjusted (%3.2e, %3.2e, %3.2e)", cell, cell_x, cell_y, cell_z, point->getX(), point->getY(), point->getZ(), delta_x, delta_y, delta_z); CMFD_PRECISION currents[_num_cmfd_groups] __attribute__ ((aligned(VEC_ALIGNMENT))); memset(currents, 0, _num_cmfd_groups * sizeof(CMFD_PRECISION)); /* Tally currents to each CMFD group locally */ for (int e=0; e < _num_moc_groups; e++) { /* Get the CMFD group */ int cmfd_group = getCmfdGroup(e); /* Increment the surface group */ currents[cmfd_group] += track_flux[e] * weight; } /* Tally starting currents to cell */ _starting_currents->incrementValues(cell, 0, _num_cmfd_groups - 1, currents); } /** * @brief Records net currents (leakage) on every CMFD cell for every group */ void Cmfd::recordNetCurrents() { #pragma omp parallel for for (int i=0; i < _local_num_x * _local_num_y * _local_num_z; i++) { for (int e=0; e < _num_cmfd_groups; e++) _net_currents->incrementValue(i, e, -1 * _starting_currents->getValue(i,e)); /* Compute cell indexes */ int cell_ind[3]; cell_ind[0] = i % _local_num_x; cell_ind[1] = (i / _local_num_x) % _local_num_y; cell_ind[2] = i / (_local_num_x * _local_num_y); /* Tally current from all surfaces including edges and corners */ for (int s=0; s < NUM_SURFACES; s++) { /* Check if edge/corner exists */ if (s >= NUM_FACES) { int idx = i * NUM_SURFACES * _num_cmfd_groups + s * _num_cmfd_groups; std::map<int, CMFD_PRECISION>::iterator it = _edge_corner_currents.find(idx); if (it == _edge_corner_currents.end()) continue; } /* Compute index and vector direction */ int direction[3]; convertSurfaceToDirection(s, direction); /* Compute the next CMFD cell from the cell indexes and direction */ int cmfd_cell_next = 0; int cell_next_ind[3]; for (int d=0; d < 3; d++) cell_next_ind[d] = cell_ind[d] + direction[d]; cmfd_cell_next = cell_next_ind[0] + cell_next_ind[1] * _local_num_x + cell_next_ind[2] * (_local_num_x * _local_num_y); if (cell_next_ind[0] < 0 || cell_next_ind[0] >= _local_num_x || cell_next_ind[1] < 0 || cell_next_ind[1] >= _local_num_y || cell_next_ind[2] < 0 || cell_next_ind[2] >= _local_num_z) cmfd_cell_next = -1; /* Tally net currents */ if (s < NUM_FACES) { int idx = s * _num_cmfd_groups; for (int e=0; e < _num_cmfd_groups; e++) { double current = 1 * _surface_currents->getValue(i, idx+e); _net_currents->incrementValue(i, e, current); } if (cmfd_cell_next != -1) { for (int e=0; e < _num_cmfd_groups; e++) { double current = -1 * _surface_currents->getValue(i, idx+e); _net_currents->incrementValue(cmfd_cell_next, e, current); } } } else { int idx = i * NUM_SURFACES * _num_cmfd_groups + s * _num_cmfd_groups; for (int e=0; e < _num_cmfd_groups; e++) { double current = _edge_corner_currents.at(idx+e); _net_currents->incrementValue(i, e, current); } if (cmfd_cell_next != -1) { for (int e=0; e < _num_cmfd_groups; e++) { double current = -1 * _edge_corner_currents.at(idx+e); _net_currents->incrementValue(cmfd_cell_next, e, current); } } } } } } /** * @brief Set width of non-uniform meshes in x y z directions. * @details An example of how this may be called from Python illustrated below: * * @code * cmfd.setWidths([[1,2,3], [4,5,6,7], [3.3,2.4]]) * @endcode * * @param widths A vector of 3 vectors for the x y z sizes of non-uniform meshes */ void Cmfd::setWidths(std::vector< std::vector<double> > widths) { if (widths.size() == 3) _cell_widths_z = widths[2]; else if (widths.size() == 2) _cell_widths_z.push_back(1.0); else log_printf(ERROR, "CMFD lattice widths must have dimension 2 or 3."); _non_uniform = true; _cell_widths_x = widths[0]; _cell_widths_y = widths[1]; } /** * @brief Print information about CMFD cell dimensions. * @details For debug use. */ void Cmfd::printCmfdCellSizes() { int i; printf("non_uniform=%d, \nNum_XYZ: %2d, %2d, %2d\n", _non_uniform, _num_x, _num_y, _num_z); printf("Num_Local_XYZ: %2d, %2d, %2d\n", _local_num_x, _local_num_y, _local_num_z); printf("width_XYZ: %f, %f, %f\n", _width_x,_width_y,_width_z); printf("cell_width_XYZ: %f, %f, %f\n", _cell_width_x, _cell_width_y,_cell_width_z); printf("cell_widths_XYZ:\n"); for (i=0; i<_num_x; i++) printf("i=%d, %f; ",i, _cell_widths_x[i]); printf("\n"); for (i=0; i<_num_y; i++) printf("i=%d, %f; ",i, _cell_widths_y[i]); printf("\n"); for (i=0; i<_num_z; i++) printf("i=%d, %f; ",i, _cell_widths_z[i]); printf("\n"); printf("accumulates_XYZ:\n"); for (i=0; i<_num_x+1; i++) printf("i=%d, %f; ",i, _accumulate_x[i]); printf("\n"); for (i=0; i<_num_y+1; i++) printf("i=%d, %f; ",i, _accumulate_y[i]); printf("\n"); for (i=0; i<_num_z+1; i++) printf("i=%d, %f; ",i, _accumulate_z[i]); printf("\n"); } /** * @brief Create a string with information about the CMFD solver. * @details For pretty printing in Python API */ std::string Cmfd::toString() { std::stringstream message; message << "CMFD acceleration at " << (void*)this << std::endl; message << "Mesh in XYZ: [" << _num_x << ", " << _num_y << ", " << _num_z; message << "]" << std::endl; message << "Condensing " << _num_moc_groups << " MOC groups to " << _num_cmfd_groups << " CMFD groups"; return message.str(); }
34.559772
93
0.622556
AI-Pranto
1552378da34476a34fdfd3a8c2c03f900a09baa3
44
hh
C++
include/trick/compat/sim_services/DMTCP/include/dmtcp_checkpoint_c_intf.hh
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
1
2021-01-17T21:02:33.000Z
2021-01-17T21:02:33.000Z
include/trick/compat/sim_services/DMTCP/include/dmtcp_checkpoint_c_intf.hh
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
null
null
null
include/trick/compat/sim_services/DMTCP/include/dmtcp_checkpoint_c_intf.hh
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
3
2021-06-22T11:02:39.000Z
2021-10-21T00:58:00.000Z
#include "trick/dmtcp_checkpoint_c_intf.hh"
22
43
0.840909
gilbertguoze
1554fd5d21463a2a7b8ec2921d65099c3e46beaa
2,953
cc
C++
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
#include "LoggerTest.h" #include <Logger> #include <sstream> using namespace hslib; class StringBufferAppender : public Appender { private: std::stringstream buffer; public: StringBufferAppender() : Appender(), buffer() { } StringBufferAppender(const StringBufferAppender& copy) : Appender(copy), buffer() { } virtual const size_t log(const LoggingEvent& event) { PatternLayout p(getLayout()); const std::string formatted = p.format(event); buffer << formatted; return formatted.length(); } const std::string str() { return buffer.str(); } }; void LoggerTest::testCtorArgs() { Logger logger("testCtorArgs"); } void LoggerTest::testCtorCopy() { Logger logger("testCtorCopy"); Logger copy(logger); CPPUNIT_ASSERT("testCtorCopy" == copy.getName()); } void LoggerTest::testAssignment() { Logger logger("testAssignment"); Logger copy = logger; CPPUNIT_ASSERT("testAssignment" == logger.getName()); } void LoggerTest::testGetName() { Logger logger("testGetName"); CPPUNIT_ASSERT("testGetName" == logger.getName()); } void LoggerTest::testGetMinimumLevel() { Logger logger("testGetMinimumLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); } void LoggerTest::testSetMinimumLevel() { Logger logger("testGetMinimumLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); logger.setMinimumLevel(Level::FATAL); CPPUNIT_ASSERT(Level::FATAL == logger.getMinimumLevel()); } void LoggerTest::testAddAppender() { StringBufferAppender ap; Logger logger("testAddAppender"); std::list<Appender*> a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 0); logger.addAppender(&ap); a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 1); } void LoggerTest::testGetAppenders() { StringBufferAppender ap; Logger logger("testGetAppenders"); std::list<Appender*> a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 0); logger.addAppender(&ap); a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 1); } void LoggerTest::testLog() { StringBufferAppender ap; Logger logger("testLog"); logger.addAppender(&ap); LoggingEvent event = LOGGING_EVENT(Level::INFO, "test"); logger.log(event); CPPUNIT_ASSERT("test\n" == ap.str()); } void LoggerTest::testOpLevel() { Logger logger("testOpLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); logger << Level::FATAL; CPPUNIT_ASSERT(Level::FATAL == logger.getMinimumLevel()); } void LoggerTest::testOpLoggingEvent() { StringBufferAppender ap; Logger logger("testLog"); logger.addAppender(&ap); LoggingEvent event = LOGGING_EVENT(Level::INFO, "test"); logger << Level::TRACE << event; CPPUNIT_ASSERT(ap.str().empty()); logger << Level::OFF << event; CPPUNIT_ASSERT("test\n" == ap.str()); }
25.678261
93
0.66678
marcbejerano