hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
438259b7ce4d2bd4fbc36998be6190d0edf9fefd | 4,087 | cc | C++ | mindspore/ccsrc/backend/optimizer/ascend/ir_fission/bce_with_logits_loss_fission.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 1 | 2021-12-27T13:42:29.000Z | 2021-12-27T13:42:29.000Z | mindspore/ccsrc/backend/optimizer/ascend/ir_fission/bce_with_logits_loss_fission.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/optimizer/ascend/ir_fission/bce_with_logits_loss_fission.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "backend/optimizer/ascend/ir_fission/bce_with_logits_loss_fission.h"
#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include "utils/utils.h"
#include "utils/ms_context.h"
#include "backend/optimizer/common/helper.h"
#include "backend/session/anf_runtime_algorithm.h"
#include "utils/trace_base.h"
namespace mindspore {
namespace opt {
AnfNodePtr BCEWithLogitsLossFission::AddReduceNode(const FuncGraphPtr &func_graph, const AnfNodePtr &node) const {
MS_EXCEPTION_IF_NULL(func_graph);
MS_EXCEPTION_IF_NULL(node);
auto cnode = node->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(cnode);
// Copy a new sigmoid node, shape of output is the same as input
std::vector<AnfNodePtr> new_simoid_inputs = {
NewValueNode(std::make_shared<Primitive>(prim::kPrimBCEWithLogitsLoss->name()))};
new_simoid_inputs.insert(new_simoid_inputs.end(), cnode->inputs().begin() + 1, cnode->inputs().end());
CNodePtr new_cnode = NewCNode(new_simoid_inputs, func_graph);
MS_EXCEPTION_IF_NULL(new_cnode);
auto predict_input = cnode->inputs()[kIndex1];
auto new_node_dtype = {AnfAlgo::GetOutputInferDataType(predict_input, 0)};
auto new_node_shape = {AnfAlgo::GetOutputInferShape(predict_input, 0)};
AnfAlgo::SetOutputInferTypeAndShape(new_node_dtype, new_node_shape, new_cnode.get());
// Add reduce node
string reduction = AnfAlgo::GetNodeAttr<std::string>(node, kAttrReduction);
MS_LOG(INFO) << "Create reduce node, reduction attr is: " << reduction;
std::vector<AnfNodePtr> reduce_inputs;
if (reduction == "sum") {
reduce_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReduceSum->name())), new_cnode};
} else if (reduction == "mean") {
reduce_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReduceMean->name())), new_cnode};
} else {
MS_LOG(INFO) << "Reduction attr is not mean or sum, can not do fission.";
return nullptr;
}
auto reduce_node = NewCNode(reduce_inputs, func_graph);
MS_EXCEPTION_IF_NULL(reduce_node);
auto type = AnfAlgo::GetOutputInferDataType(node, 0);
if (type == kNumberTypeFloat16) {
type = kNumberTypeFloat32;
}
auto shape = {AnfAlgo::GetOutputInferShape(node, 0)};
AnfAlgo::SetOutputInferTypeAndShape({type}, shape, reduce_node.get());
AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(std::vector<int64_t>{}), reduce_node);
AnfAlgo::SetNodeAttr("keep_dims", MakeValue(false), reduce_node);
AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), reduce_node);
reduce_node->set_scope(cnode->scope());
return reduce_node;
}
const BaseRef BCEWithLogitsLossFission::DefinePattern() const {
VarPtr Xs = std::make_shared<SeqVar>();
MS_EXCEPTION_IF_NULL(Xs);
return VectorRef({prim::kPrimBCEWithLogitsLoss, Xs});
}
const AnfNodePtr BCEWithLogitsLossFission::Process(const FuncGraphPtr &func_graph, const AnfNodePtr &node,
const EquivPtr &) const {
MS_EXCEPTION_IF_NULL(func_graph);
MS_EXCEPTION_IF_NULL(node);
auto cnode = node->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(cnode);
if (GetBoolAttr(cnode, kAttrVisited)) {
return nullptr;
}
AnfAlgo::SetNodeAttr(kAttrVisited, MakeValue(true), node);
if (cnode->inputs().size() == 0) {
return nullptr;
}
if (!AnfAlgo::HasNodeAttr("reduction", cnode)) {
MS_LOG(INFO) << "Has no reduction attr.";
return nullptr;
}
return AddReduceNode(func_graph, node);
}
} // namespace opt
} // namespace mindspore
| 41.282828 | 114 | 0.73379 | [
"shape",
"vector"
] |
4394949f965e82e98b9934d5d48c629017b6c384 | 5,725 | cc | C++ | modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc | laloli/webrtc_src | 2a4d70cc93ddd3074e51c0a2c2de507ac6babc2a | [
"DOC",
"BSD-3-Clause"
] | 6 | 2020-03-18T08:21:45.000Z | 2021-02-06T14:37:57.000Z | modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc | modulesio/webrtc | ea143e774b4c00a74b617f272f5a8f71169cf24e | [
"DOC",
"BSD-3-Clause"
] | 1 | 2018-02-09T17:31:28.000Z | 2018-02-25T14:28:10.000Z | modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc | modulesio/webrtc | ea143e774b4c00a74b617f272f5a8f71169cf24e | [
"DOC",
"BSD-3-Clause"
] | 3 | 2018-07-23T04:52:42.000Z | 2021-12-18T07:37:15.000Z | /*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/audio_codecs/opus/audio_decoder_opus.h"
#include "api/audio_codecs/opus/audio_encoder_opus.h"
#include "common_audio/include/audio_util.h"
#include "common_audio/lapped_transform.h"
#include "common_audio/window_generator.h"
#include "modules/audio_coding/neteq/tools/audio_loop.h"
#include "test/field_trial.h"
#include "test/gtest.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
namespace {
constexpr size_t kNumChannels = 1u;
constexpr int kSampleRateHz = 48000;
constexpr size_t kMaxLoopLengthSamples = kSampleRateHz * 50; // 50 seconds.
constexpr size_t kInputBlockSizeSamples = 10 * kSampleRateHz / 1000; // 10 ms
constexpr size_t kOutputBlockSizeSamples = 20 * kSampleRateHz / 1000; // 20 ms
constexpr size_t kFftSize = 1024;
constexpr size_t kNarrowbandSize = 4000 * kFftSize / kSampleRateHz;
constexpr float kKbdAlpha = 1.5f;
class PowerRatioEstimator : public LappedTransform::Callback {
public:
PowerRatioEstimator() : low_pow_(0.f), high_pow_(0.f) {
WindowGenerator::KaiserBesselDerived(kKbdAlpha, kFftSize, window_);
transform_.reset(new LappedTransform(kNumChannels, 0u,
kInputBlockSizeSamples, window_,
kFftSize, kFftSize / 2, this));
}
void ProcessBlock(float* data) { transform_->ProcessChunk(&data, nullptr); }
float PowerRatio() { return high_pow_ / low_pow_; }
protected:
void ProcessAudioBlock(const std::complex<float>* const* input,
size_t num_input_channels,
size_t num_freq_bins,
size_t num_output_channels,
std::complex<float>* const* output) override {
float low_pow = 0.f;
float high_pow = 0.f;
for (size_t i = 0u; i < num_input_channels; ++i) {
for (size_t j = 0u; j < kNarrowbandSize; ++j) {
float low_mag = std::abs(input[i][j]);
low_pow += low_mag * low_mag;
float high_mag = std::abs(input[i][j + kNarrowbandSize]);
high_pow += high_mag * high_mag;
}
}
low_pow_ += low_pow / (num_input_channels * kFftSize);
high_pow_ += high_pow / (num_input_channels * kFftSize);
}
private:
std::unique_ptr<LappedTransform> transform_;
float window_[kFftSize];
float low_pow_;
float high_pow_;
};
float EncodedPowerRatio(AudioEncoder* encoder,
AudioDecoder* decoder,
test::AudioLoop* audio_loop) {
// Encode and decode.
uint32_t rtp_timestamp = 0u;
constexpr size_t kBufferSize = 500;
rtc::Buffer encoded(kBufferSize);
std::vector<int16_t> decoded(kOutputBlockSizeSamples);
std::vector<float> decoded_float(kOutputBlockSizeSamples);
AudioDecoder::SpeechType speech_type = AudioDecoder::kSpeech;
PowerRatioEstimator power_ratio_estimator;
for (size_t i = 0; i < 1000; ++i) {
encoded.Clear();
AudioEncoder::EncodedInfo encoder_info =
encoder->Encode(rtp_timestamp, audio_loop->GetNextBlock(), &encoded);
rtp_timestamp += kInputBlockSizeSamples;
if (encoded.size() > 0) {
int decoder_info = decoder->Decode(
encoded.data(), encoded.size(), kSampleRateHz,
decoded.size() * sizeof(decoded[0]), decoded.data(), &speech_type);
if (decoder_info > 0) {
S16ToFloat(decoded.data(), decoded.size(), decoded_float.data());
power_ratio_estimator.ProcessBlock(decoded_float.data());
}
}
}
return power_ratio_estimator.PowerRatio();
}
} // namespace
TEST(BandwidthAdaptationTest, BandwidthAdaptationTest) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-AdjustOpusBandwidth/Enabled/");
constexpr float kMaxNarrowbandRatio = 0.003f;
constexpr float kMinWidebandRatio = 0.03f;
// Create encoder.
AudioEncoderOpusConfig enc_config;
enc_config.bitrate_bps = rtc::Optional<int>(7999);
enc_config.num_channels = kNumChannels;
constexpr int payload_type = 17;
auto encoder = AudioEncoderOpus::MakeAudioEncoder(enc_config, payload_type);
// Create decoder.
AudioDecoderOpus::Config dec_config;
dec_config.num_channels = kNumChannels;
auto decoder = AudioDecoderOpus::MakeAudioDecoder(dec_config);
// Open speech file.
const std::string kInputFileName =
webrtc::test::ResourcePath("audio_coding/speech_mono_32_48kHz", "pcm");
test::AudioLoop audio_loop;
EXPECT_EQ(kSampleRateHz, encoder->SampleRateHz());
ASSERT_TRUE(audio_loop.Init(kInputFileName, kMaxLoopLengthSamples,
kInputBlockSizeSamples));
EXPECT_LT(EncodedPowerRatio(encoder.get(), decoder.get(), &audio_loop),
kMaxNarrowbandRatio);
encoder->OnReceivedTargetAudioBitrate(9000);
EXPECT_LT(EncodedPowerRatio(encoder.get(), decoder.get(), &audio_loop),
kMaxNarrowbandRatio);
encoder->OnReceivedTargetAudioBitrate(9001);
EXPECT_GT(EncodedPowerRatio(encoder.get(), decoder.get(), &audio_loop),
kMinWidebandRatio);
encoder->OnReceivedTargetAudioBitrate(8000);
EXPECT_GT(EncodedPowerRatio(encoder.get(), decoder.get(), &audio_loop),
kMinWidebandRatio);
encoder->OnReceivedTargetAudioBitrate(12001);
EXPECT_GT(EncodedPowerRatio(encoder.get(), decoder.get(), &audio_loop),
kMinWidebandRatio);
}
} // namespace webrtc
| 37.664474 | 79 | 0.700262 | [
"vector"
] |
4396d5c0cc593f1aeb937be960d65a716da5237f | 761 | hpp | C++ | src/prx/simulation/collision_checking/collision_checker.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 3 | 2021-05-31T11:28:03.000Z | 2021-05-31T13:49:30.000Z | src/prx/simulation/collision_checking/collision_checker.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 1 | 2021-09-03T09:39:32.000Z | 2021-12-10T22:17:56.000Z | src/prx/simulation/collision_checking/collision_checker.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 2 | 2021-09-03T09:17:45.000Z | 2021-10-04T15:52:58.000Z | #pragma once
#include "prx/simulation/plant.hpp"
// #ifndef BULLET_NOT_BUILT
// #include "prx/bullet_sim/plants/bullet_plant.hpp"
// #endif
#include "prx/simulation/collision_checking/collision_group.hpp"
#include "prx/utilities/defs.hpp"
#include <unordered_map>
namespace prx
{
class collision_checker_t
{
public:
collision_checker_t();
virtual ~collision_checker_t();
virtual void add_collision_group(const std::string& group_name, const std::vector<system_ptr_t>& in_plants,const std::vector<std::shared_ptr<movable_object_t>>& in_obstacles);
std::shared_ptr<collision_group_t> get_collision_group(const std::string& group_name);
protected:
std::unordered_map<std::string,std::shared_ptr<collision_group_t>> collision_groups;
};
}
| 25.366667 | 177 | 0.777924 | [
"vector"
] |
439ab1b7114d5ccb349a0a76e5b4731b5799909a | 1,943 | cpp | C++ | Bots/C/AI_Template/src/GoalDodgePosition.cpp | lamhoangtung/AI-Tank-Contest | 89b3804368d1b378e8ea350cee7b45bf49c3aa5e | [
"MIT"
] | 4 | 2018-05-14T18:18:40.000Z | 2020-07-21T02:45:27.000Z | Bots/C/AI_Template/src/GoalDodgePosition.cpp | lamhoangtung/AI-Tank-Contest | 89b3804368d1b378e8ea350cee7b45bf49c3aa5e | [
"MIT"
] | null | null | null | Bots/C/AI_Template/src/GoalDodgePosition.cpp | lamhoangtung/AI-Tank-Contest | 89b3804368d1b378e8ea350cee7b45bf49c3aa5e | [
"MIT"
] | 2 | 2019-05-05T22:30:26.000Z | 2021-12-24T04:24:33.000Z | #include "GoalDodgePosition.h"
#include "GoalType.h"
#include "GoalCover.h"
#include "GoalShootEnemy.h"
GoalDodgePosition::GoalDodgePosition(MyTank* pOwner):
GoalComposite<MyTank>(pOwner, goal_dodge_position)
{
}
GoalDodgePosition::~GoalDodgePosition()
{
}
void GoalDodgePosition::Activate()
{
m_iStatus = active;
RemoveAllSubgoals();
int coolDownToShoot = 2;
Tank* closestEnemyTank = TargetMgr->GetClosestEnemyTank(m_pOwner->GetPosition());
if (closestEnemyTank)
{
glm::vec2 tankPos = m_pOwner->GetPosition();
glm::vec2 enemyPos = glm::vec2(closestEnemyTank->GetX(), closestEnemyTank->GetY());
if (TargetMgr->isShootableAEnemy(enemyPos, tankPos))
{
int timeToHit = m_pOwner->GetTimeToHitDodgePosition();
int bestTimeToDodge = m_pOwner->GetBestTImeToDodgePosition();
int tankCoolDown = m_pOwner->GetCoolDown();
int enemyCoolDown = closestEnemyTank->GetCoolDown();
std::vector<glm::vec2> targetToCover;
targetToCover.push_back(enemyPos);
// if (m_pOwner->GetPosition() == glm::vec2(4,7))
// {
// std::cout << "Best time to dodge pos: " << bestTimeToDodge << std::endl;
// std::cout << "Time to hit dodge pos: " << timeToHit << std::endl;
// }
if (bestTimeToDodge > timeToHit)/*When cant dodge*/
{
if (tankCoolDown > 0)
{
AddSubgoal(new GoalCover(m_pOwner, targetToCover));
}else
{
AddSubgoal(new GoalShootEnemy(m_pOwner, enemyPos));
}
}else if (bestTimeToDodge == timeToHit)/*Can dodge if immediately dodge*/
{
if (tankCoolDown == 0 && enemyCoolDown >= coolDownToShoot)
{
AddSubgoal(new GoalShootEnemy(m_pOwner, enemyPos));
}else
{
AddSubgoal(new GoalCover(m_pOwner, targetToCover));
}
}
}else
{
//stop if cooldown == 0.
}
}
}
int GoalDodgePosition::Process()
{
ActivateIfInactive();
m_iStatus = ProcessSubgoals();
ReactivateIfFailed();
return m_iStatus;
}
void GoalDodgePosition::Terminate()
{
}
| 24.2875 | 85 | 0.69017 | [
"vector"
] |
439c29ec3d6d6c678dae0d7eb6edabff04d4cfb2 | 4,013 | hpp | C++ | src/range_min_query.hpp | keijak/cplib-cpp | 1edfd679b9faaf138c9274bc5275fe438534573f | [
"Apache-2.0"
] | null | null | null | src/range_min_query.hpp | keijak/cplib-cpp | 1edfd679b9faaf138c9274bc5275fe438534573f | [
"Apache-2.0"
] | null | null | null | src/range_min_query.hpp | keijak/cplib-cpp | 1edfd679b9faaf138c9274bc5275fe438534573f | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
template <typename T>
constexpr int num_bits = CHAR_BIT * sizeof(T);
// Log base 2 of the most significant bit that is set to 1.
inline int msb_log(unsigned x) {
assert(x != 0);
return num_bits<unsigned> - __builtin_clz(x) - 1;
}
// Range Min/Max Query based on Fischer-Heun Structure.
// - Initialization: O(n)
// - Query: O(1)
//
// Usage:
// RMQ rmq(a.size(), [&](int i, int j){ return a[i] < a[j]; });
// auto minval = a[rmq.fold(l, r)];
template <class BetterOp, class mask_t = unsigned>
struct RMQ {
static_assert(std::is_integral_v<mask_t>, "mask_t must be integral");
static_assert(std::is_unsigned_v<mask_t>, "mask_t must be unsigned");
static_assert(std::is_invocable_r_v<bool, BetterOp, int, int>);
static constexpr int block_size_ = num_bits<mask_t>;
int n_; // sequence size
int block_count_; // total number of blocks
BetterOp better_than_; // checks if lhs is strictly better than rhs.
std::vector<mask_t> indicator_;
std::vector<std::vector<int>> sparse_table_;
RMQ(int n, BetterOp better)
: n_(n),
block_count_((n_ + block_size_ - 1) / block_size_),
better_than_(std::move(better)),
indicator_(n_),
sparse_table_(
block_count_ == 0 ? 0 : msb_log(unsigned(block_count_)) + 1,
std::vector<int>(block_count_)) {
static constexpr int bufsize = block_size_ + 1;
static int buf[bufsize]; // ring buffer [lp,rp)
int lp = 1, rp = 1, rpm1 = 0; // rpm1 = rp-1 (mod bufsize)
// Build the indicator table.
for (int r = 0; r < n_; ++r) {
while (lp != rp and r - buf[lp] >= block_size_) {
++lp;
if (lp == bufsize) lp = 0;
}
while (lp != rp and not better_than_(buf[rpm1], r)) {
rp = rpm1--;
if (rp == 0) rpm1 = bufsize - 1;
}
indicator_[r] = 1;
if (lp != rp) {
const int p = buf[rpm1];
indicator_[r] |= (indicator_[p] << (r - p));
}
buf[rp] = r;
rpm1 = rp++;
if (rp == bufsize) rp = 0;
}
// Build the sparse table.
for (int i = 0; i < block_count_; ++i) {
sparse_table_[0][i] =
best_index_small(std::min(block_size_ * (i + 1), n_) - 1);
}
for (int i = 0, height = int(sparse_table_.size()) - 1; i < height; ++i) {
for (int j = 0; j < block_count_; ++j) {
sparse_table_[i + 1][j] = better_index(
sparse_table_[i][j],
sparse_table_[i][std::min(j + (1 << i), block_count_ - 1)]);
}
}
}
// Returns the index of the best value in [l, r) (half-open interval).
inline int fold(int l, int r) const {
assert(l < r);
// Internally use closed interval.
return best_index(l, r - 1);
}
private:
inline int better_index(int i, int j) const {
return better_than_(i, j) ? i : j;
}
// Returns the index of the best value in [r - width, r] (closed interval).
inline int best_index_small(int r, int width = block_size_) const {
assert(r < n_);
assert(width > 0);
assert(width <= block_size_);
mask_t ind = indicator_[r];
if (width < block_size_) {
ind &= (mask_t(1) << width) - 1;
}
return r - msb_log(ind);
}
// Returns the index of the best value in [l, r] (closed interval).
inline int best_index(int l, int r) const {
l = std::clamp(l, 0, n_ - 1);
r = std::clamp(r, 0, n_ - 1);
const int width = r - l + 1;
if (width <= block_size_) {
return best_index_small(r, width);
}
const int al = best_index_small(std::min(l + block_size_, n_) - 1);
const int ar = best_index_small(r);
int ans = better_index(al, ar);
const int bl = l / block_size_ + 1;
const int br = r / block_size_ - 1;
if (bl <= br) {
const int k = msb_log(unsigned(br - bl + 1));
const int bl2 = br - (1 << k) + 1;
const int am = better_index(sparse_table_[k][bl], sparse_table_[k][bl2]);
ans = better_index(ans, am);
}
return ans;
}
};
| 32.104 | 79 | 0.575878 | [
"vector"
] |
43a1666eab81b63d965402755e11be96a4106636 | 11,638 | cpp | C++ | uppsrc/TSql/dict.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppsrc/TSql/dict.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppsrc/TSql/dict.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// dict: user privileges, relocation, index removal.
#include "TSql.h"
#pragma hdrstop
NAMESPACE_UPP
#ifndef NOAPPSQL
int SqlUserGetRightsTo(const char* table)
{
return SqlUser().GetRightsTo(table);
}
#endif
#ifndef NOAPPSQL
bool SqlUserCanWrite(const char* table)
{
return SqlUser().CanWrite(table);
}
#endif
#ifndef NOAPPSQL
bool SqlUserCanRead(const char* table)
{
return SqlUser().CanRead(table);
}
#endif
SqlAnyTable::SqlAnyTable()
{
}
SqlAnyTable::SqlAnyTable(const char *table_name, SqlSession& session)
{
const char *n = strchr(table_name, '.');
if(n)
{ // full specification
owner = ToUpper(String(table, n - table_name));
table = ToUpper(n + 1);
}
else
{ // check table existence
static VectorMap<String, SqlAnyTable> table_map;
static String user;
if(session.GetUser() != user)
{ // another user - clear cache
user = session.GetUser();
table_map.Clear();
}
int ix = table_map.Find(table_name);
if(ix >= 0)
{
*this = table_map[ix];
return;
}
table = ToUpper(table_name);
Sql cursor(session);
owner = cursor.Select("OWNER from ALL_TABLES "
"where OWNER = USER and TABLE_NAME = ?", table);
if(IsNull(owner))
{ // table not found - look up synonym table
if(!cursor.Execute("select TABLE_OWNER, TABLE_NAME from ALL_SYNONYMS "
"where SYNONYM_NAME = ? "
"order by DECODE(OWNER, USER, 0, 'PUBLIC', 1, 2)", table))
throw SqlExc(session);
if(!cursor.Fetch(owner, table))
owner = table = String();
}
if(!IsNull(owner) && !IsNull(table))
table_map.FindAdd(table_name, *this);
}
}
SqlAnyTable::SqlAnyTable(const char* owner, const char* table)
: owner(owner), table(table)
{
}
String SqlAnyTable::Dot() const
{
String result;
if(!IsNull(owner))
result << owner << '.';
result += table;
return result;
}
bool SqlAnyTable::operator == (const SqlAnyTable& t) const
{
return owner == t.owner && table == t.table;
}
SqlAnyColumn::SqlAnyColumn()
{
}
SqlAnyColumn::SqlAnyColumn(const char* column, const char* table_name, SqlSession& session)
: SqlAnyTable(table_name, session)
, column(ToUpper(column))
{
}
SqlAnyColumn::SqlAnyColumn(const char* column, const char* owner, const char* table)
: SqlAnyTable(owner, table)
, column(ToUpper(column))
{
}
SqlAnyColumn::SqlAnyColumn(const char* column, const SqlAnyTable& table)
: SqlAnyTable(table)
, column(ToUpper(column))
{
}
String SqlAnyColumn::DotColumn() const
{
return Dot() + '.' + column;
}
bool SqlAnyColumn::operator == (const SqlAnyColumn& c) const
{
return owner == c.owner && table == c.table && column == c.column;
}
#ifndef NOAPPSQL
GLOBAL_VAR(SqlUserRights, SqlUser)
#endif
void SqlUserRights::Clear()
{
user = Null;
roles.Clear();
rights.Clear();
error = Null;
}
void SqlUserRights::Sync()
{
try
{
SqlSession& ss = GetSession();
if(!ss)
throw SqlExc(t_("User is not connected to the database."));
String new_user = ss.GetUser();
if(user == new_user) // user has not changed, rights are up to date
return;
Clear();
user = new_user;
Sql cursor(ss);
(Select(SqlId("GRANTED_ROLE")).From(SqlId("USER_ROLE_PRIVS"))
| Select(SqlId("GRANTED_ROLE")).From(SqlId("ROLE_ROLE_PRIVS"))).Force(cursor);
String temp;
while(cursor.Fetch(temp))
roles.FindAdd(temp);
// fetch rights
SqlId OWNER("OWNER");
SqlId TABLE_NAME("TABLE_NAME");
SqlId PRIVILEGE("PRIVILEGE");
Select(SqlId("OWNER, TABLE_NAME, "
"SUM(distinct DECODE(PRIVILEGE, 'SELECT', 1, 'UPDATE', 2, "
"'INSERT', 4, 'DELETE', 8, 0))"))
.From(Select(OWNER, TABLE_NAME, PRIVILEGE).From(SqlId("USER_TAB_PRIVS")) |
Select(OWNER, TABLE_NAME, PRIVILEGE).From(SqlId("ROLE_TAB_PRIVS")))
// "(select * from USER_TAB_PRIVS union select * from ROLE_TAB_PRIVS)")
.GroupBy(SqlSet(SqlId("OWNER"), SqlId("TABLE_NAME")))
.Force(cursor);
SqlAnyTable t;
int privs;
while(cursor.Fetch(t.owner, t.table, privs))
rights.Add(t.Dot(), privs);
}
catch(Exc e)
{
error = e;
}
}
int SqlUserRights::GetRightsTo(const char* table)
{
try
{
SqlSession& session = GetSession();
SqlAnyTable tbl(table, session);
if(tbl.owner == session.GetUser())
return 15; // user has always full access to his/her own schema
Sync();
int ix = rights.Find(tbl.Dot());
return (ix >= 0 ? rights[ix] : 0);
}
catch(Exc e)
{
error = e;
return 0;
}
}
bool SqlUserRights::HasRole(const char* role)
{
Sync();
return roles.Find(role) >= 0;
}
SqlIndex::SqlIndex()
{
session = NULL;
}
void SqlIndex::Open(String ind, String own, SqlSession& session)
{
SqlBool exp = SqlId("INDEX_NAME") == ind;
if(!IsNull(own))
exp &= SqlId("OWNER") == own;
Sql cursor(session);
Select(SqlId("OWNER"), SqlId("INDEX_NAME"), SqlId("TABLE_OWNER"), SqlId("TABLE_NAME"))
.From(SqlId("ALL_INDEXES"))
.Where(exp).Force(cursor);
if(cursor.Fetch(owner, index, table.owner, table.table))
FetchContainerExc(columns, Select(SqlId("COLUMN_NAME"))
.From(SqlId("ALL_IND_COLUMNS"))
.Where(SqlId("INDEX_OWNER") == owner && SqlId("INDEX_NAME") == index),
session);
dropped = false;
}
SqlIndex::SqlIndex(const SqlIndex& another, int)
{
table = another.table;
index = another.index;
columns <<= another.columns;
dropped = another.dropped;
session = another.session;
}
SqlIndex::~SqlIndex()
{
}
String SqlIndex::Dot() const
{
if(!owner.IsEmpty())
return owner + '.' + index;
else
return index;
}
void SqlIndex::Drop()
{
ASSERT(session);
Sql cursor(*session);
if(!index.IsEmpty() && cursor.Execute("drop index " + Dot()))
dropped = true;
}
void SqlIndex::Create()
{
if(index.IsEmpty() || columns.IsEmpty() || !dropped)
return;
String s;
s << "create index " << Dot() << " on " << table.Dot()
<< '(' << columns[0];
for(int i = 1; i < columns.GetCount(); i++)
s << ", " << columns[i];
s << ')';
ASSERT(session);
Sql cursor(*session);
if(cursor.Execute(s))
dropped = false;
}
SqlIndexMap::SqlIndexMap()
{
}
SqlIndexMap::~SqlIndexMap()
{
}
void SqlIndexMap::Add(const char* _table, SqlSession& session)
{
SqlAnyTable table(_table, session);
Sql cursor(session);
if(!cursor.Execute("select OWNER, INDEX_NAME from ALL_INDEXES "
"where UNIQUENESS = 'NONUNIQUE' "
"and TABLE_OWNER = ? and TABLE_NAME = ?", table.owner, table.table))
throw SqlExc(session);
String owner, index;
while(cursor.Fetch(owner, index))
AddPick(SqlIndex(index, owner, session));
}
void SqlIndexMap::Drop(Gate2<int, int> progress)
{
for(int i = 0; i < map.GetCount(); i++)
{
map[i].Drop();
if(progress(i, map.GetCount()))
throw AbortExc();
}
}
void SqlIndexMap::Create(Gate2<int, int> progress)
{
for(int i = 0; i < map.GetCount(); i++)
{
map[i].Create();
if(progress(i, map.GetCount()))
throw AbortExc();
}
}
SqlRelocate::SqlRelocate()
{
session = NULL;
}
SqlRelocate::~SqlRelocate()
{
}
void SqlRelocate::Find(SqlId table, SqlId column, SqlSession& session)
{
Find(~table.ToString(), ~column.ToString(), session);
}
void SqlRelocate::Find(const char* table, const char* column, SqlSession& sess)
{
session = &sess;
// todo: CWaitCursor without GUI / MFC?
// CWaitCursor wait;
error = Null;
reference.Clear();
canceled = false;
try
{
SqlAnyColumn col(column, table, *session);
static VectorMap<SqlAnyColumn, Vector<SqlAnyColumn> > reference_map;
int i = reference_map.Find(col);
if(i >= 0)
{
reference <<= reference_map[i];
return;
}
Vector<int> positions;
Sql cursor(*session);
if(!cursor.Execute("select distinct POSITION from ALL_CONS_COLUMNS "
"where OWNER = ? and TABLE_NAME = ? "
"and COLUMN_NAME = ? and POSITION is not NULL",
col.owner, col.table, col.column))
throw SqlExc(*session);
int temp;
if(cursor.Fetch(temp))
{ // positions exist
do
positions.Add(temp);
while(cursor.Fetch(temp));
for(int pos = 0; pos < positions.GetCount(); pos++)
{
if(!cursor.Execute(
"select OWNER, TABLE_NAME, COLUMN_NAME from ALL_CONS_COLUMNS "
"where (OWNER, CONSTRAINT_NAME, POSITION) in "
"(select OWNER, CONSTRAINT_NAME, ? from ALL_CONSTRAINTS "
"where CONSTRAINT_TYPE = 'R' and (OWNER, R_CONSTRAINT_NAME) in "
"(select OWNER, CONSTRAINT_NAME from ALL_CONS_COLUMNS "
"where OWNER = ? and TABLE_NAME = ? "
"and COLUMN_NAME = ? and POSITION = ?))",
positions[pos], col.owner, col.table, col.column, positions[pos]))
throw SqlExc(*session);
SqlAnyColumn rcol;
while(cursor.Fetch(rcol.owner, rcol.table, rcol.column))
reference.Add(rcol);
}
}
reference_map.Add(col, reference);
}
catch(Exc e)
{
error = e;
}
ClearResult();
}
void SqlRelocate::Move(const Vector<int>& old_seq, const Vector<int>& new_seq, int options, Gate2<int, int> progress)
{
ASSERT(session);
if(!error.IsEmpty()) // don't do anything when Find() failed
return;
ASSERT(old_seq.GetCount() == new_seq.GetCount());
Vector<SqlSet> old_sub, new_sub, dec_sub;
int c = 0;
for(int i = 0; i < old_seq.GetCount(); i++)
if(!IsNull(old_seq[i]) && new_seq[i] != old_seq[i])
{
if(c >= 50 || old_sub.IsEmpty())
{
old_sub.Add();
new_sub.Add();
dec_sub.Add();
c = 0;
}
c++;
old_sub.Top().Cat(old_seq[i]);
new_sub.Top().Cat(new_seq[i]);
dec_sub.Top().Cat(old_seq[i]).Cat(new_seq[i]);
}
if(old_sub.IsEmpty())
return;
canceled = false;
ClearResult();
// todo: CWaitCursor without GUI / MFC?
// CWaitCursor wait;
try
{
SqlBlock block(*session);
Sql cursor(*session);
if(progress(0, GetCount()) && !(options & NO_CANCEL))
{
canceled = true;
throw AbortExc();
}
for(int i = 0; i < GetCount(); i++)
{
const SqlAnyColumn& column = reference[i];
SqlId tbl(column.Dot());
SqlId col(column.column);
for(int s = 0; s < old_sub.GetCount(); s++)
{
if(!IsNull(cursor % Select(1).From(tbl).Where(col == old_sub[s] && SqlId("ROWNUM") == 1)))
{
SqlSet dec_set = dec_sub[s];
dec_set.Cat(col);
if(!Update(tbl)(col, Decode(col, dec_set))
.Where(col == old_sub[s]).Execute(cursor))
{ // update failed
if(!(options & TRY_ALL))
throw SqlExc(*session);
else if(error.IsEmpty())
error = SqlExc(*session); // just store error & continue trying other tables
}
else
result[i] = true;
}
else
result[i] = true;
}
// progress.SetText(
// Format("Upravuji %s", column.column), false);
if(progress(i, GetCount()) && !(options & NO_CANCEL))
{ // set 'canceled' flag & exit
canceled = true;
throw AbortExc();
}
}
block.Commit();
}
catch(Exc e)
{
error = e;
}
}
void SqlRelocate::Move(int old_seq, int new_seq, int options, Gate2<int, int> progress)
{
Vector<int> src, dest;
src << old_seq;
dest << new_seq;
Move(src, dest, options, progress);
}
void SqlRelocate::ClearResult()
{
result.SetCount(reference.GetCount());
Fill(result.Begin(), result.End(), false);
}
Vector<SqlAnyColumn> SqlRelocate::GetReferences(int seq) const
{
ASSERT(session);
Vector<SqlAnyColumn> result;
if(IsNull(seq))
return result;
Sql cursor(*session);
for(int i = 0; i < GetCount(); i++)
{
const SqlAnyColumn& column = reference[i];
if(seq == (int)cursor.Select(column.column + " from " + column.Dot()
+ " where " + column.column + " = ? and ROWNUM = 1", seq))
result.Add(column);
}
return result;
}
unsigned GetHashValue(const SqlAnyTable& t)
{
return GetHashValue(t.owner) ^ GetHashValue(t.table);
}
unsigned GetHashValue(const SqlAnyColumn& t)
{
return GetHashValue(static_cast<const SqlAnyTable&>(t)) ^ GetHashValue(t.column);
}
END_UPP_NAMESPACE
| 21.87594 | 117 | 0.651057 | [
"vector"
] |
43aa4fa3d58f8f92025bd3d65b0ab8e6ceb68d2c | 730 | hpp | C++ | waterbox/ares64/ares/nall/cd/scrambler.hpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | waterbox/ares64/ares/nall/cd/scrambler.hpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 296 | 2021-10-16T18:00:18.000Z | 2022-03-31T12:09:00.000Z | waterbox/ares64/ares/nall/cd/scrambler.hpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | #pragma once
namespace nall::CD::Scrambler {
//polynomial(x) = x^15 + x + 1
inline auto polynomial(u32 x) -> u8 {
static u8 lookup[2340]{};
static bool once = false;
if(!once) { once = true;
u16 shift = 0x0001;
for(u32 n : range(2340)) {
lookup[n] = shift;
for(u32 b : range(8)) {
bool carry = shift & 1 ^ shift >> 1 & 1;
shift = (carry << 15 | shift) >> 1;
}
}
}
return lookup[x];
}
//
inline auto transform(array_span<u8> sector) -> bool {
if(sector.size() == 2352) sector += 12; //header is not scrambled
if(sector.size() != 2340) return false; //F1 frames only
for(u32 index : range(2340)) {
sector[index] ^= polynomial(index);
}
return true;
}
}
| 20.277778 | 68 | 0.568493 | [
"transform"
] |
43b251ef97840ef57673dc3c600f1ebedc6e54ce | 253,482 | hpp | C++ | openconfig/ydk/models/openconfig/fragmented/openconfig_network_instance_7.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | openconfig/ydk/models/openconfig/fragmented/openconfig_network_instance_7.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | openconfig/ydk/models/openconfig/fragmented/openconfig_network_instance_7.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _OPENCONFIG_NETWORK_INSTANCE_7_
#define _OPENCONFIG_NETWORK_INSTANCE_7_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
#include "openconfig_network_instance_0.hpp"
#include "openconfig_network_instance_2.hpp"
#include "openconfig_network_instance_4.hpp"
#include "openconfig_network_instance_6.hpp"
namespace openconfig {
namespace openconfig_network_instance {
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkAttributes::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList local_protection; //type: list of LocalProtection
class LocalProtection;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkAttributes::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType : public ydk::Entity
{
public:
LinkProtectionType();
~LinkProtectionType();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList link_protection_type; //type: list of LinkProtectionType_
class LinkProtectionType_;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints : public ydk::Entity
{
public:
BandwidthConstraints();
~BandwidthConstraints();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BandwidthConstraint; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint
ydk::YList bandwidth_constraint;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint : public ydk::Entity
{
public:
BandwidthConstraint();
~BandwidthConstraint();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::State::model_id)
ydk::YLeaf model_id;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::State
class Constraints; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints> constraints;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf model_id; //type: uint8
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints : public ydk::Entity
{
public:
Constraints();
~Constraints();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Constraint; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint
ydk::YList constraint;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint : public ydk::Entity
{
public:
Constraint();
~Constraint();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint32 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint::State::constraint_id)
ydk::YLeaf constraint_id;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf constraint_id; //type: uint32
ydk::YLeaf bandwidth; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::BandwidthConstraints::BandwidthConstraint::Constraints::Constraint::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp : public ydk::Entity
{
public:
UnconstrainedLsp();
~UnconstrainedLsp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf unconstrained_lsp; //type: uint16
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UnconstrainedLsp::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids : public ydk::Entity
{
public:
AdjacencySids();
~AdjacencySids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class AdjacencySid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid
ydk::YList adjacency_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid : public ydk::Entity
{
public:
AdjacencySid();
~AdjacencySid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint32 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State::value_)
ydk::YLeaf value_;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeaf weight; //type: uint8
ydk::YLeafList flags; //type: list of Flags
class Flags;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids : public ydk::Entity
{
public:
LanAdjacencySids();
~LanAdjacencySids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class LanAdjacencySid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid
ydk::YList lan_adjacency_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid : public ydk::Entity
{
public:
LanAdjacencySid();
~LanAdjacencySid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint32 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State::value_)
ydk::YLeaf value_;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeaf weight; //type: uint8
ydk::YLeaf neighbor_id; //type: string
ydk::YLeafList flags; //type: list of Flags
class Flags;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay : public ydk::Entity
{
public:
LinkDelay();
~LinkDelay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf a_bit; //type: boolean
ydk::YLeaf delay; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelay::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay : public ydk::Entity
{
public:
MinMaxLinkDelay();
~MinMaxLinkDelay();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf a_bit; //type: boolean
ydk::YLeaf min_delay; //type: uint32
ydk::YLeaf max_delay; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::MinMaxLinkDelay::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation : public ydk::Entity
{
public:
LinkDelayVariation();
~LinkDelayVariation();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf delay; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkDelayVariation::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss : public ydk::Entity
{
public:
LinkLoss();
~LinkLoss();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf a_bit; //type: boolean
ydk::YLeaf link_loss; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkLoss::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth : public ydk::Entity
{
public:
ResidualBandwidth();
~ResidualBandwidth();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf residual_bandwidth; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::ResidualBandwidth::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth : public ydk::Entity
{
public:
AvailableBandwidth();
~AvailableBandwidth();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf available_bandwidth; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AvailableBandwidth::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth : public ydk::Entity
{
public:
UtilizedBandwidth();
~UtilizedBandwidth();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf utilized_bandwidth; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::UtilizedBandwidth::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs : public ydk::Entity
{
public:
UndefinedSubtlvs();
~UndefinedSubtlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class UndefinedSubtlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv
ydk::YList undefined_subtlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv : public ydk::Entity
{
public:
UndefinedSubtlv();
~UndefinedSubtlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv::State::type)
ydk::YLeaf type;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: uint8
ydk::YLeaf length; //type: uint8
ydk::YLeaf value_; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::UndefinedSubtlvs::UndefinedSubtlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability : public ydk::Entity
{
public:
MtIpv4Reachability();
~MtIpv4Reachability();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Prefixes; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes> prefixes;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes : public ydk::Entity
{
public:
Prefixes();
~Prefixes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Prefix; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix
ydk::YList prefix;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix : public ydk::Entity
{
public:
Prefix();
~Prefix();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint16 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State::mt_id)
ydk::YLeaf mt_id;
//type: string (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State::prefix)
ydk::YLeaf prefix;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State
class Subtlvs; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs
class UndefinedSubtlvs; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs> subtlvs;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs> undefined_subtlvs;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf up_down; //type: boolean
ydk::YLeaf s_bit; //type: boolean
ydk::YLeaf prefix; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf mt_id; //type: uint16
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs : public ydk::Entity
{
public:
Subtlvs();
~Subtlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Subtlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv
ydk::YList subtlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv : public ydk::Entity
{
public:
Subtlv();
~Subtlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State
class Tag; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag
class Tag64; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64
class Flags; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags
class Ipv4SourceRouterId; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId
class Ipv6SourceRouterId; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId
class PrefixSids; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag> tag;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64> tag64;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags> flags;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId> ipv4_source_router_id;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId> ipv6_source_router_id;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids> prefix_sids;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag : public ydk::Entity
{
public:
Tag();
~Tag();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList tag32; //type: list of uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64 : public ydk::Entity
{
public:
Tag64();
~Tag64();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList tag64; //type: list of uint64
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags : public ydk::Entity
{
public:
Flags();
~Flags();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeafList flags; //type: list of Flags_
class Flags_;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId : public ydk::Entity
{
public:
Ipv4SourceRouterId();
~Ipv4SourceRouterId();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf ipv4_source_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId : public ydk::Entity
{
public:
Ipv6SourceRouterId();
~Ipv6SourceRouterId();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf ipv6_source_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids : public ydk::Entity
{
public:
PrefixSids();
~PrefixSids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class PrefixSid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid
ydk::YList prefix_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid : public ydk::Entity
{
public:
PrefixSid();
~PrefixSid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint32 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State::value_)
ydk::YLeaf value_;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeaf algorithm; //type: uint8
ydk::YLeafList flags; //type: list of Flags
class Flags;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs : public ydk::Entity
{
public:
UndefinedSubtlvs();
~UndefinedSubtlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class UndefinedSubtlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv
ydk::YList undefined_subtlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv : public ydk::Entity
{
public:
UndefinedSubtlv();
~UndefinedSubtlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State::type)
ydk::YLeaf type;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: uint8
ydk::YLeaf length; //type: uint8
ydk::YLeaf value_; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability : public ydk::Entity
{
public:
MtIpv6Reachability();
~MtIpv6Reachability();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Prefixes; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes> prefixes;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes : public ydk::Entity
{
public:
Prefixes();
~Prefixes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Prefix; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix
ydk::YList prefix;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix : public ydk::Entity
{
public:
Prefix();
~Prefix();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: string (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State::prefix)
ydk::YLeaf prefix;
//type: uint16 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State::mt_id)
ydk::YLeaf mt_id;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State
class Subtlvs; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs
class UndefinedSubtlvs; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs> subtlvs;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs> undefined_subtlvs;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf up_down; //type: boolean
ydk::YLeaf x_bit; //type: boolean
ydk::YLeaf s_bit; //type: boolean
ydk::YLeaf prefix; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf mt_id; //type: uint16
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs : public ydk::Entity
{
public:
Subtlvs();
~Subtlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Subtlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv
ydk::YList subtlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv : public ydk::Entity
{
public:
Subtlv();
~Subtlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State
class Tag; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag
class Tag64; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64
class Flags; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags
class Ipv4SourceRouterId; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId
class Ipv6SourceRouterId; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId
class PrefixSids; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag> tag;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64> tag64;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags> flags;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId> ipv4_source_router_id;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId> ipv6_source_router_id;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids> prefix_sids;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag : public ydk::Entity
{
public:
Tag();
~Tag();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList tag32; //type: list of uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64 : public ydk::Entity
{
public:
Tag64();
~Tag64();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList tag64; //type: list of uint64
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Tag64::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags : public ydk::Entity
{
public:
Flags();
~Flags();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeafList flags; //type: list of Flags_
class Flags_;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId : public ydk::Entity
{
public:
Ipv4SourceRouterId();
~Ipv4SourceRouterId();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf ipv4_source_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv4SourceRouterId::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId : public ydk::Entity
{
public:
Ipv6SourceRouterId();
~Ipv6SourceRouterId();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: ISISSUBTLVTYPE
ydk::YLeaf ipv6_source_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Ipv6SourceRouterId::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids : public ydk::Entity
{
public:
PrefixSids();
~PrefixSids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class PrefixSid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid
ydk::YList prefix_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid : public ydk::Entity
{
public:
PrefixSid();
~PrefixSid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint32 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State::value_)
ydk::YLeaf value_;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeaf algorithm; //type: uint8
ydk::YLeafList flags; //type: list of Flags
class Flags;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs : public ydk::Entity
{
public:
UndefinedSubtlvs();
~UndefinedSubtlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class UndefinedSubtlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv
ydk::YList undefined_subtlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv : public ydk::Entity
{
public:
UndefinedSubtlv();
~UndefinedSubtlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State::type)
ydk::YLeaf type;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: uint8
ydk::YLeaf length; //type: uint8
ydk::YLeaf value_; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::UndefinedSubtlvs::UndefinedSubtlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs : public ydk::Entity
{
public:
UndefinedTlvs();
~UndefinedTlvs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class UndefinedTlv; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv
ydk::YList undefined_tlv;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv : public ydk::Entity
{
public:
UndefinedTlv();
~UndefinedTlv();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv::State::type)
ydk::YLeaf type;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf type; //type: uint8
ydk::YLeaf length; //type: uint8
ydk::YLeaf value_; //type: binary
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::UndefinedTlvs::UndefinedTlv::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering : public ydk::Entity
{
public:
TrafficEngineering();
~TrafficEngineering();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enabled; //type: boolean
ydk::YLeaf ipv4_router_id; //type: string
ydk::YLeaf ipv6_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enabled; //type: boolean
ydk::YLeaf ipv4_router_id; //type: string
ydk::YLeaf ipv6_router_id; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::TrafficEngineering::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference : public ydk::Entity
{
public:
RoutePreference();
~RoutePreference();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf external_route_preference; //type: uint8
ydk::YLeaf internal_route_preference; //type: uint8
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf external_route_preference; //type: uint8
ydk::YLeaf internal_route_preference; //type: uint8
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::RoutePreference::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication : public ydk::Entity
{
public:
Authentication();
~Authentication();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::State
class Key; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key
class Keychain; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Keychain
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key> key;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Keychain> keychain;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf csnp_authentication; //type: boolean
ydk::YLeaf psnp_authentication; //type: boolean
ydk::YLeaf lsp_authentication; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf csnp_authentication; //type: boolean
ydk::YLeaf psnp_authentication; //type: boolean
ydk::YLeaf lsp_authentication; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key : public ydk::Entity
{
public:
Key();
~Key();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auth_password; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auth_password; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Key::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Keychain : public ydk::Entity
{
public:
Keychain();
~Keychain();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::Authentication::Keychain
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces : public ydk::Entity
{
public:
Interfaces();
~Interfaces();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Interface; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface
ydk::YList interface;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface : public ydk::Entity
{
public:
Interface();
~Interface();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: string (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Config::interface_id)
ydk::YLeaf interface_id;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::State
class CircuitCounters; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters
class Authentication; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication
class AfiSafi; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi
class Levels; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels
class Timers; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Timers
class Bfd; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Bfd
class InterfaceRef; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::InterfaceRef
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters> circuit_counters;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication> authentication;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi> afi_safi;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels> levels;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Timers> timers;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Bfd> bfd;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::InterfaceRef> interface_ref;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enabled; //type: boolean
ydk::YLeaf interface_id; //type: string
ydk::YLeaf passive; //type: boolean
ydk::YLeaf hello_padding; //type: HelloPaddingType
ydk::YLeaf circuit_type; //type: CircuitType
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf enabled; //type: boolean
ydk::YLeaf interface_id; //type: string
ydk::YLeaf passive; //type: boolean
ydk::YLeaf hello_padding; //type: HelloPaddingType
ydk::YLeaf circuit_type; //type: CircuitType
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters : public ydk::Entity
{
public:
CircuitCounters();
~CircuitCounters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf adj_changes; //type: uint32
ydk::YLeaf init_fails; //type: uint32
ydk::YLeaf rejected_adj; //type: uint32
ydk::YLeaf id_field_len_mismatches; //type: uint32
ydk::YLeaf max_area_address_mismatches; //type: uint32
ydk::YLeaf auth_type_fails; //type: uint32
ydk::YLeaf auth_fails; //type: uint32
ydk::YLeaf lan_dis_changes; //type: uint32
ydk::YLeaf adj_number; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::CircuitCounters::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication : public ydk::Entity
{
public:
Authentication();
~Authentication();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::State
class Key; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key
class Keychain; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Keychain
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key> key;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Keychain> keychain;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf hello_authentication; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf hello_authentication; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key : public ydk::Entity
{
public:
Key();
~Key();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auth_password; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf auth_password; //type: string
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Key::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Keychain : public ydk::Entity
{
public:
Keychain();
~Keychain();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Authentication::Keychain
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi : public ydk::Entity
{
public:
AfiSafi();
~AfiSafi();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Af; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af
ydk::YList af;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af : public ydk::Entity
{
public:
Af();
~Af();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::AfiSafi::Af::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels : public ydk::Entity
{
public:
Levels();
~Levels();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Level; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level
ydk::YList level;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level : public ydk::Entity
{
public:
Level();
~Level();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: uint8 (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Config::level_number)
ydk::YLeaf level_number;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::State
class PacketCounters; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters
class Adjacencies; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies
class Timers; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers
class AfiSafi; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi
class HelloAuthentication; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::HelloAuthentication
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters> packet_counters;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies> adjacencies;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers> timers;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi> afi_safi;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::HelloAuthentication> hello_authentication;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf level_number; //type: uint8
ydk::YLeaf passive; //type: boolean
ydk::YLeaf priority; //type: uint8
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf level_number; //type: uint8
ydk::YLeaf passive; //type: boolean
ydk::YLeaf priority; //type: uint8
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters : public ydk::Entity
{
public:
PacketCounters();
~PacketCounters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Lsp; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp
class Iih; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih
class Ish; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish
class Esh; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh
class Psnp; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp
class Cnsp; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp
class Unknown; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp> lsp;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih> iih;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish> ish;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh> esh;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp> psnp;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp> cnsp;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown> unknown;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp : public ydk::Entity
{
public:
Lsp();
~Lsp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Lsp::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih : public ydk::Entity
{
public:
Iih();
~Iih();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Iih::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish : public ydk::Entity
{
public:
Ish();
~Ish();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Ish::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh : public ydk::Entity
{
public:
Esh();
~Esh();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Esh::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp : public ydk::Entity
{
public:
Psnp();
~Psnp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Psnp::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp : public ydk::Entity
{
public:
Cnsp();
~Cnsp();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Cnsp::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown : public ydk::Entity
{
public:
Unknown();
~Unknown();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf received; //type: uint32
ydk::YLeaf processed; //type: uint32
ydk::YLeaf dropped; //type: uint32
ydk::YLeaf sent; //type: uint32
ydk::YLeaf retransmit; //type: uint32
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::PacketCounters::Unknown::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies : public ydk::Entity
{
public:
Adjacencies();
~Adjacencies();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Adjacency; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency
ydk::YList adjacency;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency : public ydk::Entity
{
public:
Adjacency();
~Adjacency();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: string (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State::system_id)
ydk::YLeaf system_id;
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf system_id; //type: string
ydk::YLeaf neighbor_ipv4_address; //type: string
ydk::YLeaf neighbor_ipv6_address; //type: string
ydk::YLeaf neighbor_snpa; //type: string
ydk::YLeaf local_extended_circuit_id; //type: uint32
ydk::YLeaf neighbor_extended_circuit_id; //type: uint32
ydk::YLeaf priority; //type: uint8
ydk::YLeaf dis_system_id; //type: string
ydk::YLeaf neighbor_circuit_type; //type: LevelType
ydk::YLeaf adjacency_type; //type: LevelType
ydk::YLeaf adjacency_state; //type: IsisInterfaceAdjState
ydk::YLeaf remaining_hold_time; //type: uint16
ydk::YLeaf up_time; //type: uint32
ydk::YLeaf multi_topology; //type: boolean
ydk::YLeaf restart_support; //type: boolean
ydk::YLeaf restart_suppress; //type: boolean
ydk::YLeaf restart_status; //type: boolean
ydk::YLeafList topology; //type: list of AFISAFITYPE
ydk::YLeafList area_address; //type: list of string
ydk::YLeafList nlpid; //type: list of Nlpid
class Nlpid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers : public ydk::Entity
{
public:
Timers();
~Timers();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf hello_interval; //type: uint32
ydk::YLeaf hello_multiplier; //type: uint8
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf hello_interval; //type: uint32
ydk::YLeaf hello_multiplier; //type: uint8
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Timers::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi : public ydk::Entity
{
public:
AfiSafi();
~AfiSafi();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Af; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af
ydk::YList af;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af : public ydk::Entity
{
public:
Af();
~Af();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::State
class SegmentRouting; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::State> state;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting> segment_routing;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
ydk::YLeaf metric; //type: uint32
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_name; //type: AFITYPE
ydk::YLeaf safi_name; //type: SAFITYPE
ydk::YLeaf metric; //type: uint32
ydk::YLeaf enabled; //type: boolean
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting : public ydk::Entity
{
public:
SegmentRouting();
~SegmentRouting();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class PrefixSids; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids
class AdjacencySids; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids> prefix_sids;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids> adjacency_sids;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids : public ydk::Entity
{
public:
PrefixSids();
~PrefixSids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class PrefixSid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid
ydk::YList prefix_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid : public ydk::Entity
{
public:
PrefixSid();
~PrefixSid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: union (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config::prefix)
ydk::YLeaf prefix;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf sid_id; //type: one of union, string
ydk::YLeaf label_options; //type: LabelOptions
class LabelOptions;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf sid_id; //type: one of union, string
ydk::YLeaf label_options; //type: LabelOptions
class LabelOptions;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::State
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids : public ydk::Entity
{
public:
AdjacencySids();
~AdjacencySids();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class AdjacencySid; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid
ydk::YList adjacency_sid;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid : public ydk::Entity
{
public:
AdjacencySid();
~AdjacencySid();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
//type: union (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config::neighbor)
ydk::YLeaf neighbor;
//type: union (refers to openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config::sid_id)
ydk::YLeaf sid_id;
class Config; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config
class State; //type: NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::State
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config> config;
std::shared_ptr<openconfig::openconfig_network_instance::NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::State> state;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config : public ydk::Entity
{
public:
Config();
~Config();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf sid_id; //type: one of union, enumeration
ydk::YLeaf protection_eligible; //type: boolean
ydk::YLeaf group; //type: boolean
ydk::YLeaf neighbor; //type: string
class SidId;
}; // NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkAttributes::State::LocalProtection : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf LOCAL_PROTECTION;
static const ydk::Enum::YLeaf LINK_EXCLUDED;
static int get_enum_value(const std::string & name) {
if (name == "LOCAL_PROTECTION") return 0;
if (name == "LINK_EXCLUDED") return 1;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LinkProtectionType::State::LinkProtectionType_ : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf EXTRA_TRAFFIC;
static const ydk::Enum::YLeaf UNPROTECTED;
static const ydk::Enum::YLeaf SHARED;
static const ydk::Enum::YLeaf ONE_ONE;
static const ydk::Enum::YLeaf PLUS_ONE;
static const ydk::Enum::YLeaf ENHANCED;
static int get_enum_value(const std::string & name) {
if (name == "EXTRA_TRAFFIC") return 0;
if (name == "UNPROTECTED") return 1;
if (name == "SHARED") return 2;
if (name == "ONE_ONE") return 3;
if (name == "PLUS_ONE") return 4;
if (name == "ENHANCED") return 5;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::AdjacencySids::AdjacencySid::State::Flags : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ADDRESS_FAMILY;
static const ydk::Enum::YLeaf BACKUP;
static const ydk::Enum::YLeaf VALUE;
static const ydk::Enum::YLeaf LOCAL;
static const ydk::Enum::YLeaf SET;
static int get_enum_value(const std::string & name) {
if (name == "ADDRESS_FAMILY") return 0;
if (name == "BACKUP") return 1;
if (name == "VALUE") return 2;
if (name == "LOCAL") return 3;
if (name == "SET") return 4;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIsisNeighborAttribute::Neighbors::Neighbor::Subtlvs::Subtlv::LanAdjacencySids::LanAdjacencySid::State::Flags : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ADDRESS_FAMILY;
static const ydk::Enum::YLeaf BACKUP;
static const ydk::Enum::YLeaf VALUE;
static const ydk::Enum::YLeaf LOCAL;
static const ydk::Enum::YLeaf SET;
static int get_enum_value(const std::string & name) {
if (name == "ADDRESS_FAMILY") return 0;
if (name == "BACKUP") return 1;
if (name == "VALUE") return 2;
if (name == "LOCAL") return 3;
if (name == "SET") return 4;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State::Flags_ : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf EXTERNAL_FLAG;
static const ydk::Enum::YLeaf READVERTISEMENT_FLAG;
static const ydk::Enum::YLeaf NODE_FLAG;
static int get_enum_value(const std::string & name) {
if (name == "EXTERNAL_FLAG") return 0;
if (name == "READVERTISEMENT_FLAG") return 1;
if (name == "NODE_FLAG") return 2;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv4Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State::Flags : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf READVERTISEMENT;
static const ydk::Enum::YLeaf NODE;
static const ydk::Enum::YLeaf PHP;
static const ydk::Enum::YLeaf EXPLICIT_NULL;
static const ydk::Enum::YLeaf VALUE;
static const ydk::Enum::YLeaf LOCAL;
static int get_enum_value(const std::string & name) {
if (name == "READVERTISEMENT") return 0;
if (name == "NODE") return 1;
if (name == "PHP") return 2;
if (name == "EXPLICIT_NULL") return 3;
if (name == "VALUE") return 4;
if (name == "LOCAL") return 5;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::Flags::State::Flags_ : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf EXTERNAL_FLAG;
static const ydk::Enum::YLeaf READVERTISEMENT_FLAG;
static const ydk::Enum::YLeaf NODE_FLAG;
static int get_enum_value(const std::string & name) {
if (name == "EXTERNAL_FLAG") return 0;
if (name == "READVERTISEMENT_FLAG") return 1;
if (name == "NODE_FLAG") return 2;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Levels::Level::LinkStateDatabase::Lsp::Tlvs::Tlv::MtIpv6Reachability::Prefixes::Prefix::Subtlvs::Subtlv::PrefixSids::PrefixSid::State::Flags : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf READVERTISEMENT;
static const ydk::Enum::YLeaf NODE;
static const ydk::Enum::YLeaf PHP;
static const ydk::Enum::YLeaf EXPLICIT_NULL;
static const ydk::Enum::YLeaf VALUE;
static const ydk::Enum::YLeaf LOCAL;
static int get_enum_value(const std::string & name) {
if (name == "READVERTISEMENT") return 0;
if (name == "NODE") return 1;
if (name == "PHP") return 2;
if (name == "EXPLICIT_NULL") return 3;
if (name == "VALUE") return 4;
if (name == "LOCAL") return 5;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::Adjacencies::Adjacency::State::Nlpid : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf IPV4;
static const ydk::Enum::YLeaf IPV6;
static int get_enum_value(const std::string & name) {
if (name == "IPV4") return 0;
if (name == "IPV6") return 1;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::Config::LabelOptions : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf NO_PHP;
static const ydk::Enum::YLeaf EXPLICIT_NULL;
static int get_enum_value(const std::string & name) {
if (name == "NO_PHP") return 0;
if (name == "EXPLICIT_NULL") return 1;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::PrefixSids::PrefixSid::State::LabelOptions : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf NO_PHP;
static const ydk::Enum::YLeaf EXPLICIT_NULL;
static int get_enum_value(const std::string & name) {
if (name == "NO_PHP") return 0;
if (name == "EXPLICIT_NULL") return 1;
return -1;
}
};
class NetworkInstances::NetworkInstance::Protocols::Protocol::Isis::Interfaces::Interface::Levels::Level::AfiSafi::Af::SegmentRouting::AdjacencySids::AdjacencySid::Config::SidId : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf DYNAMIC;
static int get_enum_value(const std::string & name) {
if (name == "DYNAMIC") return 0;
return -1;
}
};
}
}
#endif /* _OPENCONFIG_NETWORK_INSTANCE_7_ */
| 66.18329 | 339 | 0.723199 | [
"vector"
] |
43b768d9047a5cba210aaaeea21cdabb1886e268 | 1,043 | cc | C++ | HeuristicUpperBoundMemo.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-07-25T15:09:11.000Z | 2015-07-25T15:09:11.000Z | HeuristicUpperBoundMemo.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-09-19T00:44:24.000Z | 2015-09-21T16:47:12.000Z | HeuristicUpperBoundMemo.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | null | null | null | #include <vector>
#include <cstdlib>
#include "HeuristicUpperBoundMemo.hh"
#include "TWUtilAlgos.hh"
int HeuristicUpperBoundMemo::upperBound(VSet S)
{
/*
if (S.asInt() % 13 == 0)
{
auto Svec = S.members();
Graph gthis = this->G;
//TODO ascending or descending?
std::sort(Svec.begin(), Svec.end(), [this](Vertex u, Vertex v)
{
auto ud = boost::degree(u, this->G);
auto vd = boost::degree(v, this->G);
return ud > vd;
} );
return permutTW(S, Svec, G);
}*/
std::vector<Vertex> members;
S.members(members);
return permutTW(nGraph, S, members, G);
//return BasicMemo::upperBound(S);
}
int HeuristicUpperBoundMemo::lowerBound(VSet S)
{
//The lower-bound for subgraph tree-width is also a lower-bound for our recurrence
//TODO prove this
//if (S.asInt() % 13 == 0)
//{
return subgraphTWLowerBound(S, this->G, this->GC);
//}
//return MMD(S, G); //0;
//return 0;
}
HeuristicUpperBoundMemo::HeuristicUpperBoundMemo(Graph G) : BasicMemo(G)
{
}
HeuristicUpperBoundMemo::~HeuristicUpperBoundMemo()
{
}
| 18.625 | 83 | 0.663471 | [
"vector"
] |
43bdc2e55b95daf568cb96d75bfc9acb15f85a5c | 892 | cpp | C++ | Graph/Dijkstra.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | Graph/Dijkstra.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | Graph/Dijkstra.cpp | maguroplusia/Library | 02e0e277986833fe1c12e20b3677a553b7b27346 | [
"CC0-1.0"
] | null | null | null | template<typename T>
struct edge {
int to;
T cost;
};
vector<int> pre;
template<typename T>
vector<T> Dijkstra(const int& N,const vector<vector<edge<T>>>& graph,const int& s) {
priority_queue<pair<T,int>,vector<pair<T,int>>,greater<pair<T,int>>> que;
vector<T> dist(N,numeric_limits<T>::max());
pre = vector<int>(N,-1);
dist[s] = 0;
que.push({0,s});
while(!que.empty()) {
auto [cost,v] = que.top();
que.pop();
if(dist[v] < cost) continue;
for(const auto& [to,d]:graph[v]) {
if(chmin(dist[to],dist[v] + d)) {
pre[to] = v;
que.push({dist[to],to});
}
}
}
return dist;
}
vector<int> GetPath(int t) {
vector<int> path;
while(t != -1) {
path.push_back(t);
t = pre[t];
}
reverse(path.begin(),path.end());
return path;
}
| 20.744186 | 84 | 0.51009 | [
"vector"
] |
43c0d3fa75060c7592c1bae7ec775eb60a547a09 | 17,999 | cc | C++ | ns-allinone-3.35/ns-3.35/src/wifi/model/wifi-phy-state-helper.cc | usi-systems/cc | 487aa9e322b2b01b6af3a92e38545c119e4980a3 | [
"Apache-2.0"
] | 1 | 2022-03-22T08:08:35.000Z | 2022-03-22T08:08:35.000Z | ns-3-dev/src/wifi/model/wifi-phy-state-helper.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null | ns-3-dev/src/wifi/model/wifi-phy-state-helper.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2005,2006 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#include <algorithm>
#include "ns3/log.h"
#include "ns3/simulator.h"
#include "ns3/packet.h"
#include "wifi-phy-state-helper.h"
#include "wifi-tx-vector.h"
#include "wifi-phy-listener.h"
#include "wifi-psdu.h"
#include "wifi-phy.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("WifiPhyStateHelper");
NS_OBJECT_ENSURE_REGISTERED (WifiPhyStateHelper);
TypeId
WifiPhyStateHelper::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::WifiPhyStateHelper")
.SetParent<Object> ()
.SetGroupName ("Wifi")
.AddConstructor<WifiPhyStateHelper> ()
.AddTraceSource ("State",
"The state of the PHY layer",
MakeTraceSourceAccessor (&WifiPhyStateHelper::m_stateLogger),
"ns3::WifiPhyStateHelper::StateTracedCallback")
.AddTraceSource ("RxOk",
"A packet has been received successfully.",
MakeTraceSourceAccessor (&WifiPhyStateHelper::m_rxOkTrace),
"ns3::WifiPhyStateHelper::RxOkTracedCallback")
.AddTraceSource ("RxError",
"A packet has been received unsuccessfully.",
MakeTraceSourceAccessor (&WifiPhyStateHelper::m_rxErrorTrace),
"ns3::WifiPhyStateHelper::RxEndErrorTracedCallback")
.AddTraceSource ("Tx", "Packet transmission is starting.",
MakeTraceSourceAccessor (&WifiPhyStateHelper::m_txTrace),
"ns3::WifiPhyStateHelper::TxTracedCallback")
;
return tid;
}
WifiPhyStateHelper::WifiPhyStateHelper ()
: m_sleeping (false),
m_isOff (false),
m_endTx (Seconds (0)),
m_endRx (Seconds (0)),
m_endCcaBusy (Seconds (0)),
m_endSwitching (Seconds (0)),
m_startTx (Seconds (0)),
m_startRx (Seconds (0)),
m_startCcaBusy (Seconds (0)),
m_startSwitching (Seconds (0)),
m_startSleep (Seconds (0)),
m_previousStateChangeTime (Seconds (0))
{
NS_LOG_FUNCTION (this);
}
void
WifiPhyStateHelper::SetReceiveOkCallback (RxOkCallback callback)
{
m_rxOkCallback = callback;
}
void
WifiPhyStateHelper::SetReceiveErrorCallback (RxErrorCallback callback)
{
m_rxErrorCallback = callback;
}
void
WifiPhyStateHelper::RegisterListener (WifiPhyListener *listener)
{
m_listeners.push_back (listener);
}
void
WifiPhyStateHelper::UnregisterListener (WifiPhyListener *listener)
{
ListenersI i = find (m_listeners.begin (), m_listeners.end (), listener);
if (i != m_listeners.end ())
{
m_listeners.erase (i);
}
}
bool
WifiPhyStateHelper::IsStateIdle (void) const
{
return (GetState () == WifiPhyState::IDLE);
}
bool
WifiPhyStateHelper::IsStateCcaBusy (void) const
{
return (GetState () == WifiPhyState::CCA_BUSY);
}
bool
WifiPhyStateHelper::IsStateRx (void) const
{
return (GetState () == WifiPhyState::RX);
}
bool
WifiPhyStateHelper::IsStateTx (void) const
{
return (GetState () == WifiPhyState::TX);
}
bool
WifiPhyStateHelper::IsStateSwitching (void) const
{
return (GetState () == WifiPhyState::SWITCHING);
}
bool
WifiPhyStateHelper::IsStateSleep (void) const
{
return (GetState () == WifiPhyState::SLEEP);
}
bool
WifiPhyStateHelper::IsStateOff (void) const
{
return (GetState () == WifiPhyState::OFF);
}
Time
WifiPhyStateHelper::GetDelayUntilIdle (void) const
{
Time retval;
switch (GetState ())
{
case WifiPhyState::RX:
retval = m_endRx - Simulator::Now ();
break;
case WifiPhyState::TX:
retval = m_endTx - Simulator::Now ();
break;
case WifiPhyState::CCA_BUSY:
retval = m_endCcaBusy - Simulator::Now ();
break;
case WifiPhyState::SWITCHING:
retval = m_endSwitching - Simulator::Now ();
break;
case WifiPhyState::IDLE:
case WifiPhyState::SLEEP:
case WifiPhyState::OFF:
retval = Seconds (0);
break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state.");
retval = Seconds (0);
break;
}
retval = Max (retval, Seconds (0));
return retval;
}
Time
WifiPhyStateHelper::GetLastRxStartTime (void) const
{
return m_startRx;
}
Time
WifiPhyStateHelper::GetLastRxEndTime (void) const
{
return m_endRx;
}
WifiPhyState
WifiPhyStateHelper::GetState (void) const
{
if (m_isOff)
{
return WifiPhyState::OFF;
}
if (m_sleeping)
{
return WifiPhyState::SLEEP;
}
else if (m_endTx > Simulator::Now ())
{
return WifiPhyState::TX;
}
else if (m_endRx > Simulator::Now ())
{
return WifiPhyState::RX;
}
else if (m_endSwitching > Simulator::Now ())
{
return WifiPhyState::SWITCHING;
}
else if (m_endCcaBusy > Simulator::Now ())
{
return WifiPhyState::CCA_BUSY;
}
else
{
return WifiPhyState::IDLE;
}
}
void
WifiPhyStateHelper::NotifyTxStart (Time duration, double txPowerDbm)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyTxStart (duration, txPowerDbm);
}
}
void
WifiPhyStateHelper::NotifyRxStart (Time duration)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyRxStart (duration);
}
}
void
WifiPhyStateHelper::NotifyRxEndOk (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyRxEndOk ();
}
}
void
WifiPhyStateHelper::NotifyRxEndError (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyRxEndError ();
}
}
void
WifiPhyStateHelper::NotifyMaybeCcaBusyStart (Time duration)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyMaybeCcaBusyStart (duration);
}
}
void
WifiPhyStateHelper::NotifySwitchingStart (Time duration)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifySwitchingStart (duration);
}
}
void
WifiPhyStateHelper::NotifySleep (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifySleep ();
}
}
void
WifiPhyStateHelper::NotifyOff (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyOff ();
}
}
void
WifiPhyStateHelper::NotifyWakeup (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyWakeup ();
}
}
void
WifiPhyStateHelper::NotifyOn (void)
{
NS_LOG_FUNCTION (this);
for (Listeners::const_iterator i = m_listeners.begin (); i != m_listeners.end (); i++)
{
(*i)->NotifyOn ();
}
}
void
WifiPhyStateHelper::LogPreviousIdleAndCcaBusyStates (void)
{
NS_LOG_FUNCTION (this);
Time now = Simulator::Now ();
Time idleStart = Max (m_endCcaBusy, m_endRx);
idleStart = Max (idleStart, m_endTx);
idleStart = Max (idleStart, m_endSwitching);
NS_ASSERT (idleStart <= now);
if (m_endCcaBusy > m_endRx
&& m_endCcaBusy > m_endSwitching
&& m_endCcaBusy > m_endTx)
{
Time ccaBusyStart = Max (m_endTx, m_endRx);
ccaBusyStart = Max (ccaBusyStart, m_startCcaBusy);
ccaBusyStart = Max (ccaBusyStart, m_endSwitching);
Time ccaBusyDuration = idleStart - ccaBusyStart;
if (ccaBusyDuration.IsStrictlyPositive ())
{
m_stateLogger (ccaBusyStart, ccaBusyDuration, WifiPhyState::CCA_BUSY);
}
}
Time idleDuration = now - idleStart;
if (idleDuration.IsStrictlyPositive ())
{
m_stateLogger (idleStart, idleDuration, WifiPhyState::IDLE);
}
}
void
WifiPhyStateHelper::SwitchToTx (Time txDuration, WifiConstPsduMap psdus, double txPowerDbm, WifiTxVector txVector)
{
NS_LOG_FUNCTION (this << txDuration << psdus << txPowerDbm << txVector);
if (!m_txTrace.IsEmpty ())
{
for (auto const& psdu : psdus)
{
m_txTrace (psdu.second->GetPacket (), txVector.GetMode (psdu.first),
txVector.GetPreambleType (), txVector.GetTxPowerLevel ());
}
}
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::RX:
/* The packet which is being received as well
* as its endRx event are cancelled by the caller.
*/
m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX);
m_endRx = now;
break;
case WifiPhyState::CCA_BUSY:
{
Time ccaStart = Max (m_endRx, m_endTx);
ccaStart = Max (ccaStart, m_startCcaBusy);
ccaStart = Max (ccaStart, m_endSwitching);
m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY);
} break;
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state.");
break;
}
m_stateLogger (now, txDuration, WifiPhyState::TX);
m_previousStateChangeTime = now;
m_endTx = now + txDuration;
m_startTx = now;
NotifyTxStart (txDuration, txPowerDbm);
}
void
WifiPhyStateHelper::SwitchToRx (Time rxDuration)
{
NS_LOG_FUNCTION (this << rxDuration);
NS_ASSERT (IsStateIdle () || IsStateCcaBusy ());
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
case WifiPhyState::CCA_BUSY:
{
Time ccaStart = Max (m_endRx, m_endTx);
ccaStart = Max (ccaStart, m_startCcaBusy);
ccaStart = Max (ccaStart, m_endSwitching);
m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY);
} break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state " << GetState ());
break;
}
m_previousStateChangeTime = now;
m_startRx = now;
m_endRx = now + rxDuration;
NotifyRxStart (rxDuration);
NS_ASSERT (IsStateRx ());
}
void
WifiPhyStateHelper::SwitchToChannelSwitching (Time switchingDuration)
{
NS_LOG_FUNCTION (this << switchingDuration);
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::RX:
/* The packet which is being received as well
* as its endRx event are cancelled by the caller.
*/
m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX);
m_endRx = now;
break;
case WifiPhyState::CCA_BUSY:
{
Time ccaStart = Max (m_endRx, m_endTx);
ccaStart = Max (ccaStart, m_startCcaBusy);
ccaStart = Max (ccaStart, m_endSwitching);
m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY);
} break;
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state.");
break;
}
if (now < m_endCcaBusy)
{
m_endCcaBusy = now;
}
m_stateLogger (now, switchingDuration, WifiPhyState::SWITCHING);
m_previousStateChangeTime = now;
m_startSwitching = now;
m_endSwitching = now + switchingDuration;
NotifySwitchingStart (switchingDuration);
NS_ASSERT (IsStateSwitching ());
}
void
WifiPhyStateHelper::ContinueRxNextMpdu (Ptr<WifiPsdu> psdu, RxSignalInfo rxSignalInfo, WifiTxVector txVector)
{
NS_LOG_FUNCTION (this << *psdu << rxSignalInfo << txVector);
std::vector<bool> statusPerMpdu;
if (!m_rxOkCallback.IsNull ())
{
m_rxOkCallback (psdu, rxSignalInfo, txVector, statusPerMpdu);
}
}
void
WifiPhyStateHelper::SwitchFromRxEndOk (Ptr<WifiPsdu> psdu, RxSignalInfo rxSignalInfo, WifiTxVector txVector, uint16_t staId, std::vector<bool> statusPerMpdu)
{
NS_LOG_FUNCTION (this << *psdu << rxSignalInfo << txVector << staId << statusPerMpdu.size () <<
std::all_of(statusPerMpdu.begin(), statusPerMpdu.end(), [](bool v) { return v; })); //returns true if all true
NS_ASSERT (statusPerMpdu.size () != 0);
NS_ASSERT (Abs (m_endRx - Simulator::Now ()) < MicroSeconds (1)); //1us corresponds to the maximum propagation delay (delay spread)
//TODO: a better fix would be to call the function once all HE TB PPDUs are received
if (!m_rxOkTrace.IsEmpty ())
{
m_rxOkTrace (psdu->GetPacket (), rxSignalInfo.snr, txVector.GetMode (staId),
txVector.GetPreambleType ());
}
NotifyRxEndOk ();
DoSwitchFromRx ();
if (!m_rxOkCallback.IsNull ())
{
m_rxOkCallback (psdu, rxSignalInfo, txVector, statusPerMpdu);
}
}
void
WifiPhyStateHelper::SwitchFromRxEndError (Ptr<WifiPsdu> psdu, double snr)
{
NS_LOG_FUNCTION (this << *psdu << snr);
NS_ASSERT (Abs (m_endRx - Simulator::Now ()) < MicroSeconds (1)); //1us corresponds to the maximum propagation delay (delay spread)
//TODO: a better fix would be to call the function once all HE TB PPDUs are received
if (!m_rxErrorTrace.IsEmpty ())
{
m_rxErrorTrace (psdu->GetPacket (), snr);
}
NotifyRxEndError ();
DoSwitchFromRx ();
if (!m_rxErrorCallback.IsNull ())
{
m_rxErrorCallback (psdu);
}
}
void
WifiPhyStateHelper::DoSwitchFromRx (void)
{
NS_LOG_FUNCTION (this);
Time now = Simulator::Now ();
m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX);
m_previousStateChangeTime = now;
m_endRx = Simulator::Now ();
NS_ASSERT (IsStateIdle () || IsStateCcaBusy ());
}
void
WifiPhyStateHelper::SwitchMaybeToCcaBusy (Time duration)
{
NS_LOG_FUNCTION (this << duration);
if (GetState () != WifiPhyState::RX)
{
NotifyMaybeCcaBusyStart (duration);
}
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
case WifiPhyState::RX:
return;
default:
break;
}
if (GetState () != WifiPhyState::CCA_BUSY)
{
m_startCcaBusy = now;
}
m_endCcaBusy = std::max (m_endCcaBusy, now + duration);
}
void
WifiPhyStateHelper::SwitchToSleep (void)
{
NS_LOG_FUNCTION (this);
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
case WifiPhyState::CCA_BUSY:
{
Time ccaStart = Max (m_endRx, m_endTx);
ccaStart = Max (ccaStart, m_startCcaBusy);
ccaStart = Max (ccaStart, m_endSwitching);
m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY);
} break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state.");
break;
}
m_previousStateChangeTime = now;
m_sleeping = true;
m_startSleep = now;
NotifySleep ();
NS_ASSERT (IsStateSleep ());
}
void
WifiPhyStateHelper::SwitchFromSleep (Time duration)
{
NS_LOG_FUNCTION (this << duration);
NS_ASSERT (IsStateSleep ());
Time now = Simulator::Now ();
m_stateLogger (m_startSleep, now - m_startSleep, WifiPhyState::SLEEP);
m_previousStateChangeTime = now;
m_sleeping = false;
NotifyWakeup ();
//update m_endCcaBusy after the sleep period
m_endCcaBusy = std::max (m_endCcaBusy, now + duration);
if (m_endCcaBusy > now)
{
NotifyMaybeCcaBusyStart (m_endCcaBusy - now);
}
}
void
WifiPhyStateHelper::SwitchFromRxAbort (void)
{
NS_LOG_FUNCTION (this);
NS_ASSERT (IsStateCcaBusy ()); //abort is called (with OBSS_PD_CCA_RESET reason) before RX is set by payload start
NotifyRxEndOk ();
DoSwitchFromRx ();
m_endCcaBusy = Simulator::Now ();
NotifyMaybeCcaBusyStart (Seconds (0));
NS_ASSERT (IsStateIdle ());
}
void
WifiPhyStateHelper::SwitchToOff (void)
{
NS_LOG_FUNCTION (this);
Time now = Simulator::Now ();
switch (GetState ())
{
case WifiPhyState::RX:
/* The packet which is being received as well
* as its endRx event are cancelled by the caller.
*/
m_stateLogger (m_startRx, now - m_startRx, WifiPhyState::RX);
m_endRx = now;
break;
case WifiPhyState::TX:
/* The packet which is being transmitted as well
* as its endTx event are cancelled by the caller.
*/
m_stateLogger (m_startTx, now - m_startTx, WifiPhyState::TX);
m_endTx = now;
break;
case WifiPhyState::IDLE:
LogPreviousIdleAndCcaBusyStates ();
break;
case WifiPhyState::CCA_BUSY:
{
Time ccaStart = Max (m_endRx, m_endTx);
ccaStart = Max (ccaStart, m_startCcaBusy);
ccaStart = Max (ccaStart, m_endSwitching);
m_stateLogger (ccaStart, now - ccaStart, WifiPhyState::CCA_BUSY);
} break;
default:
NS_FATAL_ERROR ("Invalid WifiPhy state.");
break;
}
m_previousStateChangeTime = now;
m_isOff = true;
NotifyOff ();
NS_ASSERT (IsStateOff ());
}
void
WifiPhyStateHelper::SwitchFromOff (Time duration)
{
NS_LOG_FUNCTION (this << duration);
NS_ASSERT (IsStateOff ());
Time now = Simulator::Now ();
m_previousStateChangeTime = now;
m_isOff = false;
NotifyOn ();
//update m_endCcaBusy after the off period
m_endCcaBusy = std::max (m_endCcaBusy, now + duration);
if (m_endCcaBusy > now)
{
NotifyMaybeCcaBusyStart (m_endCcaBusy - now);
}
}
} //namespace ns3
| 26.665185 | 157 | 0.664259 | [
"object",
"vector"
] |
43c2afc8fbc4a05ab10842b90ea26753a13360ad | 16,329 | cpp | C++ | octopi/library/octopus/octopus.cpp | fredhamster/feisty_meow | 66dc4221dc485a5cf9e28b724fe36268e8843043 | [
"Apache-2.0"
] | 2 | 2019-01-22T23:34:37.000Z | 2021-10-31T15:44:15.000Z | octopi/library/octopus/octopus.cpp | fredhamster/feisty_meow | 66dc4221dc485a5cf9e28b724fe36268e8843043 | [
"Apache-2.0"
] | 2 | 2020-06-01T16:35:46.000Z | 2021-10-05T21:02:09.000Z | octopi/library/octopus/octopus.cpp | fredhamster/feisty_meow | 66dc4221dc485a5cf9e28b724fe36268e8843043 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************\
* *
* Name : octopus *
* Author : Chris Koeritz *
* *
*******************************************************************************
* Copyright (c) 2002-$now By Author. 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 is online at: *
* http://www.fsf.org/copyleft/gpl.html *
* Please send any updates to: fred@gruntose.com *
\*****************************************************************************/
#include "entity_data_bin.h"
#include "entity_defs.h"
#include "identity_tentacle.h"
#include "infoton.h"
#include "octopus.h"
#include "tentacle.h"
#include "unhandled_request.h"
#include <basis/astring.h>
#include <basis/mutex.h>
#include <configuration/application_configuration.h>
#include <loggers/critical_events.h>
#include <loggers/program_wide_logger.h>
#include <mathematics/chaos.h>
#include <structures/amorph.h>
#include <structures/string_hash.h>
#include <timely/time_control.h>
#include <timely/time_stamp.h>
using namespace basis;
using namespace configuration;
using namespace loggers;
using namespace mathematics;
using namespace processes;
using namespace structures;
using namespace timely;
namespace octopi {
//#define DEBUG_OCTOPUS
// uncomment for debugging noise.
//#define DEBUG_OCTOPUS_FILTERS
// uncomment for noisy filter processing.
#undef GRAB_LOCK
#define GRAB_LOCK \
auto_synchronizer l(*_molock)
// this macro returns a result and deletes the request due to a failure. it
// stores a response for the request, in case they were expecting one, since
// otherwise they will wait a long time for a response that isn't coming. if
// those responses are never picked up, they will eventually be cleaned out.
#define WHACK_RETURN(to_ret, to_whack) { \
unhandled_request *bad_response = new unhandled_request(id, \
request->classifier(), to_ret); \
_responses->add_item(bad_response, id); \
WHACK(to_whack); \
return to_ret; \
}
const int MAXIMUM_TRASH_SIZE = 128 * KILOBYTE;
// this is how much we'll toss out on closing an entity.
#undef LOG
#define LOG(t) CLASS_EMERGENCY_LOG(program_wide_logger::get(), t)
const int OCTOPUS_CHECKING_INTERVAL = 4 * MINUTE_ms;
// the frequency in milliseconds of cleaning on the response bin. this
// doesn't need to happen very often; it only tosses data that has been
// abandoned in the response bin.
//////////////
class filter_list : public array<tentacle *>
{
public:
bool remove(tentacle *to_remove) {
for (int i = 0; i < length(); i++) {
if (get(i) == to_remove) {
zap(i, i);
return true;
}
}
return false;
}
};
//////////////
class tentacle_record
{
public:
tentacle *_limb;
bool _filter;
tentacle_record(tentacle *limb, bool filter)
: _limb(limb), _filter(filter) {}
~tentacle_record() { WHACK(_limb); }
};
//////////////
class modula_oblongata : public amorph<tentacle_record>
{
public:
modula_oblongata() : amorph<tentacle_record>() {}
int find_index(const string_array &group) {
for (int i = 0; i < elements(); i++) {
if (borrow(i)->_limb->group().prefix_compare(group))
return i;
}
return common::NOT_FOUND;
}
tentacle *find(const string_array &group) {
int indy = find_index(group);
if (negative(indy)) return NULL_POINTER;
return borrow(indy)->_limb;
}
bool zap(int a, int b) {
outcome ret = amorph<tentacle_record>::zap(a, b);
return ret == common::OKAY;
}
bool zap(const string_array &group) {
int indy = find_index(group);
if (negative(indy)) return false;
amorph<tentacle_record>::zap(indy, indy);
return true;
}
};
//////////////
octopus::octopus(const astring &name, int max_per_ent)
: _name(new astring(name)),
_tentacles(new modula_oblongata),
_molock(new mutex),
_responses(new entity_data_bin(max_per_ent)),
_disallow_removals(0),
_next_cleaning(new time_stamp(OCTOPUS_CHECKING_INTERVAL)),
_clean_lock(new mutex),
_filters(new filter_list),
_sequencer(new safe_roller(1, MAXINT32 / 2)),
_rando(new chaos)
{
add_tentacle(new identity_tentacle(*this), true);
// register a way to issue identities. this is a filter.
add_tentacle(new unhandled_request_tentacle(false), false);
// provide a way to unpack the unhandled_request object.
}
octopus::~octopus()
{
FUNCDEF("destructor");
WHACK(_filters);
WHACK(_tentacles);
WHACK(_responses);
WHACK(_next_cleaning);
WHACK(_clean_lock);
WHACK(_name);
WHACK(_molock);
WHACK(_rando);
WHACK(_sequencer);
}
void octopus::lock_tentacles() { _molock->lock(); }
void octopus::unlock_tentacles() { _molock->unlock(); }
entity_data_bin &octopus::responses() { return *_responses; }
int octopus::locked_tentacle_count() { return _tentacles->elements(); }
const astring &octopus::name() const { return *_name; }
tentacle *octopus::locked_get_tentacle(int indy)
{ return _tentacles->borrow(indy)->_limb; }
infoton *octopus::acquire_specific_result(const octopus_request_id &id)
{ return _responses->acquire_for_identifier(id); }
infoton *octopus::acquire_result(const octopus_entity &requester,
octopus_request_id &id)
{ return _responses->acquire_for_entity(requester, id); }
void octopus::unlock_tentacle(tentacle *to_unlock)
{
to_unlock = NULL_POINTER;
_molock->unlock();
}
void octopus::expunge(const octopus_entity &to_remove)
{
FUNCDEF("expunge");
{
// temporary lock so we can keep tentacles from evaporating.
GRAB_LOCK;
_disallow_removals++;
}
// we've now ensured that no tentacles will be removed, so at most the
// list would get longer. we'll settle on its current length.
int len = _tentacles->elements();
for (int i = 0; i < len; i++) {
tentacle_record *curr = _tentacles->borrow(i);
if (!curr || !curr->_limb) {
//complain... logic error.
continue;
}
// activate the expunge method on the current tentacle.
curr->_limb->expunge(to_remove);
}
{
// re-enable tentacle removals.
GRAB_LOCK;
_disallow_removals--;
}
// throw out any data that was waiting for that guy.
int items_found = 1;
infoton_list junk;
while (items_found) {
// grab a chunk of items to be trashed.
items_found = responses().acquire_for_entity(to_remove, junk,
MAXIMUM_TRASH_SIZE);
junk.reset();
//#ifdef DEBUG_OCTOPUS
if (items_found)
LOG(a_sprintf("cleaned %d items for expunged entity ", items_found)
+ to_remove.mangled_form());
//#endif
}
}
outcome octopus::zap_tentacle(const string_array &tentacle_name)
{
tentacle *found = NULL_POINTER;
outcome ret = remove_tentacle(tentacle_name, found);
WHACK(found);
return ret;
}
outcome octopus::add_tentacle(tentacle *to_add, bool filter)
{
FUNCDEF("add_tentacle");
if (!to_add) return tentacle::BAD_INPUT;
if (!to_add->group().length()) return tentacle::BAD_INPUT;
outcome zapped_it = zap_tentacle(to_add->group());
if (zapped_it == tentacle::OKAY) {
//#ifdef DEBUG_OCTOPUS
LOG(astring("removed existing tentacle: ") + to_add->group().text_form());
//#endif
}
GRAB_LOCK;
tentacle *found = _tentacles->find(to_add->group());
// if found is non-null, then that would be a serious logic error since
// we just zapped it above.
if (found) return tentacle::ALREADY_EXISTS;
to_add->attach_storage(*_responses);
tentacle_record *new_record = new tentacle_record(to_add, filter);
_tentacles->append(new_record);
if (filter) *_filters += to_add;
#ifdef DEBUG_OCTOPUS
LOG(astring("added tentacle on ") + to_add->group().text_form());
#endif
return tentacle::OKAY;
}
outcome octopus::remove_tentacle(const string_array &group_name,
tentacle * &free_me)
{
FUNCDEF("remove_tentacle");
free_me = NULL_POINTER;
if (!group_name.length()) return tentacle::BAD_INPUT;
while (true) {
// repeatedly grab the lock and make sure we're allowed to remove. if
// we're told we can't remove yet, then we drop the lock again and pause.
_molock->lock();
if (!_disallow_removals) {
// we ARE allowed to remove it right now. we leave the loop in
// possession of the lock.
break;
}
if (_disallow_removals < 0) {
continuable_error(class_name(), func, "logic error in removal "
"reference counter.");
}
_molock->unlock();
time_control::sleep_ms(0); // yield thread's execution to another thread.
}
int indy = _tentacles->find_index(group_name);
if (negative(indy)) {
// nope, no match.
_molock->unlock();
return tentacle::NOT_FOUND;
}
// found the match.
tentacle_record *freeing = _tentacles->acquire(indy);
_tentacles->zap(indy, indy);
free_me = freeing->_limb;
_filters->remove(free_me);
_molock->unlock();
freeing->_limb = NULL_POINTER;
WHACK(freeing);
return tentacle::OKAY;
}
outcome octopus::restore(const string_array &classifier,
byte_array &packed_form, infoton * &reformed)
{
#ifdef DEBUG_OCTOPUS
FUNCDEF("restore");
#endif
periodic_cleaning(); // freshen up if it's that time.
reformed = NULL_POINTER;
if (!classifier.length()) return tentacle::BAD_INPUT;
if (!packed_form.length()) return tentacle::BAD_INPUT;
if (!classifier.length()) return tentacle::BAD_INPUT;
{
// keep anyone from being removed until we're done.
GRAB_LOCK;
_disallow_removals++;
}
tentacle *found = _tentacles->find(classifier);
outcome to_return;
if (!found) {
#ifdef DEBUG_OCTOPUS
LOG(astring("tentacle not found for: ") + classifier.text_form());
#endif
to_return = tentacle::NOT_FOUND;
} else {
to_return = found->reconstitute(classifier, packed_form, reformed);
}
// re-enable tentacle removals.
GRAB_LOCK;
_disallow_removals--;
return to_return;
}
outcome octopus::evaluate(infoton *request, const octopus_request_id &id,
bool now)
{
FUNCDEF("evaluate");
periodic_cleaning(); // freshen up if it's that time.
// check that the classifier is well formed.
if (!request->classifier().length()) {
#ifdef DEBUG_OCTOPUS
LOG("failed due to empty classifier.");
#endif
WHACK_RETURN(tentacle::BAD_INPUT, request);
}
_molock->lock();
// block tentacle removals while we're working.
_disallow_removals++;
// ensure that we pass this infoton through all the filters for vetting.
for (int i = 0; i < _filters->length(); i++) {
tentacle *current = (*_filters)[i];
#ifdef DEBUG_OCTOPUS_FILTERS
LOG(a_sprintf("%d: checking ", i + 1) + current->group().text_form());
#endif
// check if the infoton is addressed specifically by this filter.
bool is_relevant = current->group().prefix_compare(request->classifier());
#ifdef DEBUG_OCTOPUS_FILTERS
if (is_relevant)
LOG(astring("found it to be relevant! for ") + id.text_form())
else
LOG(astring("found it to not be relevant. for ") + id.text_form());
#endif
// this infoton is _for_ this filter.
_molock->unlock();
// unlock octopus to allow others to operate.
byte_array transformed;
//hmmm: maybe there should be a separate filter method?
outcome to_return = current->consume(*request, id, transformed);
// pass the infoton into the current filter.
if (is_relevant) {
// the infoton was _for_ the current filter. that means that we are
// done processing it now.
#ifdef DEBUG_OCTOPUS_FILTERS
LOG(astring("filter ") + current->group().text_form() + " consumed "
"infoton from " + id.text_form() + " with result "
+ tentacle::outcome_name(to_return));
#endif
WHACK(request);
GRAB_LOCK; // short re-establishment of the lock.
_disallow_removals--;
return to_return;
} else {
// the infoton was vetted by the filter. make sure it was liked.
#ifdef DEBUG_OCTOPUS_FILTERS
LOG(astring("filter ") + current->group().text_form() + " vetted "
"infoton " + id.text_form() + " with result "
+ tentacle::outcome_name(to_return));
#endif
if (to_return == tentacle::PARTIAL) {
// if the infoton is partially complete, then we're allowed to keep
// going. this outcome means it was not prohibited.
// make sure they didn't switch it out on us.
if (transformed.length()) {
// we need to substitute the transformed version for the original.
string_array classif;
byte_array decro; // decrypted packed infoton.
bool worked = infoton::fast_unpack(transformed, classif, decro);
if (!worked) {
LOG("failed to fast_unpack the transformed data.");
} else {
infoton *new_req = NULL_POINTER;
outcome rest_ret = restore(classif, decro, new_req);
if (rest_ret == tentacle::OKAY) {
// we got a good transformed version.
WHACK(request);
request = new_req; // substitution complete.
} else {
LOG("failed to restore transformed infoton.");
}
}
}
_molock->lock(); // get the lock again.
continue;
} else {
// this is a failure to process that object.
#ifdef DEBUG_OCTOPUS_FILTERS
LOG(astring("filter ") + current->group().text_form() + " denied "
"infoton from " + id.text_form());
#endif
{
GRAB_LOCK; // short re-establishment of the lock.
_disallow_removals--;
}
WHACK_RETURN(to_return, request);
}
}
}
// if we're here, then the infoton has been approved by all filters.
#ifdef DEBUG_OCTOPUS_FILTERS
LOG(astring("all filters approved infoton: ") + id.text_form());
#endif
// locate the appropriate tentacle for this request.
tentacle *found = _tentacles->find(request->classifier());
_molock->unlock();
// from here in, the octopus itself is not locked up. but we have sent
// the signal that no one must remove any tentacles for now.
if (!found) {
#ifdef DEBUG_OCTOPUS
LOG(astring("tentacle not found for: ")
+ request->classifier().text_form());
#endif
GRAB_LOCK; // short re-establishment of the lock.
_disallow_removals--;
WHACK_RETURN(tentacle::NOT_FOUND, request);
}
// make sure they want background execution and that the tentacle can
// support this.
if (!now && found->backgrounding()) {
// pass responsibility over to the tentacle.
outcome to_return = found->enqueue(request, id);
GRAB_LOCK; // short re-establishment of the lock.
_disallow_removals--;
return to_return;
} else {
// call the tentacle directly.
byte_array ignored;
outcome to_return = found->consume(*request, id, ignored);
WHACK(request);
GRAB_LOCK; // short re-establishment of the lock.
_disallow_removals--;
return to_return;
}
}
void octopus::periodic_cleaning()
{
FUNCDEF("periodic_cleaning");
time_stamp next_time;
{
auto_synchronizer l(*_clean_lock);
next_time = *_next_cleaning;
}
if (next_time < time_stamp()) {
// the bin locks itself, so we don't need to grab the lock here.
_responses->clean_out_deadwood();
auto_synchronizer l(*_clean_lock);
// lock before modifying the time stamp; only one writer.
_next_cleaning->reset(OCTOPUS_CHECKING_INTERVAL);
}
}
tentacle *octopus::lock_tentacle(const string_array &tentacle_name)
{
if (!tentacle_name.length()) return NULL_POINTER;
_molock->lock();
tentacle *found = _tentacles->find(tentacle_name);
if (!found) {
_molock->unlock();
return NULL_POINTER;
}
return found;
}
octopus_entity octopus::issue_identity()
{
return octopus_entity(*_name, application_configuration::process_id(), _sequencer->next_id(),
_rando->inclusive(0, MAXINT32 / 4));
}
} //namespace.
| 30.521495 | 95 | 0.655215 | [
"object"
] |
43c70f83218af68c46ebc90520bdaa7d758b131f | 5,645 | hpp | C++ | src/api/dcps/isocpp2/include/dds/sub/LoanedSamples.hpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 133 | 2017-11-09T02:10:00.000Z | 2022-03-29T09:45:10.000Z | src/api/dcps/isocpp2/include/dds/sub/LoanedSamples.hpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 131 | 2017-11-07T14:48:43.000Z | 2022-03-13T15:30:47.000Z | src/api/dcps/isocpp2/include/dds/sub/LoanedSamples.hpp | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 94 | 2017-11-09T02:26:19.000Z | 2022-02-24T06:38:25.000Z | /* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Corp.
* Copyright 2010, Real-Time Innovations, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OMG_DDS_SUB_TLOANED_SAMPLES_HPP_
#define OMG_DDS_SUB_TLOANED_SAMPLES_HPP_
#include <dds/core/ref_traits.hpp>
#include <dds/sub/Sample.hpp>
#include <dds/sub/detail/LoanedSamples.hpp>
/** @cond */
namespace dds
{
namespace sub
{
template <typename T,
template <typename Q> class DELEGATE = dds::sub::detail::LoanedSamples>
class LoanedSamples;
// Used by C++11 compilers to allow for using LoanedSamples
// and SharedSamples in a range-based for-loop.
template <typename T> typename T::const_iterator cbegin(const T& t);
template <typename T> typename T::const_iterator cend(const T& t);
}
}
/** @endcond */
/**
* @brief
* This class encapsulates and automates the management of loaned samples.
*
* It is a container which is used to hold samples which have been read
* or taken by the DataReader. Samples are effectively "loaned" from the
* DataReader to avoid the need to copy the data. When the LoanedSamples
* container goes out of scope the loan is automatically returned.
*
* LoanedSamples maintains a ref count so that the loan will only be
* returned once all copies of the same LoanedSamples have been destroyed.
*
* @anchor anchor_dds_sub_loanedsamples_example
* @code{.cpp}
* dds::domain::DomainParticipant participant(org::opensplice::domain::default_id());
* dds::topic::Topic<Foo::Bar> topic(participant, "TopicName");
* dds::sub::Subscriber subscriber(participant);
* dds::sub::DataReader<Foo::Bar> reader(subscriber, topic);
*
* // Assume there is data to read
* {
* dds::sub::LoanedSamples<Foo::Bar> samples = reader.read();
* dds::sub::LoanedSamples<Foo::Bar>::const_iterator it;
* for (it = samples.begin(); it != samples.end(); ++it) {
* const dds::sub::Sample<Foo::Bar>& sample = *it;
* const Foo::Bar& data = sample.data();
* const dds::sub::SampleInfo& info = sample.info();
* // Use sample data and meta information.
* }
*
* function(samples);
* }
* // LoanedSamples out of scope. Whether the loan is returned, depends what the reference
* // count of the LoanedSamples is. That again, depends on what the function() did with it.
* // Maybe function() stored the LoanedSamples, maybe not. Whatever the case, LoanedSamples
* // takes care of the loan and resource handling.
* @endcode
*
* @see @ref DCPS_Modules_Subscription_DataSample "DataSample" for more information
* @see @ref DCPS_Modules_Subscription_SampleInfo "SampleInfo" for more information
* @see @ref DCPS_Modules_Subscription "Subscription" for more information
*/
template <typename T, template <typename Q> class DELEGATE>
class dds::sub::LoanedSamples
{
public:
/**
* Convenience typedef for the type of the data sample.
*/
typedef T DataType;
/**
* Convenience typedef for the iterator over the loaned samples.
*/
typedef typename DELEGATE<T>::const_iterator const_iterator;
/** @cond */
typedef typename dds::core::smart_ptr_traits< DELEGATE<T> >::ref_type DELEGATE_REF_T;
/** @endcond */
public:
/**
* Constructs a LoanedSamples instance.
*/
LoanedSamples();
/**
* Implicitly return the loan if this is the last object with a reference to the
* contained loan.
*/
~LoanedSamples();
/**
* Copies a LoanedSamples instance.
*
* No actual data samples are copied.<br>
* Just references and reference counts are updated.
*/
LoanedSamples(const LoanedSamples& other);
public:
/**
* Gets an iterator pointing to the first sample in the LoanedSamples container.
*
* See @ref anchor_dds_sub_loanedsamples_example "example".
*
* @return an iterator pointing to the first sample
*/
const_iterator begin() const;
/**
* Gets an iterator pointing to the end of the LoanedSamples container.
*
* See @ref anchor_dds_sub_loanedsamples_example "example".
*
* @return an iterator pointing to the end of the container
*/
const_iterator end() const;
/**
* @cond
* The delegate part of the LoanedSamples should not be part of the API.
*/
/**
* Gets the delegate.
*
* @return the delegate
*/
const DELEGATE_REF_T& delegate() const;
/**
* Gets the delegate.
*
* @return the delegate
*/
DELEGATE_REF_T& delegate();
/** @endcond */
/**
* Gets the number of samples within the LoanedSamples container.
*
* @return the number of samples
*/
uint32_t length() const;
private:
DELEGATE_REF_T delegate_;
};
namespace dds
{
namespace sub
{
/**
* Move loan and its ownership to a new LoanedSamples object.
*
* @return LoanedSampless
*/
template <typename T, template <typename Q> class D>
LoanedSamples<T, D >
move(LoanedSamples<T, D >& a);
}
}
#include <dds/sub/detail/LoanedSamplesImpl.hpp>
#endif /* OMG_DDS_SUB_TLOANED_SAMPLES_HPP_ */
| 29.401042 | 92 | 0.686802 | [
"object"
] |
43c95378c86bd2dfc7059b94edd366f541367419 | 31,710 | cpp | C++ | src/tools/assemblyManager.cpp | bartvbw/MILO | 334e9bdec954b0cb82da0576b339729e3f39afd0 | [
"BSD-2-Clause"
] | 3 | 2018-10-23T21:04:15.000Z | 2020-01-03T21:49:05.000Z | src/tools/assemblyManager.cpp | bartvbw/MILO | 334e9bdec954b0cb82da0576b339729e3f39afd0 | [
"BSD-2-Clause"
] | 1 | 2018-11-27T23:41:57.000Z | 2018-11-27T23:41:57.000Z | src/tools/assemblyManager.cpp | bartvbw/MILO | 334e9bdec954b0cb82da0576b339729e3f39afd0 | [
"BSD-2-Clause"
] | 1 | 2018-11-13T15:53:47.000Z | 2018-11-13T15:53:47.000Z | /***********************************************************************
Multiscale/Multiphysics Interfaces for Large-scale Optimization (MILO)
Copyright 2018 National Technology & Engineering Solutions of Sandia,
LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the
U.S. Government retains certain rights in this software.”
Questions? Contact Tim Wildey (tmwilde@sandia.gov) and/or
Bart van Bloemen Waanders (bartv@sandia.gov)
************************************************************************/
#include "assemblyManager.hpp"
#include <boost/algorithm/string.hpp>
// ========================================================================================
/* Constructor to set up the problem */
// ========================================================================================
AssemblyManager::AssemblyManager(const Teuchos::RCP<LA_MpiComm> & Comm_, Teuchos::RCP<Teuchos::ParameterList> & settings,
Teuchos::RCP<panzer_stk::STK_Interface> & mesh_, Teuchos::RCP<discretization> & disc_,
Teuchos::RCP<physics> & phys_, Teuchos::RCP<panzer::DOFManager> & DOF_,
vector<vector<Teuchos::RCP<cell> > > & cells_,
vector<vector<Teuchos::RCP<BoundaryCell> > > & boundaryCells_,
Teuchos::RCP<ParameterManager> & params_) :
Comm(Comm_), mesh(mesh_), disc(disc_), phys(phys_), DOF(DOF_), cells(cells_), boundaryCells(boundaryCells_), params(params_) {
// Get the required information from the settings
milo_debug_level = settings->get<int>("debug level",0);
if (milo_debug_level > 0) {
if (Comm->getRank() == 0) {
cout << "**** Starting assembly manager constructor ..." << endl;
}
}
verbosity = settings->get<int>("verbosity",0);
usestrongDBCs = settings->sublist("Solver").get<bool>("use strong DBCs",true);
useNewBCs = settings->sublist("Solver").get<bool>("use new BCs",true);
use_meas_as_dbcs = settings->sublist("Mesh").get<bool>("Use Measurements as DBCs", false);
// needed information from the mesh
mesh->getElementBlockNames(blocknames);
// needed information from the physics interface
numVars = phys->numVars; //
varlist = phys->varlist;
if (milo_debug_level > 0) {
if (Comm->getRank() == 0) {
cout << "**** Finished assembly manager constructor" << endl;
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Worksets
/////////////////////////////////////////////////////////////////////////////
void AssemblyManager::createWorkset() {
if (milo_debug_level > 0) {
if (Comm->getRank() == 0) {
cout << "**** Starting AssemblyManager::createWorkset ..." << endl;
}
}
for (size_t b=0; b<cells.size(); b++) {
wkset.push_back(Teuchos::rcp( new workset(cells[b][0]->getInfo(), disc->ref_ip[b],
disc->ref_wts[b], disc->ref_side_ip[b],
disc->ref_side_wts[b], disc->basis_types[b],
disc->basis_pointers[b],
params->discretized_param_basis,
mesh->getCellTopology(blocknames[b]),
phys->var_bcs[b]) ) );
wkset[b]->isInitialized = true;
wkset[b]->block = b;
}
//phys->setWorkset(wkset);
//params->wkset = wkset;
if (milo_debug_level > 0) {
if (Comm->getRank() == 0) {
cout << "**** Finished AssemblyManager::createWorkset" << endl;
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::updateJacDBC(matrix_RCP & J, size_t & e, size_t & block, int & fieldNum,
size_t & localSideId, const bool & compute_disc_sens) {
// given a "block" and the unknown field update jacobian to enforce Dirichlet BCs
string blockID = blocknames[block];
vector<GO> GIDs;// = cells[block][e]->GIDs;
DOF->getElementGIDs(e, GIDs, blockID);
const pair<vector<int>,vector<int> > SideIndex = DOF->getGIDFieldOffsets_closure(blockID, fieldNum,
(phys->spaceDim)-1, localSideId);
const vector<int> elmtOffset = SideIndex.first; // local nodes on that side
const vector<int> basisIdMap = SideIndex.second;
Teuchos::Array<ScalarT> vals(1);
Teuchos::Array<GO> cols(1);
for( size_t i=0; i<elmtOffset.size(); i++ ) { // for each node
GO row = GIDs[elmtOffset[i]]; // global row
if (compute_disc_sens) {
vector<GO> paramGIDs;// = cells[block][e]->paramGIDs;
params->paramDOF->getElementGIDs(e, paramGIDs, blockID);
for( size_t col=0; col<paramGIDs.size(); col++ ) {
GO ind = paramGIDs[col];
ScalarT m_val = 0.0; // set ALL of the entries to 0 in the Jacobian
//J.ReplaceGlobalValues(row, 1, &m_val, &ind);
J->replaceGlobalValues(ind, 1, &m_val, &row);
}
}
else {
for( size_t col=0; col<GIDs.size(); col++ ) {
cols[0] = GIDs[col];
vals[0] = 0.0; // set ALL of the entries to 0 in the Jacobian
//J->replaceGlobalValues(row, 1, &m_val, &ind);
J->replaceGlobalValues(row, cols, vals);
}
cols[0] = row;
vals[0] = 1.0; // set diagonal entry to 1
//J->replaceGlobalValues(row, 1, &val, &row);
J->replaceGlobalValues(row, cols, vals);
//cout << Comm->getRank() << " " << row << " " << vals[0] << endl;
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::updateJacDBC(matrix_RCP & J, const vector<GO> & dofs, const bool & compute_disc_sens) {
// given a "block" and the unknown field update jacobian to enforce Dirichlet BCs
//size_t numcols = J->getGlobalNumCols();
for( int i=0; i<dofs.size(); i++ ) { // for each node
if (compute_disc_sens) {
GO numcols = globalParamUnknowns;
for( GO col=0; col<numcols; col++ ) {
ScalarT m_val = 0.0; // set ALL of the entries to 0 in the Jacobian
//J.ReplaceGlobalValues(row, 1, &m_val, &ind);
J->replaceGlobalValues(col, 1, &m_val, &dofs[i]);
}
}
else {
GO numcols = J->getGlobalNumCols();
for( GO col=0; col<numcols; col++ ) {
ScalarT m_val = 0.0; // set ALL of the entries to 0 in the Jacobian
J->replaceGlobalValues(dofs[i], 1, &m_val, &col);
}
ScalarT val = 1.0; // set diagonal entry to 1
J->replaceGlobalValues(dofs[i], 1, &val, &dofs[i]);
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::updateResDBC(vector_RCP & resid, size_t & e, size_t & block, int & fieldNum,
size_t & localSideId) {
// given a "block" and the unknown field update resid to enforce Dirichlet BCs
string blockID = blocknames[block];
vector<GO> elemGIDs;
DOF->getElementGIDs(e, elemGIDs, blockID); // compute element global IDs
int numRes = resid->getNumVectors();
const pair<vector<int>,vector<int> > SideIndex = DOF->getGIDFieldOffsets_closure(blockID, fieldNum,
(phys->spaceDim)-1,
localSideId);
const vector<int> elmtOffset = SideIndex.first; // local nodes on that side
const vector<int> basisIdMap = SideIndex.second;
for( size_t i=0; i<elmtOffset.size(); i++ ) { // for each node
GO row = elemGIDs[elmtOffset[i]]; // global row
ScalarT r_val = 0.0; // set residual to 0
for( int j=0; j<numRes; j++ ) {
resid->replaceGlobalValue(row, j, r_val); // replace the value
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::updateResDBC(vector_RCP & resid, const vector<GO> & dofs) {
// given a "block" and the unknown field update resid to enforce Dirichlet BCs
int numRes = resid->getNumVectors();
for( size_t i=0; i<dofs.size(); i++ ) { // for each node
ScalarT r_val = 0.0; // set residual to 0
for( int j=0; j<numRes; j++ ) {
resid->replaceGlobalValue(dofs[i], j, r_val); // replace the value
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::updateResDBCsens(vector_RCP & resid, size_t & e, size_t & block, int & fieldNum, size_t & localSideId,
const std::string & gside, const ScalarT & current_time) {
int fnum = DOF->getFieldNum(varlist[block][fieldNum]);
string blockID = blocknames[block];
vector<GO> elemGIDs;// = cells[block][e]->GIDs[p];
DOF->getElementGIDs(e, elemGIDs, blockID);
int numRes = resid->getNumVectors();
const pair<vector<int>,vector<int> > SideIndex = DOF->getGIDFieldOffsets_closure(blockID, fnum,
(phys->spaceDim)-1,
localSideId);
const vector<int> elmtOffset = SideIndex.first; // local nodes on that side
const vector<int> basisIdMap = SideIndex.second;
for( size_t i=0; i<elmtOffset.size(); i++ ) { // for each node
int row = elemGIDs[elmtOffset[i]]; // global row
ScalarT r_val = 0.0;
for( int j=0; j<numRes; j++ ) {
resid->replaceGlobalValue(row, j, r_val); // replace the value
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::setInitial(vector_RCP & rhs, matrix_RCP & mass, const bool & useadjoint) {
for (size_t b=0; b<cells.size(); b++) {
for (size_t e=0; e<cells[b].size(); e++) {
int numElem = cells[b][e]->numElem;
Kokkos::View<GO**,HostDevice> GIDs = cells[b][e]->GIDs;
Kokkos::View<ScalarT**,AssemblyDevice> localrhs = cells[b][e]->getInitial(true, useadjoint);
Kokkos::View<ScalarT***,AssemblyDevice> localmass = cells[b][e]->getMass();
// assemble into global matrix
for (int c=0; c<numElem; c++) {
for( size_t row=0; row<GIDs.extent(1); row++ ) {
GO rowIndex = GIDs(c,row);
ScalarT val = localrhs(c,row);
rhs->sumIntoGlobalValue(rowIndex,0, val);
for( size_t col=0; col<GIDs.extent(1); col++ ) {
GO colIndex = GIDs(c,col);
ScalarT val = localmass(c,row,col);
mass->insertGlobalValues(rowIndex, 1, &val, &colIndex);
}
}
}
}
}
mass->fillComplete();
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::setInitial(vector_RCP & initial, const bool & useadjoint) {
for (size_t b=0; b<cells.size(); b++) {
for (size_t e=0; e<cells[b].size(); e++) {
Kokkos::View<GO**,HostDevice> GIDs = cells[b][e]->GIDs;
Kokkos::View<ScalarT**,AssemblyDevice> localinit = cells[b][e]->getInitial(false, useadjoint);
int numElem = cells[b][e]->numElem;
for (int c=0; c<numElem; c++) {
for( size_t row=0; row<GIDs.extent(1); row++ ) {
int rowIndex = GIDs(c,row);
ScalarT val = localinit(c,row);
initial->replaceGlobalValue(rowIndex,0, val);
}
}
}
}
}
// ========================================================================================
// ========================================================================================
void AssemblyManager::assembleJacRes(vector_RCP & u, vector_RCP & u_dot,
vector_RCP & phi, vector_RCP & phi_dot,
const ScalarT & alpha, const ScalarT & beta,
const bool & compute_jacobian, const bool & compute_sens,
const bool & compute_disc_sens,
vector_RCP & res, matrix_RCP & J, const bool & isTransient,
const ScalarT & current_time,
const bool & useadjoint, const bool & store_adjPrev,
const int & num_active_params,
vector_RCP & Psol, const bool & is_final_time) {
if (milo_debug_level > 1) {
if (Comm->getRank() == 0) {
cout << "******** Starting AssemblyManager::assembleJacRes ..." << endl;
}
}
for (size_t b=0; b<cells.size(); b++) {
this->assembleJacRes(u, u_dot, phi, phi_dot, alpha, beta, compute_jacobian,
compute_sens, compute_disc_sens, res, J, isTransient,
current_time, useadjoint, store_adjPrev, num_active_params,
Psol, is_final_time, b);
}
if (milo_debug_level > 1) {
if (Comm->getRank() == 0) {
cout << "******** Finished AssemblyManager::assembleJacRes" << endl;
}
}
}
void AssemblyManager::assembleJacRes(vector_RCP & u, vector_RCP & u_dot,
vector_RCP & phi, vector_RCP & phi_dot,
const ScalarT & alpha, const ScalarT & beta,
const bool & compute_jacobian, const bool & compute_sens,
const bool & compute_disc_sens,
vector_RCP & res, matrix_RCP & J, const bool & isTransient,
const ScalarT & current_time,
const bool & useadjoint, const bool & store_adjPrev,
const int & num_active_params,
vector_RCP & Psol, const bool & is_final_time,
const int & b) {
int numRes = res->getNumVectors();
Teuchos::TimeMonitor localassemblytimer(*assemblytimer);
//for (size_t b=0; b<cells.size(); b++) {
//////////////////////////////////////////////////////////////////////////////////////
// Set up the worksets and allocate the local residual and Jacobians
//////////////////////////////////////////////////////////////////////////////////////
wkset[b]->time = current_time;
wkset[b]->time_KV(0) = current_time;
wkset[b]->isTransient = isTransient;
wkset[b]->isAdjoint = useadjoint;
wkset[b]->alpha = alpha;
if (isTransient)
wkset[b]->deltat = 1.0/alpha;
else
wkset[b]->deltat = 1.0;
int numElem = cells[b][0]->numElem;
int numDOF = cells[b][0]->GIDs.extent(1);
int numParamDOF = 0;
if (compute_disc_sens) {
numParamDOF = cells[b][0]->paramGIDs.extent(1);
}
Kokkos::View<ScalarT***,AssemblyDevice> local_res, local_J, local_Jdot;
if (compute_sens) {
local_res = Kokkos::View<ScalarT***,AssemblyDevice>("local residual",numElem,numDOF,num_active_params);
}
else {
local_res = Kokkos::View<ScalarT***,AssemblyDevice>("local residual",numElem,numDOF,1);
}
if (compute_disc_sens) {
local_J = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian",numElem,numDOF,numParamDOF);
local_Jdot = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian dot",numElem,numDOF,numParamDOF);
}
else {
local_J = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian",numElem,numDOF,numDOF);
local_Jdot = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian dot",numElem,numDOF,numDOF);
}
//Kokkos::View<ScalarT**,AssemblyDevice> aPrev;
/////////////////////////////////////////////////////////////////////////////
// Perform gather to cells
/////////////////////////////////////////////////////////////////////////////
{
Teuchos::TimeMonitor localtimer(*gathertimer);
// Local gather of solutions
this->performGather(b,u,0,0);
this->performGather(b,u_dot,1,0);
this->performGather(b,Psol,4,0);
if (useadjoint) {
this->performGather(b,phi,2,0);
this->performGather(b,phi_dot,3,0);
}
}
/////////////////////////////////////////////////////////////////////////////
// Volume contribution
/////////////////////////////////////////////////////////////////////////////
for (size_t e=0; e < cells[b].size(); e++) {
wkset[b]->localEID = e;
cells[b][e]->updateData();
if (isTransient && useadjoint && !cells[0][0]->cellData->multiscale) {
if (is_final_time) {
cells[b][e]->resetAdjPrev(0.0);
}
}
/////////////////////////////////////////////////////////////////////////////
// Compute the local residual and Jacobian on this cell
/////////////////////////////////////////////////////////////////////////////
{
Teuchos::TimeMonitor localtimer(*phystimer);
parallel_for(RangePolicy<AssemblyDevice>(0,local_res.extent(0)), KOKKOS_LAMBDA (const int p ) {
for (int n=0; n<numDOF; n++) {
for (int s=0; s<local_res.extent(2); s++) {
local_res(p,n,s) = 0.0;
}
for (int s=0; s<local_J.extent(2); s++) {
local_J(p,n,s) = 0.0;
local_Jdot(p,n,s) = 0.0;
}
}
});
cells[b][e]->computeJacRes(current_time, isTransient, useadjoint, compute_jacobian, compute_sens,
num_active_params, compute_disc_sens, false, store_adjPrev,
local_res, local_J, local_Jdot);
}
if (milo_debug_level > 2) {
if (Comm->getRank() == 0) {
KokkosTools::print(local_res);
KokkosTools::print(local_J);
KokkosTools::print(local_Jdot);
}
}
///////////////////////////////////////////////////////////////////////////
// Insert into global matrix/vector
///////////////////////////////////////////////////////////////////////////
this->insert(J, res, local_res, local_J, local_Jdot,
cells[b][e]->GIDs, cells[b][e]->paramGIDs,
compute_jacobian, compute_disc_sens, alpha);
} // element loop
//} // block loop
//////////////////////////////////////////////////////////////////////////////////////
// Boundary terms
//////////////////////////////////////////////////////////////////////////////////////
if (!cells[0][0]->cellData->multiscale && useNewBCs) {
//for (size_t b=0; b<boundaryCells.size(); b++) {
{
Teuchos::TimeMonitor localtimer(*gathertimer);
// Local gather of solutions
// Do not need to gather u_dot or phi_dot on boundaries (for now)
this->performBoundaryGather(b,u,0,0);
this->performBoundaryGather(b,Psol,4,0);
if (useadjoint) {
this->performBoundaryGather(b,phi,2,0);
}
}
for (size_t e=0; e < boundaryCells[b].size(); e++) {
if (boundaryCells[b][e]->numElem > 0) {
wkset[b]->localEID = e;
//////////////////////////////////////////////////////////////////////////////////////
// Set up the worksets and allocate the local residual and Jacobians
//////////////////////////////////////////////////////////////////////////////////////
int numElem = boundaryCells[b][e]->numElem;
int numDOF = boundaryCells[b][e]->GIDs.extent(1);
int numParamDOF = 0;
if (compute_disc_sens) {
numParamDOF = boundaryCells[b][e]->paramGIDs.extent(1);
}
Kokkos::View<ScalarT***,AssemblyDevice> local_res, local_J, local_Jdot;
if (compute_sens) {
local_res = Kokkos::View<ScalarT***,AssemblyDevice>("local residual",numElem,numDOF,num_active_params);
}
else {
local_res = Kokkos::View<ScalarT***,AssemblyDevice>("local residual",numElem,numDOF,1);
}
if (compute_disc_sens) {
local_J = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian",numElem,numDOF,numParamDOF);
local_Jdot = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian dot",numElem,numDOF,numParamDOF);
}
else {
local_J = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian",numElem,numDOF,numDOF);
local_Jdot = Kokkos::View<ScalarT***,AssemblyDevice>("local Jacobian dot",numElem,numDOF,numDOF);
}
/////////////////////////////////////////////////////////////////////////////
// Compute the local residual and Jacobian on this cell
/////////////////////////////////////////////////////////////////////////////
{
Teuchos::TimeMonitor localtimer(*phystimer);
parallel_for(RangePolicy<AssemblyDevice>(0,local_res.extent(0)), KOKKOS_LAMBDA (const int p ) {
for (int n=0; n<numDOF; n++) {
for (int s=0; s<local_res.extent(2); s++) {
local_res(p,n,s) = 0.0;
}
for (int s=0; s<local_J.extent(2); s++) {
local_J(p,n,s) = 0.0;
local_Jdot(p,n,s) = 0.0;
}
}
});
boundaryCells[b][e]->computeJacRes(current_time, isTransient, useadjoint, compute_jacobian, compute_sens,
num_active_params, compute_disc_sens, false, store_adjPrev,
local_res, local_J, local_Jdot);
}
if (milo_debug_level > 2) {
if (Comm->getRank() == 0) {
KokkosTools::print(local_res);
KokkosTools::print(local_J);
KokkosTools::print(local_Jdot);
}
}
///////////////////////////////////////////////////////////////////////////
// Insert into global matrix/vector
///////////////////////////////////////////////////////////////////////////
this->insert(J, res, local_res, local_J, local_Jdot,
boundaryCells[b][e]->GIDs, boundaryCells[b][e]->paramGIDs,
compute_jacobian, compute_disc_sens, alpha);
}
} // element loop
//} // block loop
}
// ************************** STRONGLY ENFORCE DIRICHLET BCs *******************************************
if (usestrongDBCs) {
Teuchos::TimeMonitor localtimer(*dbctimer);
vector<vector<GO> > fixedDOFs = phys->dbc_dofs;
for (size_t b=0; b<cells.size(); b++) {
vector<size_t> boundDirichletElemIDs; // list of elements on the Dirichlet boundary
vector<size_t> localDirichletSideIDs; // local side numbers for Dirichlet boundary sides
vector<size_t> globalDirichletSideIDs; // local side numbers for Dirichlet boundary sides
for (int n=0; n<numVars[b]; n++) {
int fnum = DOF->getFieldNum(varlist[b][n]);
boundDirichletElemIDs = phys->boundDirichletElemIDs[b][n];
localDirichletSideIDs = phys->localDirichletSideIDs[b][n];
globalDirichletSideIDs = phys->globalDirichletSideIDs[b][n];
size_t numDBC = boundDirichletElemIDs.size();
for (size_t e=0; e<numDBC; e++) {
size_t eindex = boundDirichletElemIDs[e];
size_t sindex = localDirichletSideIDs[e];
size_t gside_index = globalDirichletSideIDs[e];
if (compute_jacobian) {
this->updateJacDBC(J, eindex, b, fnum, sindex, compute_disc_sens);
}
std::string gside = phys->sideSets[gside_index];
this->updateResDBCsens(res, eindex, b, n, sindex, gside, current_time);
}
}
if (compute_jacobian) {
this->updateJacDBC(J,fixedDOFs[b],compute_disc_sens);
}
this->updateResDBC(res,fixedDOFs[b]);
}
}
}
// ========================================================================================
//
// ========================================================================================
void AssemblyManager::performGather(const size_t & b, const vector_RCP & vec,
const int & type, const size_t & entry) {
// Get a view of the vector on the HostDevice
auto vec_kv = vec->getLocalView<HostDevice>();
// Get a corresponding view on the AssemblyDevice
Kokkos::View<LO***,AssemblyDevice> index;
Kokkos::View<LO*,AssemblyDevice> numDOF;
Kokkos::View<ScalarT***,AssemblyDevice> data;
for (size_t c=0; c < cells[b].size(); c++) {
switch(type) {
case 0 :
index = cells[b][c]->index;
numDOF = cells[b][c]->numDOF;
data = cells[b][c]->u;
break;
case 1 :
index = cells[b][c]->index;
numDOF = cells[b][c]->numDOF;
data = cells[b][c]->u_dot;
break;
case 2 :
index = cells[b][c]->index;
numDOF = cells[b][c]->numDOF;
data = cells[b][c]->phi;
break;
case 3 :
index = cells[b][c]->index;
numDOF = cells[b][c]->numDOF;
data = cells[b][c]->phi_dot;
break;
case 4:
index = cells[b][c]->paramindex;
numDOF = cells[b][c]->numParamDOF;
data = cells[b][c]->param;
break;
case 5 :
index = cells[b][c]->auxindex;
numDOF = cells[b][c]->numAuxDOF;
data = cells[b][c]->aux;
break;
default :
cout << "ERROR - NOTHING WAS GATHERED" << endl;
}
if (milo_debug_level > 2) {
if (Comm->getRank() == 0) {
KokkosTools::print(index);
KokkosTools::print(numDOF);
KokkosTools::print(data);
}
}
parallel_for(RangePolicy<AssemblyDevice>(0,index.extent(0)), KOKKOS_LAMBDA (const int e ) {
for (size_t n=0; n<index.extent(1); n++) {
for(size_t i=0; i<numDOF(n); i++ ) {
data(e,n,i) = vec_kv(index(e,n,i),entry);
}
}
});
}
}
// ========================================================================================
//
// ========================================================================================
void AssemblyManager::performBoundaryGather(const size_t & b, const vector_RCP & vec,
const int & type, const size_t & entry) {
if (boundaryCells.size() > b) {
// Get a view of the vector on the HostDevice
auto vec_kv = vec->getLocalView<HostDevice>();
// Get a corresponding view on the AssemblyDevice
Kokkos::View<LO***,AssemblyDevice> index;
Kokkos::View<LO*,AssemblyDevice> numDOF;
Kokkos::View<ScalarT***,AssemblyDevice> data;
for (size_t c=0; c < boundaryCells[b].size(); c++) {
if (boundaryCells[b][c]->numElem > 0) {
switch(type) {
case 0 :
index = boundaryCells[b][c]->index;
numDOF = boundaryCells[b][c]->numDOF;
data = boundaryCells[b][c]->u;
break;
case 1 :
index = boundaryCells[b][c]->index;
numDOF = boundaryCells[b][c]->numDOF;
data = boundaryCells[b][c]->u_dot;
break;
case 2 :
index = boundaryCells[b][c]->index;
numDOF = boundaryCells[b][c]->numDOF;
data = boundaryCells[b][c]->phi;
break;
case 3 :
index = boundaryCells[b][c]->index;
numDOF = boundaryCells[b][c]->numDOF;
data = boundaryCells[b][c]->phi_dot;
break;
case 4:
index = boundaryCells[b][c]->paramindex;
numDOF = boundaryCells[b][c]->numParamDOF;
data = boundaryCells[b][c]->param;
break;
case 5 :
index = boundaryCells[b][c]->auxindex;
numDOF = boundaryCells[b][c]->numAuxDOF;
data = boundaryCells[b][c]->aux;
break;
default :
cout << "ERROR - NOTHING WAS GATHERED" << endl;
}
if (milo_debug_level > 2) {
if (Comm->getRank() == 0) {
KokkosTools::print(index);
KokkosTools::print(numDOF);
KokkosTools::print(data);
}
}
parallel_for(RangePolicy<AssemblyDevice>(0,index.extent(0)), KOKKOS_LAMBDA (const int e ) {
for (size_t n=0; n<index.extent(1); n++) {
for(size_t i=0; i<numDOF(n); i++ ) {
data(e,n,i) = vec_kv(index(e,n,i),entry);
}
}
});
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void AssemblyManager::insert(matrix_RCP & J, vector_RCP & res,
Kokkos::View<ScalarT***,AssemblyDevice> & local_res,
Kokkos::View<ScalarT***,AssemblyDevice> & local_J,
Kokkos::View<ScalarT***,AssemblyDevice> & local_Jdot,
Kokkos::View<GO**,HostDevice> & GIDs,
Kokkos::View<GO**,HostDevice> & paramGIDs,
const bool & compute_jacobian,
const bool & compute_disc_sens,
const ScalarT & alpha) {
Teuchos::TimeMonitor localtimer(*inserttimer);
for (int i=0; i<GIDs.extent(0); i++) {
Teuchos::Array<ScalarT> vals(GIDs.extent(1));
Teuchos::Array<GO> cols(GIDs.extent(1));
for( size_t row=0; row<GIDs.extent(1); row++ ) {
GO rowIndex = GIDs(i,row);
for (int g=0; g<local_res.extent(2); g++) {
ScalarT val = local_res(i,row,g);
res->sumIntoGlobalValue(rowIndex,g, val);
}
if (compute_jacobian) {
if (compute_disc_sens) {
for( size_t col=0; col<paramGIDs.extent(1); col++ ) {
GO colIndex = paramGIDs(i,col);
ScalarT val = local_J(i,row,col) + alpha*local_Jdot(i,row,col);
J->insertGlobalValues(colIndex, 1, &val, &rowIndex);
}
}
else {
for( size_t col=0; col<GIDs.extent(1); col++ ) {
vals[col] = local_J(i,row,col) + alpha*local_Jdot(i,row,col);
cols[col] = GIDs(i,col);
}
//J->sumIntoGlobalValues(rowIndex, GIDs[i].size(), &vals[0], &GIDs[i][0]);
J->sumIntoGlobalValues(rowIndex, cols, vals);
}
}
}
}
}
| 39.489415 | 126 | 0.476916 | [
"mesh",
"vector"
] |
43c98cf5c87c7c58634dddefdb00a59ded57e78f | 11,320 | cpp | C++ | src/csim.cpp | nickerso/csim-archived | 4f1fd55d556e88680d7032afd08ae3fd4bfb418e | [
"Apache-2.0"
] | null | null | null | src/csim.cpp | nickerso/csim-archived | 4f1fd55d556e88680d7032afd08ae3fd4bfb418e | [
"Apache-2.0"
] | null | null | null | src/csim.cpp | nickerso/csim-archived | 4f1fd55d556e88680d7032afd08ae3fd4bfb418e | [
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#ifndef _MSC_VER
# include <getopt.h>
#endif
#include <time.h>
#include <signal.h>
#include <string>
#include <iostream>
#ifdef __cplusplus
extern "C"
{
#endif
#include "version.h"
#include "common.h"
#include "utils.h"
#include "cellml.h"
#include "simulation.h"
#include "timer.h"
#ifdef __cplusplus
}
#endif
#include "xpath.hpp"
#include "integrator.hpp"
#include "CellmlCode.hpp"
#include "ModelCompiler.hpp"
#include "ExecutableModel.hpp"
/* Just for convenience */
#define PRE_EXIT_FREE \
if (inputURI) free(inputURI); \
if (simulation) DestroySimulation(&simulation); \
if (cellmlCode) delete cellmlCode;
/* and for use when program is interrupted */
struct SignalHandlerData
{
CellmlCode* code;
void (*handler)(int);
};
static struct SignalHandlerData signalData;
/* make sure we tidy up created files */
void signalHandler(int s)
{
if (signalData.code)
delete signalData.code;
ERROR("signalHandler", "Caught an interrupt signal. Exiting...\n");
if (signalData.handler)
{
ERROR("signalHandler", "Passing through signal.\n");
signalData.handler(s);
}
exit(1);
}
static int runSimulation(struct Simulation* simulation, ExecutableModel* em);
static void printVersion()
{
char* version = getVersion((char*) NULL, (char*) NULL);
printf("%s\n", version);
printf(
"Copyright (C) 2007-2012 David Nickerson.\n"
"This is free software; see the source for copying conditions. There \n"
"is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A \n"
"PARTICULAR PURPOSE.\n");
free(version);
}
static void usage(char* prog)
{
printf("Examines given input CellML and executes the\n"
"simulation that is found, writing the simulation outputs to the terminal.\n\n");
#ifdef _MSC_VER
printf("Usage: %s <input file> [XXX]\n\n", prog);
printf("No options for windows version yet, but put random characters after the <input file>\n"
"to get some help.\n\n");
#else
printf("Usage: %s [options] <input file>\n\n", prog);
printf(
"Available options:\n"
" --help\n\tDisplay help and exit.\n"
" --version\n\tDisplay version information and exit.\n"
" --quiet\n\tTurn off all printing to terminal except the simulation outputs.\n"
" --save-temp-files\n"
"\tSave the temporary files generated from CellML.\n"
" --debug\n"
"\tMainly for development, more occurrences more output.\n"
" --generate-debug-code\n"
"\tGenerate code with debug bits included, useful for finding errors in "
"models.\n"
"\n");
#endif // _MSC_VER
}
static void help(char* prog)
{
usage(prog);
printf("\n\n");
const char * sundials_version = getSundialsVersion();
printf("Useful links:\n"
"http://cellml.sourceforge.net\n"
"http://code.google.com/p/cellml-simulator/\n"
"http://www.cellml.org\n"
"http://www.cellml.org/specifications\n"
"\n"
"%s uses:\n"
"- The CellML API (version 1.12)\n"
" http://www.cellml.org\n"
"- LLVM/Clang (version 3.1)\n" // FIXME: need to pull in verson better?
" http://www.llvm.org\n"
"- The CVODES integrator from sundials (version %s)\n"
" http://www.llnl.gov/CASC/sundials/\n", prog, sundials_version);
printf("\n");
printf("Report bugs to nickerso@users.sourceforge.net\n");
}
/*
*-------------------------------
* Main Program
*-------------------------------
*/
int main(int argc, char* argv[])
{
char* inputURI = (char*) NULL;
struct Simulation* simulation = (struct Simulation*) NULL;
CellmlCode* cellmlCode = NULL;
signalData.code = NULL;
/* Parse command line arguments */
int invalidargs = 0;
static int helpRequest = 0;
static int versionRequest = 0;
static int saveTempFiles = 0;
static int generateDebugCode = 0;
#ifdef _MSC_VER
// no standard getopt_long for windows, so default some decent options
setQuiet();
int optind;
if (argc == 2)
{
optind = 1;
}
else if (argc == 3)
{
printVersion();
helpRequest = 1;
}
else
{
invalidargs = 1;
optind = argc + 1;
}
#else
while (1)
{
static struct option long_options[] =
{
{ "help", no_argument, &helpRequest, 1 },
{ "version", no_argument, &versionRequest, 1 },
{ "save-temp-files", no_argument, &saveTempFiles, 1 },
{ "generate-debug-code", no_argument, &generateDebugCode, 1 },
{ "quiet", no_argument, NULL, 13 },
{ "debug", no_argument, NULL, 14 },
{ 0, 0, 0, 0 } };
int option_index;
int c = getopt_long(argc, argv, "", long_options, &option_index);
/* check if we're finished the options */
if (c == -1)
break;
/* check what option we got */
switch (c)
{
case 0:
{
/* do nothing ?? */
/*printf ("option %s", long_options[option_index].name);
if (optarg) printf (" with arg %s", optarg);
printf ("\n");*/
}
break;
case 13:
{
/* quiet - to stop all non-error output */
setQuiet();
}
break;
case 14:
{
/* debug level, the more times the more debug output */
setDebugLevel();
}
break;
case '?':
{
/* unknown option/missing argument found */
invalidargs = 1;
}
break;
default:
{
/* ?? */
invalidargs = 1;
}
break;
}
}
#endif
if (helpRequest)
{
help(argv[0]);
PRE_EXIT_FREE;
return (0);
}
else if (versionRequest)
{
printVersion();
PRE_EXIT_FREE;
return (0);
}
/* CellML model should be the only other entry on the command line */
if (optind < argc)
inputURI = getAbsoluteURI(argv[optind]);
if (debugLevel() > 98)
{
if (inputURI)
{
DEBUG(99, "main", "inputURI found and is: %s\n", inputURI);
}
else
{
DEBUG(99, "main", "inputURI not found\n");
}
}
/* Check required arguments */
if (inputURI == NULL)
{
ERROR("main", "Missing input file URI\n");
invalidargs = 1;
}
if (invalidargs)
{
usage(argv[0]);
PRE_EXIT_FREE;
return (1);
}
/* Create the CellML Code */
cellmlCode = new CellmlCode(saveTempFiles == 1);
signalData.code = cellmlCode;
/* set up the signal handler to ensure we clean up temporary files when
interrupt signal is received, and save any existing handler? */
signalData.handler = signal(SIGINT, &signalHandler);
DEBUG(99, "main", "About to try and get the simulation from: %s\n", inputURI);
/* look for a single simulation */
simulation = getSimulation(inputURI);
DEBUG(99, "main", "Got the simulation from: %s\n", inputURI);
int code = OK;
if (simulation)
{
if (simulationIsValidDescription(simulation))
{
// create the code from the cellml model
cellmlCode->createCodeForSimulation(simulation, generateDebugCode == 1);
// create the LLVM/Clang model compiler
ModelCompiler mc(argv[0], quietSet() == 0, generateDebugCode == 1);
// and the executable model
ExecutableModel em;
if (em.initialise(&mc, cellmlCode->codeFileName(), simulationGetBvarStart(simulation)) != 0)
{
ERROR("main", "Unable to create the executable model from '%s'\n",
cellmlCode->codeFileName());
PRE_EXIT_FREE;
return -1;
}
char* simulationName = simulationGetID(simulation);
MESSAGE("Running the simulation: %s\n", simulationName);
//simulationPrint(simulation, stdout, "###");
DEBUG(0, "main", "Running the simulation: %s\n", simulationName);
if (runSimulation(simulation, &em) == OK)
{
DEBUG(
0,
"main",
"Ran the simulation (%s) successfully\n", simulationName);
}
else
{
ERROR("main",
"Unable to run the simulation: %s\n", simulationName);
code = ERR;
}
if (simulationName)
free(simulationName);
}
else
{
ERROR("main", "Invalid simulation description\n");
code = ERR;
}
DestroySimulation(&simulation);
}
else DEBUG(
0,
"main",
"No simulations (or not exactly one simulation found), probably something missing\n");
if (code == OK)
{
}
else DEBUG(0, "main", "Something went wrong getting all the "
"simulation results?\n");
PRE_EXIT_FREE;
return (0);
}
static int runSimulation(struct Simulation* simulation, ExecutableModel* em)
{
int code = ERR;
if (em && simulation && simulationIsValidDescription(simulation))
{
struct Integrator* integrator = CreateIntegrator(simulation, em);
if (integrator)
{
DEBUG(0, "runSimulation", "Initialised the simulation data\n");
double tStart = simulationGetBvarStart(simulation);
double tEnd = simulationGetBvarEnd(simulation);
double tabT = simulationGetBvarTabStep(simulation);
int iout = 0;
double tout = tStart + tabT;
if (tout > tEnd)
tout = tEnd;
struct Timer* timer = CreateTimer();
startTimer(timer);
double integrationTimes[3] =
{ 0.0, 0.0, 0.0 };
double dataStoreTimes[3] =
{ 0.0, 0.0, 0.0 };
int i;
for (i = 0; i < em->nOutputs; i++)
printf("\t%15.10e", em->outputs[i]);
printf("\n");
while (1)
{
DEBUG(5, "runSimulation", "tout = " REAL_FORMAT "\n", tout);
double t;
iout++;
TIME_FUNCTION_CALL(integrationTimes, intTimer, code,
integrate, integrator, tout, &t);
if (code == OK)
{
int i;
for (i = 0; i < em->nOutputs; i++)
printf("\t%15.10e", em->outputs[i]);
printf("\n");
if (code == OK)
{
/* have we reached tEnd? */
if (fabs(tEnd - t) < ZERO_TOL)
break;
/* if not, increase tout */
tout += tabT;
/* and make sure we don't go past tEnd */
if (tout > tEnd)
tout = tEnd;
}
else
{
DEBUG(0, "runSimulation",
"Error appending integration results "
"at time: " REAL_FORMAT "\n", tout);
break;
}
}
else
{
DEBUG(
0,
"runSimulation",
"Error integrating at time: " REAL_FORMAT "\n", tout);
break;
}
}
stopTimer(timer);
double user = getUserTime(timer);
double system = getSystemTime(timer);
double total = user + system;
double wall = getWallTime(timer);
DestroyTimer(&timer);
MESSAGE(" Wall clock time : " REAL_FORMAT " s\n", wall);
MESSAGE(
" (integration " REAL_FORMAT " s)\n", integrationTimes[2]);
MESSAGE(
" (data store " REAL_FORMAT " s)\n", dataStoreTimes[2]);
MESSAGE(
" CPU time : " REAL_FORMAT " s "
"(user " REAL_FORMAT "/system " REAL_FORMAT ")\n", total, user, system);
MESSAGE(
" (integration " REAL_FORMAT " s)\n", integrationTimes[0]+integrationTimes[1]);
MESSAGE(
" (data store " REAL_FORMAT " s)\n", dataStoreTimes[0]+dataStoreTimes[1]);
if (!quietSet())
{
printMemoryStats();
/* Print some final statistics from the integrator */
PrintFinalStats(integrator);
}
if (code == OK)
{
DEBUG(2, "runSimulation", "Simulation complete\n");
//simulationFlagResultsComplete(simulation,1);
}
else
{
DEBUG(0, "runSimulation", "Something went wrong with the "
"integration so flagging partial results\n");
//simulationFlagResultsComplete(simulation,0);
}
DestroyIntegrator(&integrator);
}
else
ERROR("runSimulation", "Error creating integrator\n");
}
else DEBUG(0, "runSimulation", "Invalid arguments\n");
return (code);
}
| 25.727273 | 102 | 0.623852 | [
"model"
] |
43cd311eeb15d7a4447baaffbebde5a0aad061be | 3,475 | cpp | C++ | src/compiler/ParserParameter.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | src/compiler/ParserParameter.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | src/compiler/ParserParameter.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <algorithm>
#include <boost/variant/get.hpp>
#include <pga/core/Axis.h>
#include <pga/core/RepeatMode.h>
#include "ParserParameter.h"
namespace PGA
{
namespace Compiler
{
namespace Parser
{
//////////////////////////////////////////////////////////////////////////
std::shared_ptr<PGA::Compiler::Parameter> createParameter(Parameter param)
{
return createParameter(param, {}, {});
}
//////////////////////////////////////////////////////////////////////////
std::shared_ptr<PGA::Compiler::Parameter> createParameter(Parameter param,
const std::initializer_list<int>& allowed,
const std::initializer_list<int>& forbidden)
{
auto adtParamType = param.which();
if (std::find(allowed.begin(), allowed.end(), adtParamType) == allowed.end())
if (std::find(forbidden.begin(), forbidden.end(), adtParamType) != forbidden.end())
throw std::runtime_error("PGA::Compiler::Parser::createParameter(): trying to create a parameter of forbidden type");
switch (adtParamType)
{
case 0:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::Axis(static_cast<PGA::Axis>(boost::get<Axis>(param).type)));
case 1:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::RepeatMode(static_cast<PGA::RepeatMode>(boost::get<RepeatMode>(param).type)));
case 2:
{
auto vec2 = boost::get<Vec2>(param);
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::Vec2(vec2.x, vec2.y));
}
case 3:
{
auto shapeAttribute = boost::get<ShapeAttribute>(param);
switch (shapeAttribute.type)
{
case SHAPE_POS:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis));
case SHAPE_SIZE:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis));
case SHAPE_ROTATION:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis, shapeAttribute.component));
case SHAPE_NORMAL:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis));
case SHAPE_SEED:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis));
case SHAPE_CUSTOM_ATTR:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::ShapeAttr(static_cast<PGA::Compiler::ShapeAttribute>(shapeAttribute.type), shapeAttribute.axis));
default:
throw std::runtime_error("PGA::Compiler::Parser::createParameter(): unknown shape attribute");
}
break;
}
case 4:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::Rand(boost::get<Rand>(param).min, boost::get<Rand>(param).max));
case 5:
return toParameter(boost::get<Expression>(param));
case 6:
return std::shared_ptr<PGA::Compiler::Parameter>(new PGA::Compiler::Scalar(boost::get<double>(param)));
default:
throw std::runtime_error("PGA::Compiler::Parser::createParameter(): unknown ADT parameter type");
}
}
}
}
} | 43.4375 | 197 | 0.675971 | [
"shape"
] |
43d068037955ddcad7ea2ca391c379810e4dd5c4 | 2,402 | cpp | C++ | Ancestor/src/Platform/OpenGL/OpenGLMesh.cpp | AlerHugu3s/Ancestor | 4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d | [
"Apache-2.0"
] | null | null | null | Ancestor/src/Platform/OpenGL/OpenGLMesh.cpp | AlerHugu3s/Ancestor | 4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d | [
"Apache-2.0"
] | null | null | null | Ancestor/src/Platform/OpenGL/OpenGLMesh.cpp | AlerHugu3s/Ancestor | 4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d | [
"Apache-2.0"
] | null | null | null | #include "acpch.h"
#include "OpenGLMesh.h"
#include "glad/glad.h"
#include "OpenGLShader.h"
namespace Ancestor {
// constructor
OpenGLMesh::OpenGLMesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Ref<Texture>> textures)
{
m_Indices = indices;
m_vertices = vertices;
m_Textures = textures;
VAO = VertexArray::Create();
VBO = VertexBuffer::Create(m_vertices);
IBO = IndexBuffer::Create(m_Indices);
// now that we have all the required data, set the vertex buffers and its attribute pointers.
setupMesh();
}
// render the mesh
void OpenGLMesh::Draw(Ref<Shader> shader)
{
// bind appropriate textures
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
unsigned int customNr = 1;
for (unsigned int i = 0; i < m_Textures.size(); i++)
{
// active proper texture unit before binding
m_Textures[i]->Active(i);
// retrieve texture number (the N in diffuse_textureN)
std::string number;
std::string name = m_Textures[i]->GetType();
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++); // transfer unsigned int to stream
else if (name == "texture_normal")
number = std::to_string(normalNr++); // transfer unsigned int to stream
else if (name == "texture_height")
number = std::to_string(heightNr++); // transfer unsigned int to stream
else
number = std::to_string(customNr++); // transfer unsigned int to stream
m_Textures[i]->Bind();
std::dynamic_pointer_cast<OpenGLShader>(shader)->UploadUniformInt1(name + number, i);
}
// draw mesh
VAO->Bind();
glDrawElements(GL_TRIANGLES, m_Indices.size(), GL_UNSIGNED_INT, 0);
VAO->UnBind();
// always good practice to set everything back to defaults once configured.
//glActiveTexture(GL_TEXTURE0);
}
// initializes all the buffer objects/arrays
void OpenGLMesh::setupMesh()
{
BufferLayout layout = BufferLayout{
{Ancestor::ShaderDataType::Float3 ,"a_Pos" },
{Ancestor::ShaderDataType::Float3 ,"a_Normal" },
{Ancestor::ShaderDataType::Float2 ,"a_TexCoords" },
{Ancestor::ShaderDataType::Float3 ,"a_Tangent" },
{Ancestor::ShaderDataType::Float3 ,"a_Bitangent" }
};
VBO->SetLayout(layout);
VAO->AddVertexBuffer(VBO);
VAO->SetIndexBuffer(IBO);
}
} | 32.459459 | 124 | 0.697336 | [
"mesh",
"render",
"vector"
] |
43d427934ab3cbb58c74d73b07d0528c8c41a53b | 1,418 | cpp | C++ | Hildur/src/Hildur/Component/DirectionalLight.cpp | FelipeCalin/Hildur | 13e60a357e6f84ac1de842d9a9bd980155968cbc | [
"Apache-2.0"
] | null | null | null | Hildur/src/Hildur/Component/DirectionalLight.cpp | FelipeCalin/Hildur | 13e60a357e6f84ac1de842d9a9bd980155968cbc | [
"Apache-2.0"
] | null | null | null | Hildur/src/Hildur/Component/DirectionalLight.cpp | FelipeCalin/Hildur | 13e60a357e6f84ac1de842d9a9bd980155968cbc | [
"Apache-2.0"
] | null | null | null | #include "hrpcheaders.h"
#include "DirectionalLight.h"
#include "Hildur/Core/System/Renderer.h"
#include <glm/gtc/matrix_transform.hpp>
#include <imgui.h>
namespace Hildur {
void DirectionalLight::Init()
{
m_Type = LE_DIRECTIONAL;
Renderer::AddToLightList(this);
m_LightProjection = glm::ortho(-5.0f, 5.0f, -5.0f, 5.0f, 0.1f, 100.0f);
}
DirectionalLight::~DirectionalLight()
{
//shadowBuffer->clear();
}
void DirectionalLight::Destroy()
{
//Lighting::removeLight(this);
Renderer::RemoveFromLightList(this);
}
void DirectionalLight::RenderInspector()
{
ImGui::BeginGroup();
ImGui::ColorEdit3("Color", &m_Color[0]);
ImGui::InputFloat("Intensity", &m_Intensity);
ImGui::EndGroup();
ImGui::NewLine();
}
/*
void DirectionalLight::renderShadowMap(bool captureMode)
{
shadowBuffer->enable();
shadowBuffer->clear();
//Renderer::render(_depthShader, captureMode);
if(!captureMode){
ImGui::Begin("Depth");
ImGui::Image((ImTextureID)shadowBuffer->getAttachment("depth")->id, ImVec2(_shadowMapResolution/15.0f, _shadowMapResolution/15.0f), ImVec2(0, 1), ImVec2(1, 0));
ImGui::End();
}
//FrameBuffer::resetDefaultBuffer();
}
*/
void DirectionalLight::OnEnable()
{
//Lighting::addLight(this);
Renderer::AddToLightList(this);
}
void DirectionalLight::OnDisable()
{
//Lighting::removeLight(this);
Renderer::RemoveFromLightList(this);
}
} | 18.415584 | 163 | 0.69464 | [
"render"
] |
43d743b3e7ffb71d0aa0cb982df77b0fc45986b3 | 18,387 | cpp | C++ | mainwindow.cpp | brandonesford/CUHRes | 0a414b7e8efd779dbfb71514bc8118bcebbf49fe | [
"MIT"
] | null | null | null | mainwindow.cpp | brandonesford/CUHRes | 0a414b7e8efd779dbfb71514bc8118bcebbf49fe | [
"MIT"
] | null | null | null | mainwindow.cpp | brandonesford/CUHRes | 0a414b7e8efd779dbfb71514bc8118bcebbf49fe | [
"MIT"
] | null | null | null | /*
* Class: MainWindow
* Purpose: The purpose of this class is to provide the GUI
* for the CuNICS system.
*/
#include <QMessageBox>
#include <QFileDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "userorm.h"
#include "roleorm.h"
#include "employeecontrol.h"
#include "applyraisescontrol.h"
#include "cuhresparser.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow), db(CunicsDb::db())
{
QSqlError error;
if ((error = db.initDb()).isValid()) {
qWarning() << "test" << error.text();
}
ui->setupUi(this);
ui->stackedWidget->setCurrentIndex(0); //set the first page to the login window
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_login_clicked()
{
QString userID = ui->lineEdit_ID->text(); //get the text entered by the user & assign it to the userID var
QList<User*> userList = UserOrm::find(userID.toInt());
if (userList.isEmpty()) {
QMessageBox::warning(this, "login", "The user ID does not exist");
return;
}
User* user = userList[0];
if (user->getType() == "payroll_specialist") {
QMessageBox::information(this, "login", "Login successful!"); //display this info
ui->stackedWidget->setCurrentIndex(1);
} else { //if employee
QMessageBox::information(this, "login", "Login successful!"); //display this info
ui->stackedWidget->setCurrentIndex(3);
}
delete user;
}
void MainWindow::on_pushButton_filter_clicked()
{
QString filterParams = ui->lineEdit_filter->text();
filterParams = "lname LIKE '%" + filterParams + "%'";
QList<Employee*> filteredList = EmployeeOrm::filter(filterParams);
QStandardItemModel* model = employeesToModel(filteredList);
ui->employeesList->setModel(model);
for (int i = 0; i < filteredList.size(); i++)
delete filteredList[i];
}
void MainWindow::on_pushButton_loadTable_clicked()
{
QList<Employee*> list = EmployeeOrm::all();
QStandardItemModel* model = employeesToModel(list);
QItemSelectionModel *oldModel = ui->employeesList->selectionModel();
ui->employeesList->setModel(model);
if (oldModel)
delete oldModel;
for (int i = 0; i < list.size(); i++)
delete list[i];
}
void MainWindow::on_pushButton_logoutPS_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_addEmployee_clicked()
{
ui->stackedWidget->setCurrentIndex(4);
}
void MainWindow::on_pushButton_logoutEmployee_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_returnFromAddEmployee_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_logoutFromAddEmployee_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_employeesList_clicked(const QModelIndex &index)
{
QString id = model->index(index.row(),0).data().toString(); //get content of cell
QString role = model->index(index.row(), 2).data().toString();
ui->stackedWidget->setCurrentIndex(5);
selectedEmployeeId = id.toInt();
updateDisplay(selectedEmployeeId, role);
}
void MainWindow::assignEmployeeParams(QHash<QString, QVariant> ¶ms)
{
params["fname"] = ui->lineEdit_firstNameEdit->text();
params["lname"] = ui->lineEdit_lastNameEdit->text();
params["role"] = getCurrentRole();
if (!ui->lineEdit_hoursEdit->text().isEmpty()) {
params["hours"] = ui->lineEdit_hoursEdit->text().toInt();
}
if (!ui->dateEdit_termFrom->text().isEmpty() && !ui->dateEdit_termTo->text().isEmpty()) {
params["start_term"] = ui->dateEdit_termFrom->text();
params["end_term"] = ui->dateEdit_termTo->text();
}
if (!ui->dateEdit_leaveFrom->text().isEmpty()) {
params["start_leave"] = ui->dateEdit_leaveFrom->text();
}
if (!ui->dateEdit_leaveTo->text().isEmpty()) {
params["end_leave"] = ui->dateEdit_leaveTo->text();
}
params["leave_percentage"] = ui->double_leavePerc->value();
QString type;
if (ui->radioButton_fullTime->isChecked()) {
type = "full-time";
} else if (ui->radioButton_partTime->isChecked()) {
type = "part-time";
} else if (ui->radioButton_term->isChecked()) {
type = "term";
} else if(ui->radioButton_continuing->isChecked()) {
type = "continuing";
}
params["type"] = type;
}
void MainWindow::updateDisplayToRole(int employeeId, QString role)
{
Employee *e = EmployeeOrm::find(employeeId).first();
EmployeePosition* position = e->getPositionForRole(role);
if (position) {
ui->lineEdit_hoursEdit->setText(QString::number(position->getHours()));
ui->label_wageAmount->setText("$" + QString::number(position->getWage()));
ui->dateEdit_termFrom->setDate(QDate::fromString(position->getTerm().getSDate(), "yyyy-MM-dd"));
ui->dateEdit_termTo->setDate(QDate::fromString(position->getTerm().getEDate(), "yyyy-MM-dd"));
if(position->getRole() == "TA") {
ui->radioButton_TA->setChecked(true);
} else if(position->getRole() =="RA") {
ui->radioButton_RA->setChecked(true);
} else if(position->getRole() == "Staff") {
ui->radioButton_staff->setChecked(true);
} else if(position->getRole() == "Faculty") {
ui->radioButton_faculty->setChecked(true);
}
if (position->getType() == "full-time") {
ui->radioButton_fullTime->setChecked(true);
} else if (position->getType() == "part-time") {
ui->radioButton_partTime->setChecked(true);
} else if (position->getType() == "term") {
ui->radioButton_term->setChecked(true);
} else if(position->getType() =="continuing") {
ui->radioButton_continuing->setChecked(true);
}
} else {
ui->lineEdit_hoursEdit->clear();
ui->label_wageAmount->clear();
ui->dateEdit_termFrom->setDate(QDate::currentDate());
ui->dateEdit_termTo->setDate(QDate::currentDate());
if(role == "TA") {
ui->radioButton_TA->setChecked(true);
} else if(role =="RA") {
ui->radioButton_RA->setChecked(true);
} else if(role == "Staff") {
ui->radioButton_staff->setChecked(true);
} else if(role == "Faculty") {
ui->radioButton_faculty->setChecked(true);
}
ui->radioButton_fullTime->setChecked(false);
ui->radioButton_partTime->setChecked(false);
ui->radioButton_term->setChecked(false);
ui->radioButton_continuing->setChecked(false);
}
updateEmployeeEditRestrictions(e, role);
delete e;
}
QString MainWindow::getCurrentRole()
{
QString role;
if (ui->radioButton_TA->isChecked()) {
role = "TA";
} else if (ui->radioButton_RA->isChecked()) {
role = "RA";
} else if (ui->radioButton_faculty->isChecked()) {
role = "Faculty";
} else if(ui->radioButton_staff->isChecked()) {
role = "Staff";
}
return role;
}
void MainWindow::updateDisplay(int employeeId, QString roleString)
{
if (roleString.isEmpty()) {
roleString = getCurrentRole();
}
Employee *e = EmployeeOrm::find(employeeId).first();
ui->lineEdit_firstNameEdit->setText(e->getName().getFName());
ui->lineEdit_lastNameEdit->setText(e->getName().getLName());
ui->dateEdit_leaveFrom->setDate(QDate::fromString(e->getStartLeave(), "yyyy-MM-dd"));
ui->dateEdit_leaveTo->setDate(QDate::fromString(e->getEndLeave(), "yyyy-MM-dd"));
ui->double_leavePerc->setValue(e->getLeavePerc());
updateDisplayToRole(employeeId, roleString);
delete e;
}
void MainWindow::updateEmployeeEditRestrictions(Employee* e, QString role)
{
EmployeePosition *position = e->getPositionForRole(role);
QString type = "";
if (position)
type = position->getType();
ui->radioButton_fullTime->setDisabled(false);
ui->radioButton_partTime->setDisabled(false);
ui->radioButton_term->setDisabled(false);
ui->radioButton_continuing->setDisabled(false);
ui->radioButton_TA->setDisabled(false);
ui->radioButton_RA->setDisabled(false);
ui->radioButton_staff->setDisabled(false);
ui->radioButton_faculty->setDisabled(false);
// type
if (role == "Faculty") {
ui->radioButton_partTime->setDisabled(true);
} else if (role == "RA" || role == "TA") {
ui->radioButton_fullTime->setDisabled(true);
ui->radioButton_continuing->setDisabled(true);
}
// leave
if (role != "Staff" && role != "Faculty" && type == "continuing") {
ui->dateEdit_leaveFrom->setDisabled(true);
ui->dateEdit_leaveTo->setDisabled(true);
}
// role
if (role == "Staff" || role == "RA" || role == "TA") {
ui->radioButton_faculty->setDisabled(true);
} else if (role == "Faculty") {
ui->radioButton_staff->setDisabled(true);
ui->radioButton_RA->setDisabled(true);
ui->radioButton_TA->setDisabled(true);
}
}
QStandardItemModel* MainWindow::employeesToModel(QList<Employee*> &list)
{
model = new QStandardItemModel(list.size(),9,this);
model->setHorizontalHeaderItem(0, new QStandardItem(QString("ID")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("Name")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("Role")));
model->setHorizontalHeaderItem(3, new QStandardItem(QString("Type")));
model->setHorizontalHeaderItem(4, new QStandardItem(QString("Hours")));
model->setHorizontalHeaderItem(5, new QStandardItem(QString("Wage")));
model->setHorizontalHeaderItem(6, new QStandardItem(QString("Salary")));
model->setHorizontalHeaderItem(7, new QStandardItem(QString("Start Date")));
model->setHorizontalHeaderItem(8, new QStandardItem(QString("End Date")));
int entryRow = 0;
for (int i=0; i<list.size(); i++)
{
Employee* employee = list[i];
QList<EmployeePosition*> &positions = employee->getPositions();
if (positions.size() == 0)
{
QStandardItem *id = new QStandardItem(QString::number(employee->getUID()));
model->setItem(entryRow,0,id);
const UserName &userName = employee->getName();
QStandardItem *name = new QStandardItem(QString(userName.getFName() + " " + userName.getLName()));
model->setItem(entryRow,1,name);
entryRow++;
}
for (int j=0; j < positions.size(); j++) {
EmployeePosition *position = positions[j];
QStandardItem *id = new QStandardItem(QString::number(employee->getUID()));
model->setItem(entryRow,0,id);
const UserName &userName = employee->getName();
QStandardItem *name = new QStandardItem(QString(userName.getFName() + " " + userName.getLName()));
model->setItem(entryRow,1,name);
QStandardItem *role = new QStandardItem(QString(position->getRole()));
model->setItem(entryRow,2,role);
QStandardItem *type = new QStandardItem(QString(position->getType()));
model->setItem(entryRow,3,type);
QStandardItem *hours = new QStandardItem(QString::number(position->getHours()));
model->setItem(entryRow,4,hours);
QStandardItem *wage = new QStandardItem(QString::number(position->getWage()));
model->setItem(entryRow,5,wage);
QStandardItem *salary = new QStandardItem(QString::number(position->calcSalary()));
model->setItem(entryRow,6,salary);
WorkTerm workTerm = position->getTerm();
QStandardItem *startDate = new QStandardItem(QString(workTerm.getSDate()));
model->setItem(entryRow,7,startDate);
QStandardItem *endDate = new QStandardItem(QString(workTerm.getEDate()));
model->setItem(entryRow,8,endDate);
entryRow++;
}
}
return model;
}
void MainWindow::on_pushButton_applyRaises_clicked()
{
ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_pushButton_logoutFromEditEmployee_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_cancelEdit_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_cancelAdd_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_cancelRaise_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
ui->doubleSpinBox_raisePercentage->setEnabled(true);
ui->doubleSpinBox_raiseAmount->setEnabled(true);
}
void MainWindow::on_pushButton_logoutFromApplyRaises_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_psHelp_clicked()
{
QMessageBox::information(this, "help", "\nTo update the list of employees: click on 'Update Table'\n"
"\nTo edit an employee: select the employee name from the table\n"
"\nTo filter employees based on their last name:\n"
"\nType the last name in the search box then hit 'Filter'\n"
"\nTo apply a raise to an employee: click on 'Apply Raises'\n"); //display this info
}
void MainWindow::on_pushButton_psHelp_applyRaises_clicked()
{
QMessageBox::information(this, "help", "\n1- Select the category of employees that you would like to apply a raise to\n"
"\n2- Enter the raise amount in percentage OR fixed amount\n"
"\n3- Click Apply\n"
);
}
void MainWindow::on_pushButton_helpEditForm_clicked()
{
QMessageBox::information(this, "help", "\nEnter your changes then click on 'save changes'\n"
"\nTo return back to the Home Page: click on 'back'");
}
void MainWindow::on_stackedWidget_currentChanged(int index)
{
if (index == 1) {
QList<Employee*> list = EmployeeOrm::all();
QStandardItemModel* model = employeesToModel(list);
ui->employeesList->setModel(model);
for (int i = 0; i < list.size(); i++)
delete list[i];
} else if (index == 2) {
updateRaiseDisplay();
}
}
void MainWindow::on_pushButton_saveEdit_clicked()
{
QHash<QString, QVariant> params;
assignEmployeeParams(params);
EmployeeControl::updateEmployee(selectedEmployeeId, params);
updateDisplay(selectedEmployeeId);
QMessageBox::information(this, "Update", "Update successful!");
}
void MainWindow::on_pushButton_applyRaise_clicked()
{
double raiseAmount = ui->doubleSpinBox_raiseAmount->value();
double raisePercentage = ui->doubleSpinBox_raisePercentage->value();
if (raiseAmount > 0 && raisePercentage > 100) {
ui->doubleSpinBox_raiseAmount->setValue(0);
ui->doubleSpinBox_raisePercentage->setValue(0);
QMessageBox::warning(this, "Invalid Amount", "Select either amount or percentage, but not both.");
return;
}
QString roleId;
if (ui->radioButton_facultyRaise->isChecked()) {
roleId = "Faculty";
} else if (ui->radioButton_staffRaise->isChecked()) {
roleId = "Staff";
} else {
QMessageBox::warning(this, "Invalid Role", "Select a role before performing a raise.");
return;
}
double resultWage;
if (raiseAmount > 0)
resultWage = ApplyRaisesControl::applyRaise(roleId, raiseAmount, false);
else
resultWage = ApplyRaisesControl::applyRaise(roleId, raisePercentage, true);
updateRaiseDisplay();
QMessageBox::information(this, "Raise Success", "Raise of " + QString::number(resultWage) + " applied successfully.");
}
void MainWindow::updateRaiseDisplay()
{
Role* facultyRole = RoleOrm::find("Faculty").first();
Role* staffRole = RoleOrm::find("Staff").first();
ui->label_facultyWage->setText("$" + QString::number(facultyRole->getWage()));
ui->label_staffWage->setText("$" + QString::number(staffRole->getWage()));
delete facultyRole;
delete staffRole;
}
void MainWindow::on_radioButton_TA_clicked()
{
updateDisplayToRole(selectedEmployeeId, "TA");
}
void MainWindow::on_radioButton_RA_clicked()
{
updateDisplayToRole(selectedEmployeeId, "RA");
}
void MainWindow::on_radioButton_faculty_clicked()
{
updateDisplayToRole(selectedEmployeeId, "Faculty");
}
void MainWindow::on_radioButton_staff_clicked()
{
updateDisplayToRole(selectedEmployeeId, "Staff");
}
void MainWindow::on_pushButton_import_clicked()
{
QString filter = "Cunics Files (*.cunics);; Text Files(*.txt);; All Files (*.*)";
QString filename = QFileDialog::getOpenFileName(
this,
tr("Import File"),
QDir::homePath(),
filter
);
if (!filename.isEmpty()) {
ui->label_fileName->setText("File selected: " + filename);
transactionFileName = filename;
}
}
void MainWindow::on_pushButton_DataIntegrationTool_clicked()
{
ui->stackedWidget->setCurrentIndex(6);
}
void MainWindow::on_pushButton_cancel_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_backFromEdit_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_backFromRaises_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_backFromDit_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_createEmployee_clicked()
{
}
void MainWindow::on_pushButton_update_clicked()
{
CuHRESParser parser;
bool fileParsed = parser.parseTransactionFile(transactionFileName);
if(fileParsed) {
QMessageBox::information(this,tr("Transaction"),"Changes have been updated successfully!");
/* clear transaction file selection on successful parse */
ui->label_fileName->clear();
transactionFileName = "";
} else if (transactionFileName.isEmpty()) {
QMessageBox::warning(this,tr("Transaction"),"No Transaction file selected. Please import one");
} else {
QMessageBox::warning(this,tr("Transaction"),"Errors found in the transaction file!");
}
}
| 34.240223 | 127 | 0.650677 | [
"model"
] |
43ddbf2366a97d0339858e7e67894d77148d26e9 | 1,145 | cpp | C++ | polish-spoj/MWP2_1A/solution.cpp | kpagacz/spoj | 8bff809c6c5227a6e85e9b12f808dd921f24e587 | [
"MIT"
] | 1 | 2021-12-06T16:01:55.000Z | 2021-12-06T16:01:55.000Z | polish-spoj/MWP2_1A/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | polish-spoj/MWP2_1A/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | // link to the problem https://pl.spoj.com/problems/MWP2_1A/
#include<iostream>
#include<vector>
#include<algorithm>
int rotate_and_count_matching(std::vector<int>& numbers) {
int matching = 0;
for (auto i = 0; i < numbers.size(); i++) {
if (numbers[i] == i + 1) matching++;
}
std::rotate(numbers.begin(), numbers.begin() + 1, numbers.end());
return matching;
}
void test_case(int no) {
int numbers_count;
std::cin >> numbers_count;
std::vector<int> numbers(numbers_count);
for (auto& n : numbers) std::cin >> n;
int match_max = 0;
int match;
int max_rot = 0;
for (auto current_rotation = 0; current_rotation < numbers_count; current_rotation++) {
match = rotate_and_count_matching(numbers);
if (match > match_max) {
match_max = match;
max_rot = current_rotation;
}
if (match_max > numbers_count / 2) break;
}
std::rotate(numbers.begin(), numbers.begin() + max_rot, numbers.end());
for (auto& n : numbers) std::cout << n << " ";
std::cout << '\n';
}
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(nullptr);
int tests;
std::cin >> tests;
while (tests) {
test_case(tests);
--tests;
}
} | 24.361702 | 88 | 0.659389 | [
"vector"
] |
43e16ac138adb183bfc56fb7d78b3bac8706f042 | 252,135 | cpp | C++ | src/core/OTPseudonym.cpp | lclc/opentxs | 0bc847c6601d20e3346bb2faf81feda3a14ab303 | [
"Apache-2.0"
] | null | null | null | src/core/OTPseudonym.cpp | lclc/opentxs | 0bc847c6601d20e3346bb2faf81feda3a14ab303 | [
"Apache-2.0"
] | null | null | null | src/core/OTPseudonym.cpp | lclc/opentxs | 0bc847c6601d20e3346bb2faf81feda3a14ab303 | [
"Apache-2.0"
] | null | null | null | /************************************************************
*
* OTPseudonym.cpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#include <opentxs/core/stdafx.hpp>
#include <opentxs/core/OTPseudonym.hpp>
#include <opentxs/core/crypto/OTCredential.hpp>
#include <opentxs/core/util/OTFolders.hpp>
#include <opentxs/core/OTLedger.hpp>
#include <opentxs/core/OTLog.hpp>
#include <opentxs/core/OTMessage.hpp>
#include <opentxs/core/crypto/OTPassword.hpp>
#include <opentxs/core/crypto/OTPasswordData.hpp>
#include <opentxs/core/crypto/OTSignedFile.hpp>
#include <opentxs/core/OTStorage.hpp>
#include <opentxs/core/crypto/OTSubkey.hpp>
#include <opentxs/core/crypto/OTSymmetricKey.hpp>
#include <irrxml/irrXML.hpp>
#include <algorithm>
#include <fstream>
#include <memory>
// static
namespace opentxs
{
OTPseudonym* OTPseudonym::LoadPublicNym(const OTIdentifier& NYM_ID,
const String* pstrName,
const char* szFuncName)
{
const char* szFunc =
(nullptr != szFuncName) ? szFuncName : "OTPseudonym::LoadPublicNym";
const String strNymID(NYM_ID);
// If name is empty, construct one way,
// else construct a different way.
//
OTPseudonym* pNym = ((nullptr == pstrName) || !pstrName->Exists())
? (new OTPseudonym(NYM_ID))
: (new OTPseudonym(*pstrName, strNymID, strNymID));
OT_ASSERT_MSG(nullptr != pNym,
"OTPseudonym::LoadPublicNym: Error allocating memory.\n");
bool bLoadedKey =
pNym->LoadPublicKey(); // Deprecated. Only used for old-style Nyms.
// Eventually, remove this. Currently
// LoadPublicKey calls LoadCredentials, which is
// what we should be calling, once the nym's own
// keypair is eliminated.
// First load the public key
if (!bLoadedKey)
otWarn << __FUNCTION__ << ": " << szFunc
<< ": Unable to find nym: " << strNymID << "\n";
else if (!pNym->VerifyPseudonym())
otErr << __FUNCTION__ << ": " << szFunc
<< ": Security: Failure verifying Nym: " << strNymID << "\n";
else if (!pNym->LoadSignedNymfile(*pNym)) {
otLog4 << "OTPseudonym::LoadPublicNym " << szFunc
<< ": Usually normal: There's no Nymfile (" << strNymID
<< "), though there IS a public "
"key, which checks out. It's probably just someone else's "
"Nym. (So I'm still returning this Nym to "
"the caller so he can still use the public key.)\n";
return pNym;
}
else // success
return pNym;
delete pNym;
pNym = nullptr;
return nullptr;
}
/*
Normally when I read someone ELSE'S public key, I DON'T have their Nymfile.
Therefore I don't HAVE any of their credentials, I only have the NymID and the
public key itself. Which was fine before, since you hashed the public key to
verify the NymID -- and if it matched, then all was good.
But let's say I'm reading a public key from a key credential... the hash of
that key
(or credential) is NOT necessarily the hash of the Nym's ID. So how can I
verify it?
Normally I read from: ~/.ot/client_data/pubkeys/NYM_ID (for the public key
for that Nym.)
Instead I want to read up all available credentials for that Nym.
Let's say their IDs are stored in: ~/.ot/client_data/pubkeys/NYM_ID.cred
And the credentials themselves:
~/.ot/client_data/pubkeys/credentials/NYM_ID/CREDENTIAL_ID
So let's say I have a NymID and I need to load his credentials and use his keys
to verify
the Nym and also to send him messages, verify his signatures on instruments,
etc.
pNym->LoadPublicKey() should load the UNSIGNED Nymfile from:
~/.ot/client_data/pubkeys/NYM_ID.cred
Which, in the course of loading, should automatically load all its credentials
from
~/.ot/client_data/pubkeys/credentials/NYM_ID/CREDENTIAL_ID
From there, we call VerifyPseudonym, which verifies all the credentials
internally, including
their signatures, and which verifies them against their source, which can also
be hashed to
reproduce the NymID.
...SINCE all the credentials verify AGAINST THEIR SOURCE, and the source hashes
to form the NymID,
then the Nym is therefore self-verifying, without having to sign the nymfile
itself (for public nyms.)
If I want to sign it anyway, well I will need a private Nym to sign it with, I
cannot sign it with
only a public Nym. So I will have to pass the signer in if I want to do that.
But it's unnecessary,
and in fact it's also unnecessary for private Nyms, (or is it?) because all the
credentials ARE signed
contracts already, and since they all ultimately verify to their source.
Therefore this eliminates LoadSignedNymfile? And SaveSignedNymFile? Or augments
-- since we will be backwards compatible...
I'll load the local Nym's credential list and the public nym's credential list
from the same
place: ~/.ot/client_data/credentials/NYM_ID.cred
EITHER WAY I'll load the actual credentials, each from
~/.ot/client_data/credentials/NYM_ID/CRED_ID
Then for the local Nym, I'll load his Nymfile like normal from
~/.ot/client_data/nyms/NYM_ID
(For public Nyms, I don't need to load a Nymfile or anything else -- the
credentials are all there is.)
But I still want my Nymfile itself signed, so people can't mess with my
transaction numbers.
What it comes down to is, I must put the credential list in a separate file,
load it, verify it,
and then use it to verify the signature on the Nymfile which contains
everything else. So the
"LoadSignedNymfile" process isn't going to change for the Nymfile itself, and I
will have the credential
list in a separate file, just like the certs were in a separate file in the
original system (for the
same reasons.)
*/
// static
OTPseudonym* OTPseudonym::LoadPrivateNym(const OTIdentifier& NYM_ID,
bool bChecking, const String* pstrName,
const char* szFuncName,
const OTPasswordData* pPWData,
const OTPassword* pImportPassword)
{
const char* szFunc =
(nullptr != szFuncName) ? szFuncName : "OTPseudonym::LoadPrivateNym";
if (NYM_ID.IsEmpty()) return nullptr;
const String strNymID(NYM_ID);
// If name is empty, construct one way,
// else construct a different way.
//
OTPseudonym* pNym = ((nullptr == pstrName) || !pstrName->Exists())
? (new OTPseudonym(NYM_ID))
: (new OTPseudonym(*pstrName, strNymID, strNymID));
OT_ASSERT_MSG(nullptr != pNym,
"OTPseudonym::LoadPrivateNym: Error allocating memory.\n");
OTPasswordData thePWData(OT_PW_DISPLAY);
if (nullptr == pPWData) pPWData = &thePWData;
bool bLoadedKey = pNym->Loadx509CertAndPrivateKey(
bChecking, pPWData,
pImportPassword); // old style. (Deprecated.) Eventually remove this.
//*** Right now Loadx509CertAndPrivateKey calls LoadCredentials at its top,
// which is what we should be calling here. But that function handles
// old-style Nyms too, so we keep it around until we lose those. //
//<====================
// Error loading x509CertAndPrivateKey.
if (!bLoadedKey)
OTLog::vOutput(
bChecking ? 1 : 0,
"%s: %s: (%s: is %s). Unable to load credentials, "
"cert and private key for: %s (maybe this nym doesn't exist?)\n",
__FUNCTION__, szFunc, "bChecking", bChecking ? "true" : "false",
strNymID.Get());
// success loading x509CertAndPrivateKey,
// failure verifying pseudonym public key.
else if (!pNym->VerifyPseudonym()) // <====================
otErr << __FUNCTION__ << " " << szFunc
<< ": Failure verifying Nym public key: " << strNymID << "\n";
// success verifying pseudonym public key.
// failure loading signed nymfile.
else if (!pNym->LoadSignedNymfile(*pNym)) // Unlike with public key,
// with private key we DO
// expect nymfile to be
// here.
otErr << __FUNCTION__ << " " << szFunc
<< ": Failure calling LoadSignedNymfile: " << strNymID << "\n";
else // ultimate success.
return pNym;
delete pNym;
pNym = nullptr;
return nullptr;
}
// pstrSourceForNymID if left nullptr, will use the Nym's public key (OT's
// original
// method.)
// Since that is already the Nym's ID (hash of public key) then providing the
// Nym's public
// key here will naturally hash to the correct ID and thus is the logical
// default action.
//
// But pstrSourceForNymID might contain a Bitcoin or Namecoin address, or the DN
// info from
// a traditional Certificate Authority, or a Freenet or Tor or I2P URL, or
// indeed any URL
// at all... We will also continue to support a simple public key, and by
// default, if none
// is provided, we will use the Nym's own public key as the source, and if the
// credential
// contents are not provided, the public cert or public key in full raw text
// shall be placed
// in this field.
//
// In the case of a traditional CA-issued cert, you would pass the unique issuer
// and subject DN
// info into the pstrSourceForNymID parameter (where the hash of that data
// results in the NymID,
// so you should only do it with a brand-new Nym in that case, since it will
// change the NymID.
// So for the API for creating new Nyms, we will force it that way in the
// interface to keep things
// safe, but at this low of a level, the power exists.) Continuing that same
// example, you would
// pass your actual public cert as pstrCredentialContents.
//
// If pstrSourceForNymID was a URL, then perhaps pstrCredentialContents would
// contain the contents
// located at that URL. As long as the contents of the string
// pstrCredentialContents can also
// be found at pstrSourceForNymID (or a list of hashes of similar strings...)
// then the master
// credential will verify. So for example, at the URL you might just post the
// same public cert,
// or you might have some OTCredential serialized string that contains the Nym
// ID, the Master
// credential IDs and subcredential IDs that are valid and invalid.
//
// Thought: Seems that there are three ways of exporting the OTCredential: as
// IDs only, as IDs
// with public keys, and as IDs with public keys and private keys.
//
// hash of pstrSourceForNymID is the NymID, and hash of pstrCredentialContents
// is the credential ID for this new master credential.
//
bool OTPseudonym::AddNewMasterCredential(
String& strOutputMasterCredID,
const String* pstrSourceForNymID, // If nullptr, it uses the Nym's
// (presumed) existing source
// as the source.
const int32_t nBits, // Ignored unless pmapPrivate is nullptr.
const String::Map* pmapPrivate, // If nullptr, then the keys are
// generated in here.
const String::Map* pmapPublic, // In the case of key credentials,
// public is optional since it can
// already be derived from
// private. For now we pass it
// through... May eliminate this
// parameter later if not needed.
const OTPasswordData* pPWData, // Pass in the string to show users here,
// if/when asking for the passphrase.
bool bChangeNymID) // Must be explicitly set to true, to change
// the Nym's ID. Other restrictions also
// apply... must be your first master
// credential. Must have no accounts.
// Basically can only be used for brand-new
// Nyms in circumstances where it's assumed
// the Nym's ID is in the process of being
// generated anyway. Should never be used on
// some existing Nym who is already in the
// wallet and who may even have accounts
// somewhere already.
{
const String* pstrSourceToUse = nullptr;
String strTempSource; // Used sometimes.
const String::Map* pmapActualPrivate = nullptr;
const String::Map* pmapActualPublic = nullptr;
String::Map mapPrivate, mapPublic; // Used sometimes.
// If keys are passed in, then those are the keys we're meant to use for the
// credential.
//
// Note: if the Nym is self-signed, then his "source" is his public key,
// which can thus
// never change (because it would change his ID.) We only allow this in the
// case where a
// Nym is first being created.
//
// But if the Nym has a real source (such as a URL, or Namecoin address,
// etc) then he should
// be able to create new credentials, and should BOTH be able to generate
// keys on the spot,
// OR pass in keys to use that were generated before this function was
// called.
//
// Therefore here, we choose to use the keys passed in--if they were
// passed--and otherwise
// we generate the keys.
//
OT_ASSERT(nullptr != m_pkeypair);
if (nullptr == pmapPrivate) // If no keys were passed in...
{
// That means to use (or generate) my existing keypair as the signing
// key,
// and generate the other two keypairs also.
const size_t sizeMapPublic = mapPublic.size();
const size_t sizeMapPrivate = mapPrivate.size();
String strReason, strPublicError, strPrivateError;
// Nym already has a keypair. (Use it as the signing key.)
//
// NOTE: We only want to do this if the Nym doesn't already have any
// credentials.
// Presumably if there are already credentials, then we want any NEW
// credentials to
// have their own keys. Only when there are none (meaning, we are
// currently creating
// the FIRST one) do we want to use the existing keypair. Otherwise we
// want to generate
// a new signing key.
//
// Exception: "Presumably if there are already credentials, then we want
// any NEW credentials
// to have their own keys" ==> If it's a self-signed Nym, then EVEN if
// there are existing
// credentials, we want to use the existing signing key, since in that
// case, all credentials
// would have the same signing key, which is also the Nym ID source (we
// cannot ever change it,
// since that would also change the Nym's ID. That is the drawback of
// self-signed Nyms.)
//
// Therefore we need to check here to see if the Nym is self-signed:
//
OTIdentifier theSelfSignedNymID;
m_pkeypair->CalculateID(theSelfSignedNymID);
if ((m_mapCredentials.empty() ||
CompareID(theSelfSignedNymID)) && // If there AREN'T any
// credentials yet, or if
// the Nym is self-signed,
(HasPublicKey() || // and if we have a keypair already, use it
LoadPublicKey())) // to create the first credential.
{
strReason.Set("Using existing signing key for new master "
"credential (preserving existing Nym keypair.)");
strPublicError.Set("using existing public key as");
strPrivateError.Set("using existing private key as");
}
else // GENERATE A NEW KEYPAIR.
{
const bool bCreateKeySigning = m_pkeypair->MakeNewKeypair(nBits);
OT_ASSERT(bCreateKeySigning);
m_pkeypair->SaveAndReloadBothKeysFromTempFile(); // Keys won't be
// right until this
// happens.
// (Necessary evil
// until better
// fix.) Todo:
// eliminate need
// to do this.
strReason.Set("Generating signing key for new master credential.");
strPublicError.Set("creating");
strPrivateError.Set("creating");
}
// SIGNING KEY
//
String strPublicKey, strPrivateCert;
const bool b1 = m_pkeypair->GetPublicKey(
strPublicKey, false); // bEscaped=true by default.
const bool b2 = m_pkeypair->SaveCertAndPrivateKeyToString(
strPrivateCert, &strReason);
if (b1 && b2) {
mapPublic.insert(
std::pair<std::string, std::string>("S", strPublicKey.Get()));
mapPrivate.insert(
std::pair<std::string, std::string>("S", strPrivateCert.Get()));
}
if (!b1 || !(mapPublic.size() > sizeMapPublic)) {
OTLog::vError("In %s, line %d: Failed %s public signing key in "
"OTPseudonym::%s.\n",
__FILE__, __LINE__, strPublicError.Get(),
__FUNCTION__);
return false;
}
if (!b2 || !(mapPrivate.size() > sizeMapPrivate)) {
OTLog::vError("In %s, line %d: Failed %s private signing key in "
"OTPseudonym::%s.\n",
__FILE__, __LINE__, strPrivateError.Get(),
__FUNCTION__);
return false;
}
// *************************************************************************************8
// Whether the Nym already had a keypair, and we used it as the signing
// key,
// or whether we generated the signing key on the spot, either way we
// still
// need to generate the other two keys.
//
// Create 2 keypairs here (for authentication and for encryption.)
//
// Use the public/private data for all 3 keypairs onto mapPublic and
// mapPrivate.
//
OTKeypair keyAuth, keyEncr; // (The signing keypair already exists by
// this point. These are the other two we
// need.)
const bool bCreateKeyAuth = keyAuth.MakeNewKeypair();
const bool bCreateKeyEncr = keyEncr.MakeNewKeypair();
OT_ASSERT(bCreateKeyAuth && bCreateKeyEncr);
keyAuth.SaveAndReloadBothKeysFromTempFile(); // Keys won't be right
// until this happens.
keyEncr.SaveAndReloadBothKeysFromTempFile(); // (Necessary evil until
// better fix.) Todo:
// eliminate need to do
// this.
strPublicKey.Release();
strPrivateCert.Release();
const bool b3 = keyAuth.GetPublicKey(
strPublicKey, false); // bEscaped=true by default.
const bool b4 =
keyAuth.SaveCertAndPrivateKeyToString(strPrivateCert, &strReason);
if (b3 && b4) {
mapPublic.insert(
std::pair<std::string, std::string>("A", strPublicKey.Get()));
mapPrivate.insert(
std::pair<std::string, std::string>("A", strPrivateCert.Get()));
}
strPublicKey.Release();
strPrivateCert.Release();
const bool b5 = keyEncr.GetPublicKey(
strPublicKey, false); // bEscaped=true by default.
const bool b6 =
keyEncr.SaveCertAndPrivateKeyToString(strPrivateCert, &strReason);
if (b5 && b6) {
mapPublic.insert(
std::pair<std::string, std::string>("E", strPublicKey.Get()));
mapPrivate.insert(
std::pair<std::string, std::string>("E", strPrivateCert.Get()));
}
if (!(mapPublic.size() >= (sizeMapPublic + 3))) {
otErr
<< "In " << __FILE__ << ", line " << __LINE__
<< ": Failed adding (auth or encr) public keys in OTPseudonym::"
<< __FUNCTION__ << ".\n";
return false;
}
if (!(mapPrivate.size() >= (sizeMapPrivate + 3))) {
otErr << "In " << __FILE__ << ", line " << __LINE__
<< ": Failed adding (auth or encr) private keys in "
"OTPseudonym::" << __FUNCTION__ << ".\n";
return false;
}
pmapActualPrivate = &mapPrivate;
pmapActualPublic = &mapPublic;
} // A private key wasn't passed in.
// A keypair WAS passed in...
//
else {
// If keys were passed in, then we're going to use those to create the
// new credential.
//
pmapActualPrivate = pmapPrivate;
pmapActualPublic = pmapPublic;
// Therefore in that case, the Nym had better not be self-signed, since
// if he was,
// he couldn't change the key (since his NymID is a hash of the public
// key.)
//
// Thus the Nym should have some other source besides his own key, or at
// least he
// should be a new Nym being created.
}
//
// SOURCE
//
// A source was passed in. We know it's not a public key, since its hash
// will not match the existing
// Nym ID. (Only the existing public key will match that when hashed, and
// you can use that by passing nullptr
// already, which is the following block.) Therefore it must be one of the
// other choices: a Freenet/I2P/Tor URL,
// or indeed any URL at all, a Bitcoin address, a Namecoin address (which is
// actually a form of URL also.)
// Or of course, the Issuer/Subject DN info from a traditionally-issued
// cert. In which case we are low-level
// enough that we will potentially change the NymID here based on that
// option. But we won't do that for a public
// key, unless you pass nullptr.
//
if ((nullptr != pstrSourceForNymID) &&
pstrSourceForNymID->Exists()) // A source was passed in.
{
// -- Perhaps he already has a source, in which case he one he already
// has should match the
// one that was passed in. (If one was.)
// -- Or perhaps he doesn't have a source, in which case one SHOULD have
// been passed in.
// -- Assuming that's the case, that's what we'll use.
// -- But if he doesn't have one, AND one wasn't passed in, then we will
// just created a self-signed Nym.
//
pstrSourceToUse = pstrSourceForNymID;
if (!bChangeNymID && m_strSourceForNymID.Exists() &&
!pstrSourceForNymID->Compare(m_strSourceForNymID)) {
otErr << "In " << __FILE__ << ", line " << __LINE__
<< ", OTPseudonym::" << __FUNCTION__
<< ": The Nym already has a source, but a different "
"source was passed in (they should be identical, since "
"you can't change a Nym's "
"source without changing his ID.)\n";
return false;
}
}
else // No source was passed in. That means use the existing one if it
// exists,
{ // or otherwise create it based on the key (self-signed Nym.)
//
if (m_strSourceForNymID.Exists()) // Use existing source.
strTempSource = m_strSourceForNymID;
// No source exists (nor was one passed in.) Thus create it based on the
// signing key (self-signed Nym.)
else if ((HasPublicKey() || LoadPublicKey()))
m_pkeypair->GetPublicKey(strTempSource); // bEscaped=true by
// default. Todo: someday
// change this to false.
// (It will invalidate
// existing NymIDs.)
else {
otErr << "In " << __FILE__ << ", line " << __LINE__
<< ", OTPseudonym::" << __FUNCTION__
<< ": Error: The Nym had no ID source, nor were we able "
"to derive one from his (non-existent) public key.\n";
return false;
}
pstrSourceToUse = &strTempSource;
// Hash the purported source, and see if it matches the existing NymID.
//
OTIdentifier theTempID;
theTempID.CalculateDigest(*pstrSourceToUse);
// m_pkeypair->CalculateID(theTempID);
if (!bChangeNymID && !CompareID(theTempID)) {
String strNymID;
GetIdentifier(strNymID);
OTIdentifier theKeypairNymID;
m_pkeypair->CalculateID(theKeypairNymID);
const String strKeypairNymID(theKeypairNymID),
strCalculatedNymID(theTempID);
otOut << __FUNCTION__
<< ": No NymID Source was passed in, so I tried to use the "
"existing source (or if that was missing, the existing "
"public key) for "
"the Nym, but hashing that failed to produce the Nym's "
"ID. Meaning the Nym must have "
"some other source already, which needs to be passed into "
"this function, for it to work on this Nym.\n"
"NOTE: Pass 'bChangeNymID' into this function as true, if "
"you want to override this behavior.\n"
"NYM ID: " << strNymID
<< " \n KEY PAIR CALCULATED ID: " << strKeypairNymID
<< " \n CONTENTS CALCULATED ID: " << strCalculatedNymID
<< " \n NYM ID SOURCE: " << pstrSourceToUse->Get() << "\n";
return false;
}
}
// By this point, pstrSourceToUse is good to go, and calculates to the
// correct ID for this Nym.
// Also by this point, the Nym's source and ID are both definitely set and
// correct (before this function is even called.)
// Also by this point, pmapActualPrivate and pmapActualPublic are each set
// with their 3 keys.
OT_ASSERT(nullptr != pstrSourceToUse);
// See if there are any other master credentials already. If there are, make
// sure they have the same source string calculated above.
//
if (!m_mapCredentials.empty()) {
for (auto& it : m_mapCredentials) {
OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
if (false ==
pstrSourceToUse->Compare(pCredential->GetSourceForNymID())) {
otOut << __FUNCTION__
<< ": Attempt to add new master credential failed to "
"match the NymID Source on an existing master "
"credential.\n";
return false;
}
}
// bChangeNymID only works if we are adding the FIRST credential. You
// can't be changing
// a Nym's ID if he already has credentials, since we only made that
// possible in the first
// place to make it possible to add the first credential.
//
if (bChangeNymID) {
otErr << __FUNCTION__
<< ": Failure: cannot change NymID for Nym who "
"already has credentials.\n";
return false;
}
}
// Can't change the NymID if it's already registered at a server somewhere.
//
if (bChangeNymID && (!m_mapRequestNum.empty())) {
otErr << __FUNCTION__ << ": Failure: cannot change NymID for Nym who "
"already is registered at "
"transaction servers.\n";
return false;
}
OT_ASSERT(nullptr != pmapActualPrivate);
OT_ASSERT(nullptr != pmapActualPublic);
// Create a new master credential, and set its source string (which also
// sets
// the NymID).
//
OTCredential* pMaster = OTCredential::CreateMaster(
*pstrSourceToUse, nBits, pmapActualPrivate, pmapActualPublic, pPWData);
if (nullptr == pMaster) // Below this block, pMaster must be cleaned up.
{
otErr << __FUNCTION__ << ": Failed trying to create a new master "
"credential, while calling "
"OTCredential::CreateMaster.\n";
return false;
}
// NOTE: The only way to verify a Master Credential is to go to its source
// (for its NymID)
// and see if the Master Credential ID is posted at that source. And since
// the Master Credential
// ID cannot possibly be known before the Master Credential is created and
// hashed, there is no
// way that Credential's ID could have already been posted at that source.
// Therefore it's
// impossible for the Credential to verify against the source at this time.
// (Although it must
// verify by the time the credential is registered at any OT server.)
// We can still verify the credential internally, however. (Everything but
// the source.)
//
String strNymID;
GetIdentifier(strNymID);
if (!pMaster->VerifyInternally()) {
OTIdentifier theTempID;
theTempID.CalculateDigest(*pstrSourceToUse);
const String strTempID(theTempID);
otErr << __FUNCTION__
<< ": Failed trying to verify the new master credential.\n"
"Nym ID: " << strNymID << "\nHash of Source: " << strTempID
<< "\n Source: " << pstrSourceToUse->Get() << "\n";
delete pMaster;
pMaster = nullptr;
return false;
}
// OTFolders::Credential() is for private credentials (I've created.)
// OTFolders::Pubcred() is for public credentials (I've downloaded.)
// ...(FYI.)
//
if (OTDB::Exists(OTFolders::Credential().Get(), strNymID.Get(),
pMaster->GetMasterCredID().Get())) {
otErr << __FUNCTION__
<< ": Failure: Apparently there is already a credential stored "
"for this ID (even though this is a new master credential, "
"just generated.)\n";
delete pMaster;
pMaster = nullptr;
return false;
}
// It's already signed (inside CreateMaster) but it's still not added to the
// Nym,
// or saved to local storage. So let's do that next...
//
String strFoldername, strFilename;
strFoldername.Format("%s%s%s", OTFolders::Credential().Get(),
OTLog::PathSeparator(), strNymID.Get());
strFilename.Format("%s", pMaster->GetMasterCredID().Get());
const bool bSaved =
const_cast<OTMasterkey&>(pMaster->GetMasterkey())
.SaveContract(strFoldername.Get(), strFilename.Get());
if (!bSaved) {
otErr << __FUNCTION__ << ": Failed trying to save new master "
"credential to local storage.\n";
delete pMaster;
pMaster = nullptr;
return false;
}
m_mapCredentials.insert(std::pair<std::string, OTCredential*>(
pMaster->GetMasterCredID().Get(), pMaster));
strOutputMasterCredID = pMaster->GetMasterCredID();
m_strSourceForNymID = *pstrSourceToUse; // This may be superfluous.
// (Or may just go inside the
// below block.)
if (bChangeNymID) {
m_nymID.CalculateDigest(m_strSourceForNymID);
}
//
// Todo: someday we'll add "source" and "altLocation" to CreateNym
// (currently the public key is just assumed to be the source.)
// When that time comes, we'll need to set the altLocation here as
// well, since it will be optional whenever there is a source involved.
SaveCredentialList();
return true;
}
bool OTPseudonym::AddNewSubkey(
const OTIdentifier& idMasterCredential,
int32_t nBits, // Ignored unless pmapPrivate is nullptr.
const String::Map* pmapPrivate, // If nullptr, then the keys are
// generated in here.
const OTPasswordData* pPWData, String* pstrNewID)
{
const String strMasterCredID(idMasterCredential);
auto it = m_mapCredentials.find(strMasterCredID.Get());
if (it == m_mapCredentials.end()) // Didn't find it.
{
otOut << __FUNCTION__ << ": Failed trying to add key credential to "
"nonexistent master credential.\n";
return false;
}
OTCredential* pMaster = it->second;
OT_ASSERT(nullptr != pMaster);
OTSubkey* pSubkey = nullptr;
const bool bAdded =
pMaster->AddNewSubkey(nBits, pmapPrivate, pPWData, &pSubkey);
if (!bAdded) {
otOut
<< __FUNCTION__
<< ": Failed trying to add key credential to master credential.\n";
return false;
}
OT_ASSERT(nullptr != pSubkey);
if (!pSubkey->VerifyInternally()) {
otErr << "NYM::ADD_NEW_SUBKEY: 2.5 \n";
otErr << __FUNCTION__
<< ": Failed trying to verify the new key credential.\n";
// todo: remove it again, since it failed to verify.
return false;
}
// It's already signed (inside AddNewSubkey) but it's still not added to the
// Nym,
// or saved to local storage. So let's do that next...
//
String strNymID, strSubkeyID;
GetIdentifier(strNymID);
pSubkey->GetIdentifier(strSubkeyID);
// OTFolders::Credential() is for private credentials (I've created.)
// OTFolders::Pubcred() is for public credentials (I've downloaded.)
//
if (OTDB::Exists(OTFolders::Credential().Get(), strNymID.Get(),
strSubkeyID.Get())) {
otErr << __FUNCTION__
<< ": Failure: Apparently there is already a credential stored "
"for this ID (even though this is a new credential, just "
"generated.)\n";
return false;
}
String strFoldername, strFilename;
strFoldername.Format("%s%s%s", OTFolders::Credential().Get(),
OTLog::PathSeparator(), strNymID.Get());
strFilename.Format("%s", strSubkeyID.Get());
const bool bSaved =
pSubkey->SaveContract(strFoldername.Get(), strFilename.Get());
if (!bSaved) {
otErr
<< __FUNCTION__
<< ": Failed trying to save new key credential to local storage.\n";
return false;
}
SaveCredentialList();
if (nullptr != pstrNewID) *pstrNewID = strSubkeyID;
return true;
}
bool OTPseudonym::AddNewSubcredential(
const OTIdentifier& idMasterCredential,
const String::Map* pmapPrivate, // If nullptr, then the keys are
// generated in here.
const String::Map* pmapPublic, // In the case of key credentials,
// public is optional since it can
// already be derived from
// private. For now we pass it
// through... May eliminate this
// parameter later if not needed.
const OTPasswordData* pPWData)
{
const String strMasterCredID(idMasterCredential);
auto it = m_mapCredentials.find(strMasterCredID.Get());
if (it == m_mapCredentials.end()) // Didn't find it.
{
otOut << __FUNCTION__ << ": Failed trying to add subcredential to "
"nonexistent master credential.\n";
return false;
}
OTCredential* pMaster = it->second;
OT_ASSERT(nullptr != pMaster);
OTSubcredential* pSubcredential = nullptr;
const bool bAdded = pMaster->AddNewSubcredential(*pmapPrivate, *pmapPublic,
pPWData, &pSubcredential);
if (!bAdded) {
otOut << __FUNCTION__
<< ": Failed trying to add subcredential to master credential.\n";
return false;
}
OT_ASSERT(nullptr != pSubcredential);
if (!pSubcredential->VerifyInternally()) {
otErr << __FUNCTION__
<< ": Failed trying to verify the new subcredential.\n";
// todo: remove it again, since it failed to verify.
return false;
}
// It's already signed (inside AddNewSubcredential) but it's still not added
// to the Nym,
// or saved to local storage. So let's do that next...
//
String strNymID, strSubcredentialID;
GetIdentifier(strNymID);
pSubcredential->GetIdentifier(strSubcredentialID);
if (OTDB::Exists(OTFolders::Credential().Get(), strNymID.Get(),
strSubcredentialID.Get())) {
otErr << __FUNCTION__
<< ": Failure: Apparently there is already a credential stored "
"for this ID (even though this is a new credential, just "
"generated.)\n";
return false;
}
String strFoldername, strFilename;
strFoldername.Format("%s%s%s", OTFolders::Credential().Get(),
OTLog::PathSeparator(), strNymID.Get());
strFilename.Format("%s", strSubcredentialID.Get());
const bool bSaved =
pSubcredential->SaveContract(strFoldername.Get(), strFilename.Get());
if (!bSaved) {
otErr
<< __FUNCTION__
<< ": Failed trying to save new subcredential to local storage.\n";
return false;
}
SaveCredentialList();
return true;
}
/// Though the parameter is a reference (forcing you to pass a real object),
/// the Nym DOES take ownership of the object. Therefore it MUST be allocated
/// on the heap, NOT the stack, or you will corrupt memory with this call.
///
void OTPseudonym::AddMail(OTMessage& theMessage) // a mail message is a form of
// transaction, transported via
// Nymbox
{
m_dequeMail.push_front(&theMessage);
}
/// return the number of mail items available for this Nym.
int32_t OTPseudonym::GetMailCount() const
{
return static_cast<int32_t>(m_dequeMail.size());
}
// Look up a piece of mail by index.
// If it is, return a pointer to it, otherwise return nullptr.
OTMessage* OTPseudonym::GetMailByIndex(int32_t nIndex) const
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeMail.empty() || (nIndex < 0) || (uIndex >= m_dequeMail.size()))
return nullptr;
return m_dequeMail.at(nIndex);
}
bool OTPseudonym::RemoveMailByIndex(int32_t nIndex) // if false, mail
// index was bad.
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeMail.empty() || (nIndex < 0) || (uIndex >= m_dequeMail.size()))
return false;
OTMessage* pMessage = m_dequeMail.at(nIndex);
OT_ASSERT(nullptr != pMessage);
m_dequeMail.erase(m_dequeMail.begin() + nIndex);
delete pMessage;
return true;
}
void OTPseudonym::ClearMail()
{
while (GetMailCount() > 0) RemoveMailByIndex(0);
}
/// Though the parameter is a reference (forcing you to pass a real object),
/// the Nym DOES take ownership of the object. Therefore it MUST be allocated
/// on the heap, NOT the stack, or you will corrupt memory with this call.
///
void OTPseudonym::AddOutmail(OTMessage& theMessage) // a mail message is a form
// of transaction,
// transported via Nymbox
{
m_dequeOutmail.push_front(&theMessage);
}
/// return the number of mail items available for this Nym.
int32_t OTPseudonym::GetOutmailCount() const
{
return static_cast<int32_t>(m_dequeOutmail.size());
}
// Look up a transaction by transaction number and see if it is in the ledger.
// If it is, return a pointer to it, otherwise return nullptr.
OTMessage* OTPseudonym::GetOutmailByIndex(int32_t nIndex) const
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeOutmail.empty() || (nIndex < 0) ||
(uIndex >= m_dequeOutmail.size()))
return nullptr;
return m_dequeOutmail.at(nIndex);
}
bool OTPseudonym::RemoveOutmailByIndex(int32_t nIndex) // if false,
// outmail index
// was bad.
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeOutmail.empty() || (nIndex < 0) ||
(uIndex >= m_dequeOutmail.size()))
return false;
OTMessage* pMessage = m_dequeOutmail.at(nIndex);
OT_ASSERT(nullptr != pMessage);
m_dequeOutmail.erase(m_dequeOutmail.begin() + nIndex);
delete pMessage;
return true;
}
void OTPseudonym::ClearOutmail()
{
while (GetOutmailCount() > 0) RemoveOutmailByIndex(0);
}
/// Though the parameter is a reference (forcing you to pass a real object),
/// the Nym DOES take ownership of the object. Therefore it MUST be allocated
/// on the heap, NOT the stack, or you will corrupt memory with this call.
///
void OTPseudonym::AddOutpayments(OTMessage& theMessage) // a payments message is
// a form of
// transaction,
// transported via
// Nymbox
{
m_dequeOutpayments.push_front(&theMessage);
}
/// return the number of payments items available for this Nym.
int32_t OTPseudonym::GetOutpaymentsCount() const
{
return static_cast<int32_t>(m_dequeOutpayments.size());
}
// Look up a transaction by transaction number and see if it is in the ledger.
// If it is, return a pointer to it, otherwise return nullptr.
OTMessage* OTPseudonym::GetOutpaymentsByIndex(int32_t nIndex) const
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeOutpayments.empty() || (nIndex < 0) ||
(uIndex >= m_dequeOutpayments.size()))
return nullptr;
return m_dequeOutpayments.at(nIndex);
}
// if this function returns false, outpayments index was bad.
bool OTPseudonym::RemoveOutpaymentsByIndex(int32_t nIndex, bool bDeleteIt)
{
const uint32_t uIndex = nIndex;
// Out of bounds.
if (m_dequeOutpayments.empty() || (nIndex < 0) ||
(uIndex >= m_dequeOutpayments.size())) {
otErr << __FUNCTION__
<< ": Error: Index out of bounds: signed: " << nIndex
<< " unsigned: " << uIndex << " (size is "
<< m_dequeOutpayments.size() << ").\n";
return false;
}
OTMessage* pMessage = m_dequeOutpayments.at(nIndex);
OT_ASSERT(nullptr != pMessage);
m_dequeOutpayments.erase(m_dequeOutpayments.begin() + uIndex);
if (bDeleteIt) delete pMessage;
return true;
}
void OTPseudonym::ClearOutpayments()
{
while (GetOutpaymentsCount() > 0) RemoveOutpaymentsByIndex(0);
}
// Instead of a "balance statement", some messages require a "transaction
// statement".
// Whenever the number of transactions changes, you must sign the new list so
// you
// aren't responsible for cleared transactions, for example. Or so you server
// will
// allow you to take responsibility for a new transaction number (only if you've
// signed off on it!)
//
// There will have to be another version of this function for when you don't
// have
// a transaction (like a processNymbox!) Otherwise you would need a transaction
// number
// in order to do a processNymbox. This function therefore is available in that
// incarnation
// even when you don't have a transaction number. It'll just attach the balance
// item to
// the message directly.
//
OTItem* OTPseudonym::GenerateTransactionStatement(const OTTransaction& theOwner)
{
if ((theOwner.GetUserID() != m_nymID)) {
otErr << "OTPseudonym::" << __FUNCTION__
<< ": Transaction has wrong owner (expected to match nym).\n";
return nullptr;
}
// theOwner is the depositPaymentPlan, activateSmartContract, or marketOffer
// that triggered the need for this transaction statement.
// since it uses up a transaction number, I will be sure to remove that one
// from my list before signing the list.
OTItem* pBalanceItem = OTItem::CreateItemFromTransaction(
theOwner, OTItem::transactionStatement); // <=== transactionStatement
// type, with user ID, server
// ID, transaction ID.
// The above has an ASSERT, so this this will never actually happen.
if (nullptr == pBalanceItem) return nullptr;
// COPY THE ISSUED TRANSACTION NUMBERS FROM THE NYM
OTPseudonym theMessageNym;
theMessageNym.HarvestIssuedNumbers(
theOwner.GetPurportedServerID(),
*this /*unused in this case, not saving to disk*/, *this,
false); // bSave = false;
switch (theOwner.GetType()) {
case OTTransaction::cancelCronItem:
if (theOwner.GetTransactionNum() > 0) {
theMessageNym.RemoveIssuedNum(
theOwner.GetRealServerID(),
theOwner.GetTransactionNum()); // a transaction number is being
// used, and REMOVED from my list
// of responsibility,
theMessageNym.RemoveTransactionNum(
theOwner.GetRealServerID(),
theOwner.GetTransactionNum()); // so I want the new signed list
// to reflect that number has
// been REMOVED.
}
break;
// Transaction Statements usually only have a transaction number in the case
// of market offers and
// payment plans, in which case the number should NOT be removed, and
// remains in play until
// final closure from Cron.
case OTTransaction::marketOffer:
case OTTransaction::paymentPlan:
case OTTransaction::smartContract:
default:
break;
}
// What about cases where no number is being used? (Such as processNymbox)
// Perhaps then if this function is even called, it's with a 0-number
// transaction, in which
// case the above Removes probably won't hurt anything. Todo.
String strMessageNym(theMessageNym); // Okay now we have the transaction
// numbers in this MessageNym string.
pBalanceItem->SetAttachment(strMessageNym); // <======== This is where the
// server will read the
// transaction numbers from (A
// nym in item.m_ascAttachment)
pBalanceItem->SignContract(*this); // <=== Sign, save, and return.
// OTTransactionType needs to weasel in a
// "date signed" variable.
pBalanceItem->SaveContract();
return pBalanceItem;
}
bool OTPseudonym::Savex509CertAndPrivateKeyToString(String& strOutput,
const String* pstrReason)
{
return m_pkeypair->SaveCertAndPrivateKeyToString(strOutput, pstrReason);
}
bool OTPseudonym::Savex509CertAndPrivateKey(bool bCreateFile,
const String* pstrReason)
{
String strOutput;
const bool bSuccess =
m_pkeypair->SaveAndReloadBothKeysFromTempFile(&strOutput, pstrReason);
//
// At this point, the Nym's private key is set, and its public key is also
// set.
// So the object in memory is good to go.
// Now we just need to create some files, especially where the keys are
// stored,
// since the Nym normally never writes to those files (just reads.)
//
if (bSuccess) {
// NYM ID based on SOURCE
//
if (m_strSourceForNymID.Exists())
m_nymID.CalculateDigest(m_strSourceForNymID);
// (or) NYM ID based on PUBLIC SIGNING KEY
//
else if (!SetIdentifierByPubkey()) {
otErr << __FUNCTION__ << ": Error calculating Nym ID (as a digest "
"of Nym's public (signing) key.)\n";
return false;
}
// If we set the ID based on the public key (above block),
// then we should set the source to contain that public key.
else {
String strTempSource;
m_pkeypair->GetPublicKey(strTempSource); // bEscaped=true by default
SetNymIDSource(strTempSource);
}
const String strFilenameByID(m_nymID); // FILENAME based on NYM ID
if (bCreateFile &&
(false ==
OTDB::StorePlainString(strOutput.Get(), OTFolders::Cert().Get(),
strFilenameByID.Get()))) // Store as actual
// Nym ID this time
// instead of
// temp.nym
{
otErr << __FUNCTION__
<< ": Failure storing cert for new nym: " << strFilenameByID
<< "\n";
return false;
}
}
return bSuccess;
}
// use this to actually generate a new key pair and assorted nym files.
//
bool OTPseudonym::GenerateNym(int32_t nBits, bool bCreateFile, // By default, it
// creates the various
// nym files
// and certs in local storage. (Pass false when
// creating a temp Nym, like for OTPurse.)
std::string str_id_source,
std::string str_alt_location)
{
OT_ASSERT(nullptr != m_pkeypair);
if (m_pkeypair->MakeNewKeypair(nBits)) {
String strSource(str_id_source), strAltLocation(str_alt_location);
SetNymIDSource(strSource);
SetAltLocation(strAltLocation);
String strReason("Creating new Nym."); // NOTE:
// Savex509CertAndPrivateKey
// sets the ID and sometimes if
// necessary, the source.
bool bSaved = Savex509CertAndPrivateKey(
bCreateFile,
&strReason); // Todo: remove this. Credentials code will supercede.
if (bSaved && bCreateFile) {
bSaved = SaveSignedNymfile(*this); // Now we'll generate the
// NymFile as well!
// (bCreateFile will be
// false for temp Nyms..)
}
if (bCreateFile && !bSaved)
otErr << __FUNCTION__
<< ": Failed trying to save new Nym's cert or nymfile.\n";
else {
// NEW CREDENTIALS CODE!
// We've added a parameter to this function so you can pass in the
// SOURCE for
// the Nym (which is what is hashed to produce the NymID.) The
// source could be a Bitcoin
// address, a URL, the Subject/Issuer DN info from a
// traditionally-issued certificate authority,
// or a public key. (OT originally was written to hash a public key
// to form the NymID -- so we
// will just continue to support that as an option.)
//
// If the SOURCE parameter is not passed, we will assume by default
// that the Nym has an existing one,
// or uses its own public key as its source. This will become the
// first master credential, which can
// then be used to issue keyCredentials and other types of
// subCredentials.
//
// UPDATE: Huh? I STILL need to be able to pass in a source, and
// STILL have it generate the key,
// so I can't have it ONLY pass in the source when there's no key --
// because sometimes I want to
// pass the source and ALSO use the key that was generated. (Just,
// in that case, we want it to
// use the hash of that source as the NymID, instead of the hash of
// the public key.)
// (I will update AddNewMasterCredential so it allows that.)
//
String strMasterCredID;
const bool bAddedMaster = AddNewMasterCredential(
strMasterCredID,
(str_id_source.size() > 0) ? &strSource : nullptr, nBits);
if (bAddedMaster && strMasterCredID.Exists() &&
(GetMasterCredentialCount() > 0)) {
const OTIdentifier theMasterCredID(strMasterCredID);
const bool bAddedSubkey = AddNewSubkey(theMasterCredID);
if (bAddedSubkey) {
bSaved = SaveCredentialList();
}
else {
bSaved = false;
otErr << __FUNCTION__ << ": Failed trying to add new "
"keyCredential to new Master "
"credential.\n";
}
}
else {
bSaved = false;
otErr << __FUNCTION__ << ": Failed trying to add new master "
"credential to new Nym.\n";
}
}
return bSaved;
}
return false;
}
bool OTPseudonym::SetIdentifierByPubkey()
{
OT_ASSERT(nullptr != m_pkeypair);
const bool bCalculated = m_pkeypair->CalculateID(
m_nymID); // OTAsymmetricKey::CalculateID only works with public keys.
if (!bCalculated) {
otErr << __FUNCTION__ << ": Error calculating Nym ID in "
"OTAsymmetricKey::CalculateID().\n";
return false;
}
return true;
}
// If an ID is passed in, that means remove all numbers FOR THAT SERVER ID.
// If passed in, and current map doesn't match, then skip it (continue).
#ifndef CLEAR_MAP_AND_DEQUE
#define CLEAR_MAP_AND_DEQUE(the_map) \
for (auto& it : the_map) { \
if ((nullptr != pstrServerID) && (str_ServerID != it.first)) continue; \
dequeOfTransNums* pDeque = (it.second); \
OT_ASSERT(nullptr != pDeque); \
if (!(pDeque->empty())) pDeque->clear(); \
}
#endif // CLEAR_MAP_AND_DEQUE
// Sometimes for testing I need to clear out all the transaction numbers from a
// nym.
// So I added this method to make such a thing easy to do.
//
void OTPseudonym::RemoveAllNumbers(const String* pstrServerID,
bool bRemoveHighestNum) // Some callers
// don't want
// to wipe
// the highest num. Some do.
{
std::string str_ServerID(pstrServerID ? pstrServerID->Get() : "");
// These use str_ServerID (above)
//
CLEAR_MAP_AND_DEQUE(m_mapIssuedNum)
CLEAR_MAP_AND_DEQUE(m_mapTransNum)
CLEAR_MAP_AND_DEQUE(m_mapTentativeNum)
CLEAR_MAP_AND_DEQUE(m_mapAcknowledgedNum)
std::list<mapOfHighestNums::iterator> listOfHighestNums;
std::list<mapOfIdentifiers::iterator> listOfNymboxHash;
std::list<mapOfIdentifiers::iterator> listOfInboxHash;
std::list<mapOfIdentifiers::iterator> listOfOutboxHash;
std::list<mapOfIdentifiers::iterator> listOfRecentHash;
if (bRemoveHighestNum) {
for (auto it(m_mapHighTransNo.begin()); it != m_mapHighTransNo.end();
++it) {
if ((nullptr != pstrServerID) &&
(str_ServerID != it->first)) // If passed in, and current it
// doesn't match, then skip it
// (continue).
continue;
listOfHighestNums.push_back(it);
}
}
for (auto it(m_mapNymboxHash.begin()); it != m_mapNymboxHash.end(); ++it) {
if ((nullptr != pstrServerID) &&
(str_ServerID != it->first)) // If passed in, and current it doesn't
// match, then skip it (continue).
continue;
listOfNymboxHash.push_back(it);
}
// This is mapped to acct_id, not server_id.
// (So we just wipe them all.)
for (auto it(m_mapInboxHash.begin()); it != m_mapInboxHash.end(); ++it) {
listOfInboxHash.push_back(it);
}
// This is mapped to acct_id, not server_id.
// (So we just wipe them all.)
for (auto it(m_mapOutboxHash.begin()); it != m_mapOutboxHash.end(); ++it) {
listOfOutboxHash.push_back(it);
}
for (auto it(m_mapRecentHash.begin()); it != m_mapRecentHash.end(); ++it) {
if ((nullptr != pstrServerID) &&
(str_ServerID != it->first)) // If passed in, and current it doesn't
// match, then skip it (continue).
continue;
listOfRecentHash.push_back(it);
}
while (!listOfHighestNums.empty()) {
m_mapHighTransNo.erase(listOfHighestNums.back());
listOfHighestNums.pop_back();
}
while (!listOfNymboxHash.empty()) {
m_mapNymboxHash.erase(listOfNymboxHash.back());
listOfNymboxHash.pop_back();
}
while (!listOfInboxHash.empty()) {
m_mapInboxHash.erase(listOfInboxHash.back());
listOfInboxHash.pop_back();
}
while (!listOfOutboxHash.empty()) {
m_mapOutboxHash.erase(listOfOutboxHash.back());
listOfOutboxHash.pop_back();
}
while (!listOfRecentHash.empty()) {
m_mapRecentHash.erase(listOfRecentHash.back());
listOfRecentHash.pop_back();
}
}
// OTIdentifier m_NymboxHash; // (Server-side) Hash of the
// Nymbox
// mapOfIdentifiers m_mapNymboxHash; // (Client-side) Hash of Nymbox
// (OTIdentifier) mapped by ServerID (std::string)
bool OTPseudonym::GetNymboxHashServerSide(
const OTIdentifier& theServerID, OTIdentifier& theOutput) // server-side
{
if (m_NymboxHash.IsEmpty()) {
OTLedger theNymbox(m_nymID, m_nymID, theServerID);
if (theNymbox.LoadNymbox() && theNymbox.CalculateNymboxHash(theOutput))
return true;
}
return false;
}
void OTPseudonym::SetNymboxHashServerSide(
const OTIdentifier& theInput) // server-side
{
m_NymboxHash = theInput;
}
bool OTPseudonym::GetNymboxHash(const std::string& server_id,
OTIdentifier& theOutput) const // client-side
{
return GetHash(m_mapNymboxHash, server_id, theOutput);
}
bool OTPseudonym::SetNymboxHash(const std::string& server_id,
const OTIdentifier& theInput) // client-side
{
return SetHash(m_mapNymboxHash, server_id, theInput);
}
bool OTPseudonym::GetRecentHash(const std::string& server_id,
OTIdentifier& theOutput) const // client-side
{
return GetHash(m_mapRecentHash, server_id, theOutput);
}
bool OTPseudonym::SetRecentHash(const std::string& server_id,
const OTIdentifier& theInput) // client-side
{
return SetHash(m_mapRecentHash, server_id, theInput);
}
bool OTPseudonym::GetInboxHash(const std::string& acct_id,
OTIdentifier& theOutput) const // client-side
{
return GetHash(m_mapInboxHash, acct_id, theOutput);
}
bool OTPseudonym::SetInboxHash(const std::string& acct_id,
const OTIdentifier& theInput) // client-side
{
return SetHash(m_mapInboxHash, acct_id, theInput);
}
bool OTPseudonym::GetOutboxHash(const std::string& acct_id,
OTIdentifier& theOutput) const // client-side
{
return GetHash(m_mapOutboxHash, acct_id, theOutput);
}
bool OTPseudonym::SetOutboxHash(const std::string& acct_id,
const OTIdentifier& theInput) // client-side
{
return SetHash(m_mapOutboxHash, acct_id, theInput);
}
bool OTPseudonym::GetHash(const mapOfIdentifiers& the_map,
const std::string& str_id,
OTIdentifier& theOutput) const // client-side
{
bool bRetVal =
false; // default is false: "No, I didn't find a hash for that id."
theOutput.Release();
// The Pseudonym has a map of its recent hashes, one for each server
// (nymbox) or account (inbox/outbox).
// For Server Bob, with this Pseudonym, I might have hash lkjsd987345lkj.
// For but Server Alice, I might have hash 98345jkherkjghdf98gy.
// (Same Nym, but different hash for each server, as well as inbox/outbox
// hashes for each asset acct.)
//
// So let's loop through all the hashes I have, and if the ID on the map
// passed in
// matches the [server|acct] ID that was passed in, then return TRUE.
//
for (const auto& it : the_map) {
if (str_id == it.first) {
// The call has succeeded
bRetVal = true;
theOutput = it.second;
break;
}
}
return bRetVal;
}
bool OTPseudonym::SetHash(mapOfIdentifiers& the_map, const std::string& str_id,
const OTIdentifier& theInput) // client-side
{
bool bSuccess = false;
auto find_it = the_map.find(str_id);
if (the_map.end() != find_it) // found something for that str_id
{
// The call has succeeded
the_map.erase(find_it);
the_map[str_id] = theInput;
bSuccess = true;
}
// If I didn't find it in the list above (whether the list is empty or
// not....)
// that means it does not exist. (So create it.)
//
if (!bSuccess) {
the_map[str_id] = theInput;
bSuccess = true;
}
// if (bSuccess)
// {
// SaveSignedNymfile(SIGNER_NYM);
// }
return bSuccess;
}
void OTPseudonym::RemoveReqNumbers(const String* pstrServerID)
{
const std::string str_ServerID(pstrServerID ? pstrServerID->Get() : "");
for (auto it(m_mapRequestNum.begin()); it != m_mapRequestNum.end(); ++it) {
if ((nullptr != pstrServerID) &&
(str_ServerID != it->first)) // If passed in, and current it doesn't
// match, then skip it (continue).
continue;
m_mapRequestNum.erase(it);
}
}
// You can't go using a Nym at a certain server, if it's not registered there...
// BTW -- if you have never called GetRequest(), then this will wrongly return
// false!
// But as long as you call getRequest() upon successsful registration (or
// whenever) this
// function will return an accurate answer after that point, and forever.
//
bool OTPseudonym::IsRegisteredAtServer(const String& strServerID) const
{
bool bRetVal = false; // default is return false: "No, I'm NOT registered at
// that Server."
std::string strID = strServerID.Get();
// The Pseudonym has a map of the request numbers for different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then return TRUE.
for (auto& it : m_mapRequestNum) {
if (strID == it.first) {
// The call has succeeded
bRetVal = true;
break;
}
}
return bRetVal;
}
// Removes Request Num for specific server
// (Like if Nym has deleted his account on that server...)
// Caller is responsible to save Nym after this.
//
bool OTPseudonym::UnRegisterAtServer(const String& strServerID)
{
bool bRetVal = false; // default is return false: "No, I'm NOT registered at
// that Server."
std::string strID = strServerID.Get();
// The Pseudonym has a map of the request numbers for different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then delete that one.
//
for (auto it(m_mapRequestNum.begin()); it != m_mapRequestNum.end(); ++it) {
if (strID == it->first) {
// The call has succeeded
bRetVal = true;
m_mapRequestNum.erase(it);
break;
}
}
return bRetVal;
}
#ifndef WIPE_MAP_AND_DEQUE
#define WIPE_MAP_AND_DEQUE(the_map) \
while (!the_map.empty()) { \
dequeOfTransNums* pDeque = the_map.begin()->second; \
OT_ASSERT(nullptr != pDeque); \
the_map.erase(the_map.begin()); \
delete pDeque; \
pDeque = nullptr; \
}
#endif // WIPE_MAP_AND_DEQUE
void OTPseudonym::ReleaseTransactionNumbers()
{
WIPE_MAP_AND_DEQUE(m_mapTransNum)
WIPE_MAP_AND_DEQUE(m_mapIssuedNum)
WIPE_MAP_AND_DEQUE(m_mapTentativeNum)
WIPE_MAP_AND_DEQUE(m_mapAcknowledgedNum)
}
/*
ResyncWithServer:
-- OTIdentifier m_NymboxHash; // (Server-side) Hash of the
Nymbox
-- mapOfIdentifiers m_mapNymboxHash; // (Client-side) Hash of latest
DOWNLOADED Nymbox (OTIdentifier) mapped by ServerID (std::string)
-- mapOfIdentifiers m_mapRecentHash; // (Client-side) Hash of Nymbox
according to Server, based on some recent reply. (May be newer...)
-- mapOfIdentifiers m_mapInboxHash;
-- mapOfIdentifiers m_mapOutboxHash;
-- dequeOfMail m_dequeMail; // Any mail messages received by this
Nym. (And not yet deleted.)
-- dequeOfMail m_dequeOutmail; // Any mail messages sent by this
Nym. (And not yet deleted.)
-- dequeOfMail m_dequeOutpayments; // Any outoing payments sent by
this Nym. (And not yet deleted.) (payments screen.)
-- mapOfRequestNums m_mapRequestNum; // Whenever this user makes a request
to a transaction server
** mapOfTransNums m_mapTransNum; // Each Transaction Request must be
accompanied by a fresh transaction #,
** mapOfTransNums m_mapIssuedNum; // If the server has issued me
(1,2,3,4,5) and I have already used 1-3,
** mapOfTransNums m_mapTentativeNum;
** mapOfHighestNums m_mapHighTransNo; // Mapped, a single int64_t to each
server (just like request numbers are.)
-- mapOfTransNums m_mapAcknowledgedNum; // request numbers are stored
here.
// (SERVER side)
-- std::set<int64_t> m_setOpenCronItems; // Until these Cron Items are closed
out, the server-side Nym keeps a list of them handy.
// (SERVER side)
// Using strings here to avoid juggling memory crap.
-- std::set<std::string> m_setAccounts; // A list of asset account IDs.
Server side only (client side uses wallet; has multiple servers.)
// (SERVER side.)
-- int64_t m_lUsageCredits; // Server-side. The usage credits available
for this Nym. Infinite if negative.
*/
/*
OTPseudonym::RemoveAllNumbers affects (**): (-- means doesn't affect)
-- OTIdentifier m_NymboxHash; // (Server-side) Hash of the
Nymbox
** mapOfIdentifiers m_mapNymboxHash; // (Client-side) Hash of latest
DOWNLOADED Nymbox (OTIdentifier) mapped by ServerID (std::string)
** mapOfIdentifiers m_mapRecentHash; // (Client-side) Hash of Nymbox
according to Server, based on some recent reply. (May be newer...)
** mapOfIdentifiers m_mapInboxHash;
** mapOfIdentifiers m_mapOutboxHash;
-- dequeOfMail m_dequeMail; // Any mail messages received by this
Nym. (And not yet deleted.)
-- dequeOfMail m_dequeOutmail; // Any mail messages sent by this
Nym. (And not yet deleted.)
-- dequeOfMail m_dequeOutpayments; // Any outoing payments sent by
this Nym. (And not yet deleted.) (payments screen.)
-- mapOfRequestNums m_mapRequestNum;
** mapOfTransNums m_mapTransNum;
** mapOfTransNums m_mapIssuedNum;
** mapOfTransNums m_mapTentativeNum;
** mapOfHighestNums m_mapHighTransNo; // Mapped, a single int64_t to each
server (just like request numbers are.)
** mapOfTransNums m_mapAcknowledgedNum; // request nums are stored.
// (SERVER side)
-- std::set<int64_t> m_setOpenCronItems; // Until these Cron Items are closed
out, the server-side Nym keeps a list of them handy.
// (SERVER side)
-- std::set<std::string> m_setAccounts; // A list of asset account IDs.
Server side only (client side uses wallet; has multiple servers.)
// (SERVER side.)
-- int64_t m_lUsageCredits; // Server-side. The usage credits available
for this Nym. Infinite if negative.
CLEAR_MAP_AND_DEQUE(m_mapIssuedNum)
CLEAR_MAP_AND_DEQUE(m_mapTransNum)
CLEAR_MAP_AND_DEQUE(m_mapTentativeNum)
CLEAR_MAP_AND_DEQUE(m_mapAcknowledgedNum)
m_mapHighTransNo.erase(listOfHighestNums.back());
m_mapNymboxHash.erase(listOfNymboxHash.back());
m_mapRecentHash.erase(listOfRecentHash.back());
*/
// ** ResyncWithServer **
//
// Not for normal use! (Since you should never get out of sync with the server
// in the first place.)
// However, in testing, or if some bug messes up some data, or whatever, and you
// absolutely need to
// re-sync with a server, and you trust that server not to lie to you, then this
// function will do the trick.
// NOTE: Before calling this, you need to do a getNymbox() to download the
// latest Nymbox, and you need to do
// a createUserAccount() to download the server's copy of your Nym. You then
// need to load that Nymbox from
// local storage, and you need to load the server's message Nym out of the
// @createUserAccount reply, so that
// you can pass both of those objects into this function, which must assume that
// those pieces were already done
// just prior to this call.
//
bool OTPseudonym::ResyncWithServer(const OTLedger& theNymbox,
const OTPseudonym& theMessageNym)
{
bool bSuccess = true;
const OTIdentifier& theServerID = theNymbox.GetRealServerID();
const String strServerID(theServerID);
const String strNymID(m_nymID);
const int32_t nIssuedNumCount =
theMessageNym.GetIssuedNumCount(theServerID);
const int32_t nTransNumCount =
theMessageNym.GetTransactionNumCount(theServerID);
// Remove all issued, transaction, and tentative numbers for a specific
// server ID,
// as well as all acknowledgedNums, and the highest transaction number for
// that serverID,
// from *this nym. Leave our record of the highest trans num received from
// that server,
// since we will want to just keep it when re-syncing. (Server doesn't store
// that anyway.)
//
RemoveAllNumbers(&strServerID, false); // bRemoveHighestNum=true by
// default. But in this case, I
// keep it.
// Any issued or trans numbers we add to *this from theMessageNym, are also
// added here so
// they can be used to update the "highest number" record (at the bottom of
// this function.)
//
std::set<int64_t> setTransNumbers;
// Now that *this has no issued or transaction numbers for theServerID, we
// add
// them back again from theMessageNym. (So they will match, and be 'N
// SYNC!!!)
//
// Copy the issued and transaction numbers from theMessageNym onto *this.
//
for (int32_t n1 = 0; n1 < nIssuedNumCount; ++n1) {
const int64_t lNum = theMessageNym.GetIssuedNum(theServerID, n1);
if (!AddIssuedNum(strServerID, lNum)) // Add to list of
// numbers that
// haven't been
// closed yet.
{
otErr << "OTPseudonym::ResyncWithServer: Failed trying to add "
"IssuedNum (" << lNum << ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << "\n";
bSuccess = false;
}
else {
setTransNumbers.insert(lNum);
otWarn << "OTPseudonym::ResyncWithServer: Added IssuedNum (" << lNum
<< ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << " \n";
}
}
for (int32_t n2 = 0; n2 < nTransNumCount; ++n2) {
const int64_t lNum = theMessageNym.GetTransactionNum(theServerID, n2);
if (!AddTransactionNum(strServerID, lNum)) // Add to list of
// available-to-use
// numbers.
{
otErr << "OTPseudonym::ResyncWithServer: Failed trying to add "
"TransactionNum (" << lNum
<< ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << "\n";
bSuccess = false;
}
else {
setTransNumbers.insert(lNum);
otWarn << "OTPseudonym::ResyncWithServer: Added TransactionNum ("
<< lNum << ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << " \n";
}
}
// We already cleared all tentative numbers from *this (above in
// RemoveAllNumbers). Next, loop through theNymbox and add Tentative numbers
// to *this based on each successNotice in the Nymbox. This way, when the
// notices
// are processed, they will succeed because the Nym will believe he was
// expecting them.
//
for (auto& it : theNymbox.GetTransactionMap()) {
OTTransaction* pTransaction = it.second;
OT_ASSERT(nullptr != pTransaction);
// OTString strTransaction(*pTransaction);
// otErr << "TRANSACTION CONTENTS:\n%s\n", strTransaction.Get());
// (a new; ALREADY just added transaction number.)
if ((OTTransaction::successNotice !=
pTransaction->GetType())) // if !successNotice
continue;
const int64_t lNum =
pTransaction->GetReferenceToNum(); // successNotice is inRefTo the
// new transaction # that should
// be on my tentative list.
if (!AddTentativeNum(strServerID, lNum)) // Add to list of
// tentatively-being-added
// numbers.
{
otErr << "OTPseudonym::ResyncWithServer: Failed trying to add "
"TentativeNum (" << lNum
<< ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << "\n";
bSuccess = false;
}
else
otWarn << "OTPseudonym::ResyncWithServer: Added TentativeNum ("
<< lNum << ") onto *this nym: " << strNymID
<< ", for server: " << strServerID << " \n";
// There's no "else insert to setTransNumbers" here, like the other two
// blocks above.
// Why not? Because setTransNumbers is for updating the Highest Trans
// Num record on this Nym,
// and the Tentative Numbers aren't figured into that record until AFTER
// they are accepted
// from the Nymbox. So I leave them out, since this function is
// basically setting us up to
// successfully process the Nymbox, which will then naturally update the
// highest num record
// based on the tentatives, as it's removing them from the tentative
// list and adding them to
// the "available" transaction list (and issued.)
}
const std::string strID = strServerID.Get();
for (auto& it_high_num : m_mapHighTransNo) {
// We found it!
if (strID == it_high_num.first) {
// See if any numbers on the set are higher, and if so, update the
// record to match.
//
for (auto& it : setTransNumbers) {
const int64_t lTransNum = it;
// Grab a copy of the old highest trans number
const int64_t lOldHighestNumber = it_high_num.second;
if (lTransNum > lOldHighestNumber) // Did we find a bigger one?
{
// Then update the Nym's record!
m_mapHighTransNo[it_high_num.first] = lTransNum;
otWarn
<< "OTPseudonym::ResyncWithServer: Updated HighestNum ("
<< lTransNum << ") record on *this nym: " << strNymID
<< ", for server: " << strServerID << " \n";
}
}
// We only needed to do this for the one server, so we can break
// now.
break;
}
}
return (SaveSignedNymfile(*this) && bSuccess);
}
/*
typedef std::deque<int64_t> dequeOfTransNums;
typedef std::map<std::string, dequeOfTransNums *> mapOfTransNums;
*/
// Verify whether a certain transaction number appears on a certain list.
//
bool OTPseudonym::VerifyGenericNum(const mapOfTransNums& THE_MAP,
const String& strServerID,
const int64_t& lTransNum) const
{
std::string strID = strServerID.Get();
// The Pseudonym has a deque of transaction numbers for each servers.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then find the transaction
// number on
// that list, and then return true. Else return false.
//
for (auto& it : THE_MAP) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) // there are some numbers for that server ID
{
// Let's loop through them and see if the culprit is there
for (uint32_t i = 0; i < pDeque->size(); i++) {
// Found it!
if (lTransNum == pDeque->at(i)) {
return true;
}
}
}
break;
}
}
return false;
}
// On the server side: A user has submitted a specific transaction number.
// Remove it from his file so he can't use it again.
bool OTPseudonym::RemoveGenericNum(mapOfTransNums& THE_MAP,
OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum)
{
bool bRetVal = RemoveGenericNum(THE_MAP, strServerID, lTransNum);
if (bRetVal) {
SaveSignedNymfile(SIGNER_NYM);
}
return bRetVal;
}
// This function is a little lower level, and doesn't worry about saving. Used
// internally.
// Returns true IF it successfully finds and removes the number. Otherwise
// returns false.
//
bool OTPseudonym::RemoveGenericNum(mapOfTransNums& THE_MAP,
const String& strServerID,
const int64_t& lTransNum)
{
bool bRetVal = false;
std::string strID = strServerID.Get();
// The Pseudonym has a deque of transaction numbers for each servers.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then find the transaction
// number on
// that list, and then remove it, and return true. Else return false.
//
for (auto& it : THE_MAP) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) // there are some numbers for that server ID
{
// Let's loop through them and see if the culprit is there
for (uint32_t i = 0; i < pDeque->size(); i++) {
// Found it!
if (lTransNum == pDeque->at(i)) {
pDeque->erase(pDeque->begin() + i);
bRetVal = true;
break;
}
}
}
break;
}
}
return bRetVal;
}
// No signer needed for this one, and save is false.
// This version is ONLY for cases where we're not saving inside this function.
bool OTPseudonym::AddGenericNum(mapOfTransNums& THE_MAP,
const String& strServerID, int64_t lTransNum)
{
bool bSuccessFindingServerID = false, bSuccess = false;
std::string strID = strServerID.Get();
// The Pseudonym has a deque of transaction numbers for each server.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then add the transaction
// number.
//
for (auto& it : THE_MAP) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
auto iter = std::find(pDeque->begin(), pDeque->end(), lTransNum);
if (iter == pDeque->end()) // Only add it if it's not already there.
// No duplicates!
pDeque->push_front(lTransNum);
bSuccess = true;
bSuccessFindingServerID = true;
break;
}
}
// Apparently there is not yet a deque stored for this specific serverID.
// Fine. Let's create it then, and then add the transaction num to that new
// deque.
if (!bSuccessFindingServerID) {
dequeOfTransNums* pDeque = new dequeOfTransNums;
OT_ASSERT(nullptr != pDeque);
THE_MAP[strID] = pDeque;
pDeque->push_front(lTransNum);
bSuccess = true;
}
return bSuccess;
}
// Returns count of transaction numbers available for a given server.
//
int32_t OTPseudonym::GetGenericNumCount(const mapOfTransNums& THE_MAP,
const OTIdentifier& theServerID) const
{
int32_t nReturnValue = 0;
const String strServerID(theServerID);
std::string strID = strServerID.Get();
dequeOfTransNums* pDeque = nullptr;
// The Pseudonym has a deque of transaction numbers for each server.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then we found the right server.
for (auto& it : THE_MAP) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
break;
}
}
// We found the right server, so let's count the transaction numbers
// that this nym has already stored for it.
if (nullptr != pDeque) {
nReturnValue = static_cast<int32_t>(pDeque->size());
}
return nReturnValue;
}
// by index.
int64_t OTPseudonym::GetGenericNum(const mapOfTransNums& THE_MAP,
const OTIdentifier& theServerID,
int32_t nIndex) const
{
int64_t lRetVal = 0;
const String strServerID(theServerID);
std::string strID = strServerID.Get();
// The Pseudonym has a deque of numbers for each server.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// maps matches the Server ID that was passed in, then find the number on
// that list, and then return it.
//
for (auto& it : THE_MAP) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) // there are some numbers for that server ID
{
// Let's loop through them and see if the culprit is there
for (uint32_t i = 0; i < pDeque->size(); i++) {
// Found it!
if (static_cast<uint32_t>(nIndex) == i) {
lRetVal = pDeque->at(i); // <==== Got the number here.
break;
}
}
}
break;
}
}
return lRetVal;
}
// by index.
int64_t OTPseudonym::GetIssuedNum(const OTIdentifier& theServerID,
int32_t nIndex) const
{
return GetGenericNum(m_mapIssuedNum, theServerID, nIndex);
}
// by index.
int64_t OTPseudonym::GetTransactionNum(const OTIdentifier& theServerID,
int32_t nIndex) const
{
return GetGenericNum(m_mapTransNum, theServerID, nIndex);
}
// by index.
int64_t OTPseudonym::GetAcknowledgedNum(const OTIdentifier& theServerID,
int32_t nIndex) const
{
return GetGenericNum(m_mapAcknowledgedNum, theServerID, nIndex);
}
// TRANSACTION NUM
// On the server side: A user has submitted a specific transaction number.
// Verify whether he actually has a right to use it.
bool OTPseudonym::VerifyTransactionNum(
const String& strServerID, const int64_t& lTransNum) const // doesn't save
{
return VerifyGenericNum(m_mapTransNum, strServerID, lTransNum);
}
// On the server side: A user has submitted a specific transaction number.
// Remove it from his file so he can't use it again.
bool OTPseudonym::RemoveTransactionNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum) // saves
{
return RemoveGenericNum(m_mapTransNum, SIGNER_NYM, strServerID, lTransNum);
}
bool OTPseudonym::RemoveTransactionNum(const String& strServerID,
const int64_t& lTransNum) // doesn't
// save.
{
return RemoveGenericNum(m_mapTransNum, strServerID, lTransNum);
}
// Returns count of transaction numbers available for a given server.
//
int32_t OTPseudonym::GetTransactionNumCount(
const OTIdentifier& theServerID) const
{
return GetGenericNumCount(m_mapTransNum, theServerID);
}
// No signer needed for this one, and save is false.
// This version is ONLY for cases where we're not saving inside this function.
bool OTPseudonym::AddTransactionNum(const String& strServerID,
int64_t lTransNum) // doesn't save
{
return AddGenericNum(m_mapTransNum, strServerID, lTransNum);
}
// ISSUED NUM
// On the server side: A user has submitted a specific transaction number.
// Verify whether it was issued to him and still awaiting final closing.
bool OTPseudonym::VerifyIssuedNum(const String& strServerID,
const int64_t& lTransNum) const
{
return VerifyGenericNum(m_mapIssuedNum, strServerID, lTransNum);
}
// On the server side: A user has accepted a specific receipt.
// Remove it from his file so he's not liable for it anymore.
bool OTPseudonym::RemoveIssuedNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum) // saves
{
return RemoveGenericNum(m_mapIssuedNum, SIGNER_NYM, strServerID, lTransNum);
}
bool OTPseudonym::RemoveIssuedNum(const String& strServerID,
const int64_t& lTransNum) // doesn't save
{
return RemoveGenericNum(m_mapIssuedNum, strServerID, lTransNum);
}
// Returns count of transaction numbers not yet cleared for a given server.
//
int32_t OTPseudonym::GetIssuedNumCount(const OTIdentifier& theServerID) const
{
return GetGenericNumCount(m_mapIssuedNum, theServerID);
}
// No signer needed for this one, and save is false.
// This version is ONLY for cases where we're not saving inside this function.
bool OTPseudonym::AddIssuedNum(const String& strServerID,
const int64_t& lTransNum) // doesn't save.
{
return AddGenericNum(m_mapIssuedNum, strServerID, lTransNum);
}
// TENTATIVE NUM
// On the server side: A user has submitted a specific transaction number.
// Verify whether it was issued to him and still awaiting final closing.
bool OTPseudonym::VerifyTentativeNum(const String& strServerID,
const int64_t& lTransNum) const
{
return VerifyGenericNum(m_mapTentativeNum, strServerID, lTransNum);
}
// On the server side: A user has accepted a specific receipt.
// Remove it from his file so he's not liable for it anymore.
bool OTPseudonym::RemoveTentativeNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum) // saves
{
return RemoveGenericNum(m_mapTentativeNum, SIGNER_NYM, strServerID,
lTransNum);
}
bool OTPseudonym::RemoveTentativeNum(const String& strServerID,
const int64_t& lTransNum) // doesn't save
{
return RemoveGenericNum(m_mapTentativeNum, strServerID, lTransNum);
}
// No signer needed for this one, and save is false.
// This version is ONLY for cases where we're not saving inside this function.
bool OTPseudonym::AddTentativeNum(const String& strServerID,
const int64_t& lTransNum) // doesn't save.
{
return AddGenericNum(m_mapTentativeNum, strServerID, lTransNum);
}
// ACKNOWLEDGED NUM
// These are actually used for request numbers, so both sides can determine
// which
// replies are already acknowledged. Used purely for optimization, to avoid
// downloading
// a large number of box receipts (specifically the replyNotices.)
// Client side: See if I've already seen the server's reply to a certain request
// num.
// Server side: See if I've already seen the client's acknowledgment of a reply
// I sent.
//
bool OTPseudonym::VerifyAcknowledgedNum(const String& strServerID,
const int64_t& lRequestNum) const
{
return VerifyGenericNum(m_mapAcknowledgedNum, strServerID, lRequestNum);
}
// On client side: server acknowledgment has been spotted in a reply message, so
// I can remove it from my ack list.
// On server side: client has removed acknowledgment from his list (as evident
// since its sent with client messages), so server can remove it as well.
//
bool OTPseudonym::RemoveAcknowledgedNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lRequestNum) // saves
{
return RemoveGenericNum(m_mapAcknowledgedNum, SIGNER_NYM, strServerID,
lRequestNum);
}
bool OTPseudonym::RemoveAcknowledgedNum(const String& strServerID,
const int64_t& lRequestNum) // doesn't
// save
{
return RemoveGenericNum(m_mapAcknowledgedNum, strServerID, lRequestNum);
}
// Returns count of request numbers that the client has already seen the reply
// to
// (Or in the case of server-side, the list of request numbers that the client
// has
// told me he has already seen the reply to.)
//
int32_t OTPseudonym::GetAcknowledgedNumCount(
const OTIdentifier& theServerID) const
{
return GetGenericNumCount(m_mapAcknowledgedNum, theServerID);
}
#ifndef OT_MAX_ACK_NUMS
#define OT_MAX_ACK_NUMS 100
#endif
// No signer needed for this one, and save is false.
// This version is ONLY for cases where we're not saving inside this function.
bool OTPseudonym::AddAcknowledgedNum(const String& strServerID,
const int64_t& lRequestNum) // doesn't
// save.
{
// We're going to call AddGenericNum, but first, let's enforce a cap on the
// total
// number of ackNums allowed...
//
std::string strID = strServerID.Get();
// The Pseudonym has a deque of transaction numbers for each server.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then we'll pop the size of the
// deque
// down to our max size (off the back) before then calling AddGenericNum
// which will
// push the new request number onto the front.
//
for (auto& it : m_mapAcknowledgedNum) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
while (pDeque->size() > OT_MAX_ACK_NUMS) {
pDeque->pop_back(); // This fixes knotwork's issue where he had
// thousands of ack nums somehow never
// getting cleared out. Now we have a MAX
// and always keep it clean otherwise.
}
break;
}
}
return AddGenericNum(m_mapAcknowledgedNum, strServerID,
lRequestNum); // <=== Here we finally add the new
// request number, the actual purpose of
// this function.
}
// HIGHER LEVEL...
// Client side: We have received a new trans num from server. Store it.
// Now the server uses this too, for storing these numbers so it can verify them
// later.
//
bool OTPseudonym::AddTransactionNum(
OTPseudonym& SIGNER_NYM, const String& strServerID, int64_t lTransNum,
bool bSave) // SAVE OR NOT (your choice) High-Level.
{
bool bSuccess1 = AddTransactionNum(
strServerID,
lTransNum); // Add to list of available-to-use, outstanding numbers.
bool bSuccess2 =
AddIssuedNum(strServerID, lTransNum); // Add to list of numbers that
// haven't been closed yet.
if (bSuccess1 && !bSuccess2)
RemoveGenericNum(m_mapTransNum, strServerID, lTransNum);
else if (bSuccess2 && !bSuccess1)
RemoveGenericNum(m_mapIssuedNum, strServerID, lTransNum);
if (bSuccess1 && bSuccess2 && bSave)
bSave = SaveSignedNymfile(SIGNER_NYM);
else
bSave = true; // so the return at the bottom calculates correctly.
return (bSuccess1 && bSuccess2 && bSave);
}
// Client side: We have received a server's successful reply to a processNymbox
// accepting a specific new transaction number(s).
// Or, if the reply was lost, then we still found out later that the acceptance
// was successful, since a notice is still dropped
// into the Nymbox. Either way, this function removes the Tentative number,
// right before calling the above AddTransactionNum()
// in order to make it available for the Nym's use on actual transactions.
//
bool OTPseudonym::RemoveTentativeNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum,
bool bSave) // SAVE OR NOT (your choice)
// High-Level.
{
bool bSuccess = RemoveTentativeNum(
strServerID, lTransNum); // Remove from list of numbers that haven't
// been made available for use yet, though
// they're "tentative"...
if (bSuccess && bSave)
bSave = SaveSignedNymfile(SIGNER_NYM);
else
bSave = true; // so the return at the bottom calculates correctly.
return (bSuccess && bSave);
}
// Client side: We have accepted a certain receipt. Remove the transaction
// number from my list of issued numbers.
// The server uses this too, also for keeping track of issued numbers, and
// removes them around same time as client.
// (When receipt is accepted.) Also, There is no "RemoveTransactionNum" at this
// level since GetNextTransactionNum handles that.
//
bool OTPseudonym::RemoveIssuedNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lTransNum,
bool bSave) // SAVE OR NOT (your choice)
// High-Level.
{
bool bSuccess =
RemoveIssuedNum(strServerID, lTransNum); // Remove from list of numbers
// that are still signed out.
if (bSuccess && bSave)
bSave = SaveSignedNymfile(SIGNER_NYM);
else
bSave = true; // so the return at the bottom calculates correctly.
return (bSuccess && bSave);
}
// Client keeps track of server replies it's already seen.
// Server keeps track of these client acknowledgments.
// (Server also removes from Nymbox, any acknowledged message
// that wasn't already on his list based on request num.)
// Server already removes from his list, any number the client
// has removed from his.
// This is all purely for optimization, since it allows us to avoid
// downloading all the box receipts that contain replyNotices.
//
bool OTPseudonym::RemoveAcknowledgedNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
const int64_t& lRequestNum,
bool bSave) // SAVE OR NOT (your choice)
// High-Level.
{
bool bSuccess = RemoveAcknowledgedNum(
strServerID,
lRequestNum); // Remove from list of acknowledged request numbers.
if (bSuccess && bSave)
bSave = SaveSignedNymfile(SIGNER_NYM);
else
bSave = true; // so the return at the bottom calculates correctly.
return (bSuccess && bSave);
}
/// OtherNym is used as container for server to send us new transaction numbers
/// Currently unused. (old) NEW USE:
/// Okay then, new use: This will be the function that does what the below
/// function
/// does (OTPseudonym::HarvestIssuedNumbers), EXCEPT it only adds numbers that
/// aren't on the TENTATIVE list. Also, it will set the new "highest" trans num
/// for the appropriate server, based on the new numbers being harvested.
void OTPseudonym::HarvestTransactionNumbers(const OTIdentifier& theServerID,
OTPseudonym& SIGNER_NYM,
OTPseudonym& theOtherNym,
bool bSave)
{
int64_t lTransactionNumber = 0;
std::set<int64_t> setInput, setOutputGood, setOutputBad;
for (auto& it : theOtherNym.GetMapIssuedNum()) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
String OTstrServerID = strServerID.c_str();
const OTIdentifier theTempID(OTstrServerID);
if (!(pDeque->empty()) &&
(theServerID == theTempID)) // only for the matching serverID.
{
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
// If number wasn't already on issued list, then add to BOTH
// lists.
// Otherwise do nothing (it's already on the issued list, and no
// longer
// valid on the available list--thus shouldn't be re-added there
// anyway.)
//
if ((true == VerifyTentativeNum(
OTstrServerID,
lTransactionNumber)) && // If I've actually
// requested this
// number and waiting
// on it...
(false ==
VerifyIssuedNum(OTstrServerID,
lTransactionNumber)) // and if it's not
// already on my
// issued list...
)
setInput.insert(lTransactionNumber);
}
break; // We found it! Might as well break out.
}
} // for
// Looks like we found some numbers to harvest
// (tentative numbers we had already been waiting for,
// yet hadn't processed onto our issued list yet...)
//
if (!setInput.empty()) {
const String strServerID(theServerID), strNymID(m_nymID);
int64_t lViolator = UpdateHighestNum(
SIGNER_NYM, strServerID, setInput, setOutputGood,
setOutputBad); // bSave=false (saved below already, if necessary)
// NOTE: Due to the possibility that a server reply could be processed
// twice (due to redundancy
// for the purposes of preventing syncing issues) then we expect we
// might get numbers in here
// that are below our "last highest num" (due to processing the same
// numbers twice.) Therefore
// we don't need to assume an error in this case. UpdateHighestNum() is
// already smart enough to
// only update based on the good numbers, while ignoring the bad (i.e.
// already-processed) ones.
// Thus we really only have a problem if we receive a (-1), which would
// mean an error occurred.
// Also, the above call will log an FYI that it is skipping any numbers
// below the line, so no need
// to log more in the case of lViolater being >0 but less than the 'last
// highest number.'
//
if ((-1) == lViolator)
otErr << "OTPseudonym::HarvestTransactionNumbers"
<< ": ERROR: UpdateHighestNum() returned (-1), "
"which is an error condition. "
"(Should never happen.)\nNym ID: " << strNymID << " \n";
else {
// We only remove-tentative-num/add-transaction-num for the numbers
// that were above our 'last highest number'.
// The contents of setOutputBad are thus ignored for these purposes.
//
for (auto& it : setOutputGood) {
const int64_t lNoticeNum = it;
// We already know it's on the TentativeNum list, since we
// checked that in the above for loop.
// We also already know that it's not on the issued list, since
// we checked that as well.
// That's why the below calls just ASSUME those things already.
//
RemoveTentativeNum(
strServerID, lNoticeNum); // doesn't save (but saved below)
AddTransactionNum(SIGNER_NYM, strServerID, lNoticeNum,
false); // bSave = false (but saved below...)
}
// We save regardless of whether any removals or additions are made,
// because data was
// updated in UpdateHighestNum regardless.
//
if (bSave) SaveSignedNymfile(SIGNER_NYM);
}
}
}
// OtherNym is used as container for us to send server list of issued
// transaction numbers.
// NOTE: in more recent times, a class has been added for managing lists of
// numbers. But
// we didn't have that back when this was written.
//
// The above function is good for accepting new numbers onto my list, numbers
// that I already
// tried to sign for and are thus waiting in my tentative list. When calling
// that function,
// I am trying to accept those new numbers (the ones I was expecting already),
// and NO other
// numbers.
//
// Whereas with the below function, I am adding as "available" all the numbers
// that I didn't
// already have issued to me, REGARDLESS of tentative status. Why would I do
// this? Well,
// perhaps a temp nym is being used during some calculations, and I want to copy
// all the numbers
// over to the temp nym, period, regardless of his tentative list, because he
// has no tentative
// list, because he's not a nym in the first place.
//
void OTPseudonym::HarvestIssuedNumbers(const OTIdentifier& theServerID,
OTPseudonym& SIGNER_NYM,
OTPseudonym& theOtherNym, bool bSave)
{
bool bChangedTheNym = false;
int64_t lTransactionNumber = 0;
for (auto& it : theOtherNym.GetMapIssuedNum()) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
String OTstrServerID =
((strServerID.size()) > 0 ? strServerID.c_str() : "");
const OTIdentifier theTempID(OTstrServerID);
if (!(pDeque->empty()) && (theServerID == theTempID)) {
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
// If number wasn't already on issued list, then add to BOTH
// lists.
// Otherwise do nothing (it's already on the issued list, and no
// longer
// valid on the available list--thus shouldn't be re-added there
// anyway.)
//
if (false ==
VerifyIssuedNum(OTstrServerID, lTransactionNumber)) {
AddTransactionNum(
SIGNER_NYM, OTstrServerID, lTransactionNumber,
false); // bSave = false (but saved below...)
bChangedTheNym = true;
}
}
break; // We found it! Might as well break out.
}
} // for
if (bChangedTheNym && bSave) {
SaveSignedNymfile(SIGNER_NYM);
}
}
/// When a number IS already on my issued list, but NOT on my available list
/// (because I already used it on some transaction) then this function will
/// verify that and then add it BACK to my available list. (Like if the
/// transaction failed and I just want to get my numbers back so I can use
/// them on a different transaction.)
///
bool OTPseudonym::ClawbackTransactionNumber(
const OTIdentifier& theServerID,
const int64_t& lTransClawback, // the number being clawed back.
bool bSave, // false because you might call this function 10
// times in a loop, and not want to save EVERY
// iteration.
OTPseudonym* pSIGNER_NYM)
{
if (nullptr == pSIGNER_NYM) pSIGNER_NYM = this;
// Below this point, pSIGNER_NYM is definitely a good pointer.
const String strServerID(theServerID);
// Only re-add the transaction number if it's already on my issued list.
// (Otherwise, why am I "adding it back again" if I never had it in the
// first place? Doesn't sound like a real clawback situation in that case.)
//
if (true == VerifyIssuedNum(strServerID, lTransClawback)) {
AddTransactionNum(*pSIGNER_NYM, strServerID, lTransClawback, bSave);
return true;
}
return false;
}
/// Client side.
/// Get the next available transaction number for the serverID
/// The lTransNum parameter is for the return value.
/// SAVES if successful.
bool OTPseudonym::GetNextTransactionNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
int64_t& lTransNum, bool bSave)
{
bool bRetVal = false;
std::string strID = strServerID.Get();
// The Pseudonym has a deque of transaction numbers for each server.
// These deques are mapped by Server ID.
//
// So let's loop through all the deques I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then send out the transaction
// number.
//
for (auto& it : m_mapTransNum) {
// if the ServerID passed in matches the serverID for the current deque
if (strID == it.first) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
lTransNum = pDeque->front();
pDeque->pop_front();
// The call has succeeded
bRetVal = true;
}
break;
}
}
if (bRetVal && bSave) {
if (!SaveSignedNymfile(SIGNER_NYM))
otErr << "Error saving signed NymFile in "
"OTPseudonym::GetNextTransactionNum\n";
}
return bRetVal;
}
// returns true on success, value goes into lReqNum
// Make sure the Nym is LOADED before you call this,
// otherwise it won't be there to get.
//
bool OTPseudonym::GetHighestNum(const String& strServerID,
int64_t& lHighestNum) const
{
bool bRetVal = false;
std::string strID = strServerID.Get();
// The Pseudonym has a map of the highest transaction # it's received from
// different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then send out the highest
// number.
//
// Since the transaction number only ever gets bigger, this is a way of
// preventing
// the server from EVER tricking us by trying to give us a number that we've
// already seen before.
//
for (auto& it : m_mapHighTransNo) {
if (strID == it.first) {
// Setup return value.
lHighestNum = (it.second);
// The call has succeeded
bRetVal = true;
break;
}
}
return bRetVal;
}
// Go through setNumbers and make sure none of them is lower than the highest
// number I already have for this
// server. At the same time, keep a record of the largest one in the set. If
// successful, that becomes the new
// "highest" number I've ever received that server. Otherwise fail.
// If success, returns 0. If failure, returns the number that caused us to fail
// (by being lower than the last
// highest number.) I should NEVER receive a new transaction number that is
// lower than any I've gotten before.
// They should always only get bigger. UPDATE: Unless I happen to be processing
// an old receipt twice... (which
// can happen, due to redundancy used for preventing syncing issues, such as
// Nymbox notices.)
//
int64_t OTPseudonym::UpdateHighestNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
std::set<int64_t>& setNumbers,
std::set<int64_t>& setOutputGood,
std::set<int64_t>& setOutputBad,
bool bSave)
{
bool bFoundServerID = false;
int64_t lReturnVal = 0; // 0 is success.
// First find the highest and lowest numbers out of the new set.
//
int64_t lHighestInSet = 0;
int64_t lLowestInSet = 0;
for (auto& it : setNumbers) {
const int64_t lSetNum = it;
if (lSetNum > lHighestInSet)
lHighestInSet = lSetNum; // Set lHighestInSet to contain the highest
// number out of setNumbers (input)
if (0 == lLowestInSet)
lLowestInSet = lSetNum; // If lLowestInSet is still 0, then set it
// to the current number (happens first
// iteration.)
else if (lSetNum < lLowestInSet)
lLowestInSet = lSetNum; // If current number is less than
// lLowestInSet, then set lLowestInSet to
// current Number.
}
// By this point, lLowestInSet contains the lowest number in setNumbers,
// and lHighestInSet contains the highest number in setNumbers.
//
// The Pseudonym has a map of the "highest transaction numbers" for
// different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then update it there (then
// break.)
//
// Make sure to save the Pseudonym afterwards, so the new numbers are saved.
std::string strID = strServerID.Get();
for (auto& it : m_mapHighTransNo) {
// We found the serverID key on the map?
// We now know the highest trans number for that server?
//
if (strID == it.first) // Iterates inside this block zero times or one
// time. (One if it finds it, zero if not.)
{
// We found it!
// Presumably we ONLY found it because this Nym has been properly
// loaded first.
// Good job! Otherwise, the list would have been empty even though
// the highest number
// was sitting in the file.
// Grab a copy of the old highest trans number for this server.
//
const int64_t lOldHighestNumber =
it.second; // <=========== The previous "highest number".
// Loop through the numbers passed in, and for each, see if it's
// less than
// the previous "highest number for this server."
//
// If it's less, then we can't add it (must have added it
// already...)
// So we add it to the bad list.
// But if it's more,
for (auto& it_numbers : setNumbers) {
const int64_t lSetNum = it_numbers;
// If the current number (this iteration) is less than or equal
// to the
// "old highest number", then it's not going to be added twice.
// (It goes on the "bad list.")
//
if (lSetNum <= lOldHighestNumber) {
otWarn << "OTPseudonym::UpdateHighestNum: New transaction "
"number is less-than-or-equal-to "
"last known 'highest trans number' record. (Must "
"be seeing the same server reply for "
"a second time, due to a receipt in my Nymbox.) "
"FYI, last known 'highest' number received: "
<< lOldHighestNumber
<< " (Current 'violator': " << lSetNum
<< ") Skipping...\n";
setOutputBad.insert(lSetNum);
}
// The current number this iteration, as it should be, is HIGHER
// than any transaction
// number I've ever received before. (Although sometimes old
// messages will 'echo'.)
// I want to replace the "highest" record with this one
else {
setOutputGood.insert(lSetNum);
}
}
// Here we're making sure that all the numbers in the set are larger
// than any others
// that we've had before for the same server (They should only ever
// get larger.)
//
// if (lLowestInSet <= lOldHighestNumber) // ERROR!!! The
// new numbers should ALWAYS be larger than the previous ones!
if ((lLowestInSet > 0) &&
(lLowestInSet <= lOldHighestNumber)) // WARNING! The new numbers
// should ALWAYS be larger
// than the previous ones!
// UPDATE: Unless we happen to be processing the same receipt
// for a second time, due to redundancy in the system (for
// preventing syncing errors.)
lReturnVal = lLowestInSet; // We return the violator (otherwise
// 0 if success).
// The loop has succeeded in finding the server ID and its
// associated "highest number" value.
//
bFoundServerID = true;
break;
// This main for only ever has one active iteration: the one with
// the right server ID. Once we find it, we break (no matter what.)
} // server ID matches.
}
// If we found the server ID, that means the highest number was previously
// recorded.
// We don't want to replace it unless we were successful in this function.
// And if we
// were, then we want to replace it with the new "highest number in the
// set."
//
// IF we found the server ID for a previously recorded highestNum, and
// IF this function was a success in terms of the new numbers all exceeding
// that old record,
// THEN ERASE that old record and replace it with the new highest number.
//
// Hmm: Should I require ALL new numbers to be valid? Or should I take the
// valid ones,
// and ignore the invalid ones?
//
// Update: Just found this comment from the calling function:
// NOTE: Due to the possibility that a server reply could be processed twice
// (due to redundancy
// for the purposes of preventing syncing issues) then we expect we might
// get numbers in here
// that are below our "last highest num" (due to processing the same numbers
// twice.) Therefore
// we don't need to assume an error in this case. UpdateHighestNum() is
// already smart enough to
// only update based on the good numbers, while ignoring the bad (i.e.
// already-processed) ones.
// Thus we really only have a problem if we receive a (-1), which would mean
// an error occurred.
// Also, the above call will log an FYI that it is skipping any numbers
// below the line, so no need
// to log more in the case of lViolater being >0 but less than the 'last
// highest number.'
//
// ===> THEREFORE, we don't need an lReturnVal of 0 in order to update the
// highest record.
// Instead, we just need bFoundServerID to be true, and we need
// setOutputGood to not be empty
// (we already know the numbers in setOutputGood are higher than the last
// highest recorded trans
// num... that's why they are in setOutputGood instead of setOutputBad.)
//
if (!setOutputGood.empty()) // There's numbers worth savin'!
{
if (bFoundServerID) {
otOut << "OTPseudonym::UpdateHighestNum: Raising Highest Trans "
"Number from " << m_mapHighTransNo[strID] << " to "
<< lHighestInSet << ".\n";
// We KNOW it's there, so we can straight-away just
// erase it and insert it afresh..
//
m_mapHighTransNo.erase(strID);
m_mapHighTransNo.insert(
std::pair<std::string, int64_t>(strID, lHighestInSet));
}
// If I didn't find the server in the list above (whether the list is
// empty or not....)
// that means the record does not yet exist. (So let's create it)--we
// wouldn't even be
// here unless we found valid transaction numbers and added them to
// setOutputGood.
// (So let's record lHighestInSet mapped to strID, just as above.)
else {
otOut << "OTPseudonym::UpdateHighestNum: Creating "
"Highest Transaction Number entry for this server as '"
<< lHighestInSet << "'.\n";
m_mapHighTransNo.insert(
std::pair<std::string, int64_t>(strID, lHighestInSet));
}
// By this point either the record was created, or we were successful
// above in finding it
// and updating it. Either way, it's there now and potentially needs to
// be saved.
//
if (bSave) SaveSignedNymfile(SIGNER_NYM);
}
else // setOutputGood was completely empty in this case...
{ // (So there's nothing worth saving.) A repeat message.
//
// Should I return a -1 here or something? Let's say it's
// a redundant message...I've already harvested these numbers. So
// they are ignored this time, my record of 'highest' is unimpacted,
// and if I just return lReturnVal below, it will contain 0 for success
// or a transaction number (the min/low violator) but even that is
// considered
// a "success" in the sense that some of the numbers would still
// normally be
// expected to have passed through.
// The caller will check for -1 in case of some drastic error, but so
// far I don't
// see a place here for that return value.
//
}
return lReturnVal; // Defaults to 0 (success) but above, might have been set
// to "lLowestInSet" (if one was below the mark.)
}
// returns true on success, value goes into lReqNum
// Make sure the Nym is LOADED before you call this,
// otherwise it won't be there to get.
// and if the request number needs to be incremented,
// then make sure you call IncrementRequestNum (below)
bool OTPseudonym::GetCurrentRequestNum(const String& strServerID,
int64_t& lReqNum) const
{
bool bRetVal = false;
std::string strID = strServerID.Get();
// The Pseudonym has a map of the request numbers for different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then send out the request
// number.
for (auto& it : m_mapRequestNum) {
if (strID == it.first) {
// Setup return value.
lReqNum = (it.second);
// The call has succeeded
bRetVal = true;
break;
}
}
return bRetVal;
}
// Make SURE you call SavePseudonym after you call this.
// Otherwise it will increment in memory but not in the file.
// In fact, I cannot allow that. I will call SavePseudonym myself.
// Therefore, make SURE you fully LOAD this Pseudonym before you save it.
// You don't want to overwrite what's in that file.
// THEREFORE we need a better database than the filesystem.
// I will research a good, free, secure database (or encrypt everything
// before storing it there) and soon these "load/save" commands will use that
// instead of the filesystem.
void OTPseudonym::IncrementRequestNum(OTPseudonym& SIGNER_NYM,
const String& strServerID)
{
bool bSuccess = false;
// The Pseudonym has a map of the request numbers for different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then send out the request
// number and
// increment it so it will be ready for the next request.
//
// Make sure to save the Pseudonym so the new request number is saved.
std::string strID = strServerID.Get();
for (auto& it : m_mapRequestNum) {
if (strID == it.first) {
// We found it!
// Presumably we ONLY found it because this Nym has been properly
// loaded first.
// Good job! Otherwise, the list would have been empty even though
// the request number
// was sitting in the file.
// Grab a copy of the old request number
int64_t lOldRequestNumber = m_mapRequestNum[it.first];
// Set the new request number to the old one plus one.
m_mapRequestNum[it.first] = lOldRequestNumber + 1;
// Now we can log BOTH, before and after... // debug here
otLog4 << "Incremented Request Number from " << lOldRequestNumber
<< " to " << m_mapRequestNum[it.first] << ". Saving...\n";
// The call has succeeded
bSuccess = true;
break;
}
}
// If I didn't find it in the list above (whether the list is empty or
// not....)
// that means it does not exist. So create it.
if (!bSuccess) {
otOut << "Creating Request Number entry as '100'. Saving...\n";
m_mapRequestNum[strServerID.Get()] = 100;
bSuccess = true;
}
if (bSuccess) {
SaveSignedNymfile(SIGNER_NYM);
}
}
// if the server sends us a @getRequest
void OTPseudonym::OnUpdateRequestNum(OTPseudonym& SIGNER_NYM,
const String& strServerID,
int64_t lNewRequestNumber)
{
bool bSuccess = false;
// The Pseudonym has a map of the request numbers for different servers.
// For Server Bob, with this Pseudonym, I might be on number 34.
// For but Server Alice, I might be on number 59.
//
// So let's loop through all the numbers I have, and if the server ID on the
// map
// matches the Server ID that was passed in, then send out the request
// number and
// increment it so it will be ready for the next request.
//
// Make sure to save the Pseudonym so the new request number is saved.
std::string strID = strServerID.Get();
for (auto& it : m_mapRequestNum) {
if (strID == it.first) {
// We found it!
// Presumably we ONLY found it because this Nym has been properly
// loaded first.
// Good job! Otherwise, the list would have been empty even though
// the request number
// was sitting in the file.
// The call has succeeded
bSuccess = true;
// Grab a copy of the old request number
int64_t lOldRequestNumber = m_mapRequestNum[it.first];
// Set the new request number to the old one plus one.
m_mapRequestNum[it.first] = lNewRequestNumber;
// Now we can log BOTH, before and after...
otLog4 << "Updated Request Number from " << lOldRequestNumber
<< " to " << m_mapRequestNum[it.first] << ". Saving...\n";
break;
}
}
// If I didn't find it in the list above (whether the list is empty or
// not....)
// that means it does not exist. So create it.
if (!bSuccess) {
otOut << "Creating Request Number entry as '" << lNewRequestNumber
<< "'. Saving...\n";
m_mapRequestNum[strServerID.Get()] = lNewRequestNumber;
bSuccess = true;
}
if (bSuccess) {
SaveSignedNymfile(SIGNER_NYM);
}
}
size_t OTPseudonym::GetMasterCredentialCount() const
{
return m_mapCredentials.size();
}
size_t OTPseudonym::GetRevokedCredentialCount() const
{
return m_mapRevoked.size();
}
/*
How will VerifyPseudonym change now that we are adding credentials?
Before it was easy: hash the public key, and compare the result to the NymID
as it was already set by the wallet. If they match, then this really is the
public
key that I was expecting. (You could not change out that key without causing
the ID
to also change.)
How are things with credentials?
The public key may not directly hash to the Nym ID, but even if it did, which
public key?
Aren't there THREE public keys for each credential? That is, a signing,
authentication, and
encryption key. Which one is used as that Key ID? Perhaps all three are hashed
together?
And that collective three-key is only valid for a given Nym, if its credential
contract is
signed by a master key for that Nym. And that master key is only valid if its
authority
verifies properly. And the Nym's ID should be a hash somehow, of that
authority. All of those
things must verify in VerifyPseudonym, in the new system.
Is that really true?
Pseudo-code:
Loop through the credentials for this Nym.
For each, the authority/source string (which resolve to the NymID) should be
identical.
Resolve the NymID and compare it to the one that was expected.
An extended version will also verify the authority itself, to see if it
verifies the key.
For example if this Nym is issued based on a Namecoin address, then the code
would actually
check Namecoin itself to verify the NymID is the same one posted there.
*/
bool OTPseudonym::VerifyPseudonym() const
{
// If there are credentials, then we verify the Nym via his credentials.
if (!m_mapCredentials.empty()) {
// Verify Nym by his own credentials.
for (const auto& it : m_mapCredentials) {
const OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
const OTIdentifier theCredentialNymID(pCredential->GetNymID());
if (!CompareID(theCredentialNymID)) {
String strNymID;
GetIdentifier(strNymID);
otOut << __FUNCTION__ << ": Credential NymID ("
<< pCredential->GetNymID()
<< ") doesn't match actual NymID: " << strNymID << "\n";
return false;
}
if (!pCredential->VerifyInternally()) {
otOut << __FUNCTION__ << ": Credential ("
<< pCredential->GetMasterCredID()
<< ") failed its own internal verification.\n";
return false;
}
// Warning: time-intensive. Todo optimize: load a contract here
// which verifies authorization,
// based on a signature from a separate process which did an
// identity lookup externally.
// Once that authorization times out, then the identity verification
// server can just sign
// another one.
//
if (!pCredential->VerifyAgainstSource()) // todo optimize,
// warning:
// time-intensive.
{
otOut
<< __FUNCTION__
<< ": Credential failed against its source. Credential ID: "
<< pCredential->GetMasterCredID()
<< "\n"
"NymID: " << pCredential->GetNymID()
<< "\nSource: " << pCredential->GetSourceForNymID() << "\n";
return false;
}
}
// NOTE: m_pkeypair needs to be phased out entirely. TODO!!
// In the meantime, ::LoadPublicKey isn't setting m_pkeypair
// because the key isn't actually available until AFTER the
// pCredential->VerifyInternally() has occurred. Well, right
// here, it just occurred (above) and so we can actually set
// m_pkeypair at this point, where we couldn't do it before in
// LoadPublicKey.
//
// The real solution is to just phase out m_pkeypair entirely. TODO!
// But in the meantime, as long as there are vestiges of the code
// that still use it, we need to make sure it's set, and we can
// only do that here, after VerifyInternally() has finished.
//
// (So that's what I'm doing.)
//
if (!m_pkeypair->HasPublicKey()) {
auto it = m_mapCredentials.begin();
OT_ASSERT(m_mapCredentials.end() != it);
OTCredential* pCredential = it->second;
OT_ASSERT(nullptr != pCredential);
String strSigningKey;
if (const_cast<OTKeypair&>(
pCredential->GetSignKeypair(&m_listRevokedIDs))
.GetPublicKey(strSigningKey, false)) // bEscaped
return m_pkeypair->SetPublicKey(strSigningKey,
false); // bEscaped
else
otErr << __FUNCTION__ << ": Failed in call to "
"pCredential->GetPublicSignKey()."
"GetPublicKey()\n";
}
return true;
}
otErr << "No credentials.\n";
return false;
}
bool OTPseudonym::CompareID(const OTPseudonym& RHS) const
{
return RHS.CompareID(m_nymID);
}
bool OTPseudonym::SavePseudonymWallet(String& strOutput) const
{
String nymID;
GetIdentifier(nymID);
OTASCIIArmor ascName;
if (m_strName.Exists()) // name is in the clear in memory, and base64 in
// storage.
{
ascName.SetString(m_strName, false); // linebreaks == false
}
strOutput.Concatenate("<pseudonym name=\"%s\"\n"
" nymID=\"%s\" />\n\n",
ascName.Get(), nymID.Get());
return true;
}
bool OTPseudonym::SavePseudonymWallet(std::ofstream& ofs) const
{
String strOutput;
if (SavePseudonymWallet(strOutput))
ofs << strOutput;
else
return false;
return true;
}
// This function saves the public key to a file.
//
bool OTPseudonym::SavePublicKey(const String& strPath) const
{
const char* szFoldername = OTFolders::Pubkey().Get();
const char* szFilename = strPath.Get();
OT_ASSERT(nullptr != szFoldername);
OT_ASSERT(nullptr != szFilename);
OT_ASSERT(nullptr != m_pkeypair);
// By passing in an OTString instead of OTASCIIArmor, it knows to add the
// bookends
// ----- BEGIN PUBLIC KEY etc. These bookends are necessary for
// OTASCIIArmor to later
// read the thing back up into memory again.
String strKey;
if (m_pkeypair->GetPublicKey(strKey, false)) // false means "do not ESCAPE
// the bookends"
// Ie we'll get ----------- instead of - ---------
{
bool bStored =
OTDB::StorePlainString(strKey.Get(), szFoldername, szFilename);
if (!bStored) {
otErr << "Failure in OTPseudonym::SavePublicKey while saving to "
"storage: " << szFoldername << OTLog::PathSeparator()
<< szFilename << "\n";
return false;
}
}
else {
otErr << "Error in OTPseudonym::SavePublicKey: unable to GetPublicKey "
"from Nym\n";
return false;
}
return true;
}
bool OTPseudonym::SavePublicKey(std::ofstream& ofs) const
{
OT_ASSERT(nullptr != m_pkeypair);
// By passing in an OTString instead of OTASCIIArmor, it knows to add the
// bookends
// ----- BEGIN PUBLIC KEY etc. These bookends are necessary for
// OTASCIIArmor to later
// read the thing back up into memory again.
String strKey;
if (m_pkeypair->GetPublicKey(strKey, false)) // false means "do not ESCAPE
// the bookends"
// Ie we'll get ----------- instead of - ---------
{
strKey.WriteToFile(ofs);
}
else {
otErr << "Error in OTPseudonym::SavePublicKey: unable to GetPublicKey "
"from Nym\n";
return false;
}
return true;
}
// pstrID is an output parameter.
bool OTPseudonym::Server_PubKeyExists(String* pstrID) // Only used
// on server
// side.
{
String strID;
if (nullptr == pstrID) {
pstrID = &strID;
}
GetIdentifier(*pstrID);
// Below this point, pstrID is a GOOD pointer, no matter what. (And no need
// to delete it.)
return OTDB::Exists(OTFolders::Pubkey().Get(), pstrID->Get());
}
// This version is run on the server side, and assumes only a Public Key.
// This code reads up the file, discards the bookends, and saves only the
// gibberish itself.
bool OTPseudonym::LoadPublicKey()
{
OT_ASSERT(nullptr != m_pkeypair);
// Here we try to load credentials first and if it's successful, we
// use that to set the public key from the credential, and then return.
//
if (LoadCredentials() && (GetMasterCredentialCount() > 0)) {
return true;
// NOTE: LoadPublicKey (this function) calls LoadCredentials (above.) On
// the server side, these are
// public credentials which do not contain keys, per se. Instead, it
// contains a single variable which in
// turn contains the master-signed version of itself which then contains
// the public keys.
//
// That means when the credentials are first loaded, there are no public
// keys loaded! Each subcredential
// is signed by itself, and contains a master-signed version of itself
// that's signed by the master. It's
// only AFTER loading, in verification
// (OTSubcredential::VerifyInternally) when we verify the master
// signature
// on the master-signed version, and if it all checks out, THEN we copy
// the public keys from the master-signed
// version up into the actual subcredential. UNTIL WE DO THAT, the
// actual subcredential HAS NO PUBLIC KEYS IN IT.
//
// That's why the above code was having problems -- we are trying to
// "GetPublicKey" when there can be no
// possibility that the public key will be there.
// For now I'm going to NOT set m_pkeypair, since the public key isn't
// available to set onto it yet.
// We want to phase out m_pkeypair anyway, but I just hope this doesn't
// cause problems where it was expected
// in the future, where I still need to somehow make sure it's set.
// (AFTER verification, apparently.)
//
// Notice however, that this only happens in cases where the credentials
// were actually available, so maybe it
// will just work, since the below block is where we handle cases where
// the credentials WEREN'T available, so
// we load the old key the old way. (Meaning we definitely know that
// those "old cases" will continue to work.)
// Any potential problems will have to be in cases where credentials ARE
// available, but the code was nonetheless
// still expecting things to work the old way -- and these are precisely
// the sorts of cases I probably want to
// uncover, so I can convert things over...
}
otInfo << __FUNCTION__ << ": Failure.\n";
return false;
}
// DISPLAY STATISTICS
void OTPseudonym::DisplayStatistics(String& strOutput)
{
for (auto& it : m_mapRequestNum) {
std::string strServerID = it.first;
int64_t lRequestNumber = it.second;
// Now we can log BOTH, before and after...
strOutput.Concatenate("Req# is %" PRId64 " for server ID: %s\n",
lRequestNumber, strServerID.c_str());
}
for (auto& it : m_mapHighTransNo) {
std::string strServerID = it.first;
const int64_t lHighestNum = it.second;
strOutput.Concatenate("Highest trans# was %" PRId64 " for server: %s\n",
lHighestNum, strServerID.c_str());
}
for (auto& it : m_mapIssuedNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
strOutput.Concatenate(
"---- Transaction numbers still signed out from server: %s\n",
strServerID.c_str());
for (uint32_t i = 0; i < pDeque->size(); i++) {
int64_t lTransactionNumber = pDeque->at(i);
strOutput.Concatenate(0 == i ? "%" PRId64 : ", %" PRId64,
lTransactionNumber);
}
strOutput.Concatenate("\n");
}
} // for
for (auto& it : m_mapTransNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
strOutput.Concatenate(
"---- Transaction numbers still usable on server: %s\n",
strServerID.c_str());
for (uint32_t i = 0; i < pDeque->size(); i++) {
int64_t lTransactionNumber = pDeque->at(i);
strOutput.Concatenate(0 == i ? "%" PRId64 : ", %" PRId64,
lTransactionNumber);
}
strOutput.Concatenate("\n");
}
} // for
for (auto& it : m_mapAcknowledgedNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
strOutput.Concatenate("---- Request numbers for which Nym has "
"already received a reply from server: %s\n",
strServerID.c_str());
for (uint32_t i = 0; i < pDeque->size(); i++) {
int64_t lRequestNumber = pDeque->at(i);
strOutput.Concatenate(0 == i ? "%" PRId64 : ", %" PRId64,
lRequestNumber);
}
strOutput.Concatenate("\n");
}
} // for
strOutput.Concatenate("Source for ID:\n%s\n", m_strSourceForNymID.Get());
strOutput.Concatenate("Alt. location: %s\n\n", m_strAltLocation.Get());
const size_t nMasterCredCount = GetMasterCredentialCount();
if (nMasterCredCount > 0) {
for (int32_t iii = 0; iii < static_cast<int64_t>(nMasterCredCount);
++iii) {
const OTCredential* pCredential = GetMasterCredentialByIndex(iii);
if (nullptr != pCredential) {
strOutput.Concatenate("Credential ID: %s \n",
pCredential->GetMasterCredID().Get());
const size_t nSubcredentialCount =
pCredential->GetSubcredentialCount();
if (nSubcredentialCount > 0) {
for (size_t vvv = 0; vvv < nSubcredentialCount; ++vvv) {
const std::string str_subcred_id(
pCredential->GetSubcredentialIDByIndex(vvv));
strOutput.Concatenate(" Subcredential: %s \n",
str_subcred_id.c_str());
}
}
}
}
strOutput.Concatenate("%s", "\n");
}
strOutput.Concatenate("==> Name: %s %s\n", m_strName.Get(),
m_bMarkForDeletion ? "(MARKED FOR DELETION)" : "");
strOutput.Concatenate(" Version: %s\n", m_strVersion.Get());
// This is used on server-side only. (Client side sees this value
// by querying the server.)
// Therefore since m_lUsageCredits is unused on client side, why display
// it in the client API? Makes no sense.
// strOutput.Concatenate("Usage Credits: %" PRId64 "\n", m_lUsageCredits);
strOutput.Concatenate(" Mail count: %" PRI_SIZE "\n",
m_dequeMail.size());
strOutput.Concatenate(" Outmail count: %" PRI_SIZE "\n",
m_dequeOutmail.size());
strOutput.Concatenate("Outpayments count: %" PRI_SIZE "\n",
m_dequeOutpayments.size());
String theStringID;
GetIdentifier(theStringID);
strOutput.Concatenate("Nym ID: %s\n", theStringID.Get());
}
bool OTPseudonym::SavePseudonym()
{
if (!m_strNymfile.GetLength()) {
String nymID;
GetIdentifier(nymID);
m_strNymfile.Format("%s", nymID.Get());
}
otInfo << "Saving nym to: " << OTFolders::Nym() << OTLog::PathSeparator()
<< m_strNymfile << "\n";
return SavePseudonym(OTFolders::Nym().Get(), m_strNymfile.Get());
}
bool OTPseudonym::SavePseudonym(const char* szFoldername,
const char* szFilename)
{
OT_ASSERT(nullptr != szFoldername);
OT_ASSERT(nullptr != szFilename);
String strNym;
SavePseudonym(strNym);
bool bSaved =
OTDB::StorePlainString(strNym.Get(), szFoldername, szFilename);
if (!bSaved)
otErr << __FUNCTION__ << ": Error saving file: " << szFoldername
<< OTLog::PathSeparator() << szFilename << "\n";
return bSaved;
}
bool OTPseudonym::SavePseudonym(std::ofstream& ofs)
{
String strNym;
SavePseudonym(strNym);
ofs << strNym;
return true;
}
// Used when importing/exporting Nym into and out-of the sphere of the cached
// key
// in the wallet.
bool OTPseudonym::ReEncryptPrivateCredentials(
bool bImporting, // bImporting=true, or false if exporting.
const OTPasswordData* pPWData, const OTPassword* pImportPassword)
{
const OTPassword* pExportPassphrase = nullptr;
std::unique_ptr<const OTPassword> thePasswordAngel;
if (nullptr == pImportPassword) {
// whether import/export, this display string is for the OUTSIDE OF
// WALLET
// portion of that process.
//
String strDisplay(
nullptr != pPWData
? pPWData->GetDisplayString()
: (bImporting ? "Enter passphrase for the Nym being imported."
: "Enter passphrase for exported Nym."));
// Circumvents the cached key.
pExportPassphrase = OTSymmetricKey::GetPassphraseFromUser(
&strDisplay, !bImporting); // bAskTwice is true when exporting
// (since the export passphrase is being
// created at that time.)
thePasswordAngel.reset(pExportPassphrase);
if (nullptr == pExportPassphrase) {
otErr << __FUNCTION__ << ": Failed in GetPassphraseFromUser.\n";
return false;
}
// otOut << "%s: DEBUGGING pExportPassphrase, size %d, contains: %s
// \n",
// __FUNCTION__,
// pExportPassphrase->getPasswordSize(),
// pExportPassphrase->getPassword());
}
else {
pExportPassphrase = pImportPassword;
// otOut << "%s: DEBUGGING pImportPassword, size %d, contains: %s
// \n",
// __FUNCTION__, pImportPassword->getPasswordSize(),
// pImportPassword->getPassword());
}
for (auto& it : m_mapCredentials) {
OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
if (false ==
pCredential->ReEncryptPrivateCredentials(*pExportPassphrase,
bImporting))
return false;
}
return true;
}
// If the Nym's source is a URL, he needs to post his valid master credential
// IDs
// there, so they can be verified against their source. This method is what
// creates
// the file which you can post at that URL. (Containing only the valid IDs, not
// the revoked ones.)
// Optionally it also returns the contents of the public credential files,
// mapped by their
// credential IDs.
//
void OTPseudonym::GetPublicCredentials(String& strCredList,
String::Map* pmapCredFiles) const
{
String strNymID;
GetIdentifier(strNymID);
strCredList.Concatenate("<?xml version=\"%s\"?>\n",
"2.0"); // todo hardcoding.
strCredList.Concatenate("<OTuser version=\"%s\"\n"
" nymID=\"%s\""
">\n\n",
m_strVersion.Get(), strNymID.Get());
SerializeNymIDSource(strCredList);
for (auto& it : m_mapCredentials) {
OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
pCredential->SerializeIDs(strCredList, m_listRevokedIDs,
pmapCredFiles); // bShowRevoked=false by
// default, bValid=true by
// default. (True since we're
// looping m_mapCredentials
// only, and not
// m_mapRevoked.)
}
strCredList.Concatenate("</OTuser>\n");
}
void OTPseudonym::GetPrivateCredentials(String& strCredList,
String::Map* pmapCredFiles)
{
String strNymID;
GetIdentifier(strNymID);
strCredList.Concatenate("<?xml version=\"%s\"?>\n",
"2.0"); // todo hardcoding.
strCredList.Concatenate("<OTuser version=\"%s\"\n"
" nymID=\"%s\""
">\n\n",
m_strVersion.Get(), strNymID.Get());
SerializeNymIDSource(strCredList);
SaveCredentialsToString(strCredList, nullptr, pmapCredFiles);
strCredList.Concatenate("</OTuser>\n");
}
void OTPseudonym::SerializeNymIDSource(String& strOutput) const
{
// We encode these before storing.
if (m_strSourceForNymID.Exists()) {
const OTASCIIArmor ascSourceForNymID(m_strSourceForNymID);
if (m_strAltLocation.Exists()) {
OTASCIIArmor ascAltLocation;
ascAltLocation.SetString(m_strAltLocation,
false); // bLineBreaks=true by default.
strOutput.Concatenate(
"<nymIDSource altLocation=\"%s\">\n%s</nymIDSource>\n\n",
ascAltLocation.Get(), ascSourceForNymID.Get());
}
else
strOutput.Concatenate("<nymIDSource>\n%s</nymIDSource>\n\n",
ascSourceForNymID.Get());
}
}
void OTPseudonym::SaveCredentialListToString(String& strOutput)
{
String strNymID;
GetIdentifier(strNymID);
strOutput.Concatenate("<?xml version=\"%s\"?>\n",
"2.0"); // todo hardcoding.
strOutput.Concatenate("<OTuser version=\"%s\"\n"
" nymID=\"%s\""
">\n\n",
m_strVersion.Get(), strNymID.Get());
SerializeNymIDSource(strOutput);
SaveCredentialsToString(strOutput);
strOutput.Concatenate("</OTuser>\n");
}
bool OTPseudonym::SaveCredentialList()
{
String strNymID, strOutput;
GetIdentifier(strNymID);
SaveCredentialListToString(strOutput);
if (strOutput.Exists()) {
OTASCIIArmor ascOutput(strOutput);
strOutput.Release();
if (ascOutput.WriteArmoredString(
strOutput, "CREDENTIAL LIST") && // bEscaped=false by default.
strOutput.Exists()) {
// Save it to local storage.
String strFilename;
strFilename.Format("%s.cred", strNymID.Get());
std::string str_Folder = HasPrivateKey()
? OTFolders::Credential().Get()
: OTFolders::Pubcred().Get();
if (!OTDB::StorePlainString(strOutput.Get(), str_Folder,
strFilename.Get())) {
otErr << __FUNCTION__ << ": Failure trying to store "
<< (HasPrivateKey() ? "private" : "public")
<< " credential list for Nym: " << strNymID << "\n";
return false;
}
return true;
}
}
return false;
}
// Use this to load the keys for a Nym (whether public or private), and then
// call VerifyPseudonym, and then load the actual Nymfile using
// LoadSignedNymfile.
//
bool OTPseudonym::LoadCredentials(bool bLoadPrivate, // Loads public credentials
// by default. For
// private, pass true.
const OTPasswordData* pPWData,
const OTPassword* pImportPassword)
{
String strReason(nullptr == pPWData ? OT_PW_DISPLAY
: pPWData->GetDisplayString());
ClearCredentials();
String strNymID;
GetIdentifier(strNymID);
String strFilename;
strFilename.Format("%s.cred", strNymID.Get());
const char* szFoldername = bLoadPrivate ? OTFolders::Credential().Get()
: OTFolders::Pubcred().Get();
const char* szFilename = strFilename.Get();
if (OTDB::Exists(szFoldername, szFilename)) {
String strFileContents(
OTDB::QueryPlainString(szFoldername, szFilename));
// The credential list file is like the nymfile except with ONLY
// credential IDs inside.
// Therefore, we LOAD it like we're loading a Nymfile from string.
// There's no need for
// the list itself to be signed, since we verify it fully before using
// it to verify the
// signature on the actual nymfile.
// How is the list safe not to be signed? Because the Nym ID's source
// string must hash
// to form the NymID, and any credential IDs on the list must be found
// on a lookup to
// that source. An attacker cannot add a credential without putting it
// inside the source,
// which the user controls, and the attacker cannot change the source
// without changing
// the NymID. Therefore the credential list file itself doesn't need to
// be signed, for
// the same reason that the public key didn't need to be signed: because
// you can prove
// its validity by hashing (the source string that validates the
// credentials in that list,
// or by hashing/ the public key for that Nym, if doing things the old
// way.)
//
if (strFileContents.Exists() && strFileContents.DecodeIfArmored()) {
const bool bLoaded = LoadFromString(
strFileContents,
nullptr, // map of credentials--if nullptr, it loads
// them from local storage.
&strReason, pImportPassword); // optional to provide a
// passphrase (otherwise one is
// prompted for.)
// Potentially set m_pkeypair here, though it's currently set in
// LoadPublicKey and Loadx509CertAndPrivateKey.
// (And thus set in static calls OTPseudonym::LoadPublicNym and
// LoadPrivateNym.)
return bLoaded;
}
else {
otErr << __FUNCTION__
<< ": Failed trying to load credential list from file: "
<< szFoldername << OTLog::PathSeparator() << szFilename
<< "\n";
}
}
return false; // No log on failure, since often this may be used to SEE if
// credentials exist.
// (No need for error message every time they don't exist.)
}
void OTPseudonym::SaveCredentialsToString(String& strOutput,
String::Map* pmapPubInfo,
String::Map* pmapPriInfo)
{
// IDs for revoked subcredentials are saved here.
for (auto& it : m_listRevokedIDs) {
std::string str_revoked_id = it;
strOutput.Concatenate("<revokedCredential\n"
" ID=\"%s\""
"/>\n\n",
str_revoked_id.c_str());
}
// Serialize master and sub-credentials here.
for (auto& it : m_mapCredentials) {
OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
pCredential->SerializeIDs(
strOutput, m_listRevokedIDs, pmapPubInfo, pmapPriInfo,
true); // bShowRevoked=false by default (true here), bValid=true
}
// Serialize Revoked master credentials here, including their subkeys.
for (auto& it : m_mapRevoked) {
OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
pCredential->SerializeIDs(
strOutput, m_listRevokedIDs, pmapPubInfo, pmapPriInfo, true,
false); // bShowRevoked=false by default. (Here it's true.)
// bValid=true by default. Here is for revoked, so false.
}
}
// Save the Pseudonym to a string...
bool OTPseudonym::SavePseudonym(String& strNym)
{
String nymID;
GetIdentifier(nymID);
strNym.Concatenate("<?xml version=\"%s\"?>\n", "2.0");
if (m_lUsageCredits == 0)
strNym.Concatenate("<OTuser version=\"%s\"\n"
" nymID=\"%s\""
">\n\n",
m_strVersion.Get(), nymID.Get());
else
strNym.Concatenate("<OTuser version=\"%s\"\n"
" nymID=\"%s\"\n"
" usageCredits=\"%" PRId64 "\""
">\n\n",
m_strVersion.Get(), nymID.Get(), m_lUsageCredits);
SerializeNymIDSource(strNym);
// For now I'm saving the credential list to a separate file. (And then of
// course,
// each credential also gets its own file.) We load the credential list
// file,
// and any associated credentials, before loading the Nymfile proper.
// Then we use the keys from those credentials possibly to verify the
// signature on
// the Nymfile (or not, in the case of the server which uses its own key.)
// SaveCredentialsToString(strNym);
for (auto& it : m_mapRequestNum) {
std::string strServerID = it.first;
int64_t lRequestNum = it.second;
strNym.Concatenate("<requestNum\n"
" serverID=\"%s\"\n"
" currentRequestNum=\"%" PRId64 "\""
"/>\n\n",
strServerID.c_str(), lRequestNum);
}
for (auto& it : m_mapHighTransNo) {
std::string strServerID = it.first;
int64_t lHighestNum = it.second;
strNym.Concatenate("<highestTransNum\n"
" serverID=\"%s\"\n"
" mostRecent=\"%" PRId64 "\""
"/>\n\n",
strServerID.c_str(), lHighestNum);
}
// When you delete a Nym, it just marks it.
// Actual deletion occurs during maintenance sweep (targeting marked
// nyms...)
//
if (m_bMarkForDeletion)
strNym.Concatenate(
"<MARKED_FOR_DELETION>\n"
"%s</MARKED_FOR_DELETION>\n\n",
"THIS NYM HAS BEEN MARKED FOR DELETION AT ITS OWN REQUEST");
int64_t lTransactionNumber = 0;
for (auto& it : m_mapTransNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
// if (!(pDeque->empty()) && (strServerID.size() > 0) )
// {
// for (uint32_t i = 0; i < pDeque->size(); i++)
// {
// lTransactionNumber = pDeque->at(i);
//
// strNym.Concatenate("<transactionNum\n"
// " serverID=\"%s\"\n"
// " transactionNum=\"%" PRId64 "\""
// "/>\n\n",
// strServerID.c_str(),
// lTransactionNumber
// );
// }
// }
if (!(pDeque->empty()) && (strServerID.size() > 0)) {
OTNumList theList;
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
theList.Add(lTransactionNumber);
}
String strTemp;
if ((theList.Count() > 0) && theList.Output(strTemp) &&
strTemp.Exists()) {
const OTASCIIArmor ascTemp(strTemp);
if (ascTemp.Exists())
strNym.Concatenate("<transactionNums "
"serverID=\"%s\">\n%s</"
"transactionNums>\n\n",
strServerID.c_str(), ascTemp.Get());
}
}
} // for
lTransactionNumber = 0;
for (auto& it : m_mapIssuedNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
// if (!(pDeque->empty()) && (strServerID.size() > 0) )
// {
// for (uint32_t i = 0; i < pDeque->size(); i++)
// {
// lTransactionNumber = pDeque->at(i);
//
// strNym.Concatenate("<issuedNum\n"
// " serverID=\"%s\"\n"
// " transactionNum=\"%" PRId64 "\""
// "/>\n\n",
// strServerID.c_str(),
// lTransactionNumber
// );
// }
// }
if (!(pDeque->empty()) && (strServerID.size() > 0)) {
OTNumList theList;
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
theList.Add(lTransactionNumber);
}
String strTemp;
if ((theList.Count() > 0) && theList.Output(strTemp) &&
strTemp.Exists()) {
const OTASCIIArmor ascTemp(strTemp);
if (ascTemp.Exists())
strNym.Concatenate(
"<issuedNums serverID=\"%s\">\n%s</issuedNums>\n\n",
strServerID.c_str(), ascTemp.Get());
}
}
} // for
lTransactionNumber = 0;
for (auto& it : m_mapTentativeNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
// if (!(pDeque->empty()) && (strServerID.size() > 0) )
// {
// for (uint32_t i = 0; i < pDeque->size(); i++)
// {
// lTransactionNumber = pDeque->at(i);
//
// strNym.Concatenate("<tentativeNum\n"
// " serverID=\"%s\"\n"
// " transactionNum=\"%" PRId64 "\""
// "/>\n\n",
// strServerID.c_str(),
// lTransactionNumber
// );
// }
// }
if (!(pDeque->empty()) && (strServerID.size() > 0)) {
OTNumList theList;
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
theList.Add(lTransactionNumber);
}
String strTemp;
if ((theList.Count() > 0) && theList.Output(strTemp) &&
strTemp.Exists()) {
const OTASCIIArmor ascTemp(strTemp);
if (ascTemp.Exists())
strNym.Concatenate("<tentativeNums "
"serverID=\"%s\">\n%s</"
"tentativeNums>\n\n",
strServerID.c_str(), ascTemp.Get());
}
}
} // for
// although mapOfTransNums is used, in this case,
// request numbers are what is actually being stored.
// The data structure just happened to be appropriate
// in this case, with generic manipulation functions
// already written, so I used that pre-existing system.
//
for (auto& it : m_mapAcknowledgedNum) {
std::string strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
// if (!(pDeque->empty()) && (strServerID.size() > 0) )
// {
// for (uint32_t i = 0; i < pDeque->size(); i++)
// {
// const int64_t lRequestNumber = pDeque->at(i);
//
// strNym.Concatenate("<acknowledgedNum\n"
// " serverID=\"%s\"\n"
// " requestNum=\"%" PRId64 "\""
// "/>\n\n",
// strServerID.c_str(),
// lRequestNumber
// );
// }
// }
if (!(pDeque->empty()) && (strServerID.size() > 0)) {
OTNumList theList;
for (uint32_t i = 0; i < pDeque->size(); i++) {
const int64_t lRequestNumber = pDeque->at(i);
theList.Add(lRequestNumber);
}
String strTemp;
if ((theList.Count() > 0) && theList.Output(strTemp) &&
strTemp.Exists()) {
const OTASCIIArmor ascTemp(strTemp);
if (ascTemp.Exists())
strNym.Concatenate(
"<ackNums serverID=\"%s\">\n%s</ackNums>\n\n",
strServerID.c_str(), ascTemp.Get());
}
}
} // for
if (!(m_dequeMail.empty())) {
for (uint32_t i = 0; i < m_dequeMail.size(); i++) {
OTMessage* pMessage = m_dequeMail.at(i);
OT_ASSERT(nullptr != pMessage);
String strMail(*pMessage);
OTASCIIArmor ascMail;
if (strMail.Exists()) ascMail.SetString(strMail);
if (ascMail.Exists())
strNym.Concatenate("<mailMessage>\n"
"%s</mailMessage>\n\n",
ascMail.Get());
}
}
if (!(m_dequeOutmail.empty())) {
for (uint32_t i = 0; i < m_dequeOutmail.size(); i++) {
OTMessage* pMessage = m_dequeOutmail.at(i);
OT_ASSERT(nullptr != pMessage);
String strOutmail(*pMessage);
OTASCIIArmor ascOutmail;
if (strOutmail.Exists()) ascOutmail.SetString(strOutmail);
if (ascOutmail.Exists())
strNym.Concatenate("<outmailMessage>\n"
"%s</outmailMessage>\n\n",
ascOutmail.Get());
}
}
if (!(m_dequeOutpayments.empty())) {
for (uint32_t i = 0; i < m_dequeOutpayments.size(); i++) {
OTMessage* pMessage = m_dequeOutpayments.at(i);
OT_ASSERT(nullptr != pMessage);
String strOutpayments(*pMessage);
OTASCIIArmor ascOutpayments;
if (strOutpayments.Exists())
ascOutpayments.SetString(strOutpayments);
if (ascOutpayments.Exists())
strNym.Concatenate("<outpaymentsMessage>\n"
"%s</outpaymentsMessage>\n\n",
ascOutpayments.Get());
}
}
// These are used on the server side.
// (That's why you don't see the server ID saved here.)
//
if (!(m_setOpenCronItems.empty())) {
for (auto& it : m_setOpenCronItems) {
strNym.Concatenate("<hasOpenCronItem ID=\"%" PRId64 "\" />\n\n",
it);
}
}
// These are used on the server side.
// (That's why you don't see the server ID saved here.)
//
if (!(m_setAccounts.empty())) {
for (auto& it : m_setAccounts) {
strNym.Concatenate("<ownsAssetAcct ID=\"%s\" />\n\n", it.c_str());
}
}
// client-side
for (auto& it : m_mapNymboxHash) {
std::string strServerID = it.first;
OTIdentifier& theID = it.second;
if ((strServerID.size() > 0) && !theID.IsEmpty()) {
const String strNymboxHash(theID);
strNym.Concatenate("<nymboxHashItem\n"
" serverID=\"%s\"\n"
" nymboxHash=\"%s\""
"/>\n\n",
strServerID.c_str(), strNymboxHash.Get());
}
} // for
// client-side
for (auto& it : m_mapRecentHash) {
std::string strServerID = it.first;
OTIdentifier& theID = it.second;
if ((strServerID.size() > 0) && !theID.IsEmpty()) {
const String strRecentHash(theID);
strNym.Concatenate("<recentHashItem\n"
" serverID=\"%s\"\n"
" recentHash=\"%s\""
"/>\n\n",
strServerID.c_str(), strRecentHash.Get());
}
} // for
// server-side
if (!m_NymboxHash.IsEmpty()) {
const String strNymboxHash(m_NymboxHash);
strNym.Concatenate("<nymboxHash\n"
" value=\"%s\""
"/>\n\n",
strNymboxHash.Get());
}
// client-side
for (auto& it : m_mapInboxHash) {
std::string strAcctID = it.first;
OTIdentifier& theID = it.second;
if ((strAcctID.size() > 0) && !theID.IsEmpty()) {
const String strHash(theID);
strNym.Concatenate("<inboxHashItem\n"
" accountID=\"%s\"\n"
" hashValue=\"%s\""
"/>\n\n",
strAcctID.c_str(), strHash.Get());
}
} // for
// client-side
for (auto& it : m_mapOutboxHash) {
std::string strAcctID = it.first;
OTIdentifier& theID = it.second;
if ((strAcctID.size() > 0) && !theID.IsEmpty()) {
const String strHash(theID);
strNym.Concatenate("<outboxHashItem\n"
" accountID=\"%s\"\n"
" hashValue=\"%s\""
"/>\n\n",
strAcctID.c_str(), strHash.Get());
}
} // for
strNym.Concatenate("</OTuser>\n");
return true;
}
OTCredential* OTPseudonym::GetMasterCredential(const String& strID)
{
auto iter = m_mapCredentials.find(strID.Get());
OTCredential* pCredential = nullptr;
if (iter != m_mapCredentials.end()) // found it
pCredential = iter->second;
return pCredential;
}
OTCredential* OTPseudonym::GetRevokedCredential(const String& strID)
{
auto iter = m_mapRevoked.find(strID.Get());
OTCredential* pCredential = nullptr;
if (iter != m_mapRevoked.end()) // found it
pCredential = iter->second;
return pCredential;
}
const OTCredential* OTPseudonym::GetMasterCredentialByIndex(
int32_t nIndex) const
{
if ((nIndex < 0) ||
(nIndex >= static_cast<int64_t>(m_mapCredentials.size()))) {
otErr << __FUNCTION__ << ": Index out of bounds: " << nIndex << "\n";
}
else {
int32_t nLoopIndex = -1;
for (const auto& it : m_mapCredentials) {
const OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
++nLoopIndex; // 0 on first iteration.
if (nLoopIndex == nIndex) return pCredential;
}
}
return nullptr;
}
const OTCredential* OTPseudonym::GetRevokedCredentialByIndex(
int32_t nIndex) const
{
if ((nIndex < 0) || (nIndex >= static_cast<int64_t>(m_mapRevoked.size()))) {
otErr << __FUNCTION__ << ": Index out of bounds: " << nIndex << "\n";
}
else {
int32_t nLoopIndex = -1;
for (const auto& it : m_mapRevoked) {
const OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
++nLoopIndex; // 0 on first iteration.
if (nLoopIndex == nIndex) return pCredential;
}
}
return nullptr;
}
const OTSubcredential* OTPseudonym::GetSubcredential(
const String& strMasterID, const String& strSubCredID) const
{
auto iter = m_mapCredentials.find(strMasterID.Get());
const OTCredential* pMaster = nullptr;
if (iter != m_mapCredentials.end()) // found it
pMaster = iter->second;
if (nullptr != pMaster) {
const OTSubcredential* pSub =
pMaster->GetSubcredential(strSubCredID, &m_listRevokedIDs);
if (nullptr != pSub) return pSub;
}
return nullptr;
}
// std::set<int64_t> m_setOpenCronItems; // Until these Cron Items are closed
// out, the server-side Nym keeps a list of them handy.
// std::set<std::string> m_setAccounts; // A list of asset account IDs. Server
// side only (client side uses wallet; has multiple servers.)
/*
Enumeration for all xml nodes which are parsed by IrrXMLReader.
Enumeration values:
EXN_NONE No xml node. This is usually the node if you did not read
anything yet.
EXN_ELEMENT A xml element, like <foo>.
EXN_ELEMENT_END End of an xml element, like </foo>.
EXN_TEXT Text within a xml element: <foo> this is the text. </foo>.
EXN_COMMENT An xml comment like <!-- I am a comment --> or a DTD
definition.
EXN_CDATA An xml cdata section like <![CDATA[ this is some CDATA
]]>.
EXN_UNKNOWN Unknown element.
Definition at line 180 of file irrXML.h.
*/
// todo optimize
bool OTPseudonym::LoadFromString(
const String& strNym,
String::Map* pMapCredentials, // pMapCredentials can be passed,
// if you prefer to use a specific
// set, instead of just loading the
// actual set from storage (such as
// during registration, when the
// credentials have been sent
// inside a message.)
String* pstrReason, const OTPassword* pImportPassword)
{
bool bSuccess = false;
ClearAll(); // Since we are loading everything up... (credentials are NOT
// cleared here. See note in OTPseudonym::ClearAll.)
OTStringXML strNymXML(strNym); // todo optimize
irr::io::IrrXMLReader* xml = irr::io::createIrrXMLReader(strNymXML);
OT_ASSERT(nullptr != xml);
std::unique_ptr<irr::io::IrrXMLReader> theCleanup(xml);
// parse the file until end reached
while (xml && xml->read()) {
// switch(xml->getNodeType())
// {
// case(EXN_NONE):
// otErr << "ACK NUMS: EXN_NONE -- No xml node. This is
// usually the node if you did not read anything yet.\n";
// break;
// case(EXN_ELEMENT):
// otErr << "ACK NUMS: EXN_ELEMENT -- An xml element such
// as <foo>.\n";
// break;
// case(EXN_ELEMENT_END):
// otErr << "ACK NUMS: EXN_ELEMENT_END -- End of an xml
// element such as </foo>.\n";
// break;
// case(EXN_TEXT):
// otErr << "ACK NUMS: EXN_TEXT -- Text within an xml
// element: <foo> this is the text. <foo>.\n";
// break;
// case(EXN_COMMENT):
// otErr << "ACK NUMS: EXN_COMMENT -- An xml comment like
// <!-- I am a comment --> or a DTD definition.\n";
// break;
// case(EXN_CDATA):
// otErr << "ACK NUMS: EXN_CDATA -- An xml cdata section
// like <![CDATA[ this is some CDATA ]]>.\n";
// break;
// case(EXN_UNKNOWN):
// otErr << "ACK NUMS: EXN_UNKNOWN -- Unknown
// element.\n";
// break;
// default:
// otErr << "ACK NUMS: default!! -- SHOULD NEVER
// HAPPEN...\n";
// break;
// }
// otErr << "OTPseudonym::LoadFromString: NODE DATA: %s\n",
// xml->getNodeData());
// strings for storing the data that we want to read out of the file
//
switch (xml->getNodeType()) {
case irr::io::EXN_NONE:
case irr::io::EXN_TEXT:
case irr::io::EXN_COMMENT:
case irr::io::EXN_ELEMENT_END:
case irr::io::EXN_CDATA:
// in this xml file, the only text which occurs is the messageText
// messageText = xml->getNodeData();
// switch(xml->getNodeType())
// {
// case(EXN_NONE):
// otErr << "SKIPPING: EXN_NONE -- No xml node.
// This is usually the node if you did not read anything yet.\n";
// break;
// case(EXN_TEXT):
// otErr << "SKIPPING: EXN_TEXT -- Text within an
// xml element: <foo> this is the text. <foo>.\n";
// break;
// case(EXN_COMMENT):
// otErr << "SKIPPING: EXN_COMMENT -- An xml
// comment like <!-- I am a comment --> or a DTD definition.\n";
// break;
// case(EXN_ELEMENT_END):
// otErr << "SKIPPING: EXN_ELEMENT_END -- End of
// an xml element such as </foo>.\n";
// break;
// case(EXN_CDATA):
// otErr << "SKIPPING: EXN_CDATA -- An xml cdata
// section like <![CDATA[ this is some CDATA ]]>.\n";
// break;
// default:
// otErr << "SKIPPING: default!! -- SHOULD NEVER
// HAPPEN...\n";
// break;
// }
break;
case irr::io::EXN_ELEMENT: {
const String strNodeName = xml->getNodeName();
// otErr << "PROCESSING EXN_ELEMENT: NODE NAME: %s\n",
// strNodeName.Get());
if (strNodeName.Compare("OTuser")) {
m_strVersion = xml->getAttributeValue("version");
const String UserNymID = xml->getAttributeValue("nymID");
// Server-side only...
String strCredits = xml->getAttributeValue("usageCredits");
if (strCredits.GetLength() > 0)
m_lUsageCredits = strCredits.ToLong();
else
m_lUsageCredits =
0; // This is the default anyway, but just being safe...
// TODO: no need to set the ID again here. We already know the
// ID
// at this point. Better to check and compare they are the same
// here.
// m_nymID.SetString(UserNymID);
if (UserNymID.GetLength())
otLog3 << "\nLoading user, version: " << m_strVersion
<< " NymID:\n" << UserNymID << "\n";
bSuccess = true;
}
else if (strNodeName.Compare("nymIDSource")) {
// otLog3 << "Loading nymIDSource...\n");
OTASCIIArmor ascAltLocation =
xml->getAttributeValue("altLocation"); // optional.
if (ascAltLocation.Exists())
ascAltLocation.GetString(
m_strAltLocation,
false); // bLineBreaks=true by default.
if (!OTContract::LoadEncodedTextField(xml,
m_strSourceForNymID)) {
otErr << "Error in " << __FILE__ << " line " << __LINE__
<< ": failed loading expected nymIDSource field.\n";
return false; // error condition
}
}
else if (strNodeName.Compare("revokedCredential")) {
const String strRevokedID = xml->getAttributeValue("ID");
otLog3 << "revokedCredential ID: " << strRevokedID << "\n";
auto iter =
std::find(m_listRevokedIDs.begin(), m_listRevokedIDs.end(),
strRevokedID.Get());
if (iter == m_listRevokedIDs.end()) // It's not already there,
// so it's safe to add it.
m_listRevokedIDs.push_back(
strRevokedID.Get()); // todo optimize.
}
else if (strNodeName.Compare("masterCredential")) {
const String strID = xml->getAttributeValue("ID");
const String strValid = xml->getAttributeValue("valid");
const bool bValid = strValid.Compare("true");
otLog3 << "Loading " << (bValid ? "valid" : "invalid")
<< " masterCredential ID: " << strID << "\n";
String strNymID;
GetIdentifier(strNymID);
OTCredential* pCredential = nullptr;
if (nullptr == pMapCredentials) // pMapCredentials is an option
// that allows you to read
// credentials from the map instead
// of from local storage. (While
// loading the Nym...) In this
// case, the option isn't being
// employed...
pCredential = OTCredential::LoadMaster(strNymID, strID);
else // In this case, it potentially is on the map...
{
auto it_cred = pMapCredentials->find(strID.Get());
if (it_cred ==
pMapCredentials->end()) // Nope, didn't find it on the
// map. But if a Map was passed,
// then it SHOULD have contained
// all the listed credentials
// (including the one we're
// trying to load now.)
otErr << __FUNCTION__
<< ": Expected master credential (" << strID
<< ") on map of credentials, but couldn't find "
"it. (Failure.)\n";
else // Found it on the map passed in (so no need to load
// from storage, we'll load from string instead.)
{
const String strMasterCredential(
it_cred->second.c_str());
if (strMasterCredential.Exists()) {
OTPasswordData thePWData(
nullptr == pstrReason
? "OTPseudonym::LoadFromString"
: pstrReason->Get());
pCredential = OTCredential::LoadMasterFromString(
strMasterCredential, strNymID, strID,
&thePWData, pImportPassword);
}
}
}
if (nullptr == pCredential) {
otErr << __FUNCTION__
<< ": Failed trying to load Master Credential ID: "
<< strID << "\n";
return false;
}
else // pCredential must be cleaned up or stored somewhere.
{
mapOfCredentials* pMap =
bValid ? &m_mapCredentials : &m_mapRevoked;
auto iter = pMap->find(strID.Get()); // todo optimize.
if (iter == pMap->end()) // It's not already there, so it's
// safe to add it.
pMap->insert(std::pair<std::string, OTCredential*>(
strID.Get(), pCredential)); // <=====
else {
otErr << __FUNCTION__ << ": While loading credential ("
<< strID << "), discovered it was already there "
"on my list, or one with the exact "
"same ID! Therefore, failed "
"adding this newer one.\n";
delete pCredential;
pCredential = nullptr;
return false;
}
}
}
else if (strNodeName.Compare("keyCredential")) {
const String strID = xml->getAttributeValue("ID");
const String strValid = xml->getAttributeValue(
"valid"); // If this is false, the ID is already on
// revokedCredentials list. (FYI.)
const String strMasterCredID =
xml->getAttributeValue("masterID");
const bool bValid = strValid.Compare("true");
otLog3 << "Loading " << (bValid ? "valid" : "invalid")
<< " keyCredential ID: " << strID
<< "\n ...For master credential: " << strMasterCredID
<< "\n";
OTCredential* pCredential =
GetMasterCredential(strMasterCredID); // no need to cleanup.
if (nullptr == pCredential)
pCredential = GetRevokedCredential(strMasterCredID);
if (nullptr == pCredential) {
otErr << __FUNCTION__
<< ": While loading keyCredential, failed trying to "
"find expected Master Credential ID: "
<< strMasterCredID << "\n";
return false;
}
else // We found the master credential that this keyCredential
// belongs to.
{
bool bLoaded = false;
if (nullptr ==
pMapCredentials) // pMapCredentials is an option
// that allows you to read
// credentials from the map
// instead of from local
// storage. (While loading the
// Nym...) In this case, the
// option isn't being
// employed...
bLoaded = pCredential->LoadSubkey(strID);
else // In this case, it potentially is on the map...
{
auto it_cred = pMapCredentials->find(strID.Get());
if (it_cred ==
pMapCredentials->end()) // Nope, didn't find it on
// the map. But if a Map was
// passed, then it SHOULD
// have contained all the
// listed credentials
// (including the one we're
// trying to load now.)
otErr << __FUNCTION__
<< ": Expected keyCredential (" << strID
<< ") on map of credentials, but couldn't "
"find it. (Failure.)\n";
else // Found it on the map passed in (so no need to
// load from storage, we'll load from string
// instead.)
{
const String strSubCredential(
it_cred->second.c_str());
if (strSubCredential.Exists())
bLoaded = pCredential->LoadSubkeyFromString(
strSubCredential, strID, pImportPassword);
}
}
if (!bLoaded) {
String strNymID;
GetIdentifier(strNymID);
otErr << __FUNCTION__
<< ": Failed loading keyCredential " << strID
<< " for master credential " << strMasterCredID
<< " for Nym " << strNymID << ".\n";
return false;
}
}
}
else if (strNodeName.Compare("subCredential")) {
const String strID = xml->getAttributeValue("ID");
const String strValid = xml->getAttributeValue(
"valid"); // If this is false, the ID is already on
// revokedCredentials list. (FYI.)
const String strMasterCredID =
xml->getAttributeValue("masterID");
const bool bValid = strValid.Compare("true");
otLog3 << "Loading " << (bValid ? "valid" : "invalid")
<< " subCredential ID: " << strID
<< "\n ...For master credential: " << strMasterCredID
<< "\n";
OTCredential* pCredential =
GetMasterCredential(strMasterCredID); // no need to cleanup.
if (nullptr == pCredential)
pCredential = GetRevokedCredential(strMasterCredID);
if (nullptr == pCredential) {
otErr << __FUNCTION__
<< ": While loading subCredential, failed trying to "
"find expected Master Credential ID: "
<< strMasterCredID << "\n";
return false;
}
else // We found the master credential that this subCredential
// belongs to.
{
bool bLoaded = false;
if (nullptr ==
pMapCredentials) // pMapCredentials is an option
// that allows you to read
// credentials from the map
// instead of from local
// storage. (While loading the
// Nym...) In this case, the
// option isn't being
// employed...
bLoaded = pCredential->LoadSubcredential(strID);
else // In this case, it potentially is on the map...
{
auto it_cred = pMapCredentials->find(strID.Get());
if (it_cred ==
pMapCredentials->end()) // Nope, didn't find it on
// the map. But if a Map was
// passed, then it SHOULD
// have contained all the
// listed credentials
// (including the one we're
// trying to load now.)
otErr << __FUNCTION__
<< ": Expected subCredential (" << strID
<< ") on map of credentials, but couldn't "
"find it. (Failure.)\n";
else // Found it on the map passed in (so no need to
// load from storage, we'll load from string
// instead.)
{
const String strSubCredential(
it_cred->second.c_str());
if (strSubCredential.Exists())
bLoaded =
pCredential->LoadSubcredentialFromString(
strSubCredential, strID,
pImportPassword);
}
}
if (!bLoaded) {
String strNymID;
GetIdentifier(strNymID);
otErr << __FUNCTION__
<< ": Failed loading subCredential " << strID
<< " for master credential " << strMasterCredID
<< " for Nym " << strNymID << ".\n";
return false;
}
}
}
else if (strNodeName.Compare("requestNum")) {
const String ReqNumServerID =
xml->getAttributeValue("serverID");
const String ReqNumCurrent =
xml->getAttributeValue("currentRequestNum");
otLog3 << "\nCurrent Request Number is " << ReqNumCurrent
<< " for ServerID: " << ReqNumServerID << "\n";
// Make sure now that I've loaded this request number, to add it
// to my
// internal map so that it is available for future lookups.
m_mapRequestNum[ReqNumServerID.Get()] = ReqNumCurrent.ToLong();
}
else if (strNodeName.Compare("nymboxHash")) {
const String strValue = xml->getAttributeValue("value");
otLog3 << "\nNymboxHash is: " << strValue << "\n";
if (strValue.Exists()) m_NymboxHash.SetString(strValue);
}
else if (strNodeName.Compare("nymboxHashItem")) {
const String strServerID = xml->getAttributeValue("serverID");
const String strNymboxHash =
xml->getAttributeValue("nymboxHash");
otLog3 << "\nNymboxHash is " << strNymboxHash
<< " for ServerID: " << strServerID << "\n";
// Make sure now that I've loaded this nymboxHash, to add it to
// my
// internal map so that it is available for future lookups.
if (strServerID.Exists() && strNymboxHash.Exists()) {
const OTIdentifier theID(strNymboxHash);
m_mapNymboxHash[strServerID.Get()] = theID;
}
}
else if (strNodeName.Compare("recentHashItem")) {
const String strServerID = xml->getAttributeValue("serverID");
const String strRecentHash =
xml->getAttributeValue("recentHash");
otLog3 << "\nRecentHash is " << strRecentHash
<< " for ServerID: " << strServerID << "\n";
// Make sure now that I've loaded this RecentHash, to add it to
// my
// internal map so that it is available for future lookups.
if (strServerID.Exists() && strRecentHash.Exists()) {
const OTIdentifier theID(strRecentHash);
m_mapRecentHash[strServerID.Get()] = theID;
}
}
else if (strNodeName.Compare("inboxHashItem")) {
const String strAccountID = xml->getAttributeValue("accountID");
const String strHashValue = xml->getAttributeValue("hashValue");
otLog3 << "\nInboxHash is " << strHashValue
<< " for Account ID: " << strAccountID << "\n";
// Make sure now that I've loaded this InboxHash, to add it to
// my
// internal map so that it is available for future lookups.
//
if (strAccountID.Exists() && strHashValue.Exists()) {
const OTIdentifier theID(strHashValue);
m_mapInboxHash[strAccountID.Get()] = theID;
}
}
else if (strNodeName.Compare("outboxHashItem")) {
const String strAccountID = xml->getAttributeValue("accountID");
const String strHashValue = xml->getAttributeValue("hashValue");
otLog3 << "\nOutboxHash is " << strHashValue
<< " for Account ID: " << strAccountID << "\n";
// Make sure now that I've loaded this OutboxHash, to add it to
// my
// internal map so that it is available for future lookups.
//
if (strAccountID.Exists() && strHashValue.Exists()) {
const OTIdentifier theID(strHashValue);
m_mapOutboxHash[strAccountID.Get()] = theID;
}
}
else if (strNodeName.Compare("highestTransNum")) {
const String HighNumServerID =
xml->getAttributeValue("serverID");
const String HighNumRecent =
xml->getAttributeValue("mostRecent");
otLog3 << "\nHighest Transaction Number ever received is "
<< HighNumRecent << " for ServerID: " << HighNumServerID
<< "\n";
// Make sure now that I've loaded this highest number, to add it
// to my
// internal map so that it is available for future lookups.
m_mapHighTransNo[HighNumServerID.Get()] =
HighNumRecent.ToLong();
}
else if (strNodeName.Compare("transactionNums")) {
const String tempServerID = xml->getAttributeValue("serverID");
String strTemp;
if (!tempServerID.Exists() ||
!OTContract::LoadEncodedTextField(xml, strTemp)) {
otErr << __FUNCTION__
<< ": Error: transactionNums field without value.\n";
return false; // error condition
}
OTNumList theNumList;
if (strTemp.Exists()) theNumList.Add(strTemp);
int64_t lTemp = 0;
while (theNumList.Peek(lTemp)) {
theNumList.Pop();
otLog3 << "Transaction Number " << lTemp
<< " ready-to-use for ServerID: " << tempServerID
<< "\n";
AddTransactionNum(tempServerID, lTemp); // This version
// doesn't save to
// disk. (Why save
// to disk AS WE'RE
// LOADING?)
}
}
else if (strNodeName.Compare("issuedNums")) {
const String tempServerID = xml->getAttributeValue("serverID");
String strTemp;
if (!tempServerID.Exists() ||
!OTContract::LoadEncodedTextField(xml, strTemp)) {
otErr << __FUNCTION__
<< ": Error: issuedNums field without value.\n";
return false; // error condition
}
OTNumList theNumList;
if (strTemp.Exists()) theNumList.Add(strTemp);
int64_t lTemp = 0;
while (theNumList.Peek(lTemp)) {
theNumList.Pop();
otLog3 << "Currently liable for issued trans# " << lTemp
<< " at ServerID: " << tempServerID << "\n";
AddIssuedNum(tempServerID, lTemp); // This version doesn't
// save to disk. (Why
// save to disk AS WE'RE
// LOADING?)
}
}
else if (strNodeName.Compare("tentativeNums")) {
const String tempServerID = xml->getAttributeValue("serverID");
String strTemp;
if (!tempServerID.Exists() ||
!OTContract::LoadEncodedTextField(xml, strTemp)) {
otErr << "OTPseudonym::LoadFromString: Error: "
"tentativeNums field without value.\n";
return false; // error condition
}
OTNumList theNumList;
if (strTemp.Exists()) theNumList.Add(strTemp);
int64_t lTemp = 0;
while (theNumList.Peek(lTemp)) {
theNumList.Pop();
otLog3 << "Tentative: Currently awaiting success notice, "
"for accepting trans# " << lTemp
<< " for ServerID: " << tempServerID << "\n";
AddTentativeNum(tempServerID, lTemp); // This version
// doesn't save to
// disk. (Why save to
// disk AS WE'RE
// LOADING?)
}
}
else if (strNodeName.Compare("ackNums")) {
const String tempServerID = xml->getAttributeValue("serverID");
String strTemp;
if (!tempServerID.Exists()) {
otErr << __FUNCTION__
<< ": Error: While loading ackNums "
"field: Missing serverID. Nym contents:\n\n"
<< strNym << "\n\n";
return false; // error condition
}
// xml->read(); // there should be a text field
// next, with the data for the list of acknowledged numbers.
// Note: I think I was forced to add this when the numlist was
// empty, one time, so this may come back
// to haunt me, but I want to fix it right, not kludge it.
if (!OTContract::LoadEncodedTextField(xml, strTemp)) {
otErr << __FUNCTION__
<< ": Error: ackNums field without value "
"(at least, unable to LoadEncodedTextField on "
"that value.)\n";
return false; // error condition
}
OTNumList theNumList;
if (strTemp.Exists()) theNumList.Add(strTemp);
int64_t lTemp = 0;
while (theNumList.Peek(lTemp)) {
theNumList.Pop();
otInfo << "Acknowledgment record exists for server reply, "
"for Request Number " << lTemp
<< " for ServerID: " << tempServerID << "\n";
AddAcknowledgedNum(tempServerID, lTemp); // This version
// doesn't save to
// disk. (Why save
// to disk AS WE'RE
// LOADING?)
}
}
// THE BELOW FOUR ARE DEPRECATED, AND ARE REPLACED BY THE ABOVE
// FOUR.
else if (strNodeName.Compare("transactionNum")) {
const String TransNumServerID =
xml->getAttributeValue("serverID");
const String TransNumAvailable =
xml->getAttributeValue("transactionNum");
otLog3 << "Transaction Number " << TransNumAvailable
<< " available for ServerID: " << TransNumServerID
<< "\n";
AddTransactionNum(
TransNumServerID,
TransNumAvailable.ToLong()); // This version doesn't save
// to disk. (Why save to
// disk AS WE'RE LOADING?)
}
else if (strNodeName.Compare("issuedNum")) {
const String TransNumServerID =
xml->getAttributeValue("serverID");
const String TransNumAvailable =
xml->getAttributeValue("transactionNum");
otLog3 << "Currently liable for Transaction Number "
<< TransNumAvailable
<< ", for ServerID: " << TransNumServerID << "\n";
AddIssuedNum(TransNumServerID,
TransNumAvailable.ToLong()); // This version
// doesn't save to
// disk. (Why save
// to disk AS WE'RE
// LOADING?)
}
else if (strNodeName.Compare("tentativeNum")) {
const String TransNumServerID =
xml->getAttributeValue("serverID");
const String TransNumAvailable =
xml->getAttributeValue("transactionNum");
otLog3 << "Currently waiting on server success notice, "
"accepting Transaction Number " << TransNumAvailable
<< ", for ServerID: " << TransNumServerID << "\n";
AddTentativeNum(TransNumServerID,
TransNumAvailable.ToLong()); // This version
// doesn't save
// to disk. (Why
// save to disk
// AS WE'RE
// LOADING?)
}
else if (strNodeName.Compare("acknowledgedNum")) {
const String AckNumServerID =
xml->getAttributeValue("serverID");
const String AckNumValue = xml->getAttributeValue("requestNum");
otLog3 << "Acknowledgment record exists for server reply, for "
"Request Number " << AckNumValue
<< ", for ServerID: " << AckNumServerID << "\n";
AddAcknowledgedNum(AckNumServerID,
AckNumValue.ToLong()); // This version
// doesn't save to
// disk. (Why save
// to disk AS WE'RE
// LOADING?)
}
else if (strNodeName.Compare("MARKED_FOR_DELETION")) {
m_bMarkForDeletion = true;
otLog3 << "This nym has been MARKED_FOR_DELETION (at some "
"point prior.)\n";
}
else if (strNodeName.Compare("hasOpenCronItem")) {
String strID = xml->getAttributeValue("ID");
if (strID.Exists()) {
const int64_t lNewID = strID.ToLong();
m_setOpenCronItems.insert(lNewID);
otLog3 << "This nym has an open cron item with ID: "
<< strID << "\n";
}
else
otLog3 << "This nym MISSING ID when loading open cron item "
"record.\n";
}
else if (strNodeName.Compare("ownsAssetAcct")) {
String strID = xml->getAttributeValue("ID");
if (strID.Exists()) {
m_setAccounts.insert(strID.Get());
otLog3 << "This nym has an asset account with the ID: "
<< strID << "\n";
}
else
otLog3 << "This nym MISSING asset account ID when loading "
"nym record.\n";
}
else if (strNodeName.Compare("mailMessage")) {
OTASCIIArmor armorMail;
String strMessage;
xml->read();
if (irr::io::EXN_TEXT == xml->getNodeType()) {
String strNodeData = xml->getNodeData();
// Sometimes the XML reads up the data with a prepended
// newline.
// This screws up my own objects which expect a consistent
// in/out
// So I'm checking here for that prepended newline, and
// removing it.
char cNewline;
if (strNodeData.Exists() && strNodeData.GetLength() > 2 &&
strNodeData.At(0, cNewline)) {
if ('\n' == cNewline)
armorMail.Set(strNodeData.Get() +
1); // I know all this shit is ugly. I
// refactored this in OTContract.
else // unfortunately OTNym is like a "basic type" and
// isn't derived from OTContract.
armorMail.Set(strNodeData.Get()); // TODO:
// OTContract now
// has STATIC
// methods for
// this. (Start
// using them
// here...)
if (armorMail.GetLength() > 2) {
armorMail.GetString(strMessage,
true); // linebreaks == true.
if (strMessage.GetLength() > 2) {
OTMessage* pMessage = new OTMessage;
OT_ASSERT(nullptr != pMessage);
if (pMessage->LoadContractFromString(
strMessage))
m_dequeMail.push_back(
pMessage); // takes ownership
else
delete pMessage;
}
} // armorMail
} // strNodeData
} // EXN_TEXT
}
else if (strNodeName.Compare("outmailMessage")) {
OTASCIIArmor armorMail;
String strMessage;
xml->read();
if (irr::io::EXN_TEXT == xml->getNodeType()) {
String strNodeData = xml->getNodeData();
// Sometimes the XML reads up the data with a prepended
// newline.
// This screws up my own objects which expect a consistent
// in/out
// So I'm checking here for that prepended newline, and
// removing it.
char cNewline;
if (strNodeData.Exists() && strNodeData.GetLength() > 2 &&
strNodeData.At(0, cNewline)) {
if ('\n' == cNewline)
armorMail.Set(strNodeData.Get() + 1);
else
armorMail.Set(strNodeData.Get());
if (armorMail.GetLength() > 2) {
armorMail.GetString(strMessage,
true); // linebreaks == true.
if (strMessage.GetLength() > 2) {
OTMessage* pMessage = new OTMessage;
OT_ASSERT(nullptr != pMessage);
if (pMessage->LoadContractFromString(
strMessage))
m_dequeOutmail.push_back(
pMessage); // takes ownership
else
delete pMessage;
}
} // armorMail
} // strNodeData
} // EXN_TEXT
} // outpayments message
else if (strNodeName.Compare("outpaymentsMessage")) {
OTASCIIArmor armorMail;
String strMessage;
xml->read();
if (irr::io::EXN_TEXT == xml->getNodeType()) {
String strNodeData = xml->getNodeData();
// Sometimes the XML reads up the data with a prepended
// newline.
// This screws up my own objects which expect a consistent
// in/out
// So I'm checking here for that prepended newline, and
// removing it.
char cNewline;
if (strNodeData.Exists() && strNodeData.GetLength() > 2 &&
strNodeData.At(0, cNewline)) {
if ('\n' == cNewline)
armorMail.Set(strNodeData.Get() + 1);
else
armorMail.Set(strNodeData.Get());
if (armorMail.GetLength() > 2) {
armorMail.GetString(strMessage,
true); // linebreaks == true.
if (strMessage.GetLength() > 2) {
OTMessage* pMessage = new OTMessage;
OT_ASSERT(nullptr != pMessage);
if (pMessage->LoadContractFromString(
strMessage))
m_dequeOutpayments.push_back(
pMessage); // takes ownership
else
delete pMessage;
}
}
} // strNodeData
} // EXN_TEXT
} // outpayments message
else {
// unknown element type
otErr << "Unknown element type in " << __FUNCTION__ << ": "
<< xml->getNodeName() << "\n";
bSuccess = false;
}
break;
}
default: {
otLog5 << "Unknown XML type in " << __FUNCTION__ << ": "
<< xml->getNodeName() << "\n";
break;
}
} // switch
} // while
return bSuccess;
}
bool OTPseudonym::LoadSignedNymfile(OTPseudonym& SIGNER_NYM)
{
// Get the Nym's ID in string form
String nymID;
GetIdentifier(nymID);
// Create an OTSignedFile object, giving it the filename (the ID) and the
// local directory ("nyms")
OTSignedFile theNymfile(OTFolders::Nym(), nymID);
if (!theNymfile.LoadFile()) {
otWarn << __FUNCTION__ << ": Failed loading a signed nymfile: " << nymID
<< "\n\n";
}
// We verify:
//
// 1. That the file even exists and loads.
// 2. That the local subdir and filename match the versions inside the file.
// 3. That the signature matches for the signer nym who was passed in.
//
else if (!theNymfile.VerifyFile()) {
otErr << __FUNCTION__ << ": Failed verifying nymfile: " << nymID
<< "\n\n";
}
else if (!theNymfile.VerifySignature(SIGNER_NYM)) {
String strSignerNymID;
SIGNER_NYM.GetIdentifier(strSignerNymID);
otErr << __FUNCTION__
<< ": Failed verifying signature on nymfile: " << nymID
<< "\n Signer Nym ID: " << strSignerNymID << "\n";
}
// NOTE: Comment out the above two blocks if you want to load a Nym without
// having
// to verify his information. (For development reasons. Never do that
// normally.)
else {
otInfo
<< "Loaded and verified signed nymfile. Reading from string...\n";
if (theNymfile.GetFilePayload().GetLength() > 0)
return LoadFromString(
theNymfile.GetFilePayload()); // <====== Success...
else {
const int64_t lLength =
static_cast<int64_t>(theNymfile.GetFilePayload().GetLength());
otErr << __FUNCTION__ << ": Bad length (" << lLength
<< ") while loading nymfile: " << nymID << "\n";
}
}
return false;
}
bool OTPseudonym::SaveSignedNymfile(OTPseudonym& SIGNER_NYM)
{
// Get the Nym's ID in string form
String strNymID;
GetIdentifier(strNymID);
// Create an OTSignedFile object, giving it the filename (the ID) and the
// local directory ("nyms")
OTSignedFile theNymfile(OTFolders::Nym().Get(), strNymID);
theNymfile.GetFilename(m_strNymfile);
otInfo << "Saving nym to: " << m_strNymfile << "\n";
// First we save this nym to a string...
// Specifically, the file payload string on the OTSignedFile object.
SavePseudonym(theNymfile.GetFilePayload());
// Now the OTSignedFile contains the path, the filename, AND the
// contents of the Nym itself, saved to a string inside the OTSignedFile
// object.
if (theNymfile.SignContract(SIGNER_NYM) && theNymfile.SaveContract()) {
const bool bSaved = theNymfile.SaveFile();
if (!bSaved) {
String strSignerNymID;
SIGNER_NYM.GetIdentifier(strSignerNymID);
otErr << __FUNCTION__
<< ": Failed while calling theNymfile.SaveFile() for Nym "
<< strNymID << " using Signer Nym " << strSignerNymID << "\n";
}
return bSaved;
}
else {
String strSignerNymID;
SIGNER_NYM.GetIdentifier(strSignerNymID);
otErr << __FUNCTION__
<< ": Failed trying to sign and save Nymfile for Nym " << strNymID
<< " using Signer Nym " << strSignerNymID << "\n";
}
return false;
}
/// See if two nyms have identical lists of issued transaction numbers (#s
/// currently signed for.)
bool OTPseudonym::VerifyIssuedNumbersOnNym(OTPseudonym& THE_NYM)
{
int64_t lTransactionNumber = 0; // Used in the loop below.
int32_t nNumberOfTransactionNumbers1 = 0; // *this
int32_t nNumberOfTransactionNumbers2 = 0; // THE_NYM.
std::string strServerID;
// First, loop through the Nym on my side (*this), and count how many
// numbers total he has...
//
for (auto& it : GetMapIssuedNum()) {
dequeOfTransNums* pDeque = (it.second);
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
nNumberOfTransactionNumbers1 +=
static_cast<int32_t>(pDeque->size());
}
} // for
// Next, loop through THE_NYM, and count his numbers as well...
// But ALSO verify that each one exists on *this, so that each individual
// number is checked.
//
for (auto& it : THE_NYM.GetMapIssuedNum()) {
strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
OT_ASSERT(nullptr != pDeque);
String OTstrServerID = strServerID.c_str();
if (!(pDeque->empty())) {
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
// if ()
{
nNumberOfTransactionNumbers2++;
if (false ==
VerifyIssuedNum(OTstrServerID, lTransactionNumber)) {
otOut << "OTPseudonym::" << __FUNCTION__
<< ": Issued transaction # " << lTransactionNumber
<< " from THE_NYM not found on *this.\n";
return false;
}
}
}
}
} // for
// Finally, verify that the counts match...
if (nNumberOfTransactionNumbers1 != nNumberOfTransactionNumbers2) {
otOut << "OTPseudonym::" << __FUNCTION__
<< ": Issued transaction # Count mismatch: "
<< nNumberOfTransactionNumbers1 << " and "
<< nNumberOfTransactionNumbers2 << "\n";
return false;
}
return true;
}
// This is client-side. It's called by VerifyTransactionReceipt and
// VerifyBalanceReceipt.
//
// It's okay if some issued transaction #s in THE_NYM (the receipt's Nym) aren't
// found on *this, (client-side Nym)
// since the last balance agreement may have cleaned them out after they were
// recorded in THE_NYM
// (from the transaction statement receipt).
//
// But I should never see transaction #s APPEAR in *this that aren't in THE_NYM
// on receipt, since a balance agreement
// can ONLY remove numbers, not add them. So any numbers left over should still
// be accounted for on the
// last signed receipt (which supplied THE_NYM as that list of numbers.)
//
// Conclusion: Loop through *this, which is newer, and make sure ALL numbers
// appear on THE_NYM.
// No need to check the reverse, and no need to match the count.
//
bool OTPseudonym::VerifyTransactionStatementNumbersOnNym(
OTPseudonym& THE_NYM) // THE_NYM is from the receipt.
{
int64_t lTransactionNumber = 0; // Used in the loop below.
std::string strServerID;
// First, loop through the Nym on my side (*this), and verify that all those
// #s appear on the last receipt (THE_NYM)
//
for (auto& it : GetMapIssuedNum()) {
strServerID = it.first;
dequeOfTransNums* pDeque = it.second;
String OTstrServerID = strServerID.c_str();
OT_ASSERT(nullptr != pDeque);
if (!(pDeque->empty())) {
for (uint32_t i = 0; i < pDeque->size(); i++) {
lTransactionNumber = pDeque->at(i);
if (false ==
THE_NYM.VerifyIssuedNum(OTstrServerID,
lTransactionNumber)) {
otOut << "OTPseudonym::" << __FUNCTION__
<< ": Issued transaction # " << lTransactionNumber
<< " from *this not found on THE_NYM.\n";
return false;
}
}
}
} // for
// Getting here means that, though issued numbers may have been removed from
// my responsibility
// in a subsequent balance agreement (since the transaction agreement was
// signed), I know
// for a fact that no numbers have been ADDED to my list of responsibility.
// That's the most we can verify here, since we don't know the account
// number that was
// used for the last balance agreement.
return true;
}
bool OTPseudonym::Loadx509CertAndPrivateKeyFromString(
const String& strInput, const OTPasswordData* pPWData,
const OTPassword* pImportPassword)
{
OT_ASSERT(nullptr != m_pkeypair);
if (!strInput.Exists()) {
const String strID(m_nymID);
otErr << __FUNCTION__ << ": strInput does not exist. (Returning "
"false.) ID currently set to: " << strID
<< "\n";
return false;
}
String strReason(nullptr == pPWData ? OT_PW_DISPLAY
: pPWData->GetDisplayString());
return m_pkeypair->LoadCertAndPrivateKeyFromString(strInput, &strReason,
pImportPassword);
}
// Todo: if the above function works fine, then call it in the below function
// (to reduce code bloat.)
bool OTPseudonym::Loadx509CertAndPrivateKey(bool bChecking,
const OTPasswordData* pPWData,
const OTPassword* pImportPassword)
{
OT_ASSERT(nullptr != m_pkeypair);
OTPasswordData thePWData(OT_PW_DISPLAY);
if (nullptr == pPWData) pPWData = &thePWData;
String strReason(pPWData->GetDisplayString());
// Here we try to load credentials first and if it's successful, we
// use that to set the private/public keypair from the credential, and then
// return.
//
if (LoadCredentials(true, pPWData, pImportPassword) &&
(GetMasterCredentialCount() > 0)) {
// return true;
auto it = m_mapCredentials.begin();
OT_ASSERT(m_mapCredentials.end() != it);
OTCredential* pCredential = it->second;
OT_ASSERT(nullptr != pCredential);
String strPubAndPrivCert;
if (const_cast<OTKeypair&>(
pCredential->GetSignKeypair(&m_listRevokedIDs))
.SaveCertAndPrivateKeyToString(strPubAndPrivCert, &strReason,
pImportPassword)) {
const bool bReturnValue =
m_pkeypair->LoadCertAndPrivateKeyFromString(
strPubAndPrivCert, &strReason, pImportPassword);
if (!bReturnValue)
otErr << __FUNCTION__
<< ": Failed in call to m_pkeypair->SetPrivateKey.\n";
return bReturnValue;
}
}
otErr << __FUNCTION__ << "LoadCredentials failed.\n";
return false;
}
// static
bool OTPseudonym::DoesCertfileExist(const String& strNymID)
{
String strCredListFile;
strCredListFile.Format("%s.cred", strNymID.Get());
return OTDB::Exists(OTFolders::Cert().Get(),
strNymID.Get()) || // Old-school.
OTDB::Exists(OTFolders::Credential().Get(),
strCredListFile.Get()); // New-school.
}
bool OTPseudonym::HasPublicKey()
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->HasPublicKey();
}
bool OTPseudonym::HasPrivateKey()
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->HasPrivateKey();
}
// This version WILL handle the bookends: -----BEGIN CERTIFICATE------
// It will also handle the escaped version: - -----BEGIN CERTIFICATE-----
bool OTPseudonym::SetCertificate(const String& strCert, bool bEscaped)
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->LoadPublicKeyFromCertString(strCert, bEscaped);
}
// This version WILL handle the bookends -----BEGIN PUBLIC KEY------
// It will also handle the escaped version: - -----BEGIN PUBLIC KEY------
bool OTPseudonym::SetPublicKey(const String& strKey, bool bEscaped)
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->SetPublicKey(strKey, bEscaped);
}
// This version handles the ascii-armored text WITHOUT the bookends
bool OTPseudonym::SetPublicKey(const OTASCIIArmor& strKey)
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->SetPublicKey(strKey);
}
// This version WILL handle the bookends -----BEGIN ENCRYPTED PRIVATE KEY------
// It will also handle the escaped version: - -----BEGIN ENCRYPTED PRIVATE
// KEY------
//
bool OTPseudonym::SetPrivateKey(const String& strKey, bool bEscaped)
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->SetPrivateKey(strKey, bEscaped);
}
// This version handles the ascii-armored text WITHOUT the bookends
//
bool OTPseudonym::SetPrivateKey(const OTASCIIArmor& strKey)
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->SetPrivateKey(strKey);
}
const OTAsymmetricKey& OTPseudonym::GetPrivateAuthKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPrivateAuthKey(&m_listRevokedIDs); // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from where I can pluck a private "
"AUTHENTICATION key, apparently."
" Instead, using the private key on the Nym's keypair (a "
"system which is being deprecated in favor of credentials,"
" so it's not good that I'm having to do this here. Why are "
"there no credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPrivateKey();
}
}
const OTAsymmetricKey& OTPseudonym::GetPrivateEncrKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPrivateEncrKey(&m_listRevokedIDs);
; // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from where I can pluck a private "
"ENCRYPTION key, apparently. "
"Instead, using the private key on the Nym's keypair (a "
"system which is being deprecated in favor of credentials, "
"so it's not good that I'm having to do this here. Why are "
"there no credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPrivateKey();
}
}
const OTAsymmetricKey& OTPseudonym::GetPrivateSignKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPrivateSignKey(&m_listRevokedIDs); // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from where I can pluck a private "
"SIGNING key, apparently. Instead,"
" using the private key on the Nym's keypair (a system which "
"is being deprecated in favor of credentials, so it's not "
"good"
" that I'm having to do this here. Why are there no "
"credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPrivateKey();
}
}
const OTAsymmetricKey& OTPseudonym::GetPublicAuthKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPublicAuthKey(&m_listRevokedIDs); // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from which I can pluck a public "
"AUTHENTICATION key, unfortunately. Instead,"
" using the public key on the Nym's keypair (a system which "
"is being deprecated in favor of credentials, so it's not "
"good"
" that I'm having to do this here. Why are there no "
"credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPublicKey();
}
}
const OTAsymmetricKey& OTPseudonym::GetPublicEncrKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPublicEncrKey(&m_listRevokedIDs); // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from which I can pluck a public "
"ENCRYPTION key, unfortunately. Instead,"
" using the public key on the Nym's keypair (a system which "
"is being deprecated in favor of credentials, so it's not "
"good"
" that I'm having to do this here. Why are there no "
"credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPublicKey();
}
}
const OTAsymmetricKey& OTPseudonym::GetPublicSignKey() const
{
if (!m_mapCredentials.empty()) {
const OTCredential* pCredential = nullptr;
for (const auto& it : m_mapCredentials) {
// Todo: If we have some criteria, such as which master or
// subcredential
// is currently being employed by the user, we'll use that here to
// skip
// through this loop until we find the right one. Until then, I'm
// just
// going to return the first one that's valid (not null).
pCredential = it.second;
if (nullptr != pCredential) break;
}
if (nullptr == pCredential) OT_FAIL;
return pCredential->GetPublicSignKey(&m_listRevokedIDs); // success
}
else {
String strNymID;
GetIdentifier(strNymID);
otWarn << __FUNCTION__ << ": This nym (" << strNymID
<< ") has no credentials from which I can pluck a public "
"SIGNING key, unfortunately. Instead,"
" using the public key on the Nym's keypair (a system which "
"is being deprecated in favor of credentials, so it's not "
"good"
" that I'm having to do this here. Why are there no "
"credentials on this Nym?)\n";
}
// else // Deprecated.
{
OT_ASSERT(nullptr != m_pkeypair);
return m_pkeypair->GetPublicKey();
}
}
// This is being called by:
// OTContract::VerifySignature(const OTPseudonym& theNym, const OTSignature&
// theSignature, OTPasswordData * pPWData=nullptr)
//
// Note: Need to change OTContract::VerifySignature so that it checks all of
// these keys when verifying.
//
// OT uses the signature's metadata to narrow down its search for the correct
// public key.
// Return value is the count of public keys found that matched the metadata on
// the signature.
//
int32_t OTPseudonym::GetPublicKeysBySignature(listOfAsymmetricKeys& listOutput,
const OTSignature& theSignature,
char cKeyType) const
{
OT_ASSERT(nullptr != m_pkeypair);
// Unfortunately, theSignature can only narrow the search down (there may be
// multiple results.)
int32_t nCount = 0;
for (const auto& it : m_mapCredentials) {
const OTCredential* pCredential = it.second;
OT_ASSERT(nullptr != pCredential);
const int32_t nTempCount = pCredential->GetPublicKeysBySignature(
listOutput, theSignature, cKeyType);
nCount += nTempCount;
}
return nCount;
}
// sets internal member based in ID passed in
void OTPseudonym::SetIdentifier(const OTIdentifier& theIdentifier)
{
m_nymID = theIdentifier;
}
// sets argument based on internal member
void OTPseudonym::GetIdentifier(OTIdentifier& theIdentifier) const
{
theIdentifier = m_nymID;
}
// sets internal member based in ID passed in
void OTPseudonym::SetIdentifier(const String& theIdentifier)
{
m_nymID.SetString(theIdentifier);
}
// sets argument based on internal member
void OTPseudonym::GetIdentifier(String& theIdentifier) const
{
m_nymID.GetString(theIdentifier);
}
OTPseudonym::OTPseudonym()
: m_bMarkForDeletion(false)
, m_pkeypair(new OTKeypair)
, m_lUsageCredits(0)
{
OT_ASSERT(nullptr != m_pkeypair);
Initialize();
}
void OTPseudonym::Initialize()
{
m_strVersion = "1.0";
}
OTPseudonym::OTPseudonym(const String& name, const String& filename,
const String& nymID)
: m_bMarkForDeletion(false)
, m_pkeypair(new OTKeypair)
, m_lUsageCredits(0)
{
OT_ASSERT(nullptr != m_pkeypair);
Initialize();
m_strName = name;
m_strNymfile = filename;
m_nymID.SetString(nymID);
}
OTPseudonym::OTPseudonym(const OTIdentifier& nymID)
: m_bMarkForDeletion(false)
, m_pkeypair(new OTKeypair)
, m_lUsageCredits(0)
{
OT_ASSERT(nullptr != m_pkeypair);
Initialize();
m_nymID = nymID;
}
OTPseudonym::OTPseudonym(const String& strNymID)
: m_bMarkForDeletion(false)
, m_pkeypair(new OTKeypair)
, m_lUsageCredits(0)
{
OT_ASSERT(nullptr != m_pkeypair);
Initialize();
m_nymID.SetString(strNymID);
}
void OTPseudonym::ClearCredentials()
{
m_listRevokedIDs.clear();
while (!m_mapCredentials.empty()) {
OTCredential* pCredential = m_mapCredentials.begin()->second;
m_mapCredentials.erase(m_mapCredentials.begin());
delete pCredential;
pCredential = nullptr;
}
while (!m_mapRevoked.empty()) {
OTCredential* pCredential = m_mapRevoked.begin()->second;
m_mapRevoked.erase(m_mapRevoked.begin());
delete pCredential;
pCredential = nullptr;
}
}
void OTPseudonym::ClearAll()
{
m_mapRequestNum.clear();
m_mapHighTransNo.clear();
ReleaseTransactionNumbers();
// m_mapTransNum.clear();
// m_mapIssuedNum.clear();
// m_mapTentativeNum.clear();
// m_mapAcknowledgedNum.clear();
m_mapNymboxHash.clear();
m_mapRecentHash.clear();
m_mapInboxHash.clear();
m_mapOutboxHash.clear();
m_setAccounts.clear();
m_setOpenCronItems.clear();
ClearMail();
ClearOutmail();
ClearOutpayments();
// We load the Nym twice... once just to load the credentials up from the
// .cred file, and a second
// time to load the rest of the Nym up from the Nymfile. LoadFromString
// calls ClearAll before loading,
// so there's no possibility of duplicated data on the Nym. And when that
// happens, we don't want the
// credentials to get cleared, since we want them to still be there after
// the rest of the Nym is
// loaded. So this is commented out.
// ClearCredentials();
}
OTPseudonym::~OTPseudonym()
{
ClearAll();
ClearCredentials();
if (nullptr != m_pkeypair) delete m_pkeypair; // todo: else error
m_pkeypair = nullptr;
}
} // namespace opentxs
| 39.090698 | 97 | 0.548734 | [
"object"
] |
43e2fe60eb59b8561702aa91c297663a130f9217 | 21,222 | cxx | C++ | Examples/Registration/ImageRegistration9.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Examples/Registration/ImageRegistration9.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Examples/Registration/ImageRegistration9.cxx | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {QB_Suburb.png}
// INPUTS: {QB_SuburbR10X13Y17.png}
// OUTPUTS: {ImageRegistration9Output.png}
// OUTPUTS: {ImageRegistration9DifferenceBefore.png}
// OUTPUTS: {ImageRegistration9DifferenceAfter.png}
// 1.0 300
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the \doxygen{itk}{AffineTransform}
// for performing registration. The example code is, for the most part,
// identical to previous ones.
// The main difference is the use of the AffineTransform here instead of the
// \doxygen{itk}{CenteredRigid2DTransform}. We will focus on the most
// relevant changes in the current code and skip the basic elements already
// explained in previous examples.
//
// \index{itk::AffineTransform}
//
// Software Guide : EndLatex
#include "itkUnaryFunctorImageFilter.h"
#include "itkImageRegistrationMethod.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "otbImage.h"
#include "itkCenteredTransformInitializer.h"
// Software Guide : BeginLatex
//
// Let's start by including the header file of the AffineTransform.
//
// \index{itk::AffineTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkAffineTransform.h"
// Software Guide : EndCodeSnippet
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkMeanImageFilter.h"
//
// The following piece of code implements an observer
// that will monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro(Self);
protected:
CommandIterationUpdate() {}
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject& event) override
{
Execute((const itk::Object *) caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject& event) override
{
OptimizerPointer optimizer =
dynamic_cast<OptimizerPointer>(object);
if (!itk::IterationEvent().CheckEvent(&event))
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition();
// Print the angle for the trace plot
vnl_matrix<double> p(2, 2);
p[0][0] = (double) optimizer->GetCurrentPosition()[0];
p[0][1] = (double) optimizer->GetCurrentPosition()[1];
p[1][0] = (double) optimizer->GetCurrentPosition()[2];
p[1][1] = (double) optimizer->GetCurrentPosition()[3];
vnl_svd<double> svd(p);
vnl_matrix<double> r(2, 2);
r = svd.U() * vnl_transpose(svd.V());
double angle = asin(r[1][0]);
std::cout << " AffineAngle: " << angle * 45.0 / atan(1.0) << std::endl;
}
};
int main(int argc, char *argv[])
{
if (argc < 4)
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile " << std::endl;
std::cerr << " outputImagefile [differenceBeforeRegistration] " <<
std::endl;
std::cerr << " [differenceAfterRegistration] " << std::endl;
std::cerr << " [stepLength] [maxNumberOfIterations] " << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// We define then the types of the images to be registered.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef float PixelType;
typedef otb::Image<PixelType, Dimension> FixedImageType;
typedef otb::Image<PixelType, Dimension> MovingImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The transform type is instantiated using the code below. The template
// parameters of this class are the representation type of the space
// coordinates and the space dimension.
//
// \index{itk::AffineTransform!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::AffineTransform<
double,
Dimension> TransformType;
// Software Guide : EndCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType> MetricType;
typedef itk::LinearInterpolateImageFunction<
MovingImageType,
double> InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType> RegistrationType;
MetricType::Pointer metric = MetricType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric(metric);
registration->SetOptimizer(optimizer);
registration->SetInterpolator(interpolator);
// Software Guide : BeginLatex
//
// The transform object is constructed below and passed to the registration
// method.
//
// \index{itk::AffineTransform!New()}
// \index{itk::AffineTransform!Pointer}
// \index{itk::RegistrationMethod!SetTransform()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::Pointer transform = TransformType::New();
registration->SetTransform(transform);
// Software Guide : EndCodeSnippet
typedef otb::ImageFileReader<FixedImageType> FixedImageReaderType;
typedef otb::ImageFileReader<MovingImageType> MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName(argv[1]);
movingImageReader->SetFileName(argv[2]);
// Software Guide : BeginLatex
//
// Since we are working with high resolution images and expected
// shifts are larger than the resolution, we will need to smooth
// the images in order to avoid the optimizer to get stucked on
// local minima. In order to do this, we will use a simple mean filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::MeanImageFilter<
FixedImageType, FixedImageType> FixedFilterType;
typedef itk::MeanImageFilter<
MovingImageType, MovingImageType> MovingFilterType;
FixedFilterType::Pointer fixedFilter = FixedFilterType::New();
MovingFilterType::Pointer movingFilter = MovingFilterType::New();
FixedImageType::SizeType indexFRadius;
indexFRadius[0] = 4; // radius along x
indexFRadius[1] = 4; // radius along y
fixedFilter->SetRadius(indexFRadius);
MovingImageType::SizeType indexMRadius;
indexMRadius[0] = 4; // radius along x
indexMRadius[1] = 4; // radius along y
movingFilter->SetRadius(indexMRadius);
fixedFilter->SetInput(fixedImageReader->GetOutput());
movingFilter->SetInput(movingImageReader->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we can plug the output of the smoothing filters at the input
// of the registration method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetFixedImage(fixedFilter->GetOutput());
registration->SetMovingImage(movingFilter->GetOutput());
// Software Guide : EndCodeSnippet
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion());
// Software Guide : BeginLatex
//
// In this example, we use the
// \doxygen{itk}{CenteredTransformInitializer} helper class in order to compute
// a reasonable value for the initial center of rotation and the
// translation. The initializer is set to use the center of mass of each
// image as the initial correspondence correction.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CenteredTransformInitializer<
TransformType,
FixedImageType,
MovingImageType> TransformInitializerType;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
initializer->SetTransform(transform);
initializer->SetFixedImage(fixedImageReader->GetOutput());
initializer->SetMovingImage(movingImageReader->GetOutput());
initializer->MomentsOn();
initializer->InitializeTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we pass the parameters of the current transform as the initial
// parameters to be used when the registration process starts.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetInitialTransformParameters(
transform->GetParameters());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Keeping in mind that the scale of units in scaling, rotation and
// translation are quite different, we take advantage of the scaling
// functionality provided by the optimizers. We know that the first $N
// \times N$ elements of the parameters array correspond to the rotation
// matrix factor, the next $N$ correspond to the rotation center, and the
// last $N$ are the components of the translation to be applied after
// multiplication with the matrix is performed.
//
// Software Guide : EndLatex
double translationScale = 1.0 / 1000.0;
if (argc > 8)
{
translationScale = atof(argv[8]);
}
// Software Guide : BeginCodeSnippet
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales(transform->GetNumberOfParameters());
optimizerScales[0] = 1.0;
optimizerScales[1] = 1.0;
optimizerScales[2] = 1.0;
optimizerScales[3] = 1.0;
optimizerScales[4] = translationScale;
optimizerScales[5] = translationScale;
optimizer->SetScales(optimizerScales);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also set the usual parameters of the optimization method. In this
// case we are using an
// \doxygen{itk}{RegularStepGradientDescentOptimizer}. Below, we define the
// optimization parameters like initial step length, minimal step length
// and number of iterations. These last two act as stopping criteria for
// the optimization.
//
// Software Guide : EndLatex
double steplength = 0.1;
if (argc > 6)
{
steplength = atof(argv[6]);
}
unsigned int maxNumberOfIterations = 300;
if (argc > 7)
{
maxNumberOfIterations = atoi(argv[7]);
}
// Software Guide : BeginCodeSnippet
optimizer->SetMaximumStepLength(steplength);
optimizer->SetMinimumStepLength(0.0001);
optimizer->SetNumberOfIterations(maxNumberOfIterations);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also set the optimizer to do minimization by calling the
// \code{MinimizeOn()} method.
//
// \index{itk::Regular\-Step\-Gradient\-Descent\-Optimizer!MinimizeOn()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->MinimizeOn();
// Software Guide : EndCodeSnippet
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver(itk::IterationEvent(), observer);
// Software Guide : BeginLatex
//
// Finally we trigger the execution of the registration method by calling
// the \code{Update()} method. The call is placed in a \code{try/catch}
// block in case any exceptions are thrown.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
registration->Update();
}
catch (itk::ExceptionObject& err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Once the optimization converges, we recover the parameters from the
// registration method. This is done with the
// \code{GetLastTransformParameters()} method. We can also recover the
// final value of the metric with the \code{GetValue()} method and the
// final number of iterations with the \code{GetCurrentIteration()}
// method.
//
// \index{itk::RegistrationMethod!GetValue()}
// \index{itk::RegistrationMethod!GetCurrentIteration()}
// \index{itk::RegistrationMethod!GetLastTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
OptimizerType::ParametersType finalParameters =
registration->GetLastTransformParameters();
const double finalRotationCenterX = transform->GetCenter()[0];
const double finalRotationCenterY = transform->GetCenter()[1];
const double finalTranslationX = finalParameters[4];
const double finalTranslationY = finalParameters[5];
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
// Software Guide : EndCodeSnippet
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Center X = " << finalRotationCenterX << std::endl;
std::cout << " Center Y = " << finalRotationCenterY << std::endl;
std::cout << " Translation X = " << finalTranslationX << std::endl;
std::cout << " Translation Y = " << finalTranslationY << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
//Compute the rotation angle and scaling from SVD of the matrix
// \todo Find a way to figure out if the scales are along X or along Y.
// VNL returns the eigenvalues ordered from largest to smallest.
vnl_matrix<double> p(2, 2);
p[0][0] = (double) finalParameters[0];
p[0][1] = (double) finalParameters[1];
p[1][0] = (double) finalParameters[2];
p[1][1] = (double) finalParameters[3];
vnl_svd<double> svd(p);
vnl_matrix<double> r(2, 2);
r = svd.U() * vnl_transpose(svd.V());
double angle = asin(r[1][0]);
std::cout << " Scale 1 = " << svd.W(0) << std::endl;
std::cout << " Scale 2 = " << svd.W(1) << std::endl;
std::cout << " Angle (degrees) = " << angle * 45.0 / atan(1.0) << std::endl;
// Software Guide : BeginLatex
//
// Let's execute this example over two of the images provided in
// \code{Examples/Data}:
//
// \begin{itemize}
// \item \code{QB\_Suburb.png}
// \item \code{QB\_SuburbR10X13Y17.png}
// \end{itemize}
//
// The second image is the result of intentionally rotating the first
// image by $10$ degrees and then translating by $(13, 17)$. Both images
// have unit-spacing and are shown in Figure
// \ref{fig:FixedMovingImageRegistration9}. We execute the code using the
// following parameters: step length=1.0, translation scale= 0.0001 and
// maximum number of iterations = 300. With these images and parameters
// the registration takes $83$ iterations and produces
//
// \begin{center}
// \begin{verbatim}
// 20.2134 [0.983291, -0.173507, 0.174626, 0.983028, -12.1899, -16.0882]
// \end{verbatim}
// \end{center}
//
// These results are interpreted as
//
// \begin{itemize}
// \item Iterations = 83
// \item Final Metric = 20.2134
// \item Center = $( 134.152, 104.067 )$ pixels
// \item Translation = $( -12.1899, -16.0882 )$ pixels
// \item Affine scales = $(0.999024, 0.997875)$
// \end{itemize}
//
// The second component of the matrix values is usually associated with
// $\sin{\theta}$. We obtain the rotation through SVD of the affine
// matrix. The value is $10.0401$ degrees, which is approximately the
// intentional misalignment of $10.0$ degrees.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{QB_Suburb.eps}
// \includegraphics[width=0.44\textwidth]{QB_SuburbR10X13Y17.eps}
// \itkcaption[AffineTransform registration]{Fixed and moving images
// provided as input to the registration method using the AffineTransform.}
// \label{fig:FixedMovingImageRegistration9}
// \end{figure}
//
//
// \begin{figure}
// \center
// \includegraphics[width=0.32\textwidth]{ImageRegistration9Output.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration9DifferenceBefore.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration9DifferenceAfter.eps}
// \itkcaption[AffineTransform output images]{The resampled moving image
// (left), and the difference between the fixed and moving images before (center)
// and after (right) registration with the
// AffineTransform transform.}
// \label{fig:ImageRegistration9Outputs}
// \end{figure}
//
// Figure \ref{fig:ImageRegistration9Outputs} shows the output of the
// registration. The right most image of this figure shows the squared
// magnitude difference between the fixed image and the resampled
// moving image.
// Software Guide : EndLatex
// The following code is used to dump output images to files.
// They illustrate the final results of the registration.
// We will resample the moving image and write out the difference image
// before and after registration. We will also rescale the intensities of the
// difference images, so that they look better!
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType> ResampleFilterType;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetCenter(transform->GetCenter());
finalTransform->SetParameters(finalParameters);
ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform(finalTransform);
resampler->SetInput(movingImageReader->GetOutput());
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize());
resampler->SetOutputOrigin(fixedImage->GetOrigin());
resampler->SetOutputSpacing(fixedImage->GetSignedSpacing());
resampler->SetDefaultPixelValue(100);
typedef unsigned char OutputPixelType;
typedef otb::Image<OutputPixelType, Dimension> OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType> CastFilterType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName(argv[3]);
caster->SetInput(resampler->GetOutput());
writer->SetInput(caster->GetOutput());
writer->Update();
typedef itk::SubtractImageFilter<
FixedImageType,
FixedImageType,
FixedImageType> DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
difference->SetInput1(fixedImageReader->GetOutput());
difference->SetInput2(resampler->GetOutput());
WriterType::Pointer writer2 = WriterType::New();
typedef itk::RescaleIntensityImageFilter<
FixedImageType,
OutputImageType> RescalerType;
RescalerType::Pointer intensityRescaler = RescalerType::New();
intensityRescaler->SetInput(difference->GetOutput());
intensityRescaler->SetOutputMinimum(0);
intensityRescaler->SetOutputMaximum(255);
writer2->SetInput(intensityRescaler->GetOutput());
resampler->SetDefaultPixelValue(1);
// Compute the difference image between the
// fixed and resampled moving image.
if (argc > 5)
{
writer2->SetFileName(argv[5]);
writer2->Update();
}
typedef itk::IdentityTransform<double, Dimension> IdentityTransformType;
IdentityTransformType::Pointer identity = IdentityTransformType::New();
// Compute the difference image between the
// fixed and moving image before registration.
if (argc > 4)
{
resampler->SetTransform(identity);
writer2->SetFileName(argv[4]);
writer2->Update();
}
return EXIT_SUCCESS;
}
| 34.451299 | 83 | 0.705164 | [
"object",
"transform"
] |
43eb2a5ce66d0aae9c9d43a15f86b6ca8a4bbfb0 | 8,351 | cpp | C++ | src/test_lockfree.cpp | fangcun010/inline_asm_lockfree_stack | dac6ccc71c80103cadc5b76516072c29d15efa51 | [
"MIT"
] | 2 | 2020-01-19T10:28:41.000Z | 2020-01-20T05:23:30.000Z | src/test_lockfree.cpp | fangcun010/inline_asm_lockfree_stack | dac6ccc71c80103cadc5b76516072c29d15efa51 | [
"MIT"
] | null | null | null | src/test_lockfree.cpp | fangcun010/inline_asm_lockfree_stack | dac6ccc71c80103cadc5b76516072c29d15efa51 | [
"MIT"
] | 1 | 2020-01-19T13:23:49.000Z | 2020-01-19T13:23:49.000Z | /*
MIT License
Copyright(c) 2019 fangcun
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 <iostream>
#include <thread>
#include <lockfree.h>
#include <set>
#include <atomic>
#include <queue>
#include <mutex>
#include <Windows.h>
#include <boost/lockfree/stack.hpp>
#include <boost/lockfree/queue.hpp>
#define READ_THREAD_COUNT 1
#define WRITE_THREAD_COUNT 20
#define QUEUE_ITEM_COUNT_PER_THREAD 2000000
#define QUEUE_ITEM_COUNT (WRITE_THREAD_COUNT*QUEUE_ITEM_COUNT_PER_THREAD)
std::queue<unsigned int> std_queue;
std::mutex std_queue_mutex;
//boost::lockfree::queue<unsigned int> boost_queue(QUEUE_ITEM_COUNT+10);
lockfree_freelist *freelist;
lockfree_queue *queue;
std::atomic<unsigned int> read_cnt;
std::atomic<unsigned int> write_cnt;
std::thread *read_threads[128];
std::thread *write_threads[128];
void TestForStdQueue() {
auto start_time = std::chrono::high_resolution_clock::now();
read_cnt = 0;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i] = new std::thread([]() {
unsigned int val;
unsigned int last_cnt;
while (true) {
std_queue_mutex.lock();
if (std_queue.empty()==false) {
val = std_queue.front();
std_queue.pop();
std_queue_mutex.unlock();
do {
last_cnt = read_cnt;
} while (!read_cnt.compare_exchange_strong(last_cnt, last_cnt + 1));
if (last_cnt + 1 == QUEUE_ITEM_COUNT)
break;
}
else if (read_cnt == QUEUE_ITEM_COUNT) {
std_queue_mutex.unlock();
break;
}
else
std_queue_mutex.unlock();
}
});
}
write_cnt = 0;
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i] = new std::thread([]() {
unsigned int val;
for (auto i = 0; i < QUEUE_ITEM_COUNT_PER_THREAD;i++) {
val = i;
std_queue_mutex.lock();
std_queue.push(val);
std_queue_mutex.unlock();
}
});
}
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i]->join();
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i]->join();
}
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);
std::cout << "=====================================================================" << std::endl;
std::cout << READ_THREAD_COUNT << " read threads " << WRITE_THREAD_COUNT << " write threads " << QUEUE_ITEM_COUNT << " items" << std::endl;
std::cout << "std::queue+std::mutex time:";
std::cout << duration.count() << "ms" << std::endl;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
delete read_threads[i];
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
delete write_threads[i];
}
}
void TestForBoostLockFreeQueue() {
/* auto start_time = std::chrono::high_resolution_clock::now();
read_cnt = 0;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i] = new std::thread([]() {
unsigned int val;
unsigned int last_cnt;
while (true) {
if (boost_queue.pop(val)) {
do {
last_cnt = read_cnt;
} while (!read_cnt.compare_exchange_strong(last_cnt, last_cnt + 1));
if (last_cnt + 1 == QUEUE_ITEM_COUNT)
break;
}
else if (read_cnt == QUEUE_ITEM_COUNT)
break;
Sleep(0);
}
});
}
write_cnt = 0;
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i] = new std::thread([]() {
unsigned int val;
for(auto i=0;i< QUEUE_ITEM_COUNT_PER_THREAD;i++){
val = i;
boost_queue.push(val);
Sleep(0);
}
});
}
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i]->join();
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i]->join();
}
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);
std::cout << "=====================================================================" << std::endl;
std::cout << READ_THREAD_COUNT << " read threads " << WRITE_THREAD_COUNT << " write threads " << QUEUE_ITEM_COUNT << " items" << std::endl;
std::cout << "boost::lockfree::queue time:";
std::cout << duration.count() << "ms" << std::endl;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
delete read_threads[i];
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
delete write_threads[i];
}*/
}
void TestForAsmLockFreeQueue() {
freelist = lockfree_create_freelist(4);
queue = lockfree_create_queue(freelist);
for (auto i = 0; i < QUEUE_ITEM_COUNT+10; i++) {
unsigned int val;
lockfree_queue_push(queue, &val);
}
for (auto i = 0; i < QUEUE_ITEM_COUNT+10; i++) {
unsigned int val;
lockfree_queue_pop(queue, &val);
}
auto start_time = std::chrono::high_resolution_clock::now();
read_cnt = 0;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i] = new std::thread([]() {
unsigned int val;
unsigned int last_cnt;
auto last_time=std::chrono::high_resolution_clock::now();
while (true) {
if (lockfree_queue_pop(queue, &val)) {
do {
last_cnt = read_cnt;
} while (!read_cnt.compare_exchange_strong(last_cnt, last_cnt + 1));
if (last_cnt + 1 == QUEUE_ITEM_COUNT)
break;
}
else if (read_cnt == QUEUE_ITEM_COUNT)
break;
}
});
}
write_cnt = 0;
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i] = new std::thread([]() {
unsigned int val;
for(auto i=0;i< QUEUE_ITEM_COUNT_PER_THREAD;i++){
val = i;
lockfree_queue_push(queue, &val);
//MemoryBarrier();
}
});
}
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
read_threads[i]->join();
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
write_threads[i]->join();
}
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);
std::cout << "=====================================================================" << std::endl;
std::cout << READ_THREAD_COUNT << " read threads " << WRITE_THREAD_COUNT << " write threads " << QUEUE_ITEM_COUNT << " items" << std::endl;
std::cout << "asm lockfree queue time:";
std::cout << duration.count() << "ms" << std::endl;
for (auto i = 0; i < READ_THREAD_COUNT; i++) {
delete read_threads[i];
}
for (auto i = 0; i < WRITE_THREAD_COUNT; i++) {
delete write_threads[i];
}
lockfree_destroy_queue(queue);
unsigned int cnt = 0;
lockfree_freelist_node *ptr= freelist->top.ptr;
while (ptr) {
cnt++;
ptr = ptr->next.ptr;
}
std::cout << cnt << std::endl;
lockfree_destroy_freelist(freelist);
}
int main() {
/*std::cout << sizeof(unsigned short) << std::endl;
TestForStdQueue();
TestForBoostLockFreeQueue();
TestForAsmLockFreeQueue();*/
freelist = lockfree_create_freelist(4);
//lockfree_vector *vector = lockfree_create_vector(freelist);
lockfree_stack *stack = lockfree_create_stack(freelist);
unsigned int val = 100;
for (unsigned int i = 0; i < 100000; i++) {
lockfree_stack_push(stack, &i);
}
for (unsigned int i = 0; i < 100; i++) {
lockfree_stack_pop(stack, &val);
std::cout << val << std::endl;
}
lockfree_destroy_stack(stack);
lockfree_destroy_freelist(freelist);
return 0;
} | 28.896194 | 141 | 0.627111 | [
"vector"
] |
43eec0cae3caab9f75ea1e17d53bd37f2ed24390 | 1,967 | cpp | C++ | object_analytics_nodelet/src/merger/merger.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 186 | 2017-11-30T14:08:54.000Z | 2022-02-24T19:17:20.000Z | object_analytics_nodelet/src/merger/merger.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 38 | 2017-12-06T12:03:22.000Z | 2021-10-18T13:38:10.000Z | object_analytics_nodelet/src/merger/merger.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 58 | 2017-11-30T07:37:35.000Z | 2022-02-04T20:45:59.000Z | /*
* Copyright (c) 2017 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "object_analytics_nodelet/model/object_utils.h"
#include "object_analytics_nodelet/merger/merger.h"
using object_analytics_nodelet::model::ObjectUtils;
namespace object_analytics_nodelet
{
namespace merger
{
boost::shared_ptr<ObjectsInBoxes3D> Merger::merge(const ObjectsInBoxes::ConstPtr& objects_in_boxes2d,
const ObjectsInBoxes3D::ConstPtr& objects_in_boxes3d)
{
boost::shared_ptr<ObjectsInBoxes3D> msgs = boost::make_shared<ObjectsInBoxes3D>();
msgs->header = objects_in_boxes2d->header; // NOTE: MUST use detection timstamp
Object2DVector objects2d;
ObjectUtils::fill2DObjects(objects_in_boxes2d, objects2d);
Object3DVector objects3d;
ObjectUtils::fill3DObjects(objects_in_boxes3d, objects3d);
RelationVector relations;
ObjectUtils::findMaxIntersectionRelationships(objects2d, objects3d, relations);
Merger::composeResult(relations, msgs);
return msgs;
}
void Merger::composeResult(const RelationVector& relations, boost::shared_ptr<ObjectsInBoxes3D>& msgs)
{
for (auto item : relations)
{
object_analytics_msgs::ObjectInBox3D obj3d;
obj3d.roi = item.first.getRoi();
obj3d.min = item.second.getMin();
obj3d.max = item.second.getMax();
msgs->objects_in_boxes.push_back(obj3d);
}
}
} // namespace merger
} // namespace object_analytics_nodelet
| 35.125 | 103 | 0.750381 | [
"model"
] |
43ef46ea382d0bd6281040e71f4f36e421ecb308 | 4,236 | cpp | C++ | src/deps/switchres/custom_video.cpp | basharast/RetroArch-ARM | 33208e97b7eebae35cfce7831cf3fefc9d783d79 | [
"MIT"
] | 4 | 2021-12-03T14:58:12.000Z | 2022-03-05T11:17:16.000Z | src/deps/switchres/custom_video.cpp | basharast/RetroArch-ARM | 33208e97b7eebae35cfce7831cf3fefc9d783d79 | [
"MIT"
] | 2 | 2022-03-16T06:13:34.000Z | 2022-03-26T06:44:50.000Z | src/deps/switchres/custom_video.cpp | basharast/RetroArch-ARM | 33208e97b7eebae35cfce7831cf3fefc9d783d79 | [
"MIT"
] | null | null | null | /**************************************************************
custom_video.cpp - Custom video library
---------------------------------------------------------
Switchres Modeline generation engine for emulation
License GPL-2.0+
Copyright 2010-2021 Chris Kennedy, Antonio Giner,
Alexandre Wodarczyk, Gil Delescluse
**************************************************************/
#include <stdio.h>
#include "custom_video.h"
#include "log.h"
#if defined(_WIN32)
#include "custom_video_ati.h"
#include "custom_video_adl.h"
#include "custom_video_pstrip.h"
#elif defined(__linux__)
#ifdef SR_WITH_XRANDR
#include "custom_video_xrandr.h"
#endif
#ifdef SR_WITH_KMSDRM
#include "custom_video_drmkms.h"
#endif
#endif
extern bool ati_is_legacy(int vendor, int device);
//============================================================
// custom_video::make
//============================================================
custom_video *custom_video::make(char *device_name, char *device_id, int method, custom_video_settings *vs)
{
#if defined(_WIN32)
if (method == CUSTOM_VIDEO_TIMING_POWERSTRIP)
{
m_custom_video = new pstrip_timing(device_name, vs);
if (m_custom_video)
{
m_custom_method = CUSTOM_VIDEO_TIMING_POWERSTRIP;
return m_custom_video;
}
}
else
{
int vendor, device;
sscanf(device_id, "PCI\\VEN_%x&DEV_%x", &vendor, &device);
if (vendor == 0x1002) // ATI/AMD
{
if (ati_is_legacy(vendor, device))
{
m_custom_video = new ati_timing(device_name, vs);
if (m_custom_video)
{
m_custom_method = CUSTOM_VIDEO_TIMING_ATI_LEGACY;
return m_custom_video;
}
}
else
{
m_custom_video = new adl_timing(device_name, vs);
if (m_custom_video)
{
m_custom_method = CUSTOM_VIDEO_TIMING_ATI_ADL;
return m_custom_video;
}
}
}
else
log_info("Video chipset is not compatible.\n");
}
#elif defined(__linux__)
if (device_id != NULL)
log_info("Device value is %s.\n", device_id);
#ifdef SR_WITH_XRANDR
if (method == CUSTOM_VIDEO_TIMING_XRANDR || method == 0)
{
try
{
m_custom_video = new xrandr_timing(device_name, vs);
}
catch (...) {};
if (m_custom_video)
{
m_custom_method = CUSTOM_VIDEO_TIMING_XRANDR;
return m_custom_video;
}
}
#endif /* SR_WITH_XRANDR */
#ifdef SR_WITH_KMSDRM
if (method == CUSTOM_VIDEO_TIMING_DRMKMS || method == 0)
{
m_custom_video = new drmkms_timing(device_name, vs);
if (m_custom_video)
{
m_custom_method = CUSTOM_VIDEO_TIMING_DRMKMS;
return m_custom_video;
}
}
#endif /* SR_WITH_KMSDRM */
#endif
return this;
}
//============================================================
// custom_video::init
//============================================================
bool custom_video::init() { return false; }
//============================================================
// custom_video::get_timing
//============================================================
bool custom_video::get_timing(modeline *mode)
{
log_verbose("system mode\n");
mode->type |= CUSTOM_VIDEO_TIMING_SYSTEM;
return false;
}
//============================================================
// custom_video::set_timing
//============================================================
bool custom_video::set_timing(modeline *)
{
return false;
}
//============================================================
// custom_video::add_mode
//============================================================
bool custom_video::add_mode(modeline *)
{
return false;
}
//============================================================
// custom_video::delete_mode
//============================================================
bool custom_video::delete_mode(modeline *)
{
return false;
}
//============================================================
// custom_video::update_mode
//============================================================
bool custom_video::update_mode(modeline *)
{
return false;
}
//============================================================
// custom_video::process_modelist
//============================================================
bool custom_video::process_modelist(std::vector<modeline *>)
{
return false;
}
| 23.664804 | 107 | 0.508026 | [
"vector"
] |
43f02ec5c525ec695f4ba9df8f8b1dc59736039d | 1,023 | hpp | C++ | lib/common/MD5.hpp | mengxiaokun/Elastos.SDK.Contact | c95d66e813e037e2171990cb764a5f0ad7591116 | [
"MIT"
] | null | null | null | lib/common/MD5.hpp | mengxiaokun/Elastos.SDK.Contact | c95d66e813e037e2171990cb764a5f0ad7591116 | [
"MIT"
] | null | null | null | lib/common/MD5.hpp | mengxiaokun/Elastos.SDK.Contact | c95d66e813e037e2171990cb764a5f0ad7591116 | [
"MIT"
] | null | null | null | /**
* @file MD5.hpp
* @brief MD5
* @details
*
* @author xxx
* @author <xxx@xxx.com>
* @copyright (c) 2012 xxx All rights reserved.
**/
#ifndef _ELASTOS_MD5_HPP_
#define _ELASTOS_MD5_HPP_
#include <string>
#include <vector>
#include <CompatibleFileSystem.hpp>
namespace elastos {
class MD5 {
public:
/*** type define ***/
//using Task = std::bind<F, Args...>;
/*** static function and variable ***/
static std::string Get(const std::vector<uint8_t>& data);
static std::string Get(const std::string& data);
static std::string Get(const elastos::filesystem::path& datapath);
static std::string MakeHexString(const std::vector<uint8_t>& data);
/*** class function and variable ***/
// post and copy
// post and move
private:
/*** type define ***/
/*** static function and variable ***/
/*** class function and variable ***/
explicit MD5() = delete;
virtual ~MD5() = delete;
}; // class MD5
} // namespace elastos
#endif /* _ELASTOS_MD5_HPP_ */
| 20.058824 | 71 | 0.631476 | [
"vector"
] |
43f058f98781100f9d97f9eaff809cd563db994c | 5,594 | hpp | C++ | src/python_streams.hpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 5 | 2021-01-10T06:22:11.000Z | 2021-04-13T12:59:40.000Z | src/python_streams.hpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 1 | 2021-01-10T04:42:17.000Z | 2021-01-10T10:55:58.000Z | src/python_streams.hpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 1 | 2021-04-13T12:59:41.000Z | 2021-04-13T12:59:41.000Z | /* Read and write sparse matrices in text format:
* <labels(s)> <column>:<value> <column>:<value> ...
*
* BSD 2-Clause License
* Copyright (c) 2021, David Cortes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 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.
*/
#ifdef _FOR_PYTHON
#pragma once
#include "readsparse_internal.hpp"
#include "readsparse_detemplated.hpp"
#include <sstream>
template <class int_t=int64_t, class real_t=double>
bool read_multi_label_str
(
std::string &input_str,
std::vector<int_t> &indptr,
std::vector<int_t> &indices,
std::vector<real_t> &values,
std::vector<int_t> &indptr_lab,
std::vector<int_t> &indices_lab,
std::vector<int_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows,
const bool ignore_zero_valued,
const bool sort_indices,
const bool text_is_base1,
const bool assume_no_qid,
const bool assume_trailing_ws
)
{
std::basic_stringstream<char> ss;
ss.str(input_str);
return read_multi_label(
ss,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
template <class int_t=int64_t, class real_t=double>
std::string write_multi_label_str
(
int_t *indptr,
int_t *indices,
real_t *values,
int_t *indptr_lab,
int_t *indices_lab,
int_t *qid,
const int_t missing_qid,
const bool has_qid,
const size_large nrows,
const size_large ncols,
const size_large nclasses,
const bool ignore_zero_valued,
const bool sort_indices,
const bool text_is_base1,
const bool add_header,
const int decimal_places
)
{
std::basic_stringstream<char> ss;
bool succeeded = write_multi_label(
ss,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
missing_qid,
has_qid,
nrows,
ncols,
nclasses,
ignore_zero_valued,
sort_indices,
text_is_base1,
add_header,
decimal_places
);
if (!succeeded)
return std::string("e");
return ss.str();
}
template <class int_t=int64_t, class real_t=double, class label_t=double>
bool read_single_label_str
(
std::string &input_str,
std::vector<int_t> &indptr,
std::vector<int_t> &indices,
std::vector<real_t> &values,
std::vector<label_t> &labels,
std::vector<int_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows,
const bool ignore_zero_valued,
const bool sort_indices,
const bool text_is_base1,
const bool assume_no_qid,
const bool assume_trailing_ws
)
{
std::basic_stringstream<char> ss;
ss.str(input_str);
return read_single_label(
ss,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
template <class int_t=int64_t, class real_t=double, class label_t=double>
std::string write_single_label_str
(
int_t *indptr,
int_t *indices,
real_t *values,
label_t *labels,
int_t *qid,
const int_t missing_qid,
const label_t missing_label,
const bool has_qid,
const size_large nrows,
const size_large ncols,
const size_large nclasses,
const bool ignore_zero_valued,
const bool sort_indices,
const bool text_is_base1,
const bool add_header,
const int decimal_places
)
{
std::basic_stringstream<char> ss;
bool succeeded = write_single_label(
ss,
indptr,
indices,
values,
labels,
qid,
missing_qid,
missing_label,
has_qid,
nrows,
ncols,
nclasses,
ignore_zero_valued,
sort_indices,
text_is_base1,
add_header,
decimal_places
);
if (!succeeded)
return std::string("e");
return ss.str();
}
#endif
| 26.76555 | 84 | 0.655881 | [
"vector"
] |
43fb45d0ae853ffc2dbfdf68435fdef93c030902 | 10,581 | cpp | C++ | src/CollisionObject.cpp | AndresTraks/BulletSharp | c277666667f91c58191f4cfa97f117053de679ef | [
"MIT"
] | 245 | 2015-01-02T14:11:26.000Z | 2022-03-18T08:56:36.000Z | src/CollisionObject.cpp | AndresTraks/BulletSharp | c277666667f91c58191f4cfa97f117053de679ef | [
"MIT"
] | 50 | 2015-01-04T22:32:21.000Z | 2021-06-08T20:26:24.000Z | src/CollisionObject.cpp | AndresTraks/BulletSharp | c277666667f91c58191f4cfa97f117053de679ef | [
"MIT"
] | 69 | 2015-04-03T15:38:44.000Z | 2022-01-20T14:27:30.000Z | #include "StdAfx.h"
#include "BroadphaseProxy.h"
#include "CollisionObject.h"
#include "CollisionShape.h"
#include "RigidBody.h"
#ifndef DISABLE_FEATHERSTONE
#include "MultiBodyLinkCollider.h"
#endif
#ifndef DISABLE_SERIALIZE
#include "Serializer.h"
#endif
#ifndef DISABLE_SOFTBODY
#include "SoftBody.h"
#endif
CollisionObject::CollisionObject(btCollisionObject* native)
{
UnmanagedPointer = native;
}
CollisionObject::~CollisionObject()
{
this->!CollisionObject();
}
CollisionObject::!CollisionObject()
{
if (this->IsDisposed)
return;
OnDisposing(this, nullptr);
if (!_preventDelete)
{
void* userObj = _native->getUserPointer();
if (userObj)
VoidPtrToGCHandle(userObj).Free();
delete _native;
}
_isDisposed = true;
OnDisposed(this, nullptr);
}
CollisionObject::CollisionObject()
{
UnmanagedPointer = new btCollisionObject();
}
void CollisionObject::Activate(bool forceActivation)
{
_native->activate(forceActivation);
}
void CollisionObject::Activate()
{
_native->activate();
}
#ifndef DISABLE_SERIALIZE
int CollisionObject::CalculateSerializeBufferSize()
{
return _native->calculateSerializeBufferSize();
}
#endif
bool CollisionObject::CheckCollideWith(CollisionObject^ collisionObject)
{
return _native->checkCollideWith(collisionObject->_native);
}
bool CollisionObject::CheckCollideWithOverride(CollisionObject^ collisionObject)
{
return _native->checkCollideWithOverride(collisionObject->_native);
}
void CollisionObject::ForceActivationState(BulletSharp::ActivationState newState)
{
_native->forceActivationState((int)newState);
}
bool BulletSharp::CollisionObject::GetCustomDebugColor([Out] Vector3% colorRgb)
{
btVector3* colorRgbTemp = ALIGNED_NEW(btVector3);
bool ret = _native->getCustomDebugColor(*colorRgbTemp);
ALIGNED_FREE(colorRgbTemp);
return ret;
}
int CollisionObject::GetHashCode()
{
return (int)_native;
}
void CollisionObject::GetWorldTransform([Out] Matrix% outTransform)
{
BtTransformToMatrixFast(_native->getWorldTransform(), outTransform);
}
bool CollisionObject::HasAnisotropicFriction(AnisotropicFrictionFlags frictionMode)
{
return _native->hasAnisotropicFriction((int)frictionMode);
}
bool CollisionObject::HasAnisotropicFriction()
{
return _native->hasAnisotropicFriction();
}
void BulletSharp::CollisionObject::RemoveCustomDebugColor()
{
_native->removeCustomDebugColor();
}
#ifndef DISABLE_SERIALIZE
String^ CollisionObject::Serialize(IntPtr dataBuffer, BulletSharp::Serializer^ serializer)
{
return gcnew String(_native->serialize(dataBuffer.ToPointer(), serializer->_native));
}
void CollisionObject::SerializeSingleObject(BulletSharp::Serializer^ serializer)
{
_native->serializeSingleObject(serializer->_native);
}
#endif
void CollisionObject::SetAnisotropicFriction(Vector3 anisotropicFriction, AnisotropicFrictionFlags frictionMode)
{
VECTOR3_CONV(anisotropicFriction);
_native->setAnisotropicFriction(VECTOR3_USE(anisotropicFriction), (int)frictionMode);
VECTOR3_DEL(anisotropicFriction);
}
void CollisionObject::SetAnisotropicFriction(Vector3 anisotropicFriction)
{
VECTOR3_CONV(anisotropicFriction);
_native->setAnisotropicFriction(VECTOR3_USE(anisotropicFriction));
VECTOR3_DEL(anisotropicFriction);
}
void BulletSharp::CollisionObject::SetCustomDebugColor(Vector3 colorRgb)
{
VECTOR3_CONV(colorRgb);
_native->setCustomDebugColor(VECTOR3_USE(colorRgb));
VECTOR3_DEL(colorRgb);
}
void CollisionObject::SetIgnoreCollisionCheck(CollisionObject^ collisionObject, bool ignoreCollisionCheck)
{
_native->setIgnoreCollisionCheck(collisionObject->_native, ignoreCollisionCheck);
}
CollisionObject^ CollisionObject::GetManaged(btCollisionObject* collisionObject)
{
if (collisionObject == 0)
return nullptr;
void* userObj = collisionObject->getUserPointer();
if (userObj)
return static_cast<CollisionObject^>(VoidPtrToGCHandle(userObj).Target);
throw gcnew InvalidOperationException("Unknown collision object!");
}
BulletSharp::ActivationState CollisionObject::ActivationState::get()
{
return (BulletSharp::ActivationState)_native->getActivationState();
}
void CollisionObject::ActivationState::set(BulletSharp::ActivationState value)
{
_native->setActivationState((int)value);
}
Vector3 CollisionObject::AnisotropicFriction::get()
{
return Math::BtVector3ToVector3(&_native->getAnisotropicFriction());
}
void CollisionObject::AnisotropicFriction::set(Vector3 value)
{
VECTOR3_CONV(value);
_native->setAnisotropicFriction(VECTOR3_USE(value));
VECTOR3_DEL(value);
}
BroadphaseProxy^ CollisionObject::BroadphaseHandle::get()
{
return _broadphaseHandle;
}
void CollisionObject::BroadphaseHandle::set(BroadphaseProxy^ handle)
{
_native->setBroadphaseHandle(GetUnmanagedNullable(handle));
_broadphaseHandle = handle;
}
btScalar CollisionObject::CcdMotionThreshold::get()
{
return _native->getCcdMotionThreshold();
}
void CollisionObject::CcdMotionThreshold::set(btScalar ccdMotionThreshold)
{
_native->setCcdMotionThreshold(ccdMotionThreshold);
}
btScalar CollisionObject::CcdSquareMotionThreshold::get()
{
return _native->getCcdSquareMotionThreshold();
}
btScalar CollisionObject::CcdSweptSphereRadius::get()
{
return _native->getCcdSweptSphereRadius();
}
void CollisionObject::CcdSweptSphereRadius::set(btScalar radius)
{
_native->setCcdSweptSphereRadius(radius);
}
CollisionFlags CollisionObject::CollisionFlags::get()
{
return (BulletSharp::CollisionFlags)_native->getCollisionFlags();
}
void CollisionObject::CollisionFlags::set(BulletSharp::CollisionFlags flags)
{
_native->setCollisionFlags((int)flags);
}
CollisionShape^ CollisionObject::CollisionShape::get()
{
return _collisionShape;
}
void CollisionObject::CollisionShape::set(BulletSharp::CollisionShape^ collisionShape)
{
_native->setCollisionShape(GetUnmanagedNullable(collisionShape));
_collisionShape = collisionShape;
}
int CollisionObject::CompanionId::get()
{
return _native->getCompanionId();
}
void CollisionObject::CompanionId::set(int id)
{
_native->setCompanionId(id);
}
btScalar CollisionObject::ContactProcessingThreshold::get()
{
return _native->getContactProcessingThreshold();
}
void CollisionObject::ContactProcessingThreshold::set(btScalar contactProcessingThreshold)
{
_native->setContactProcessingThreshold(contactProcessingThreshold);
}
btScalar CollisionObject::DeactivationTime::get()
{
return _native->getDeactivationTime();
}
void CollisionObject::DeactivationTime::set(btScalar time)
{
_native->setDeactivationTime(time);
}
btScalar CollisionObject::Friction::get()
{
return _native->getFriction();
}
void CollisionObject::Friction::set(btScalar frict)
{
_native->setFriction(frict);
}
bool CollisionObject::HasContactResponse::get()
{
return _native->hasContactResponse();
}
btScalar CollisionObject::HitFraction::get()
{
return _native->getHitFraction();
}
void CollisionObject::HitFraction::set(btScalar hitFraction)
{
_native->setHitFraction(hitFraction);
}
Vector3 CollisionObject::InterpolationAngularVelocity::get()
{
return Math::BtVector3ToVector3(&_native->getInterpolationAngularVelocity());
}
void CollisionObject::InterpolationAngularVelocity::set(Vector3 angvel)
{
VECTOR3_CONV(angvel);
_native->setInterpolationAngularVelocity(VECTOR3_USE(angvel));
VECTOR3_DEL(angvel);
}
Vector3 CollisionObject::InterpolationLinearVelocity::get()
{
return Math::BtVector3ToVector3(&_native->getInterpolationLinearVelocity());
}
void CollisionObject::InterpolationLinearVelocity::set(Vector3 linvel)
{
VECTOR3_CONV(linvel);
_native->setInterpolationLinearVelocity(VECTOR3_USE(linvel));
VECTOR3_DEL(linvel);
}
Matrix CollisionObject::InterpolationWorldTransform::get()
{
return Math::BtTransformToMatrix(&_native->getInterpolationWorldTransform());
}
void CollisionObject::InterpolationWorldTransform::set(Matrix trans)
{
TRANSFORM_CONV(trans);
_native->setInterpolationWorldTransform(TRANSFORM_USE(trans));
TRANSFORM_DEL(trans);
}
bool CollisionObject::IsActive::get()
{
return _native->isActive();
}
bool CollisionObject::IsDisposed::get()
{
return _isDisposed;
}
bool CollisionObject::IsKinematicObject::get()
{
return _native->isKinematicObject();
}
int CollisionObject::IslandTag::get()
{
return _native->getIslandTag();
}
void CollisionObject::IslandTag::set(int tag)
{
_native->setIslandTag(tag);
}
bool CollisionObject::IsStaticObject::get()
{
return _native->isStaticObject();
}
bool CollisionObject::IsStaticOrKinematicObject::get()
{
return _native->isStaticOrKinematicObject();
}
bool CollisionObject::MergesSimulationIslands::get()
{
return _native->mergesSimulationIslands();
}
btScalar CollisionObject::Restitution::get()
{
return _native->getRestitution();
}
void CollisionObject::Restitution::set(btScalar rest)
{
_native->setRestitution(rest);
}
btScalar CollisionObject::RollingFriction::get()
{
return _native->getRollingFriction();
}
void CollisionObject::RollingFriction::set(btScalar frict)
{
_native->setRollingFriction(frict);
}
int CollisionObject::UpdateRevisionInternal::get()
{
return _native->getUpdateRevisionInternal();
}
int CollisionObject::UserIndex::get()
{
return _native->getUserIndex();
}
void CollisionObject::UserIndex::set(int index)
{
_native->setUserIndex(index);
}
Object^ CollisionObject::UserObject::get()
{
return _userObject;
}
void CollisionObject::UserObject::set(Object^ value)
{
_userObject = value;
}
Matrix CollisionObject::WorldTransform::get()
{
return Math::BtTransformToMatrix(&_native->getWorldTransform());
}
void CollisionObject::WorldTransform::set(Matrix worldTrans)
{
TRANSFORM_CONV(worldTrans);
_native->setWorldTransform(TRANSFORM_USE(worldTrans));
TRANSFORM_DEL(worldTrans);
}
btCollisionObject* CollisionObject::UnmanagedPointer::get()
{
return _native;
}
void CollisionObject::UnmanagedPointer::set(btCollisionObject* value)
{
// Inheriting classes such as SoftBody may pass 0 and then do
// additional processing before storing the native pointer.
if (value == 0) {
return;
}
_native = value;
if (_native->getUserPointer() == 0)
{
GCHandle handle = GCHandle::Alloc(this, GCHandleType::Weak);
void* obj = GCHandleToVoidPtr(handle);
_native->setUserPointer(obj);
}
}
| 24.43649 | 113 | 0.764389 | [
"object"
] |
43fdb44a50673f9e160bad792c4c363271b4cdf1 | 1,889 | cpp | C++ | aws-cpp-sdk-opsworks/source/model/DescribeRdsDbInstancesRequest.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-opsworks/source/model/DescribeRdsDbInstancesRequest.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-opsworks/source/model/DescribeRdsDbInstancesRequest.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/opsworks/model/DescribeRdsDbInstancesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::OpsWorks::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeRdsDbInstancesRequest::DescribeRdsDbInstancesRequest() :
m_stackIdHasBeenSet(false),
m_rdsDbInstanceArnsHasBeenSet(false)
{
}
Aws::String DescribeRdsDbInstancesRequest::SerializePayload() const
{
JsonValue payload;
if(m_stackIdHasBeenSet)
{
payload.WithString("StackId", m_stackId);
}
if(m_rdsDbInstanceArnsHasBeenSet)
{
Array<JsonValue> rdsDbInstanceArnsJsonList(m_rdsDbInstanceArns.size());
for(unsigned rdsDbInstanceArnsIndex = 0; rdsDbInstanceArnsIndex < rdsDbInstanceArnsJsonList.GetLength(); ++rdsDbInstanceArnsIndex)
{
rdsDbInstanceArnsJsonList[rdsDbInstanceArnsIndex].AsString(m_rdsDbInstanceArns[rdsDbInstanceArnsIndex]);
}
payload.WithArray("RdsDbInstanceArns", std::move(rdsDbInstanceArnsJsonList));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeRdsDbInstancesRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "OpsWorks_20130218.DescribeRdsDbInstances"));
return headers;
}
| 29.515625 | 133 | 0.777131 | [
"model"
] |
43fed23345f06fb7029f8722e3b750509e4d6b03 | 3,516 | cpp | C++ | Quadbit/Source/Engine/API/Compute.cpp | RMichelsen/Quadbit | d98d5c2e5e239d4d6b8e4cb527ad9b6e4e40a779 | [
"MIT"
] | 1 | 2021-09-07T00:48:00.000Z | 2021-09-07T00:48:00.000Z | Quadbit/Source/Engine/API/Compute.cpp | R-Michelsen/Quadbit | d98d5c2e5e239d4d6b8e4cb527ad9b6e4e40a779 | [
"MIT"
] | null | null | null | Quadbit/Source/Engine/API/Compute.cpp | R-Michelsen/Quadbit | d98d5c2e5e239d4d6b8e4cb527ad9b6e4e40a779 | [
"MIT"
] | null | null | null | #include "Compute.h"
#include <EASTL/string.h>
#include <EASTL/array.h>
#include <EASTL/vector.h>
#include "Engine/Rendering/Renderer.h"
#include "Engine/Rendering/Memory/ResourceManager.h"
#include "Engine/Rendering/VulkanUtils.h"
#include "Engine/Rendering/Shaders/ShaderCompiler.h"
namespace Quadbit {
Compute::Compute(QbVkRenderer* const renderer) : renderer_(renderer), resourceManager_(renderer->context_->resourceManager.get()) { }
QbVkPipelineHandle Compute::CreatePipeline(const char* computePath, const char* kernel,
const void* specConstants, const uint32_t maxInstances) {
auto handle = resourceManager_->pipelines_.GetNextHandle();
resourceManager_->pipelines_[handle] = eastl::make_unique<QbVkPipeline>(*renderer_->context_, computePath, kernel, specConstants, maxInstances);
return handle;
}
void Compute::BindResource(const QbVkPipelineHandle pipelineHandle, const eastl::string name,
const QbVkBufferHandle bufferHandle, const QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
if (descriptorsHandle != QBVK_DESCRIPTOR_SETS_NULL_HANDLE) {
pipeline->BindResource(descriptorsHandle, name, bufferHandle);
}
else {
pipeline->BindResource(name, bufferHandle);
}
}
void Compute::BindResource(const QbVkPipelineHandle pipelineHandle, const eastl::string name,
const QbVkTextureHandle textureHandle, const QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
if (descriptorsHandle != QBVK_DESCRIPTOR_SETS_NULL_HANDLE) {
pipeline->BindResource(descriptorsHandle, name, textureHandle);
}
else {
pipeline->BindResource(name, textureHandle);
}
}
void Compute::BindResourceArray(const QbVkPipelineHandle pipelineHandle, const eastl::string name,
const eastl::vector<QbVkBufferHandle> bufferHandles, const QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
if (descriptorsHandle != QBVK_DESCRIPTOR_SETS_NULL_HANDLE) {
pipeline->BindResourceArray(descriptorsHandle, name, bufferHandles);
}
else {
pipeline->BindResourceArray(name, bufferHandles);
}
}
void Compute::BindResourceArray(const QbVkPipelineHandle pipelineHandle, const eastl::string name,
const eastl::vector<QbVkTextureHandle> textureHandles, const QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
if (descriptorsHandle != QBVK_DESCRIPTOR_SETS_NULL_HANDLE) {
pipeline->BindResourceArray(descriptorsHandle, name, textureHandles);
}
else {
pipeline->BindResourceArray(name, textureHandles);
}
}
void Compute::Dispatch(const QbVkPipelineHandle pipelineHandle, uint32_t xGroups, uint32_t yGroups, uint32_t zGroups,
const void* pushConstants, uint32_t pushConstantSize, QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
pipeline->Dispatch(xGroups, yGroups, zGroups, pushConstants, pushConstantSize, descriptorsHandle);
}
void Compute::DispatchX(uint32_t X, const QbVkPipelineHandle pipelineHandle, uint32_t xGroups, uint32_t yGroups, uint32_t zGroups,
eastl::vector<const void*> pushConstantArray, uint32_t pushConstantSize, QbVkDescriptorSetsHandle descriptorsHandle) {
auto& pipeline = resourceManager_->pipelines_[pipelineHandle];
pipeline->DispatchX(X, xGroups, yGroups, zGroups, pushConstantArray, pushConstantSize, descriptorsHandle);
}
} | 45.076923 | 146 | 0.799204 | [
"vector"
] |
a101d3e0dd4dd84aa53af8092a5660b05e8a69f7 | 1,610 | hpp | C++ | PosenetOnIOS/PoseParse.hpp | toniz/posenet-on-ios | 45b2d8168e9b47a6e2b726c3e0c83d730d7c217f | [
"MIT"
] | 31 | 2019-07-18T20:25:39.000Z | 2022-03-31T00:11:59.000Z | PosenetOnIOS/PoseParse.hpp | toniz/posenet-on-ios | 45b2d8168e9b47a6e2b726c3e0c83d730d7c217f | [
"MIT"
] | null | null | null | PosenetOnIOS/PoseParse.hpp | toniz/posenet-on-ios | 45b2d8168e9b47a6e2b726c3e0c83d730d7c217f | [
"MIT"
] | 7 | 2019-08-30T08:11:59.000Z | 2020-09-14T03:14:20.000Z | //
// PoseParse.hpp
// PosenetOnIOS
//
// Created by toniz sin on 9/7/2019.
//
#ifndef PoseParse_hpp
#define PoseParse_hpp
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#define FLOAT_TO_INT 10000
#define INT_TO_FLOAT 10000.0
using namespace std;
class C3DArray
{
public:
C3DArray(int h1, int w1, int s1){
h = h1;
w = w1;
s = s1;
};
~C3DArray(){};
inline int getOffset(int y, int x, int o){
return (y * w + x) * s + o;
}
public:
int h, w, s;
};
class CDecodePose
{
public:
CDecodePose();
~CDecodePose(){};
bool isMaxScoreInLocalWindow(int y, int x, int k, float* score, int &iScore);
bool isInResultNmsRadius(int h, int w, int k, map<int, map<int, vector<int>>> &result);
bool BuildTopQueue(float *pScore, map<float, vector<int>> &topQueue);
bool findNextKeyPoint(int isForward, int edge, float* pScore,float *pShortOffset, float *pMiddleOffset, map<int, vector<int>> &keyPoints, int &scoreSum);
int decode(float *score, float *s_offset, float *m_offset, map<int, map<int, vector<int>>> &result);
public:
int m_inputHeight;
int m_inputWidth;
int m_yCnt;
int m_xCnt;
int m_kCnt;
int m_eCnt;
vector<string> m_keyPointName;
vector<int> m_childOrder;
vector<int> m_parentOrder;
private:
C3DArray* m_scoreArray;
C3DArray* m_shortOffsetArray;
C3DArray* m_middleOffsetArray;
int m_pointThreshold;
int m_localWindowRadius;
int m_outStride;
int m_nmsRadius;
int m_squaredNmsRadius;
};
#endif /* PoseParse_hpp */
| 21.466667 | 157 | 0.652795 | [
"vector"
] |
a103db1afc86b208d77c297f4d1bbe82d54a057a | 3,428 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/DeleteHandler.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/DeleteHandler.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/DeleteHandler.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/DeleteHandler>
#include <osg/Notify>
namespace osg
{
DeleteHandler::DeleteHandler(int numberOfFramesToRetainObjects):
_numFramesToRetainObjects(numberOfFramesToRetainObjects),
_currentFrameNumber(0)
{
}
DeleteHandler::~DeleteHandler()
{
// flushAll();
}
void DeleteHandler::flush()
{
typedef std::list<const osg::Referenced*> DeletionList;
DeletionList deletionList;
{
// gather all the objects to delete whilst holding the mutex to the _objectsToDelete
// list, but delete the objects outside this scoped lock so that if any objects deleted
// unref their children then no deadlock happens.
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
int frameNumberToClearTo = _currentFrameNumber - _numFramesToRetainObjects;
ObjectsToDeleteList::iterator itr;
for(itr = _objectsToDelete.begin();
itr != _objectsToDelete.end();
++itr)
{
if (itr->first > frameNumberToClearTo) break;
deletionList.push_back(itr->second);
itr->second = 0;
}
_objectsToDelete.erase( _objectsToDelete.begin(), itr);
}
for(DeletionList::iterator ditr = deletionList.begin();
ditr != deletionList.end();
++ditr)
{
doDelete(*ditr);
}
}
void DeleteHandler::flushAll()
{
int temp_numFramesToRetainObjects = _numFramesToRetainObjects;
_numFramesToRetainObjects = 0;
typedef std::list<const osg::Referenced*> DeletionList;
DeletionList deletionList;
{
// gather all the objects to delete whilst holding the mutex to the _objectsToDelete
// list, but delete the objects outside this scoped lock so that if any objects deleted
// unref their children then no deadlock happens.
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
ObjectsToDeleteList::iterator itr;
for(itr = _objectsToDelete.begin();
itr != _objectsToDelete.end();
++itr)
{
deletionList.push_back(itr->second);
itr->second = 0;
}
_objectsToDelete.erase( _objectsToDelete.begin(), _objectsToDelete.end());
}
for(DeletionList::iterator ditr = deletionList.begin();
ditr != deletionList.end();
++ditr)
{
doDelete(*ditr);
}
_numFramesToRetainObjects = temp_numFramesToRetainObjects;
}
void DeleteHandler::requestDelete(const osg::Referenced* object)
{
if (_numFramesToRetainObjects==0) doDelete(object);
else
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
_objectsToDelete.push_back(FrameNumberObjectPair(_currentFrameNumber,object));
}
}
} // end of namespace osg
| 30.607143 | 95 | 0.672404 | [
"object"
] |
a103f0cfdd397e18bf3a9a623b0204c0052d4527 | 35,975 | cpp | C++ | GLIP-Lib/src/Core/HdlShader.cpp | ronan-kerviche/glip-lib | 6ae64559db7616abc33e586364940695665795a9 | [
"MIT"
] | 16 | 2016-07-29T07:39:07.000Z | 2022-03-17T04:27:22.000Z | GLIP-Lib/src/Core/HdlShader.cpp | ronan-kerviche/glip-lib | 6ae64559db7616abc33e586364940695665795a9 | [
"MIT"
] | 2 | 2017-02-04T19:34:26.000Z | 2020-05-29T20:13:58.000Z | GLIP-Lib/src/Core/HdlShader.cpp | ronan-kerviche/glip-lib | 6ae64559db7616abc33e586364940695665795a9 | [
"MIT"
] | 4 | 2016-07-07T10:16:11.000Z | 2019-03-24T05:56:16.000Z | /* ************************************************************************************************************* */
/* */
/* GLIP-LIB */
/* OpenGL Image Processing LIBrary */
/* */
/* Author : R. Kerviche */
/* LICENSE : MIT License */
/* Website : glip-lib.net */
/* */
/* File : HdlShader.cpp */
/* Original Date : August 7th 2010 */
/* */
/* Description : OpenGL Pixel and Fragment Shader Handle */
/* */
/* ************************************************************************************************************* */
/**
* \file HdlShader.cpp
* \brief OpenGL Pixel and Fragment Shader Handle
* \author R. KERVICHE
* \date August 7th 2010
**/
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <algorithm>
#include "Core/Exception.hpp"
#include "Core/HdlShader.hpp"
#include "devDebugTools.hpp"
using namespace Glip::CoreGL;
// HdlShader :
/**
\fn HdlShader::HdlShader(GLenum _type, const ShaderSource& src)
\brief HdlShader constructor.
\param _type The kind of shader it will be : GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER.
\param src The source code used.
**/
HdlShader::HdlShader(GLenum _type, const ShaderSource& src)
: ShaderSource(src),
type(_type)
{
#ifdef GLIP_USE_GL
// Manage extensions :
NEED_EXTENSION(GLEW_VERSION_2_0)
//NEED_EXTENSION(GLEW_ARB_shader_objects)
switch(type)
{
case GL_FRAGMENT_SHADER :
NEED_EXTENSION(GLEW_ARB_fragment_shader)
NEED_EXTENSION(GLEW_ARB_fragment_program)
break;
case GL_VERTEX_SHADER :
NEED_EXTENSION(GLEW_ARB_vertex_shader)
NEED_EXTENSION(GLEW_ARB_vertex_program)
break;
case GL_COMPUTE_SHADER :
NEED_EXTENSION(GLEW_ARB_compute_shader)
break;
case GL_TESS_CONTROL_SHADER :
case GL_TESS_EVALUATION_SHADER :
NEED_EXTENSION(GLEW_ARB_tessellation_shader)
break;
case GL_GEOMETRY_SHADER :
NEED_EXTENSION(GLEW_ARB_geometry_shader4)
break;
default :
throw Exception("HdlShader::HdlShader - Unknown shader type : \"" + getGLEnumNameSafe(type) + "\".", __FILE__, __LINE__, Exception::GLException);
}
if(!src.requiresCompatibility())
FIX_MISSING_GLEW_CALL(glBindFragDataLocation, glBindFragDataLocationEXT)
FIX_MISSING_GLEW_CALL(glCompileShader, glCompileShaderARB)
FIX_MISSING_GLEW_CALL(glLinkProgram, glLinkProgramARB)
FIX_MISSING_GLEW_CALL(glGetUniformLocation, glGetUniformLocationARB)
FIX_MISSING_GLEW_CALL(glUniform1i, glUniform1iARB)
FIX_MISSING_GLEW_CALL(glUniform2i, glUniform2iARB)
FIX_MISSING_GLEW_CALL(glUniform3i, glUniform3iARB)
FIX_MISSING_GLEW_CALL(glUniform4i, glUniform4iARB)
FIX_MISSING_GLEW_CALL(glUniform1f, glUniform1fARB)
FIX_MISSING_GLEW_CALL(glUniform2f, glUniform2fARB)
FIX_MISSING_GLEW_CALL(glUniform3f, glUniform3fARB)
FIX_MISSING_GLEW_CALL(glUniform4f, glUniform4fARB)
#endif
#ifdef GLIP_USE_GL
const GLenum listCorrectEnum[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER};
#else
const GLenum listCorrectEnum[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER};
#endif
if(!belongsToGLEnums(type, listCorrectEnum))
throw Exception("HdlShader::HdlShader - Invalid enum : " + getGLEnumNameSafe(type) + ".", __FILE__, __LINE__, Exception::GLException);
// create the shader
shader = glCreateShader(type);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glCreateShader()")
#endif
if(shader==0)
{
const GLenum err = glGetError();
throw Exception("HdlShader::HdlShader - Unable to create the shader from " + getSourceName() + ". OpenGL error : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
// send the source code
const char* data = getSourceCstr();
glShaderSource(shader, 1, (const GLchar**)&data, NULL);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glShaderSource()")
#endif
// compile the shader source code
glCompileShader(shader);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glCompileShader()")
#endif
// check the compilation
GLint compile_status = GL_TRUE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status)")
#endif
if(compile_status != GL_TRUE)
{
GLint logSize;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize)")
#endif
char *log = new char[logSize+1]; // +1 <=> '/0'
memset(log, 0, logSize+1);
glGetShaderInfoLog(shader, logSize, &logSize, log);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::HdlShader", "glGetShaderInfoLog()")
#endif
log[logSize] = 0;
Exception detailedLog = this->errorLog(std::string(log));
delete[] log;
// Clean other resources :
glDeleteShader(shader);
throw detailedLog;
}
}
HdlShader::~HdlShader(void)
{
glDeleteShader(shader);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlShader::~HdlShader", "glDeleteShader()")
#endif
}
/**
\fn GLuint HdlShader::getShaderID(void) const
\brief Returns the ID of the shader for OpenGL.
\return The ID handled by the driver.
**/
GLuint HdlShader::getShaderID(void) const
{
return shader;
}
/**
\fn GLenum HdlShader::getType(void) const
\brief Returns the type of the shader for OpenGL
Return the type of the shader, among : GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER.
\return The type of this shader.
**/
GLenum HdlShader::getType(void) const
{
return type;
}
// HdlProgram :
/**
\fn HdlProgram::HdlProgram(void)
\brief HdlProgram constructor.
**/
HdlProgram::HdlProgram(void)
: valid(false),
program(0)
{
std::memset(attachedShaders, 0, numShaderTypes*sizeof(GLuint));
// create the program
program = glCreateProgram();
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::HdlProgram(void)", "glCreateProgram()")
#endif
if(program==0)
{
const GLenum err = glGetError();
throw Exception("HdlProgram::HdlProgram - Program can't be created. Last OpenGL error : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
}
HdlProgram::~HdlProgram(void)
{
for(int k=0; k<numShaderTypes; k++)
{
if(attachedShaders[k]!=0)
{
glDetachShader(program, attachedShaders[k]);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::~HdlProgram", "glDetachShader(program, attachedShaders[k])")
#endif
}
}
glDeleteProgram(program);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::~HdlProgram", "glDeleteProgram(program)")
#endif
}
/**
\fn bool HdlProgram::isValid(void) const
\brief Check if the program is valid.
\return True if the Program is valid, false otherwise.
**/
bool HdlProgram::isValid(void) const
{
return (program!=0) && valid;
}
/**
\fn void HdlProgram::updateShader(const HdlShader& shader, bool linkNow)
\brief Change a shader in the program.
\param shader The shader to add.
\param linkNow Link the program now.
**/
void HdlProgram::updateShader(const HdlShader& shader, bool linkNow)
{
unsigned int k = HandleOpenGL::getShaderTypeIndex(shader.getType());
// Dettach previous :
if(attachedShaders[k]!=0)
{
glDetachShader(program, attachedShaders[k]);
attachedShaders[k] = false;
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::update", "glDetachShader(program, attachedShaders[" + getGLEnumNameSafe(shaderType) + "])")
#endif
}
attachedShaders[k] = shader.getShaderID();
glAttachShader(program, attachedShaders[k]);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::update", "glAttachShader(program, attachedShaders[" + getGLEnumNameSafe(shaderType) + "])")
#endif
// Link the program
if(linkNow)
link();
}
/**
\fn bool HdlProgram::link(void)
\brief Link the program.
\return False in case of failure, true otherwise.
<b>WARNING</b> : This step might remove all the uniform values previously set.
**/
void HdlProgram::link(void)
{
valid = false;
// Link them
glLinkProgram(program);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::link", "glLinkProgram()")
#endif
// Look for some error during the linking
GLint link_status = GL_TRUE;
glGetProgramiv(program, GL_LINK_STATUS, &link_status);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::link", "glGetProgramiv(program, GL_LINK_STATUS, &link_status)")
#endif
if(link_status!=GL_TRUE)
{
// get the log
GLint logSize;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logSize);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::link", "glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logSize)")
#endif
char *log = new char[logSize+1]; // +1 <=> '/0'
memset(log, 0, logSize+1);
glGetProgramInfoLog(program, logSize, &logSize, log);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::link", "glGetProgramInfoLog()")
#endif
log[logSize] = 0;
std::string logstr(log);
delete[] log;
throw Exception("HdlProgram::link - Error during Program linking : \n" + logstr, __FILE__, __LINE__, Exception::ClientShaderException);
}
else
{
use();
// Clean :
activeUniforms.clear();
activeTypes.clear();
// Update available uniforms of the following types :
#ifdef GLIP_USE_GL
const GLenum interestTypes[] = {GL_FLOAT, GL_FLOAT_VEC2, GL_FLOAT_VEC3, GL_FLOAT_VEC4, GL_DOUBLE, GL_DOUBLE_VEC2, GL_DOUBLE_VEC3, GL_DOUBLE_VEC4, GL_INT, GL_INT_VEC2, GL_INT_VEC3, GL_INT_VEC4, GL_UNSIGNED_INT_VEC2, GL_UNSIGNED_INT_VEC3, GL_UNSIGNED_INT_VEC4, GL_BOOL, GL_BOOL_VEC2, GL_BOOL_VEC3, GL_BOOL_VEC4, GL_FLOAT_MAT2, GL_FLOAT_MAT3, GL_FLOAT_MAT4, /*GL_DOUBLE_MAT2, GL_DOUBLE_MAT3, GL_DOUBLE_MAT4,*/ GL_UNSIGNED_INT};
#else
const GLenum interestTypes[] = {GL_FLOAT, GL_FLOAT_VEC2, GL_FLOAT_VEC3, GL_FLOAT_VEC4, GL_INT, GL_INT_VEC2, GL_INT_VEC3, GL_INT_VEC4, GL_UNSIGNED_INT_VEC2, GL_UNSIGNED_INT_VEC3, GL_UNSIGNED_INT_VEC4, GL_BOOL, GL_BOOL_VEC2, GL_BOOL_VEC3, GL_BOOL_VEC4, GL_FLOAT_MAT2, GL_FLOAT_MAT3, GL_FLOAT_MAT4, GL_UNSIGNED_INT};
#endif
const int numAllowedTypes = sizeof(interestTypes) / sizeof(GLenum);
// Get number of uniforms :
GLint numUniforms = 0;
glGetProgramiv( program, GL_ACTIVE_UNIFORMS, &numUniforms);
const int maxLength = 1024;
char buffer[maxLength];
GLenum type;
GLint actualSize, actualSizeName;
for(int k=0; k<numUniforms; k++)
{
glGetActiveUniform( program, k, maxLength-1, &actualSizeName, &actualSize, &type, buffer);
if(std::find(interestTypes, interestTypes + numAllowedTypes, type)!=interestTypes + numAllowedTypes)
{
activeUniforms.push_back(buffer);
activeTypes.push_back(type);
}
}
valid = true;
}
}
/**
\fn void HdlProgram::use(void)
\brief Start using the program with OpenGL.
**/
void HdlProgram::use(void)
{
glUseProgram(program);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::use", "glUseProgram()")
#endif
}
/**
\fn const std::vector<std::string>& HdlProgram::getUniformsNames(void) const
\brief Get access to the list of uniform variables names of supported types managed by the program (GL based).
Some variable reported by the Driver might not be accessible. You can use HdlProgram::isUniformVariableValid to detect such variables.
\return Access to a string based vector.
**/
const std::vector<std::string>& HdlProgram::getUniformsNames(void) const
{
return activeUniforms;
}
/**
\fn const std::vector<GLenum>& HdlProgram::getUniformsTypes(void) const
\brief Get access to the list of uniform variables types corresponding to the names provided by HdlProgram::getUniformsNames (GL based).
Some variable reported by the Driver might not be accessible. You can use HdlProgram::isUniformVariableValid to detect such variables.
\return Access to a GLenum based vector, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
**/
const std::vector<GLenum>& HdlProgram::getUniformsTypes(void) const
{
return activeTypes;
}
/**
\fn void HdlProgram::setFragmentLocation(const std::string& fragName, int frag)
\brief Link the name of a fragment output variable to a fragment unit.
\param fragName Name of the fragment output variable.
\param frag Index of the desired fragment unit.
Note that the program should be linked after this call in order to push the changes.
**/
void HdlProgram::setFragmentLocation(const std::string& fragName, int frag)
{
#ifdef GLIP_USE_GL
#ifdef __GLIPLIB_DEVELOPMENT_VERBOSE__
std::cout << "HdlProgram::setFragmentLocation - FragName : " << fragName << std::endl;
#endif
glBindFragDataLocation(program, frag, fragName.c_str());
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::setFragmentLocation - Error while setting fragment location \"" + fragName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
#endif
}
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum type, int v0, int v1=0, int v2=0, int v3=0)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param type Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v0 Corresponding value to assign.
\param v1 Corresponding value to assign.
\param v2 Corresponding value to assign.
\param v3 Corresponding value to assign.
**/
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum type, unsigned int v0, unsigned int v1=0, unsigned int v2=0, unsigned int v3=0)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param type Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v0 Corresponding value to assign.
\param v1 Corresponding value to assign.
\param v2 Corresponding value to assign.
\param v3 Corresponding value to assign.
**/
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum type, float v0, float v1=0, float v2=0, float v3=0)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param type Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v0 Corresponding value to assign.
\param v1 Corresponding value to assign.
\param v2 Corresponding value to assign.
\param v3 Corresponding value to assign.
**/
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum t, int* v)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param t Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v Pointer to the values to assign.
**/
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum t, unsigned int* v)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param t Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v Pointer to the values to assign.
**/
/**
\fn void HdlProgram::setVar(const std::string& varName, GLenum t, float* v)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param t Kind of variable in, see http://www.opengl.org/sdk/docs/man/xhtml/glGetActiveUniform.xml for possible types.
\param v Pointer to the values to assign.
**/
#define GENsetVarA( argT1, argT2, argT3) \
void HdlProgram::setVar(const std::string& varName, GLenum t, argT1 v0, argT1 v1, argT1 v2, argT1 v3) \
{ \
use(); \
GLint loc = glGetUniformLocation(program, varName.c_str()); \
\
if(loc==-1) \
throw Exception("HdlProgram::setVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException); \
\
switch(t) \
{ \
case GL_##argT2 : glUniform1##argT3 (loc, v0); break; \
case GL_##argT2##_VEC2 : glUniform2##argT3 (loc, v0, v1); break; \
case GL_##argT2##_VEC3 : glUniform3##argT3 (loc, v0, v1, v2); break; \
case GL_##argT2##_VEC4 : glUniform4##argT3 (loc, v0, v1, v2, v3); break; \
default : throw Exception("HdlProgram::setVar - Unknown variable type or type mismatch for \"" + getGLEnumNameSafe(t) + "\" when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException); \
} \
\
const GLenum err = glGetError(); \
if(err!=GL_NO_ERROR) \
throw Exception("HdlProgram::setVar - An error occurred when loading data of type \"" + getGLEnumNameSafe(t) + "\" in variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException); \
} \
#define GENsetVarB( argT1, argT2, argT3) \
void HdlProgram::setVar(const std::string& varName, GLenum t, argT1* v) \
{ \
use(); \
GLint loc = glGetUniformLocation(program, varName.c_str()); \
\
if(loc==-1) \
throw Exception("HdlProgram::setVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException); \
\
switch(t) \
{ \
case GL_##argT2 : glUniform1##argT3##v(loc, 1, v); break; \
case GL_##argT2##_VEC2 : glUniform2##argT3##v(loc, 1, v); break; \
case GL_##argT2##_VEC3 : glUniform3##argT3##v(loc, 1, v); break; \
case GL_##argT2##_VEC4 : glUniform4##argT3##v(loc, 1, v); break; \
default : throw Exception("HdlProgram::setVar - Unknown variable type or type mismatch for \"" + getGLEnumNameSafe(t) + "\" when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException); \
} \
\
const GLenum err = glGetError(); \
if(err!=GL_NO_ERROR) \
throw Exception("HdlProgram::setVar - An error occurred when loading data of type \"" + getGLEnumNameSafe(t) + "\" in variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException); \
}
GENsetVarA( int, INT, i)
GENsetVarB( int, INT, i)
GENsetVarA( unsigned int, UNSIGNED_INT, ui)
GENsetVarB( unsigned int, UNSIGNED_INT, ui)
GENsetVarA( float, FLOAT, f)
#undef GENsetVar
// Last one, with matrices :
void HdlProgram::setVar(const std::string& varName, GLenum t, float* v)
{
use();
GLint loc = glGetUniformLocation(program, varName.c_str());
if(loc==-1)
throw Exception("HdlProgram::setVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
switch(t)
{
case GL_FLOAT : glUniform1fv(loc, 1, v); break;
case GL_FLOAT_VEC2 : glUniform2fv(loc, 1, v); break;
case GL_FLOAT_VEC3 : glUniform3fv(loc, 1, v); break;
case GL_FLOAT_VEC4 : glUniform4fv(loc, 1, v); break;
case GL_FLOAT_MAT2 : glUniformMatrix2fv(loc, 1, GL_FALSE, v); break;
case GL_FLOAT_MAT3 : glUniformMatrix3fv(loc, 1, GL_FALSE, v); break;
case GL_FLOAT_MAT4 : glUniformMatrix4fv(loc, 1, GL_FALSE, v); break;
default : throw Exception("HdlProgram::setVar - Unknown variable type or type mismatch for \"" + getGLEnumNameSafe(t) + "\" when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
}
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::setVar - An error occurred when loading data of type \"" + getGLEnumNameSafe(t) + "\" in variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn void HdlProgram::setVar(const std::string& varName, const HdlDynamicData& data)
\brief Change a uniform variable in a shader. Raise an exception if any error occur.
\param varName Name of the fragment output variable.
\param data The dynamic object to be used as source.
**/
void HdlProgram::setVar(const std::string& varName, const HdlDynamicData& data)
{
use();
GLint loc = glGetUniformLocation(program, varName.c_str());
if(loc==-1)
throw Exception("HdlProgram::setVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
switch(data.getGLType())
{
case GL_BYTE : glUniform1i(loc, data.get(0)); break;
case GL_UNSIGNED_BYTE : glUniform1ui(loc, data.get(0)); break;
case GL_SHORT : glUniform1i(loc, data.get(0)); break;
case GL_UNSIGNED_SHORT : glUniform1ui(loc, data.get(0)); break;
case GL_FLOAT : glUniform1fv(loc, 1, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
case GL_FLOAT_VEC2 : glUniform2fv(loc, 1, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
case GL_FLOAT_VEC3 : glUniform3fv(loc, 1, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
case GL_FLOAT_VEC4 : glUniform4fv(loc, 1, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
#ifdef GLIP_USE_GL
case GL_DOUBLE : throw Exception("HdlProgram::setVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC2 : throw Exception("HdlProgram::setVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC3 : throw Exception("HdlProgram::setVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC4 : throw Exception("HdlProgram::setVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
#endif
case GL_INT : glUniform1iv(loc, 1, reinterpret_cast<const GLint*>(data.getPtr())); break;
case GL_INT_VEC2 : glUniform2iv(loc, 1, reinterpret_cast<const GLint*>(data.getPtr())); break;
case GL_INT_VEC3 : glUniform3iv(loc, 1, reinterpret_cast<const GLint*>(data.getPtr())); break;
case GL_INT_VEC4 : glUniform4iv(loc, 1, reinterpret_cast<const GLint*>(data.getPtr())); break;
case GL_UNSIGNED_INT : glUniform1uiv(loc, 1, reinterpret_cast<const GLuint*>(data.getPtr())); break;
case GL_UNSIGNED_INT_VEC2 : glUniform1uiv(loc, 1, reinterpret_cast<const GLuint*>(data.getPtr())); break;
case GL_UNSIGNED_INT_VEC3 : glUniform1uiv(loc, 1, reinterpret_cast<const GLuint*>(data.getPtr())); break;
case GL_UNSIGNED_INT_VEC4 : glUniform1uiv(loc, 1, reinterpret_cast<const GLuint*>(data.getPtr())); break;
case GL_BOOL : throw Exception("HdlProgram::setVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC2 : throw Exception("HdlProgram::setVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC3 : throw Exception("HdlProgram::setVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC4 : throw Exception("HdlProgram::setVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_FLOAT_MAT2 : glUniformMatrix2fv(loc, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
case GL_FLOAT_MAT3 : glUniformMatrix3fv(loc, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
case GL_FLOAT_MAT4 : glUniformMatrix4fv(loc, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(data.getPtr())); break;
default : throw Exception("HdlProgram::setVar - Unknown variable type or type mismatch for \"" + getGLEnumNameSafe(data.getGLType()) + "\" when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
}
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::setVar - An error occurred when loading data of type \"" + getGLEnumNameSafe(data.getGLType()) + "\" in variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn void HdlProgram::getVar(const std::string& varName, int* ptr)
\brief Read a uniform variable from a shader. Warning : this function does not perform any type or size check which might result in a buffer overflow if not used with care.
\param varName The name of the uniform variable to read from.
\param ptr A pointer to a buffer with sufficient size in order to contain the full object (scalar, vector, matrix...).
**/
void HdlProgram::getVar(const std::string& varName, int* ptr)
{
use();
GLint loc = glGetUniformLocation(program, varName.c_str());
if(loc==-1)
throw Exception("HdlProgram::getVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
glGetUniformiv(program, loc, ptr);
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::getVar - An error occurred when reading variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn void HdlProgram::getVar(const std::string& varName, unsigned int* ptr)
\brief Read a uniform variable from a shader. Warning : this function does not perform any type or size check which might result in a buffer overflow if not used with care.
\param varName The name of the uniform variable to read from.
\param ptr A pointer to a buffer with sufficient size in order to contain the full object (scalar, vector, matrix...).
**/
void HdlProgram::getVar(const std::string& varName, unsigned int* ptr)
{
use();
GLint loc = glGetUniformLocation(program, varName.c_str());
if(loc==-1)
throw Exception("HdlProgram::getVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
glGetUniformuiv(program, loc, ptr);
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::getVar - An error occurred when reading variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn void HdlProgram::getVar(const std::string& varName, float* ptr)
\brief Read a uniform variable from a shader. Warning : this function does not perform any type or size check which might result in a buffer overflow if not used with care.
\param varName The name of the uniform variable to read from.
\param ptr A pointer to a buffer with sufficient size in order to contain the full object (scalar, vector, matrix...).
**/
void HdlProgram::getVar(const std::string& varName, float* ptr)
{
GLint loc = glGetUniformLocation(program, varName.c_str());
if (loc==-1)
throw Exception("HdlProgram::getVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
glGetUniformfv(program, loc, ptr);
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::getVar - An error occurred when reading variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn void HdlProgram::getVar(const std::string& varName, HdlDynamicData& data)
\brief Read a uniform variable from a shader. Warning : this function does not perform any type or size check which might result in a buffer overflow if not used with care.
\param varName Name of the fragment output variable.
\param data The dynamic object to be used as target.
**/
void HdlProgram::getVar(const std::string& varName, HdlDynamicData& data)
{
GLint loc = glGetUniformLocation(program, varName.c_str());
if(loc==-1)
throw Exception("HdlProgram::getVar - Wrong location, does this var exist : \"" + varName + "\"? Is it used in the program? (May be the GLCompiler swapped it because it is unused).", __FILE__, __LINE__, Exception::GLException);
switch(data.getGLType())
{
case GL_BYTE : throw Exception("HdlProgram::getVar - Byte type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_UNSIGNED_BYTE : throw Exception("HdlProgram::getVar - Unsigned Byte type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_SHORT : throw Exception("HdlProgram::getVar - Short type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_UNSIGNED_SHORT : throw Exception("HdlProgram::getVar - Unsigned Short type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_FLOAT :
case GL_FLOAT_VEC2 :
case GL_FLOAT_VEC3 :
case GL_FLOAT_VEC4 : glGetUniformfv(program, loc, reinterpret_cast<GLfloat*>(data.getPtr())); break;
#ifdef GLIP_USE_GL
case GL_DOUBLE : throw Exception("HdlProgram::getVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC2 : throw Exception("HdlProgram::getVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC3 : throw Exception("HdlProgram::getVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_DOUBLE_VEC4 : throw Exception("HdlProgram::getVar - Double type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
#endif
case GL_INT :
case GL_INT_VEC2 :
case GL_INT_VEC3 :
case GL_INT_VEC4 : glGetUniformiv(program, loc, reinterpret_cast<GLint*>(data.getPtr())); break;
case GL_UNSIGNED_INT :
case GL_UNSIGNED_INT_VEC2 :
case GL_UNSIGNED_INT_VEC3 :
case GL_UNSIGNED_INT_VEC4 : glGetUniformuiv(program, loc, reinterpret_cast<GLuint*>(data.getPtr())); break;
case GL_BOOL : throw Exception("HdlProgram::getVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC2 : throw Exception("HdlProgram::getVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC3 : throw Exception("HdlProgram::getVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_BOOL_VEC4 : throw Exception("HdlProgram::getVar - Bool type not supported when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
case GL_FLOAT_MAT2 :
case GL_FLOAT_MAT3 :
case GL_FLOAT_MAT4 : glGetUniformfv(program, loc, reinterpret_cast<GLfloat*>(data.getPtr())); break;
default : throw Exception("HdlProgram::getVar - Unknown variable type or type mismatch for \"" + getGLEnumNameSafe(data.getGLType()) + "\" when modifying uniform variable \"" + varName + "\".", __FILE__, __LINE__, Exception::GLException);
}
const GLenum err = glGetError();
if(err!=GL_NO_ERROR)
throw Exception("HdlProgram::getVar - An error occurred when reading variable \"" + varName + "\" : " + getGLEnumNameSafe(err) + " - " + getGLErrorDescription(err), __FILE__, __LINE__, Exception::GLException);
}
/**
\fn bool HdlProgram::isUniformVariableValid(const std::string& varName)
\brief Check if a variable is valid from its name.
\param varName The name of the uniform variable to read from.
\return True if the name is valid (see glGetUniformLocation at http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml) or false otherwise.
**/
bool HdlProgram::isUniformVariableValid(const std::string& varName)
{
if(program==0)
return false;
else
return glGetUniformLocation(program, varName.c_str()) != -1;
}
// Static tools :
/**
\fn int HdlProgram::maxVaryingVar(void)
\brief Returns the maximum number of varying variables available.
\return The maximum number of varying variables.
**/
int HdlProgram::maxVaryingVar(void)
{
#ifdef GLIP_USE_GL
GLint param;
glGetIntegerv(GL_MAX_VARYING_FLOATS, ¶m);
#ifdef __GLIPLIB_TRACK_GL_ERRORS__
OPENGL_ERROR_TRACKER("HdlProgram::maxVaryingVar", "glGetIntegerv()")
#endif
return param;
#else
return 0;
#endif
}
/**
\fn void HdlProgram::stopProgram(void)
\brief Stop using a program
**/
void HdlProgram::stopProgram(void)
{
glUseProgram(0);
}
| 45.711563 | 427 | 0.690507 | [
"object",
"vector"
] |
a10c78cc805dd31e7382045607e2b4098f7d20e1 | 4,686 | hpp | C++ | Programming Guide/Headers/Siv3D/BinaryWriter.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 38 | 2016-01-14T13:51:13.000Z | 2021-12-29T01:49:30.000Z | Programming Guide/Headers/Siv3D/BinaryWriter.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | null | null | null | Programming Guide/Headers/Siv3D/BinaryWriter.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 16 | 2016-01-15T11:07:51.000Z | 2021-12-29T01:49:37.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <memory>
# include <array>
# include "Fwd.hpp"
# include "IWriter.hpp"
# include "Array.hpp"
# include "ByteArray.hpp"
# include "FileSystem.hpp"
namespace s3d
{
/// <summary>
/// 書き込み用バイナリファイル
/// </summary>
class BinaryWriter : public IWriter
{
private:
class CBinaryWriter;
std::shared_ptr<CBinaryWriter> pImpl;
public:
/// <summary>
/// デフォルトコンストラクタ
/// </summary>
BinaryWriter();
/// <summary>
/// 書き込み用のバイナリファイルを開きます。
/// </summary>
/// <param name="path">
/// ファイルパス
/// </param>
/// <param name="mode">
/// オープンモード
/// </param>
explicit BinaryWriter(const FilePath& path, OpenMode mode = OpenMode::Trunc);
/// <summary>
/// デストラクタ
/// </summary>
~BinaryWriter() = default;
/// <summary>
/// 書き込み用のバイナリファイルを開きます。
/// </summary>
/// <param name="path">
/// ファイルパス
/// </param>
/// <param name="mode">
/// オープンモード
/// </param>
/// <returns>
/// ファイルのオープンに成功した場合 true, それ以外の場合は false
/// </returns>
bool open(const FilePath& path, OpenMode mode = OpenMode::Trunc);
/// <summary>
/// バイナリファイルの書き込みバッファをフラッシュします。
/// </summary>
/// <returns>
/// なし
/// </returns>
void flush();
/// <summary>
/// バイナリファイルをクローズします。
/// </summary>
/// <returns>
/// なし
/// </returns>
void close();
/// <summary>
/// バイナリファイルがオープンされているかを返します。
/// </summary>
/// <returns>
/// ファイルがオープンされている場合 true, それ以外の場合は false
/// </returns>
bool isOpened() const override;
/// <summary>
/// バイナリファイルがオープンされているかを返します。
/// </summary>
/// <returns>
/// ファイルがオープンされている場合 true, それ以外の場合は false
/// </returns>
explicit operator bool() const { return isOpened(); }
/// <summary>
/// 現在開いているファイルの内容を消去し、書き込み位置を先頭に戻します。
/// </summary>
/// <returns>
/// なし
/// </returns>
void clear();
/// <summary>
/// バイナリファイルのサイズを返します。
/// </summary>
/// <returns>
/// バイナリファイルのサイズ(バイト)
/// </returns>
int64 size() const override;
/// <summary>
/// 現在の書き込み位置を返します。
/// </summary>
/// <returns>
/// 現在の書き込み位置(バイト)
/// </returns>
int64 getPos() const override;
/// <summary>
/// 書き込み位置を変更します。
/// </summary>
/// <param name="pos">
/// 新しい書き込み位置(バイト)
/// </param>
/// <returns>
/// 書き込み位置の変更に成功した場合 true, それ以外の場合は false
/// </returns>
bool setPos(int64 pos) override;
/// <summary>
/// 書き込み位置を終端に移動します。
/// </summary>
/// <returns>
/// 新しい書き込み位置(バイト)
/// </returns>
int64 seekEnd();
/// <summary>
/// ファイルにデータを書き込みます。
/// </summary>
/// <param name="buffer">
/// 書き込むデータ
/// </param>
/// <param name="size">
/// 書き込むサイズ(バイト)
/// </param>
/// <returns>
/// 実際に書き込んだサイズ(バイト)
/// </returns>
size_t write(_In_reads_bytes_(size) const void* buffer, size_t size) override;
/// <summary>
/// ファイルにデータを書き込みます。
/// </summary>
/// <param name="src">
/// 書き込むデータ
/// </param>
/// <returns>
/// 実際に書き込んだサイズ(バイト)
/// </returns>
template <class Type>
size_t write(const Type& src)
{
static_assert(std::is_trivially_copyable<Type>::value, "Type must be trivially copyable");
return write(&src, sizeof(Type));
}
/// <summary>
/// ファイルにデータを書き込みます。
/// </summary>
/// <param name="ilist">
/// 書き込むデータ
/// </param>
/// <returns>
/// 実際に書き込んだサイズ(バイト)
/// </returns>
template <class Type>
size_t write(std::initializer_list<Type> ilist)
{
static_assert(std::is_trivially_copyable<Type>::value, "Type must be trivially copyable");
size_t result = 0;
for (const auto& elem : ilist)
{
result += write(elem);
}
return result;
}
/// <summary>
/// ファイルにデータを書き込みます。
/// </summary>
/// <param name="src">
/// 書き込むデータ
/// </param>
/// <returns>
/// 実際に書き込んだサイズ(バイト)
/// </returns>
template <class Type>
size_t write(const std::vector<Type>& src)
{
static_assert(std::is_trivially_copyable<Type>::value, "Type must be trivially copyable");
return src.empty() ? 0 : write(src.data(), src.size()*sizeof(Type));
}
/// <summary>
/// ファイルにデータを書き込みます。
/// </summary>
/// <param name="src">
/// 書き込むデータ
/// </param>
/// <returns>
/// 実際に書き込んだサイズ(バイト)
/// </returns>
size_t write(const ByteArray& src)
{
return src.size() ? write(src.data(), static_cast<size_t>(src.size())) : 0;
}
/// <summary>
/// オープンしているファイルのパスを返します。
/// </summary>
/// <remarks>
/// クローズしている場合は空の文字列です。
/// </remarks>
FilePath path() const;
};
}
| 19.689076 | 93 | 0.569569 | [
"vector"
] |
a10d5dd676a34c6b3a23d83401a8e6cf4a2897d1 | 31,016 | cpp | C++ | test/narrowphase/detail/primitive_shape_algorithm/test_sphere_box.cpp | haraisao/fcl | 6d008b63b801a2c85435c4ae959c28d7538ad270 | [
"BSD-3-Clause"
] | 2 | 2021-07-24T13:02:02.000Z | 2021-07-28T03:05:32.000Z | test/narrowphase/detail/primitive_shape_algorithm/test_sphere_box.cpp | haraisao/fcl | 6d008b63b801a2c85435c4ae959c28d7538ad270 | [
"BSD-3-Clause"
] | null | null | null | test/narrowphase/detail/primitive_shape_algorithm/test_sphere_box.cpp | haraisao/fcl | 6d008b63b801a2c85435c4ae959c28d7538ad270 | [
"BSD-3-Clause"
] | 1 | 2021-06-01T10:42:22.000Z | 2021-06-01T10:42:22.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2018. Toyota Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of CNRS-LAAS and AIST nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** @author Sean Curtis (sean@tri.global) (2018) */
// Tests the custom sphere-box tests: distance and collision.
#include "fcl/narrowphase/detail/primitive_shape_algorithm/sphere_box-inl.h"
#include <string>
#include <gtest/gtest.h>
#include "eigen_matrix_compare.h"
#include "fcl/geometry/shape/box.h"
#include "fcl/geometry/shape/sphere.h"
namespace fcl {
namespace detail {
namespace {
// In the worst case (with arbitrary frame orientations) it seems like I'm
// losing about 4 bits of precision in the solution (compared to performing
// the equivalent query without any rotations). This encodes that bit loss to
// an epsilon value appropriate to the scalar type.
template <typename S>
struct Eps {
using Real = typename constants<S>::Real;
static Real value() { return 16 * constants<S>::eps(); }
};
// NOTE: The version of Eigen in travis CI seems to be using code that when
// evaluating: X_FB.inverse() * X_FS ends up doing the equivalent of multiplying
// two 4x4 matrices (rather than exploiting the compact affine representation).
// As such, it leaks a slightly more error into the computation and this extra
// padding accounts for CI peculiarity.
template <>
struct Eps<float> {
using Real = constants<float>::Real;
static Real value() { return 20 * constants<float>::eps(); }
};
// Utility function for evaluating points inside boxes. Tests various
// configurations of points and boxes.
template <typename S> void NearestPointInBox() {
// Picking sizes that are *not* powers of two and *not* uniform in size.
Box<S> box{S(0.6), S(1.2), S(3.6)};
Vector3<S> p_BN;
Vector3<S> p_BQ;
// Case: query point at origin.
p_BQ << 0, 0, 0;
bool N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_FALSE(N_is_not_C);
EXPECT_TRUE(CompareMatrices(p_BN, p_BQ, 0, MatrixCompareType::absolute));
Vector3<S> half_size = box.side * 0.5;
// Per-octant tests:
for (S x : {-1, 1}) {
for (S y : {-1, 1}) {
for (S z : {-1, 1}) {
Vector3<S> quadrant{x, y, z};
// Case: point inside (no clamped values).
p_BQ = quadrant.cwiseProduct(half_size * 0.5);
N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_FALSE(N_is_not_C);
EXPECT_TRUE(
CompareMatrices(p_BN, p_BQ, 0, MatrixCompareType::absolute));
// For each axis:
for (int axis : {0, 1, 2}) {
// Case: one direction clamped.
Vector3<S> scale{0.5, 0.5, 0.5};
scale(axis) = 1.5;
p_BQ = quadrant.cwiseProduct(half_size.cwiseProduct(scale));
N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_TRUE(N_is_not_C);
for (int i : {0, 1, 2}) {
if (i == axis)
EXPECT_EQ(p_BN(i), quadrant(i) * half_size(i));
else
EXPECT_EQ(p_BN(i), p_BQ(i));
}
// Case: One direction unclamped.
scale << 1.5, 1.5, 1.5;
scale(axis) = 0.5;
p_BQ = quadrant.cwiseProduct(half_size.cwiseProduct(scale));
N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_TRUE(N_is_not_C);
for (int i : {0, 1, 2}) {
if (i == axis)
EXPECT_EQ(p_BN(i), p_BQ(i));
else
EXPECT_EQ(p_BN(i), quadrant(i) * half_size(i));
}
// Case: query point on face in axis direction -- unclamped.
scale << 0.5, 0.5, 0.5;
scale(axis) = 1.0;
p_BQ = quadrant.cwiseProduct(half_size.cwiseProduct(scale));
N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_FALSE(N_is_not_C);
EXPECT_TRUE(
CompareMatrices(p_BN, p_BQ, 0, MatrixCompareType::absolute));
}
// Case: external point in Voronoi region of corner (all axes clamped).
p_BQ = quadrant.cwiseProduct(half_size * 1.5);
N_is_not_C = nearestPointInBox(box.side, p_BQ, &p_BN);
EXPECT_TRUE(N_is_not_C);
for (int i : {0, 1, 2})
EXPECT_EQ(p_BN(i), quadrant(i) * half_size(i));
}
}
}
}
// Defines the test configuration for a single test. It includes the geometry
// and the pose of the sphere in the box's frame B. It also includes the
// expected answers in that same frame. It does not include those quantities
// that vary from test invocation to invocation (e.g., the pose of the box in
// the world frame or the *orientation* of the sphere).
//
// Collision and distance are complementary queries -- two objects in collision
// have no defined distance because they are *not* separated and vice versa.
// These configurations allow for the test of the complementarity property.
template <typename S>
struct TestConfiguration {
TestConfiguration(const std::string& name_in, const Vector3<S>& half_size_in,
S radius, const Vector3<S>& p_BSo_in, bool colliding)
: name(name_in), half_size(half_size_in), r(radius), p_BSo(p_BSo_in),
expected_colliding(colliding) {}
// Descriptive name of the test configuration.
std::string name;
// The half size of the axis-aligned, origin-centered box.
Vector3<S> half_size;
// Radius of the sphere.
S r;
// Position of the sphere's center in the box frame.
Vector3<S> p_BSo;
// Indicates if this test configuration is expected to be in collision.
bool expected_colliding{false};
// Collision values; only valid if expected_colliding is true.
S expected_depth{-1};
Vector3<S> expected_normal;
Vector3<S> expected_pos;
// Distance values; only valid if expected_colliding is false.
S expected_distance{-1};
// The points on sphere and box, respectively, closest to the others measured
// and expressed in the box frame B. Only defined if separated.
Vector3<S> expected_p_BSb;
Vector3<S> expected_p_BBs;
};
// Utility for creating a copy of the input configurations and appending more
// labels to the configuration name -- aids in debugging.
template <typename S>
std::vector<TestConfiguration<S>> AppendLabel(
const std::vector<TestConfiguration<S>>& configurations,
const std::string& label) {
std::vector<TestConfiguration<S>> configs;
for (const auto& config : configurations) {
configs.push_back(config);
configs.back().name += " - " + label;
}
return configs;
}
// Returns a collection of configurations where sphere and box are uniformly
// scaled.
template <typename S>
std::vector<TestConfiguration<S>> GetUniformConfigurations() {
// Common configuration values
// Box and sphere dimensions.
const S w = 0.6;
const S d = 1.2;
const S h = 3.6;
const S r = 0.7;
const Vector3<S> half_size{w / 2, d / 2, h / 2};
const bool collides = true;
std::vector<TestConfiguration<S>> configurations;
{
// Case: Completely separated. Nearest point on the +z face.
const Vector3<S> p_BS{half_size(0) * S(0.5), half_size(1) * S(0.5),
half_size(2) + r * S(1.1)};
configurations.emplace_back(
"Separated; nearest face +z", half_size, r, p_BS, !collides);
// Not colliding --> no collision values.
TestConfiguration<S>& config = configurations.back();
config.expected_distance = p_BS(2) - half_size(2) - r;
config.expected_p_BBs = Vector3<S>{p_BS(0), p_BS(1), half_size(2)};
config.expected_p_BSb = Vector3<S>{p_BS(0), p_BS(1), p_BS(2) - r};
}
{
// Case: Sphere completely separated with center in vertex Voronoi region.
const Vector3<S> p_BS = half_size + Vector3<S>{r, r, r} * S(1.25);
configurations.emplace_back(
"Separated; nearest +x, +y, +z corner", half_size, r, p_BS, !collides);
// Not colliding --> no collision values.
TestConfiguration<S>& config = configurations.back();
// position vector from sphere center (S) to nearest point on box (N).
const Vector3<S> r_SN = half_size - p_BS;
const S len_r_SN = r_SN.norm();
config.expected_distance = len_r_SN - r;
config.expected_p_BBs = half_size;
config.expected_p_BSb = p_BS + r_SN * (r / len_r_SN);
}
// Case: Intersection with the sphere center *outside* the box.
// Subcase: sphere in face voronoi region -- normal should be in face
// direction.
// Intersects the z+ face with a depth of half the radius and a normal in the
// -z direction.
{
const S target_depth = r * 0.5;
const Vector3<S> p_BS{half_size + Vector3<S>{0, 0, r - target_depth}};
configurations.emplace_back(
"Colliding: center outside, center projects onto +z face", half_size, r,
p_BS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos = Vector3<S>{p_BS(0), p_BS(1), (h - target_depth) / 2};
// Colliding; no distance values required.
}
// Subcase: sphere in vertex Voronoi region -- normal should be in the
// direction from sphere center to box corner.
{
const S target_depth = r * 0.5;
const Vector3<S> n_SB_B = Vector3<S>(-1, -2, -3).normalized();
const Vector3<S> p_BS = half_size - n_SB_B * (r - target_depth);
configurations.emplace_back(
"Colliding: center outside, center nearest +x, +y, +z vertex",
half_size, r, p_BS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = target_depth;
config.expected_normal = n_SB_B;
config.expected_pos = half_size + n_SB_B * (target_depth * 0.5);
// Colliding; no distance values required.
}
// Case: Intersection with the sphere center *inside* the box. We create six
// tests; one for each face of the box. The center will be closest to the
// target face. For the target face f, the normal should be in the -fₙ
// direction (fₙ = normal of face f), the penetration depth is
// radius plus distance to face, and the position is half the penetration
// depth from the face in the -fₙ direction.
// The distance to the face f will be some value less than the smallest half
// size to guarantee no confusion regarding different dimensions.
const std::string axis_name[] = {"x", "y", "z"};
const S center_inset = half_size.minCoeff() * 0.5;
for (int axis = 0; axis < 3; ++axis) {
for (int sign : {-1, 1}) {
const Vector3<S> dir = sign * Vector3<S>::Unit(axis);
const Vector3<S> p_BS = dir * (center_inset - half_size(axis));
configurations.emplace_back(
"Colliding: center inside, center nearest " +
std::string(sign > 0 ? "+" : "-") + axis_name[axis] + " face",
half_size, r, p_BS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = center_inset + r;
config.expected_normal = dir;
config.expected_pos = dir * ((r + center_inset) / 2 - half_size(axis));
// Colliding; no distance values required.
}
}
// TODO(SeanCurtis-TRI): Consider pushing the point off the face by less than
// epsilon.
// Sub-case: Sphere center lies on face.
{
const Vector3<S> p_BS{S(0.), S(0.), half_size(2)};
configurations.emplace_back("Sphere center lies on +z face", half_size, r,
p_BS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos << p_BS(0), p_BS(1), p_BS(2) - r / 2;
}
// Sub-case: Sphere center lies on corner.
{
// Alias the half_size as the coordinate of the +x, +y, +z corner.
const Vector3<S>& p_BS = half_size;
configurations.emplace_back("Sphere center lies on +x, +y, +z corner",
half_size, r, p_BS, collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = r;
// Sphere center is equidistant to three faces (+x, +y, +z). As documented,
// in this case, the +x face is selected (by aribtrary priority) and the
// normal points *into* that face.
config.expected_normal = -Vector3<S>::UnitX();
config.expected_pos << p_BS(0) - r / 2, p_BS(1), p_BS(2);
}
// Case: Sphere and box origins are coincident.
// Coincident centers subcase: The box is a cube, so the all directions
// produce the same minimum dimension; normal should point in the -x
// direction.
{
configurations.emplace_back(
"Sphere and cube origins coincident", Vector3<S>{10, 10, 10}, 5,
Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitX();
config.expected_pos << 2.5, 0, 0;
}
// Coincident centers subcase: Box height and depth are equal and smaller than
// width; the normal should point in the negative x-direction.
{
configurations.emplace_back(
"Sphere and box coincident - x & z are minimum dimension",
Vector3<S>{10, 15, 10}, 5, Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitX();
config.expected_pos << 2.5, 0, 0;
}
// Coincident centers subcase: Box width is the smallest dimension; the normal
// should point in the negative x-direction.
{
configurations.emplace_back(
"Sphere and box coincident - x is minimum dimension",
Vector3<S>{10, 12, 14}, 5, Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitX();
config.expected_pos << 2.5, 0, 0;
}
// Coincident centers subcase: Box height and depth are equal and smaller than
// width; the normal should point in the negative y-direction.
{
configurations.emplace_back(
"Sphere and box coincident - y & z are minimum dimension",
Vector3<S>{15, 10, 10}, 5, Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitY();
config.expected_pos << 0, 2.5, 0;
}
// Coincident centers subcase: Box depth is the smallest dimension; the normal
// should point in the negative y-direction.
{
configurations.emplace_back(
"Sphere and box coincident - y is minimum dimension",
Vector3<S>{15, 10, 14}, 5, Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitY();
config.expected_pos << 0, 2.5, 0;
}
// Coincident centers subcase: Box height is the smallest dimension; the
// normal should point in the negative z-direction.
{
configurations.emplace_back(
"Sphere and box coincident - z is minimum dimension",
Vector3<S>{15, 12, 10}, 5, Vector3<S>::Zero(), collides);
TestConfiguration<S>& config = configurations.back();
config.expected_depth = 15;
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_pos << 0, 0, 2.5;
}
return configurations;
}
// Returns a collection of configurations where sphere and box are scaled
// very differently.
template <typename S>
std::vector<TestConfiguration<S>> GetNonUniformConfigurations() {
std::vector<TestConfiguration<S>> configurations;
{
// Case: long "skinny" box and tiny sphere. Nearest feature is the +z face.
const Vector3<S> half_size(15, 1, 1);
const S r = 0.01;
{
// Subcase: colliding.
const Vector3<S> p_BS{half_size(0) * S(0.95), S(0.),
half_size(2) + r * S(0.5)};
configurations.emplace_back("Long, skinny box collides with small sphere",
half_size, r, p_BS, true /* colliding */);
TestConfiguration<S>& config = configurations.back();
config.expected_normal = -Vector3<S>::UnitZ();
config.expected_depth = r - (p_BS(2) - half_size(2));
config.expected_pos =
Vector3<S>{p_BS(0), p_BS(1),
half_size(2) - config.expected_depth / 2};
}
{
// Subcase: not-colliding.
const S distance = r * 0.1;
const Vector3<S> p_BS{half_size(0) * S(0.95), S(0.),
half_size(2) + r + distance};
configurations.emplace_back(
"Long, skinny box *not* colliding with small sphere", half_size,
r, p_BS, false /* not colliding */);
TestConfiguration<S>& config = configurations.back();
config.expected_distance = distance;
config.expected_p_BSb = p_BS - Vector3<S>{0, 0, r};
config.expected_p_BBs << p_BS(0), p_BS(1), half_size(2);
}
}
{
// Case: Large sphere collides with small box. Nearest feature is the +x,
// +y, +z corner.
const Vector3<S> half_size(0.1, 0.15, 0.2);
const S r = 10;
const Vector3<S> n_SB = Vector3<S>{-1, -2, -3}.normalized();
{
// Subcase: colliding.
S target_depth = half_size.minCoeff() * 0.5;
const Vector3<S> p_BS = half_size - n_SB * (r - target_depth);
configurations.emplace_back("Large sphere colliding with tiny box",
half_size, r, p_BS, true /* colliding */);
TestConfiguration<S>& config = configurations.back();
config.expected_normal = n_SB;
config.expected_depth = target_depth;
config.expected_pos = half_size + n_SB * (target_depth * 0.5);
}
{
// Subcase: not colliding.
S distance = half_size.minCoeff() * 0.1;
const Vector3<S> p_BS = half_size - n_SB * (r + distance);
configurations.emplace_back(
"Large sphere *not* colliding with tiny box", half_size,
r, p_BS, false /* not colliding */);
TestConfiguration<S>& config = configurations.back();
config.expected_distance = distance;
config.expected_p_BSb = p_BS + n_SB * r;
config.expected_p_BBs = half_size;
}
}
return configurations;
}
template <typename S>
using EvalFunc =
std::function<void(const TestConfiguration<S> &, const Transform3<S> &,
const Matrix3<S> &, S)>;
// This evaluates an instance of a test configuration and confirms the results
// match the expected data. The test configuration is defined in the box's
// frame with an unrotated sphere. The parameters provide the test
// configuration, an pose of the box's frame in the world frame.
//
// Evaluates the collision query twice. Once as the boolean "is colliding" test
// and once with the collision characterized with depth, normal, and position.
template <typename S>
void EvalCollisionForTestConfiguration(const TestConfiguration<S>& config,
const Transform3<S>& X_WB,
const Matrix3<S>& R_SB,
S eps) {
// Set up the experiment from input parameters and test configuration.
Box<S> box{config.half_size * 2};
Sphere<S> sphere{config.r};
Transform3<S> X_BS = Transform3<S>::Identity();
X_BS.translation() = config.p_BSo;
X_BS.linear() = R_SB;
Transform3<S> X_WS = X_WB * X_BS;
bool colliding = sphereBoxIntersect<S>(sphere, X_WS, box, X_WB, nullptr);
EXPECT_EQ(colliding, config.expected_colliding) << config.name;
std::vector<ContactPoint<S>> contacts;
colliding = sphereBoxIntersect<S>(sphere, X_WS, box, X_WB, &contacts);
EXPECT_EQ(colliding, config.expected_colliding) << config.name;
if (config.expected_colliding) {
EXPECT_EQ(contacts.size(), 1u) << config.name;
const ContactPoint<S>& contact = contacts[0];
EXPECT_NEAR(contact.penetration_depth, config.expected_depth, eps)
<< config.name;
EXPECT_TRUE(CompareMatrices(contact.normal,
X_WB.linear() * config.expected_normal, eps,
MatrixCompareType::absolute))
<< config.name;
EXPECT_TRUE(CompareMatrices(contact.pos, X_WB * config.expected_pos, eps,
MatrixCompareType::absolute))
<< config.name;
} else {
EXPECT_EQ(contacts.size(), 0u) << config.name;
}
}
// This evaluates an instance of a test configuration and confirms the results
// match the expected data. The test configuration is defined in the box's
// frame with an unrotated sphere. The parameters provide the test
// configuration.
//
// Evaluates the distance query twice. Once as the boolean "is separated" test
// and once with the separation characterized with distance and surface points.
template <typename S>
void EvalDistanceForTestConfiguration(const TestConfiguration<S>& config,
const Transform3<S>& X_WB,
const Matrix3<S>& R_SB,
S eps) {
// Set up the experiment from input parameters and test configuration.
Box<S> box{config.half_size * 2};
Sphere<S> sphere{config.r};
Transform3<S> X_BS = Transform3<S>::Identity();
X_BS.translation() = config.p_BSo;
X_BS.linear() = R_SB;
Transform3<S> X_WS = X_WB * X_BS;
bool separated = sphereBoxDistance<S>(sphere, X_WS, box, X_WB, nullptr,
nullptr, nullptr);
EXPECT_NE(separated, config.expected_colliding) << config.name;
// Initializing this to -2, to confirm that a non-colliding scenario sets
// distance to -1.
S distance{-2};
Vector3<S> p_WSb{0, 0, 0};
Vector3<S> p_WBs{0, 0, 0};
separated =
sphereBoxDistance<S>(sphere, X_WS, box, X_WB, &distance, &p_WSb, &p_WBs);
EXPECT_NE(separated, config.expected_colliding) << config.name;
if (!config.expected_colliding) {
EXPECT_NEAR(distance, config.expected_distance, eps)
<< config.name;
EXPECT_TRUE(CompareMatrices(p_WSb,
X_WB * config.expected_p_BSb, eps,
MatrixCompareType::absolute))
<< config.name;
EXPECT_TRUE(CompareMatrices(p_WBs,
X_WB * config.expected_p_BBs, eps,
MatrixCompareType::absolute))
<< config.name;
} else {
EXPECT_EQ(distance, S(-1)) << config.name;
EXPECT_TRUE(CompareMatrices(p_WSb, Vector3<S>::Zero(), 0,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(p_WBs, Vector3<S>::Zero(), 0,
MatrixCompareType::absolute));
}
}
// This test defines the transforms for performing the single collision test.
template <typename S>
void QueryWithVaryingWorldFrames(
const std::vector<TestConfiguration<S>>& configurations,
EvalFunc<S> query_eval, const Matrix3<S>& R_BS = Matrix3<S>::Identity()) {
// Evaluate all the configurations with the given box pose in frame F.
auto evaluate_all = [&R_BS, query_eval](
const std::vector<TestConfiguration<S>>& configs,
const Transform3<S>& X_FB) {
for (const auto config : configs) {
query_eval(config, X_FB, R_BS, Eps<S>::value());
}
};
// Frame F is the box frame.
Transform3<S> X_FB = Transform3<S>::Identity();
evaluate_all(AppendLabel(configurations, "X_FB = I"), X_FB);
// Simple arbitrary translation away from the origin.
X_FB.translation() << 1.3, 2.7, 6.5;
evaluate_all(AppendLabel(configurations, "X_FB is translation"), X_FB);
std::string axis_name[] = {"x", "y", "z"};
// 90 degree rotation around each axis.
for (int axis = 0; axis < 3; ++axis) {
std::string label = "X_FB is 90-degree rotation around " + axis_name[axis];
AngleAxis<S> angle_axis{constants<S>::pi() / 2, Vector3<S>::Unit(axis)};
X_FB.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, label), X_FB);
}
// Arbitrary orientation.
{
AngleAxis<S> angle_axis{constants<S>::pi() / 3,
Vector3<S>{1, 2, 3}.normalized()};
X_FB.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, "X_FB is arbitrary rotation"),
X_FB);
}
// Near axis aligned.
{
AngleAxis<S> angle_axis{constants<S>::eps_12(), Vector3<S>::UnitX()};
X_FB.linear() << angle_axis.matrix();
evaluate_all(AppendLabel(configurations, "X_FB is near identity"),
X_FB);
}
}
// Runs all test configurations across multiple poses in the world frame --
// changing the orientation of the sphere -- should have no affect on the
// results.
template <typename S>
void QueryWithOrientedSphere(
const std::vector<TestConfiguration<S>>& configurations,
EvalFunc<S> query_eval) {
std::string axis_name[] = {"x", "y", "z"};
// 90 degree rotation around each axis.
for (int axis = 0; axis < 3; ++axis) {
AngleAxis<S> angle_axis{constants<S>::pi() / 2, Vector3<S>::Unit(axis)};
std::string label = "sphere rotate 90-degrees around " + axis_name[axis];
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
// Arbitrary orientation.
{
AngleAxis<S> angle_axis{constants<S>::pi() / 3,
Vector3<S>{1, 2, 3}.normalized()};
std::string label = "sphere rotated arbitrarily";
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
// Near axis aligned.
{
AngleAxis<S> angle_axis{constants<S>::eps_12(), Vector3<S>::UnitX()};
std::string label = "sphere rotated near axes";
QueryWithVaryingWorldFrames<S>(AppendLabel(configurations, label),
query_eval, angle_axis.matrix());
}
}
//======================================================================
// Tests the helper function that finds the closest point in the box.
GTEST_TEST(SphereBoxPrimitiveTest, NearestPointInBox) {
NearestPointInBox<float>();
NearestPointInBox<double>();
}
// Evaluates collision on all test configurations across multiple poses in the
// world frame - but the sphere rotation is always the identity.
GTEST_TEST(SphereBoxPrimitiveTest, CollisionAcrossVaryingWorldFrames) {
QueryWithVaryingWorldFrames<float>(GetUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(GetUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates collision on all test configurations across multiple poses in the
// world frame - the sphere is rotated arbitrarily.
GTEST_TEST(SphereBoxPrimitiveTest, CollisionWithSphereRotations) {
QueryWithOrientedSphere<float>(GetUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithOrientedSphere<double>(GetUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates collision on a small set of configurations where the box and scale
// are of radically different scales - evaluation across multiple poses in the
// world frame.
GTEST_TEST(SphereBoxPrimitiveTest, CollisionIncompatibleScales) {
QueryWithVaryingWorldFrames<float>(GetNonUniformConfigurations<float>(),
EvalCollisionForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(
GetNonUniformConfigurations<double>(),
EvalCollisionForTestConfiguration<double>);
}
// Evaluates distance on all test configurations across multiple poses in the
// world frame - but the sphere rotation is always the identity.
GTEST_TEST(SphereBoxPrimitiveTest, DistanceAcrossVaryingWorldFrames) {
QueryWithVaryingWorldFrames<float>(GetUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(GetUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
// Evaluates distance on all test configurations across multiple poses in the
// world frame - the sphere is rotated arbitrarily.
GTEST_TEST(SphereBoxPrimitiveTest, DistanceWithSphereRotations) {
QueryWithOrientedSphere<float>(GetUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithOrientedSphere<double>(GetUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
// Evaluates distance on a small set of configurations where the box and scale
// are of radically different scales - evaluation across multiple poses in the
// world frame.
GTEST_TEST(SphereBoxPrimitiveTest, DistanceIncompatibleScales) {
QueryWithVaryingWorldFrames<float>(GetNonUniformConfigurations<float>(),
EvalDistanceForTestConfiguration<float>);
QueryWithVaryingWorldFrames<double>(GetNonUniformConfigurations<double>(),
EvalDistanceForTestConfiguration<double>);
}
} // namespace
} // namespace detail
} // namespace fcl
//==============================================================================
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 41.354667 | 80 | 0.656113 | [
"geometry",
"shape",
"vector"
] |
e161f4044b5b82e9d95b9226fd2b412783e47fe0 | 2,246 | cc | C++ | src/math/cholesky.cc | obs145628/ai-cpp | 32ff9365e0d3a36d219352ee6e3a01e62c633cc9 | [
"MIT"
] | null | null | null | src/math/cholesky.cc | obs145628/ai-cpp | 32ff9365e0d3a36d219352ee6e3a01e62c633cc9 | [
"MIT"
] | null | null | null | src/math/cholesky.cc | obs145628/ai-cpp | 32ff9365e0d3a36d219352ee6e3a01e62c633cc9 | [
"MIT"
] | null | null | null | #include "math/cholesky.hh"
#include <cassert>
#include <cmath>
#include "math/gauss.hh"
#include "math/vlist.hh"
Matrix Cholesky::ll(const Matrix& a)
{
assert(a.rows() == a.cols());
std::size_t n = a.rows();
auto l = Matrix::null(n, n);
for (std::size_t j = 0; j < n; ++j)
{
double val = a.at(j, j);
for (std::size_t k = 0; k < j; ++k)
val -= l.at(j, k) * l.at(j, k);
l.at(j, j) = std::sqrt(val);
for (std::size_t i = j + 1; i < n; ++i)
{
double val = a.at(i, j);
for (std::size_t k = 0; k < j; ++k)
val -= l.at(i, k) * l.at(j, k);
l.at(i, j) = val / l.at(j, j);
}
}
return l;
}
Vector Cholesky::system(const Matrix& a, const Vector& b)
{
assert(a.rows() == a.cols());
assert(a.rows() == b.size());
Matrix l = ll(a);
Vector y = Gauss::system_lower(l, b);
Vector x = Gauss::system_upper(l.transpose(), y);
return x;
}
Matrix Cholesky::systems(const Matrix& a, const Matrix& b)
{
assert(a.rows() == a.cols());
assert(a.rows() == b.rows());
Matrix res(b.rows(), b.cols());
for (std::size_t i = 0; i < b.cols(); ++i)
{
Vector bi = VList::col_to_vec(b, i);
Vector xi = system(a, bi);
VList::col_set(res, i, xi);
}
return res;
}
Matrix Cholesky::inverse(const Matrix& a)
{
assert(a.rows() == a.cols());
return systems(a, Matrix::id(a.rows()));
}
double Cholesky::det(const Matrix& a)
{
assert(a.rows() == a.cols());
Matrix l = ll(a);
double res = 1;
for (std::size_t i = 0; i < a.rows(); ++i)
res *= l.at(i, i);
return res * res;
}
Cholesky::ldl_t Cholesky::ldl(const Matrix& a)
{
assert(a.rows() == a.cols());
std::size_t n = a.rows();
auto l = Matrix::id(n);
auto d = Matrix::null(n, n);
for (std::size_t j = 0; j < n; ++j)
{
double val = a.at(j, j);
for (std::size_t k = 0; k < j; ++k)
val -= l.at(j, k) * l.at(j, k) * d.at(k, k);
d.at(j, j) = val;
for (std::size_t i = j + 1; i < n; ++i)
{
double val = a.at(i, j);
for (std::size_t k = 0; k < j; ++k)
val -= l.at(i, k) * l.at(j, k) * d.at(k, k);
l.at(i, j) = val / d.at(j, j);
}
}
return {l, d};
}
| 22.46 | 58 | 0.489314 | [
"vector"
] |
e16204f23356b69c81fe4bb0f5e534c0498bd18d | 12,501 | cpp | C++ | test/rocprim/test_device_radix_sort_floats.cpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | null | null | null | test/rocprim/test_device_radix_sort_floats.cpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | null | null | null | test/rocprim/test_device_radix_sort_floats.cpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2017-2021 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, 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 "common_test_header.hpp"
// required rocprim headers
#include <rocprim/device/device_radix_sort.hpp>
// required test headers
#include "test_utils_types.hpp"
#include "test_sort_comparator.hpp"
// Special floats sort test
template<
class Key,
bool Descending = false
>
struct params_special
{
using key_type = Key;
static constexpr bool descending = Descending;
};
template<class Params>
class RocprimDeviceRadixSortSpecial : public ::testing::Test {
public:
using params = Params;
};
typedef ::testing::Types<
params_special<double>,
params_special<double, true>,
params_special<float>,
params_special<float, true>,
params_special<half>,
params_special<half, true>,
params_special<rocprim::bfloat16>,
params_special<rocprim::bfloat16, true>
> Params_special;
namespace vectors
{
void put_special_values(std::vector<half>& keys)
{
keys[0] = +0.0;
keys[1] = -0.0;
uint16_t p = 0xffff; // -NaN
keys[2] = *(reinterpret_cast<half*>(&p));
p = 0x7fff; // +NaN
keys[3] = *(reinterpret_cast<half*>(&p));
p = 0x7C00; // +inf
keys[4] = *(reinterpret_cast<half*>(&p));
p = 0xFC00; // -inf
keys[5] = *(reinterpret_cast<half*>(&p));
}
void put_special_values(std::vector<rocprim::bfloat16>& keys)
{
uint16_t p = 0x0000; //+0.0
keys[0] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0x8000; // -0.0
keys[1] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0xffff; // -NaN
keys[2] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0x7fff; // +NaN
keys[3] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0x7F80; // +inf
keys[4] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0xFF80; // -inf
keys[5] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
}
void put_special_values(std::vector<float>& keys)
{
keys[0] = +0.0;
keys[1] = -0.0;
uint32_t p = 0xffffffff; // -NaN
keys[2] = *(reinterpret_cast<float*>(&p));
p = 0x7fffffff; // +NaN
keys[3] = *(reinterpret_cast<float*>(&p));
p = 0x7F800000; // +inf
keys[4] = *(reinterpret_cast<float*>(&p));
p = 0xFF800000; // -inf
keys[5] = *(reinterpret_cast<float*>(&p));
}
void put_special_values(std::vector<double>& keys)
{
keys[0] = +0.0;
keys[1] = -0.0;
uint64_t p = 0xffffffffffffffff; // -NaN
keys[2] = *(reinterpret_cast<double*>(&p));
p = 0x7fffffffffffffff; // +NaN
keys[3] = *(reinterpret_cast<double*>(&p));
p = 0x7ff0000000000000; // +inf
keys[4] = *(reinterpret_cast<double*>(&p));
p = 0xfff0000000000000; // -inf
keys[5] = *(reinterpret_cast<double*>(&p));
}
template<typename Real>
void put_other_values(std::vector<Real>& keys)
{
for(auto a : {3.5, 0.5, -1.0, -3.5, -2.5, 0.0, 2.5, 3.5, 4.0, 4.5, 2.0, \
-3.0, -2.5, 4.5, -3.5, 0.5, -1.0, 1.0, 3.0, -4.0, 3.0, 2.0, \
-0.5, -1.5, 4.0, -1.0})
{
keys.push_back(Real(a));
}
}
template<typename Real>
void put_values(std::vector<Real>& keys)
{
keys.resize(6);
put_special_values(keys);
put_other_values(keys);
}
void first_special_values_descending(std::vector<half>& keys)
{
uint16_t p = 0x7fff; // +NaN
keys[0] = *(reinterpret_cast<half*>(&p));
p = 0x7C00; // +inf
keys[1] = *(reinterpret_cast<half*>(&p));
}
void last_special_values_descending(std::vector<half>& keys)
{
uint16_t p = 0xFC00; // -inf
keys[30] = *(reinterpret_cast<half*>(&p));
p = 0xffff; // -NaN
keys[31] = *(reinterpret_cast<half*>(&p));
}
void first_special_values_descending(std::vector<rocprim::bfloat16>& keys)
{
uint16_t p = 0x7fff; // +NaN
keys[0] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0x7F80; // +inf
keys[1] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
}
void last_special_values_descending(std::vector<rocprim::bfloat16>& keys)
{
uint16_t p = 0xFF80; // -inf
keys[30] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0xffff; // -NaN
keys[31] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
}
void first_special_values_descending(std::vector<float>& keys)
{
uint32_t p = 0x7fffffff; // +NaN
keys[0] = *(reinterpret_cast<float*>(&p));
p = 0x7F800000; // +inf
keys[1] = *(reinterpret_cast<float*>(&p));
}
void last_special_values_descending(std::vector<float>& keys)
{
uint32_t p = 0xFF800000; // -inf
keys[30] = *(reinterpret_cast<float*>(&p));
p = 0xffffffff; // -NaN
keys[31] = *(reinterpret_cast<float*>(&p));
}
void first_special_values_descending(std::vector<double>& keys)
{
uint64_t p = 0x7fffffffffffffff; // +NaN
keys[0] = *(reinterpret_cast<double*>(&p));
p = 0x7ff0000000000000; // +inf
keys[1] = *(reinterpret_cast<double*>(&p));
}
void last_special_values_descending(std::vector<double>& keys)
{
uint64_t p = 0xfff0000000000000; // -inf
keys[30] = *(reinterpret_cast<double*>(&p));
p = 0xffffffffffffffff; // -NaN
keys[31] = *(reinterpret_cast<double*>(&p));
}
template<typename Real>
void expected_values_descending(std::vector<Real>& keys)
{
keys.resize(2);
first_special_values_descending(keys);
for(auto a : {4.5, 4.5, 4.0, 4.0, 3.5, 3.5, 3.0, 3.0, 2.5, 2.0, 2.0, 1.0, 0.5, 0.5, \
0.0, -0.0, 0.0, -0.5, -1.0, -1.0, -1.0, -1.5, -2.5, -2.5, -3.0, -3.5, -3.5, -4.0})
keys.push_back(Real(a));
keys.resize(32);
last_special_values_descending(keys);
}
void first_special_values_ascending(std::vector<half>& keys)
{
uint16_t p = 0xffff; // -NaN
keys[0] = *(reinterpret_cast<half*>(&p));
p = 0xFC00; // -inf
keys[1] = *(reinterpret_cast<half*>(&p));
}
void last_special_values_ascending(std::vector<half>& keys)
{
uint16_t p = 0x7C00; // +inf
keys[30] = *(reinterpret_cast<half*>(&p));
p = 0x7fff; // +NaN
keys[31] = *(reinterpret_cast<half*>(&p));
}
void first_special_values_ascending(std::vector<rocprim::bfloat16>& keys)
{
uint16_t p = 0xffff; // -NaN
keys[0] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0xFF80; // -inf
keys[1] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
}
void last_special_values_ascending(std::vector<rocprim::bfloat16>& keys)
{
uint16_t p = 0x7F80; // +inf
keys[30] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
p = 0x7fff; // +NaN
keys[31] = *(reinterpret_cast<rocprim::bfloat16*>(&p));
}
void first_special_values_ascending(std::vector<float>& keys)
{
uint32_t p = 0xffffffff; // -NaN
keys[0] = *(reinterpret_cast<float*>(&p));
p = 0xFF800000; // -inf
keys[1] = *(reinterpret_cast<float*>(&p));
}
void last_special_values_ascending(std::vector<float>& keys)
{
uint32_t p = 0x7F800000; // +inf
keys[30] = *(reinterpret_cast<float*>(&p));
p = 0x7fffffff; // +NaN
keys[31] = *(reinterpret_cast<float*>(&p));
}
void first_special_values_ascending(std::vector<double>& keys)
{
uint64_t p = 0xffffffffffffffff; // -NaN
keys[0] = *(reinterpret_cast<double*>(&p));
p = 0xfff0000000000000; // -inf
keys[1] = *(reinterpret_cast<double*>(&p));
}
void last_special_values_ascending(std::vector<double>& keys)
{
uint64_t p = 0x7ff0000000000000; // +inf
keys[30] = *(reinterpret_cast<double*>(&p));
p = 0x7fffffffffffffff; // +NaN
keys[31] = *(reinterpret_cast<double*>(&p));
}
template<typename Real>
void expected_values_ascending(std::vector<Real>& keys)
{
keys.resize(2);
first_special_values_ascending(keys);
for(auto a : {-4.0, -3.5, -3.5, -3.0, -2.5, -2.5, -1.5, -1.0, -1.0, -1.0, -0.5, \
0.0, -0.0, 0.0, 0.5, 0.5, 1.0, 2.0, 2.0, 2.5, 3.0, 3.0, 3.5, 3.5, 4.0, 4.0, 4.5, 4.5})
keys.push_back(Real(a));
keys.resize(32);
last_special_values_ascending(keys);
}
}
TYPED_TEST_SUITE(RocprimDeviceRadixSortSpecial, Params_special);
TYPED_TEST(RocprimDeviceRadixSortSpecial, SortKeys)
{
using key_type = typename TestFixture::params::key_type;
constexpr bool descending = TestFixture::params::descending;
constexpr unsigned int start_bit = 0;
constexpr unsigned int end_bit = sizeof(key_type) * 8;
hipStream_t stream = 0;
const bool debug_synchronous = false;
size_t size = 32;
// Generate data
std::vector<key_type> keys_input;
vectors::put_values(keys_input);
key_type *d_keys_input;
key_type * d_keys_output;
HIP_CHECK(test_common_utils::hipMallocHelper(&d_keys_input, size * sizeof(key_type)));
HIP_CHECK(test_common_utils::hipMallocHelper(&d_keys_output, size * sizeof(key_type)));
HIP_CHECK(
hipMemcpy(
d_keys_input, keys_input.data(),
size * sizeof(key_type),
hipMemcpyHostToDevice
)
);
// Expected results on host
std::vector<key_type> expected;
if(descending)
vectors::expected_values_descending(expected);
else
vectors::expected_values_ascending(expected);
// Use custom config
using config = rocprim::radix_sort_config<8, 5, rocprim::kernel_config<256, 3>, rocprim::kernel_config<256, 8>>;
size_t temporary_storage_bytes = 0;
HIP_CHECK(
rocprim::radix_sort_keys<config>(
nullptr, temporary_storage_bytes,
d_keys_input, d_keys_output, size,
start_bit, end_bit
)
);
ASSERT_GT(temporary_storage_bytes, 0U);
void * d_temporary_storage;
HIP_CHECK(test_common_utils::hipMallocHelper(&d_temporary_storage, temporary_storage_bytes));
if(descending)
{
HIP_CHECK(
rocprim::radix_sort_keys_desc<config>(
d_temporary_storage, temporary_storage_bytes,
d_keys_input, d_keys_output, size,
start_bit, end_bit,
stream, debug_synchronous
)
);
}
else
{
HIP_CHECK(
rocprim::radix_sort_keys<config>(
d_temporary_storage, temporary_storage_bytes,
d_keys_input, d_keys_output, size,
start_bit, end_bit,
stream, debug_synchronous
)
);
}
HIP_CHECK(hipFree(d_temporary_storage));
HIP_CHECK(hipFree(d_keys_input));
std::vector<key_type> keys_output(size);
HIP_CHECK(
hipMemcpy(
keys_output.data(), d_keys_output,
size * sizeof(key_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipFree(d_keys_output));
ASSERT_NO_FATAL_FAILURE(test_utils::assert_bit_eq(keys_output, expected));
}
| 32.302326 | 116 | 0.596752 | [
"vector"
] |
e1625fee6514609237410693ea2b8dc93cc6cfdc | 6,260 | cpp | C++ | src/phase_limiter/test_grad.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 12 | 2021-07-07T14:37:20.000Z | 2022-03-07T16:43:47.000Z | src/phase_limiter/test_grad.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | null | null | null | src/phase_limiter/test_grad.cpp | nankasuisui/phaselimiter | dd155676a3750d4977b8248d52fc77f5c28d1906 | [
"MIT"
] | 3 | 2021-04-03T13:36:02.000Z | 2021-12-28T20:21:10.000Z | #include <vector>
#include <iostream>
#include <random>
#include "bakuage/memory.h"
#include "phase_limiter/GradCore.h"
void TestGradCoreFft();
template <class SimdType>
void TestGradCoreFft() {
#if 0
typedef typename SimdType::element_type Float;
auto x = &phase_limiter::impl::ThreadVar1<SimdType>::GetThreadInstance();
const int len = 256;
// FFTが直交変換であることを確かめる
const double normalize_scale = 1.0 / std::sqrt(len);
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
x->windowed()[j] = 0;
}
x->windowed()[i] = 1 * normalize_scale;
x->doFFT(len);
double ene = bakuage::Sqr(x->spec()[0]) + bakuage::Sqr(x->spec()[len]);
for (int j = 1; j < len / 2; j++) {
ene += 2 * (bakuage::Sqr(x->spec()[2 * j]) + bakuage::Sqr(x->spec()[2 * j + 1])); // 共役分もあるので2倍
}
if (std::abs(ene - 1) > 1e-7) {
std::cerr << "grad core fft test failed " << i << " " << ene - 1 << std::endl;
}
}
// IFFTが直交変換であることを確かめる
for (int i = 0; i <= len; i++) {
if (i == 1) continue;
for (int j = 0; j <= len + 1; j++) {
x->spec()[j] = 0;
}
x->spec()[i] = ((i == 0 || i == len) ? std::sqrt(1.0) : std::sqrt(0.5)) * normalize_scale; // 共役分もあるので半分
x->doIFFT(len);
double ene = 0;
for (int j = 0; j < len; j++) {
ene += bakuage::Sqr(x->windowed()[j]);
}
if (std::abs(ene - 1) > 2e-7) {
std::cerr << "grad core ifft test failed " << i << " " << ene -1 << std::endl;
}
}
#endif
std::cerr << "grad core fft ifft test finished" << std::endl;
}
template <class SimdType>
void TestGradImpl() {
typedef typename SimdType::element_type Float;
using namespace phase_limiter;
const int windowLen = 256;
Float *wave = (Float *)bakuage::AlignedMalloc(sizeof(Float) * windowLen, PL_MEMORY_ALIGN);
Float *waveSrc = (Float *)bakuage::AlignedMalloc(sizeof(Float) * windowLen, PL_MEMORY_ALIGN);
Float *grad = (Float *)bakuage::AlignedMalloc(sizeof(Float) * windowLen, PL_MEMORY_ALIGN);
Float *gradNumerical = (Float *)bakuage::AlignedMalloc(sizeof(Float) * windowLen, PL_MEMORY_ALIGN);
const Float noise = 1e-6;
std::mt19937 engine(1);
std::normal_distribution<double> dist;
for (int i = 0; i < windowLen; i++) {
#if 1
wave[i] = dist(engine);
waveSrc[i] = dist(engine);
#else
wave[i] = 1 + i;
waveSrc[i] = 2 + i;
#endif
}
const auto calc = [=]() {
phase_limiter::GradContext<SimdType> context;
return GradCore<SimdType>::calcEval23(GradOptions::Default(windowLen), wave, waveSrc, noise, &context);
};
const auto calcGrad = [=]() {
phase_limiter::GradContext<SimdType> context;
return GradCore<SimdType>::calcEvalGrad23(GradOptions::Default(windowLen), wave, waveSrc, grad, noise, &context);
};
const auto calcGradNumerically = [=](double delta) {
const double waveEval = calc();
Float *temp = (Float *)bakuage::AlignedMalloc(sizeof(Float) * windowLen, PL_MEMORY_ALIGN);
for (int i = 0; i < windowLen; i++) {
for (int j = 0; j < windowLen; j++) {
temp[j] = wave[j];
}
temp[i] += delta;
phase_limiter::GradContext<SimdType> context;
const double neighborEval = GradCore<SimdType>::calcEval23(GradOptions::Default(windowLen), temp, waveSrc, noise, &context);
//std::cerr << "result1:" << neighborEval << "\tresult2:" << waveEval << std::endl;
gradNumerical[i] = (neighborEval - waveEval) / delta;
}
bakuage::AlignedFree(temp);
};
// test the output of calc and calcGrad is same
{
Float result1 = calc();
Float result2 = calc();
std::cerr << "result1:" << result1 << "\tresult2:" << result2 << std::endl;
}
// test the grad is correct
{
calcGrad();
calcGradNumerically(0.01);
double error = 0;
for (int i = 0; i < windowLen; i++) {
//std::cerr << "grad1:" << grad[i] << "\tgrad2:" << gradNumerical[i] << std::endl;
error += bakuage::Sqr(grad[i] - gradNumerical[i]);
}
std::cerr << "grad_error:" << error << std::endl;
}
// test the output of calc and calcGrad is same
{
Float result1 = calc();
Float result2 = calc();
std::cerr << "result1:" << result1 << "\tresult2:" << result2 << std::endl;
}
// test the grad returns same value
{
calcGrad();
std::vector<Float> v(grad, grad + windowLen);
for (int i = 0; i < windowLen; i++) {
grad[i] = 0;
}
calcGrad();
double error = 0;
for (int i = 0; i < windowLen; i++) {
error += bakuage::Sqr(grad[i] - v[i]);
}
std::cerr << "grad twice error:" << error << std::endl;
}
// パフォーマンス
{
phase_limiter::GradContext<SimdType> context;
GradCore<SimdType>::calcEvalGrad23(GradOptions::Default(windowLen), wave, waveSrc, grad, noise, &context);
bakuage::StopWatch sw;
sw.Start();
for (int i = 0; i < 1000 * 100; i++) {
GradCore<SimdType>::calcEvalGrad23(GradOptions::Default(windowLen), wave, waveSrc, grad, noise, &context);
}
std::cerr << "performance_sec:" << sw.Stop() << std::endl;
}
// splatのテスト
{
SimdType v1 = simdpp::splat(1);
SimdType v2 = simdpp::splat(2);
std::cerr << simdpp::extract<0>(v1) << " ";
std::cerr << simdpp::extract<1>(v1) << " ";
std::cerr << simdpp::extract<0>(v2) << " ";
std::cerr << simdpp::extract<1>(v2) << " ";
std::cerr << std::endl;
}
}
void TestGrad() {
TestGradImpl<simdpp::float32x4>();
TestGradImpl<simdpp::float32x8>();
TestGradImpl<simdpp::float64x2>();
TestGradImpl<simdpp::float64x4>();
TestGradCoreFft<simdpp::float32x4>();
TestGradCoreFft<simdpp::float32x8>();
TestGradCoreFft<simdpp::float64x2>();
TestGradCoreFft<simdpp::float64x4>();
}
| 34.20765 | 136 | 0.542173 | [
"vector"
] |
e16a28c10ce6c94740578448aa2e58a956619793 | 10,409 | hpp | C++ | src/p2p/sendmessage.hpp | DBCGlobal/DragonBallChain | 4d2b2c69048980e367a4235a70180dc0b9acc81f | [
"MIT"
] | 2 | 2021-10-03T14:27:03.000Z | 2021-10-19T15:29:27.000Z | src/p2p/sendmessage.hpp | DBCGlobal/DragonBallChain | 4d2b2c69048980e367a4235a70180dc0b9acc81f | [
"MIT"
] | null | null | null | src/p2p/sendmessage.hpp | DBCGlobal/DragonBallChain | 4d2b2c69048980e367a4235a70180dc0b9acc81f | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The DragonBallChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SENDMESSAGE_HPP
#define SENDMESSAGE_HPP
#include "main.h"
#include "chainmessage.h"
namespace {
struct CMainSignals {
// Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found
// in.
boost::signals2::signal<void(const uint256 &, CBaseTx *, const CBlock *)> SyncTransaction;
// Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
boost::signals2::signal<void(const uint256 &)> EraseTransaction;
// Notifies listeners of a new active block chain.
boost::signals2::signal<void(const CBlockLocator &)> SetBestChain;
// Notifies listeners about an inventory item being seen on the network.
// boost::signals2::signal<void (const uint256 &)> Inventory;
// Tells listeners to broadcast their data.
boost::signals2::signal<void()> Broadcast;
} g_signals;
} // namespace
bool SendMessages(CNode *pTo, bool fSendTrickle) {
{
// Don't send anything until we get their version message
if (pTo->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pTo->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
//if (pTo->nLastSend && GetTime() - pTo->nLastSend > 30 * 60 && pTo->vSendMsg.empty()) {
if (pTo->nPingNonceSent == 0 && pTo->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a keepalive
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
RAND_bytes((uint8_t *)&nonce, sizeof(nonce));
}
pTo->nPingNonceSent = nonce;
pTo->fPingQueued = false;
// if (pTo->nVersion > BIP0031_VERSION) {
// Take timestamp as close as possible before transmitting ping
pTo->nPingUsecStart = GetTimeMicros();
pTo->PushMessage(NetMsgType::PING, nonce);
// } else {
// // Peer is too old to support ping command with nonce, pong will never arrive, disable timing
// pTo->nPingUsecStart = 0;
// pTo->PushMessage("ping");
// }
//LogPrint(BCLog::NET, "send ping: %s\n", DateTimeStrFormat("YYYY-MM-DDTHH-MM-SS", pTo->nPingUsecStart).c_str());
}
{
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) {
{
LOCK(cs_vNodes);
for (auto pNode : vNodes) {
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pNode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen) {
CAddress addr = GetLocalAddress(&pNode->addr);
if (addr.IsRoutable())
pNode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle) {
vector<CAddress> vAddr;
vAddr.reserve(pTo->vAddrToSend.size());
for (const auto &addr : pTo->vAddrToSend) {
// returns true if wasn't already contained in the set
if (pTo->setAddrKnown.insert(addr).second) {
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000) {
pTo->PushMessage(NetMsgType::ADDR, vAddr);
vAddr.clear();
}
}
}
pTo->vAddrToSend.clear();
if (!vAddr.empty())
pTo->PushMessage(NetMsgType::ADDR, vAddr);
}
// Start block sync
if (pTo->fStartSync && !SysCfg().IsImporting() && !SysCfg().IsReindex()) {
pTo->fStartSync = false;
nSyncTipHeight = pTo->nStartingHeight;
LogPrint(BCLog::NET, "start block sync lead to getblocks\n");
PushGetBlocks(pTo, chainActive.Tip(), uint256());
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!SysCfg().IsReindex() && !SysCfg().IsImporting() && !IsInitialBlockDownload()) {
g_signals.Broadcast();
}
}
LOCK(cs_mapNodeState);
CNodeState &state = *State(pTo->GetId());
if (state.fShouldBan) {
if (pTo->addr.IsLocal()) {
LogPrint(BCLog::INFO, "Warning: not banning local node %s!\n", pTo->addr.ToString());
}
else {
LogPrint(BCLog::INFO, "Warning: banned a remote node %s!\n", pTo->addr.ToString());
pTo->fDisconnect = true;
CNode::Ban(pTo->addr);
}
state.fShouldBan = false;
}
for (const auto &reject : state.rejects)
pTo->PushMessage(NetMsgType::REJECT, (string) "block", reject.chRejectCode, reject.strRejectReason, reject.blockHash);
state.rejects.clear();
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pTo->cs_inventory);
vInv.reserve(pTo->vInventoryToSend.size());
vInvWait.reserve(pTo->vInventoryToSend.size());
for (const auto &inv : pTo->vInventoryToSend) {
if(pTo->setForceToSend.count(inv)){
pTo->setInventoryKnown.insert(inv);
vInv.push_back(inv);
pTo->setForceToSend.erase(inv);
continue;
}
if (pTo->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle) {
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt.IsNull())
hashSalt = GetRandHash();
uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
if (fTrickleWait) {
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pTo->setInventoryKnown.insert(inv).second) {
vInv.push_back(inv);
if (vInv.size() >= 1000) {
pTo->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
pTo->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pTo->PushMessage(NetMsgType::INV, vInv);
// Detect stalled peers. Require that blocks are in flight, we haven't
// received a (requested) block in one minute, and that all blocks are
// in flight for over two minutes, since we first had a chance to
// process an incoming block.
int64_t nNow = GetTimeMicros();
if (!pTo->fDisconnect && state.nBlocksInFlight &&
state.nLastBlockReceive < state.nLastBlockProcess - BLOCK_DOWNLOAD_TIMEOUT * 1000000 &&
state.vBlocksInFlight.front().nTime < state.nLastBlockProcess - 2 * BLOCK_DOWNLOAD_TIMEOUT * 1000000) {
LogPrint(BCLog::INFO, "Peer %s is stalling block download, disconnecting\n", state.name.c_str());
pTo->fDisconnect = true;
}
//
// Message: getdata (blocks)
//
vector<CInv> vGetData;
int32_t index = 0;
while (!pTo->fDisconnect && state.nBlocksToDownload && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
uint256 hash = state.vBlocksToDownload.front();
vGetData.push_back(CInv(MSG_BLOCK, hash));
MarkBlockAsInFlight(hash, pTo->GetId());
LogPrint(BCLog::NET, "send MSG_BLOCK msg! time_ms=%lld, hash=%s, peer=%s, FlightBlocks=%d, index=%d\n",
GetTimeMillis(), hash.ToString(), state.name, state.nBlocksInFlight, index++);
if (vGetData.size() >= 1000) {
pTo->PushMessage(NetMsgType::GETDATA, vGetData);
vGetData.clear();
index = 0;
}
}
//
// Message: getdata (non-blocks)
//
while (!pTo->fDisconnect && !pTo->mapAskFor.empty() && (*pTo->mapAskFor.begin()).first <= nNow) {
const CInv &inv = (*pTo->mapAskFor.begin()).second;
if (!AlreadyHave(inv)) {
LogPrint(BCLog::NET, "sending getdata: %s\n", inv.ToString());
vGetData.push_back(inv);
if (vGetData.size() >= 1000) {
pTo->PushMessage(NetMsgType::GETDATA, vGetData);
vGetData.clear();
}
}
pTo->mapAskFor.erase(pTo->mapAskFor.begin());
}
if (!vGetData.empty())
pTo->PushMessage(NetMsgType::GETDATA, vGetData);
}
return true;
}
#endif | 40.660156 | 130 | 0.525026 | [
"vector"
] |
e171f9bc2b9cd479d560bbcd05932ed9071a17c9 | 5,081 | hpp | C++ | labb3/labb3-library/math.hpp | ZetaTwo/dd2458-library | b4b8c9ba5fd5f5839674c48c5d5bd8eec31fbbd0 | [
"MIT"
] | 1 | 2015-02-13T17:14:15.000Z | 2015-02-13T17:14:15.000Z | labb3/labb3-library/math.hpp | ZetaTwo/dd2458-library | b4b8c9ba5fd5f5839674c48c5d5bd8eec31fbbd0 | [
"MIT"
] | null | null | null | labb3/labb3-library/math.hpp | ZetaTwo/dd2458-library | b4b8c9ba5fd5f5839674c48c5d5bd8eec31fbbd0 | [
"MIT"
] | null | null | null | // KTH DD2458 popuph14
// authors: magolsso@kth.se
// carlsven@kth.se
#pragma once
#include <stdexcept>
#include <vector>
#include <bitset>
#include <limits>
#include <map>
#include <algorithm>
//Calculates GCD(a, b)
template<typename T>
T gcd(T a, T b) {
T t;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
return a;
}
//Calculates GCD(a1, a2, a3, ...)
template<typename T>
T gcd(const std::vector<T>& numbers) {
auto n = numbers.begin();
T res = *n++;
while (n != numbers.end()) {
res = gcd(res, *n++);
}
return res;
}
//Calculates LCM(a, b)
template<typename T>
T lcm(T a, T b) {
T g = gcd(a, b);
return (a / g) * b;
}
//Stores result of an extended Euclidean algorithm calculation
template<typename T>
struct egcd_res {
T coeff_a;
T coeff_b;
T gcd;
T quotient_a;
T quotient_b;
};
//Extended Euclidean algorithm
template<typename T>
egcd_res<T> egcd(T a, T b) {
egcd_res<T> res = { 1, 0, a, 1, 0 };
T r = b;
T temp;
while (r != 0) {
//quotient = old_r / r
T quotient = res.gcd / r;
//(old_r, r) := (r, old_r - quotient * r)
temp = res.gcd - quotient*r;
res.gcd = r;
r = temp;
//(old_s, s) := (s, old_s - quotient * s)
temp = res.coeff_a - quotient * res.quotient_b;
res.coeff_a = res.quotient_b;
res.quotient_b = temp;
//(old_t, t) := (t, old_t - quotient * t)
temp = res.coeff_b - quotient * res.quotient_a;
res.coeff_b = res.quotient_a;
res.quotient_a = temp;
}
return res;
}
//Returns the inverse of a modulo n or n if there is no inverse
template<typename T>
T inverse(T a, T n) {
T t = 0;
T newt = 1;
T r = n;
T newr = a;
while (newr != 0) {
//quotient := r div newr
T quotient = r / newr;
//(t, newt) := (newt, t - quotient * newt)
T temp = t - quotient * newt;
t = newt;
newt = temp;
//(r, newr) := (newr, r - quotient * newr)
temp = r - quotient * newr;
r = newr;
newr = temp;
}
if (r > 1) {
return n;
}
if (t < 0) {
t += n;
}
return t;
}
//Multiplies two numbers a and b reduced by a modulo avoiding overflow.
template<typename T>
T mulmod(T a, T b, T mod) {
// Based on: http://en.wikipedia.org/wiki/Kochanski_multiplication
std::bitset<sizeof(T)*std::numeric_limits<unsigned char>::digits> mult(b);
T res = 0;
for (size_t i = mult.size(); i--;) {
res <<= 1;
res %= mod;
if (mult.test(i)) {
res += a;
}
res %= mod;
}
return res;
}
//Calculates base^exponent (mod modulus)
template<typename T>
T pow_mod(T base, T exponent, T modulus)
{
T result = 1;
while (exponent > 0)
{
if (exponent % 2 == 1)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
//Solves a system of congruences x = a_i (mod m_i)
template<typename T>
T chineseremainder(const std::vector<T>& remainders, const std::vector<T>& moduli) {
T N = 1;
for (auto& v : moduli) N *= v;
T x = 0;
for (auto ai = remainders.begin(), ni = moduli.begin(); ai != remainders.end() && ni != moduli.end(); ai++, ni++)
{
if (*ai > 0) {
T Nni = N / (*ni);
T term = mulmod(*ai, Nni, N);
term = mulmod(term, inverse(Nni, *ni), N);
x += term;
}
}
return x % N;
}
//Shorthand for solving a congruence when N=2
template<typename T>
T chineseremainder(const T& a, const T& m, const T& b, const T& n) {
return chineseremainder(std::vector<T>({ a, b }), std::vector<T>({ m, n }));
}
//Solves a system of congruences x = a_i (mod m_i) even when m_i are not pairwise-coprime.
template<typename T>
T generalchineseremainder(std::vector<T> remainders, std::vector<T> moduli) {
if (remainders.size() != moduli.size()) {
throw std::invalid_argument("Size of remainders and moduli must be equal");
}
if (remainders.size() == 0) {
return 0;
}
if (remainders.size() == 1) {
return remainders[0];
}
if (moduli[0] != moduli[1]) {
//Method of successive substitution
//http://en.wikipedia.org/wiki/Method_of_successive_substitution
if (remainders[1] > remainders[0]) {
std::swap(remainders[0], remainders[1]);
std::swap(moduli[0], moduli[1]);
}
T left = moduli[1];
T right = (remainders[0] - remainders[1]) % moduli[0];
T mod = moduli[0];
T g = gcd(left, gcd(right, mod));
left /= g;
right /= g;
mod /= g;
T inv = inverse(left, mod);
if (inv == mod) {
return -1;
}
left = (left * inv) % mod;
right = (right * inv) % mod;
T pair_rem = remainders[1] + moduli[1] * right;
T pair_mod = moduli[1] * mod;
remainders.push_back(pair_rem);
moduli.push_back(pair_mod);
}
else {
if (remainders[0] != remainders[1]) {
return -1;
}
else {
remainders.push_back(remainders[0]);
moduli.push_back(moduli[0]);
}
}
remainders.erase(remainders.begin(), remainders.begin() + 2);
moduli.erase(moduli.begin(), moduli.begin() + 2);
return generalchineseremainder(remainders, moduli);
} | 21.529661 | 115 | 0.57961 | [
"vector"
] |
e178df86fca3313e87c83eec4c9c81aeb9de7f08 | 6,961 | cpp | C++ | src/ui/TextBox.cpp | fentacoder/NanoEngine | 9c4e27b7b7b1d8335d21aa02385afc96a7ea8188 | [
"Apache-2.0"
] | null | null | null | src/ui/TextBox.cpp | fentacoder/NanoEngine | 9c4e27b7b7b1d8335d21aa02385afc96a7ea8188 | [
"Apache-2.0"
] | null | null | null | src/ui/TextBox.cpp | fentacoder/NanoEngine | 9c4e27b7b7b1d8335d21aa02385afc96a7ea8188 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************************************
Copyright 2021 Jamar Phillip
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 "TextBox.h"
namespace pen {
namespace ui {
TextBox::TextBox() { isUI = true; }
TextBox::TextBox(uint32_t objectId, std::string userText, pen::Vec3 objectPositions, int objectTextLength, float objectHeight, pen::Vec4 objectColor, pen::Vec4 objectTextColor,
pen::Item* objectParent, bool (*onClickCallback)(pen::Item*, int, int), bool objectIsFixed, std::string objectTextureName,
float itemTexCoordStartX, float itemTexCoordStartY, float itemTexCoordEndX, float itemTexCoordEndY, bool textEditor) {
/*Constructor for user supplied height*/
isUI = true;
id = objectId;
positions = objectPositions;
parent = objectParent;
userOnClickCallback = onClickCallback;
isFixed = objectIsFixed;
origText = userText;
angles = pen::Vec3(0.0f, 0.0f, 0.0f);
isClickable = false;
color = objectColor;
textColor = objectTextColor;
textureName = objectTextureName;
isTextEditor = textEditor;
/*Sets the cycles variable for how many lines of text there is*/
textLength = objectTextLength;
size.x = 0.0f;
GetTextCyclesNum(userText);
size.y = objectHeight;
/*The width of the text box gets updated here*/
SetTextCycles(userText);
texCoordStartX = itemTexCoordStartX;
texCoordStartY = itemTexCoordStartY;
texCoordEndX = itemTexCoordEndX;
texCoordEndY = itemTexCoordEndY;
/*For empty text boxes*/
if (size.x == 0.0f) size.x = 50.0f;
if (size.y == 0.0f) size.y = pen::State::Get()->textScaling;
bufferPositions = pen::Shape::GetBatchPosition(positions, size, pen::Shape::QUAD, objectColor, nullptr, 0.0f, 0.0f, 0.0f, GetAssetId(),
itemTexCoordStartX, itemTexCoordStartY, itemTexCoordEndX, itemTexCoordEndY);
shapeType = pen::Shape::QUAD;
/*CheckActiveStatus() occurs in CombineChildBuffers() as well*/
CombineChildBuffers();
}
TextBox::TextBox(uint32_t objectId, std::string userText, pen::Vec3 objectPositions, int objectTextLength, pen::Vec4 objectColor, pen::Vec4 objectTextColor,
pen::Item* objectParent, bool (*onClickCallback)(pen::Item*, int, int), bool objectIsFixed, std::string objectTextureName,
float itemTexCoordStartX, float itemTexCoordStartY, float itemTexCoordEndX, float itemTexCoordEndY, bool textEditor) {
/*Regular constructor*/
isUI = true;
id = objectId;
positions = objectPositions;
parent = objectParent;
userOnClickCallback = onClickCallback;
isFixed = objectIsFixed;
origText = userText;
angles = pen::Vec3(0.0f, 0.0f, 0.0f);
isClickable = false;
color = objectColor;
textColor = objectTextColor;
textureName = objectTextureName;
isTextEditor = textEditor;
/*Sets the cycles variable for how many lines of text there is*/
textLength = objectTextLength;
size.x = 0.0f;
GetTextCyclesNum(userText);
size.y = pen::State::Get()->textScaling * cycles + (cycles > 1 ? pen::State::Get()->textScaling : 0);
/*The width of the text box gets updated here*/
SetTextCycles(userText);
texCoordStartX = itemTexCoordStartX;
texCoordStartY = itemTexCoordStartY;
texCoordEndX = itemTexCoordEndX;
texCoordEndY = itemTexCoordEndY;
/*For empty text boxes*/
if (size.x == 0.0f) size.x = 50.0f;
if (size.y == 0.0f) size.y = pen::State::Get()->textScaling;
bufferPositions = pen::Shape::GetBatchPosition(positions, size, pen::Shape::QUAD, objectColor, nullptr, 0.0f, 0.0f, 0.0f, GetAssetId(),
itemTexCoordStartX, itemTexCoordStartY, itemTexCoordEndX, itemTexCoordEndY);
shapeType = pen::Shape::QUAD;
/*CheckActiveStatus() occurs in CombineChildBuffers() as well*/
CombineChildBuffers();
}
TextBox::~TextBox() {
bufferPositions.clear();
textureName = "";
}
void TextBox::SetTextLength() {
/*Sets the max amount of text characters per line*/
textLength = (unsigned int)((size.x / pen::State::Get()->textScaling - 1) * 2);
if (textLength <= 0) textLength = 1;
}
void TextBox::SetTextColor(pen::Vec4 itemTextColor, int pos) {
if (pos == -1) {
/*Update color for all child items, all child items are text*/
for (auto& item : childItems) item->SetColor(itemTextColor);
}
else {
/*Update color for a specific child item*/
childItems[pos]->SetColor(itemTextColor);
}
}
void TextBox::UpdateText(const std::string& userText) {
/*Remove any previous text*/
for (int i = 0; i < childItems.size(); i++) {
delete childItems[i];
}
childItems.clear();
itemCount = 0;
origText = userText;
/*Updates the cycles variable for how many lines of text there is*/
GetTextCyclesNum(userText);
size.y = (pen::State::Get()->textScaling * cycles + (cycles > 1 ? pen::State::Get()->textScaling : 0)) * itemScaling;
size.x = 0.0f;
/*Updates the text, the width of the text box gets updated here*/
SetTextCycles(userText);
/*For empty text boxes*/
if (size.x == 0.0f) size.x = 50.0f;
if (size.y == 0.0f) size.y = pen::State::Get()->textScaling;
}
}
} | 42.445122 | 185 | 0.586123 | [
"shape"
] |
e17a93b05ed5854eba379a9dec41f53522e16a82 | 2,570 | cpp | C++ | aoc10-2.cpp | LiemDQ/advent2021 | d1a7344050f35ebf8be94bacc7f4c1e80858473f | [
"MIT"
] | null | null | null | aoc10-2.cpp | LiemDQ/advent2021 | d1a7344050f35ebf8be94bacc7f4c1e80858473f | [
"MIT"
] | null | null | null | aoc10-2.cpp | LiemDQ/advent2021 | d1a7344050f35ebf8be94bacc7f4c1e80858473f | [
"MIT"
] | null | null | null | #include <vector>
#include <stack>
#include <fstream>
#include <string>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <optional>
char match_end_bracket(char brack){
switch (brack) {
case ')':
return '(';
case '}':
return '{';
case ']':
return '[';
case '>':
return '<';
default:
return brack;
}
}
char match_start_bracket(char brack){
switch (brack) {
case '(':
return ')';
case '{':
return '}';
case '[':
return ']';
case '<':
return '>';
default:
return brack;
}
}
int get_illegal_score(char brack){
switch (brack){
case ')':
return 3;
case ']':
return 57;
case '}':
return 1197;
case '>':
return 25137;
default:
return 0;
}
}
int get_completion_score(char brack){
switch(brack){
case ')':
return 1;
case ']':
return 2;
case '}':
return 3;
case '>':
return 4;
default:
return 0;
}
}
long complete_brackets(std::stack<char>& stack){
long score = 0;
while(!stack.empty()){
score *= 5;
char c = stack.top();
score += (long) get_completion_score(match_start_bracket(c));
stack.pop();
}
return score;
}
bool is_open_bracket(char brack){
if(brack == '(' || brack == '{' || brack == '[' || brack == '<'){
return true;
} else if (brack == ')' || brack == '}' || brack == ']' || brack == '>') {
return false;
} else {
assert(0 && "This branch should be unreachable; parse error encountered");
return false;
}
}
struct LegalScore {
bool is_legal;
int score;
};
std::optional<long> get_score(const std::string& str){
std::stack<char> stack;
for(char c: str){
if(is_open_bracket(c)){
stack.push(c);
} else {
char b = stack.top();
if (b == match_end_bracket(c)){
stack.pop();
continue;
} else {
//std::cout << "Expected " << match_start_bracket(b) << " but found " << c << " instead" << std::endl;
return {};
}
}
}
return std::optional<long>{complete_brackets(stack)};
}
int main(int argc, char* argv[]){
std::fstream file(argv[1]);
std::vector<std::string> brackets;
std::string inputs;
while(std::getline(file, inputs)){
brackets.push_back(inputs);
}
std::vector<long> score;
int line = 1;
for (auto& bracket_line:brackets){
//std::cout << line++ << ": ";
auto result = get_score(bracket_line);
if(result){
score.push_back(*result);
}
}
std::sort(score.begin(), score.end());
auto index = score.size()/2;
for(auto&& val:score){
std::cout << val << std::endl;
}
std::cout << "Final score is: " << score[index] << std::endl;
return 0;
} | 18.098592 | 106 | 0.58677 | [
"vector"
] |
e17c34f45758139f0f58fd12f805e25d3bc577ae | 1,505 | hpp | C++ | source/kiwi-core/Codegen/Emitter.hpp | alurin/kiwi | d428b6e70fb79f80caa096916dd570f4fc9725cf | [
"MIT"
] | null | null | null | source/kiwi-core/Codegen/Emitter.hpp | alurin/kiwi | d428b6e70fb79f80caa096916dd570f4fc9725cf | [
"MIT"
] | null | null | null | source/kiwi-core/Codegen/Emitter.hpp | alurin/kiwi | d428b6e70fb79f80caa096916dd570f4fc9725cf | [
"MIT"
] | null | null | null | /*
*******************************************************************************
* Copyright (C) 2012 Vasiliy Sheredeko
* MIT license. All Rights Reserved.
*******************************************************************************
*/
#ifndef KIWI_CODEGEN_EMITTER_INTERNAL
#define KIWI_CODEGEN_EMITTER_INTERNAL
#include "Builder.hpp"
#include <vector>
namespace kiwi {
class Callable;
/// Abstract emmiter for unary operators
class MethodPolicy {
public:
/// type for vector of expressions
typedef std::vector<ValueBuilder> ExpressionVector;
/// virtual destructor
virtual ~MethodPolicy();
/// emit IR instruction
virtual ValueBuilder emit(BlockBuilder block, const ExpressionVector& values) =0;
}; // class Emitter
class CloneEmitter : public MethodPolicy {
public:
CloneEmitter(MethodPtr callable);
/// emit IR instruction
virtual ValueBuilder emit(BlockBuilder block, const ExpressionVector& values);
protected:
MethodWeak m_callable;
};
/// Abstract converter from this type to concrete type and vice versa
class ThisConverter {
public:
/// Convert from variable to this
virtual ValueBuilder emitToThis(BlockBuilder block, ValueBuilder variableValue) =0;
/// Convert from this to variable
virtual ValueBuilder emitFromThis(BlockBuilder block, ValueBuilder thisValue) =0;
};
} // namespace kiwi::codegen
#endif
| 28.396226 | 91 | 0.611296 | [
"vector"
] |
e18897d5015ebeb5717af341b8120b794a9c3d3b | 5,699 | cpp | C++ | operators/parallelscan.cpp | damodar123/pythia-core | 6b90aafed40aa63185105a652b20c61fc5a4320d | [
"BSD-3-Clause"
] | 14 | 2015-01-25T19:11:49.000Z | 2021-08-24T18:48:37.000Z | operators/parallelscan.cpp | damodar123/pythia-core | 6b90aafed40aa63185105a652b20c61fc5a4320d | [
"BSD-3-Clause"
] | null | null | null | operators/parallelscan.cpp | damodar123/pythia-core | 6b90aafed40aa63185105a652b20c61fc5a4320d | [
"BSD-3-Clause"
] | 8 | 2015-03-16T20:08:53.000Z | 2020-09-14T02:39:48.000Z |
/*
* Copyright 2009, Pythia authors (see AUTHORS file).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "operators.h"
#include "operators_priv.h"
using std::make_pair;
static unsigned short INVALIDENTRY = static_cast<unsigned short>(-1);
void ParallelScanOp::init(libconfig::Config& root, libconfig::Setting& cfg)
{
PartitionedScanOp::init(root, cfg);
// Parameter not exists?
//
if (!cfg.exists("mapping"))
throw MissingParameterException("ParallelScanOp needs `mapping' parameter.");
libconfig::Setting& mapgrp = cfg["mapping"];
unsigned int size = mapgrp.getLength();
// Parameter not list/array?
//
if (size == 0)
throw MissingParameterException("ParallelScanOp `mapping' parameter cannot have a length of zero.");
// Parameter not of equal size to files vector?
//
if (size != vec_tbl.size())
throw InvalidParameter();
// Parse input, create vectors.
//
unsigned short maxtid = 0;
for (unsigned int i=0; i<size; ++i)
{
libconfig::Setting& threadlist = mapgrp[i];
vector<unsigned short> v;
for (int k=0; k<threadlist.getLength(); ++k)
{
unsigned int tid = threadlist[k];
maxtid = tid > maxtid ? tid : maxtid;
v.push_back(tid);
}
vec_grouptothreadlist.push_back(v);
PThreadLockCVBarrier barrier(v.size());
vec_barrier.push_back(barrier);
}
vec_threadtogroup.resize(maxtid+1, INVALIDENTRY);
for (unsigned int i=0; i<size; ++i)
{
libconfig::Setting& threadlist = mapgrp[i];
for (int k=0; k<threadlist.getLength(); ++k)
{
unsigned int tid = threadlist[k];
vec_threadtogroup.at(tid) = i;
}
}
}
void ParallelScanOp::threadInit(unsigned short threadid)
{
dbgassert(vec_threadtogroup.at(threadid) != INVALIDENTRY);
dbgassert(vec_threadtogroup.at(threadid) < vec_tbl.size());
unsigned short groupno = vec_threadtogroup[threadid];
// The first thread in each group is the unlucky one to do the allocation.
//
if (vec_grouptothreadlist[groupno][0] == threadid)
{
PartitionedScanOp::threadInit(groupno);
}
vec_barrier[groupno].Arrive();
}
Operator::ResultCode ParallelScanOp::scanStart(unsigned short threadid,
Page* indexdatapage, Schema& indexdataschema)
{
dbgassert(vec_threadtogroup.at(threadid) != INVALIDENTRY);
dbgassert(vec_threadtogroup.at(threadid) < vec_tbl.size());
unsigned short groupno = vec_threadtogroup[threadid];
// The first thread in each group is the unlucky one to do the load.
//
ResultCode res = Ready;
if (vec_grouptothreadlist[groupno][0] == threadid)
{
res = PartitionedScanOp::scanStart(groupno, indexdatapage, indexdataschema);
}
vec_barrier[groupno].Arrive();
return res;
}
Operator::ResultCode ParallelScanOp::scanStop(unsigned short threadid)
{
dbgassert(vec_threadtogroup.at(threadid) != INVALIDENTRY);
dbgassert(vec_threadtogroup.at(threadid) < vec_tbl.size());
unsigned short groupno = vec_threadtogroup[threadid];
vec_barrier[groupno].Arrive();
// The first thread in each group is the unlucky one to do the unload.
//
ResultCode res = Ready;
if (vec_grouptothreadlist[groupno][0] == threadid)
res = PartitionedScanOp::scanStop(groupno);
return res;
}
void ParallelScanOp::threadClose(unsigned short threadid)
{
dbgassert(vec_threadtogroup.at(threadid) != INVALIDENTRY);
dbgassert(vec_threadtogroup.at(threadid) < vec_tbl.size());
unsigned short groupno = vec_threadtogroup[threadid];
vec_barrier[groupno].Arrive();
// The first thread in each group is the unlucky one to do the deallocation.
//
if (vec_grouptothreadlist[groupno][0] == threadid)
PartitionedScanOp::threadClose(groupno);
}
void ParallelScanOp::destroy()
{
PartitionedScanOp::destroy();
vec_threadtogroup.clear();
vec_grouptothreadlist.clear();
vec_barrier.clear();
}
Operator::GetNextResultT ParallelScanOp::getNext(unsigned short threadid)
{
dbgassert(vec_threadtogroup.at(threadid) != INVALIDENTRY);
dbgassert(vec_threadtogroup.at(threadid) < vec_tbl.size());
unsigned short groupno = vec_threadtogroup[threadid];
dbgassert(vec_tbl.at(groupno) != NULL);
TupleBuffer* ret = vec_tbl[groupno]->atomicReadNext();
if (ret == NULL) {
return make_pair(Operator::Finished, &EmptyPage);
} else {
return make_pair(Operator::Ready, ret);
}
}
| 29.837696 | 102 | 0.742937 | [
"vector"
] |
e190f1a9ed6c8e109ebd88dca1b68373fabb5870 | 29,776 | cpp | C++ | src/lsh/sources/LocalitySensitiveHashing.cpp | Mario-Kart-Felix/Deckard | 6b14b0e3fb54b456f233c28bb7fce5597a5992e4 | [
"BSD-3-Clause"
] | 166 | 2015-02-27T14:55:02.000Z | 2022-03-16T07:14:51.000Z | src/lsh/sources/LocalitySensitiveHashing.cpp | Mario-Kart-Felix/Deckard | 6b14b0e3fb54b456f233c28bb7fce5597a5992e4 | [
"BSD-3-Clause"
] | 23 | 2015-05-01T01:25:33.000Z | 2022-02-14T05:17:04.000Z | src/lsh/sources/LocalitySensitiveHashing.cpp | Mario-Kart-Felix/Deckard | 6b14b0e3fb54b456f233c28bb7fce5597a5992e4 | [
"BSD-3-Clause"
] | 81 | 2015-01-19T22:32:24.000Z | 2022-03-22T05:48:04.000Z | /*
* Copyright (c) 2004-2005 Massachusetts Institute of Technology.
* All Rights Reserved.
*
* MIT grants permission to use, copy, modify, and distribute this software and
* its documentation for NON-COMMERCIAL purposes and without fee, provided that
* this copyright notice appears in all copies.
*
* MIT provides this software "as is," without representations or warranties of
* any kind, either expressed or implied, including but not limited to the
* implied warranties of merchantability, fitness for a particular purpose, and
* noninfringement. MIT shall not be liable for any damages arising from any
* use of this software.
*
* Author: Alexandr Andoni (andoni@mit.edu), Piotr Indyk (indyk@mit.edu)
*/
/*
The main functionality of the LSH scheme is in this file (all except
the hashing of the buckets). This file includes all the functions
for processing a PRNearNeighborStructT data structure, which is the
main R-NN data structure based on LSH scheme. The particular
functions are: initializing a DS, adding new points to the DS, and
responding to queries on the DS.
*/
#include "headers.h"
#include <assert.h>
void printRNNParameters(FILE *output, RNNParametersT parameters){
ASSERT(output != NULL);
fprintf(output, "R\n");
fprintf(output, "%0.9lf\n", parameters.parameterR);
fprintf(output, "Success probability\n");
fprintf(output, "%0.9lf\n", parameters.successProbability);
fprintf(output, "Dimension\n");
fprintf(output, "%d\n", parameters.dimension);
fprintf(output, "R^2\n");
fprintf(output, "%0.9lf\n", parameters.parameterR2);
fprintf(output, "Use <u> functions\n");
fprintf(output, "%d\n", parameters.useUfunctions);
fprintf(output, "k\n");
fprintf(output, "%d\n", parameters.parameterK);
fprintf(output, "m [# independent tuples of LSH functions]\n");
fprintf(output, "%d\n", parameters.parameterM);
fprintf(output, "L\n");
fprintf(output, "%d\n", parameters.parameterL);
fprintf(output, "W\n");
fprintf(output, "%0.9lf\n", parameters.parameterW);
fprintf(output, "T\n");
fprintf(output, "%d\n", parameters.parameterT);
fprintf(output, "typeHT\n");
fprintf(output, "%d\n", parameters.typeHT);
}
RNNParametersT readRNNParameters(FILE *input){
ASSERT(input != NULL);
RNNParametersT parameters;
char s[1000];// TODO: possible buffer overflow
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
FSCANF_REAL(input, ¶meters.parameterR);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
FSCANF_REAL(input, ¶meters.successProbability);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.dimension);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
FSCANF_REAL(input, ¶meters.parameterR2);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.useUfunctions);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.parameterK);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.parameterM);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.parameterL);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
FSCANF_REAL(input, ¶meters.parameterW);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.parameterT);
fscanf(input, "\n");fscanf(input, "%[^\n]\n", s);
fscanf(input, "%d", ¶meters.typeHT);
return parameters;
}
// Creates the LSH hash functions for the R-near neighbor structure
// <nnStruct>. The functions fills in the corresponding field of
// <nnStruct>.
void initHashFunctions(PRNearNeighborStructT nnStruct){
ASSERT(nnStruct != NULL);
LSHFunctionT **lshFunctions;
// allocate memory for the functions
FAILIF(NULL == (lshFunctions = (LSHFunctionT**)MALLOC(nnStruct->nHFTuples * sizeof(LSHFunctionT*))));
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
FAILIF(NULL == (lshFunctions[i] = (LSHFunctionT*)MALLOC(nnStruct->hfTuplesLength * sizeof(LSHFunctionT))));
for(IntT j = 0; j < nnStruct->hfTuplesLength; j++){
FAILIF(NULL == (lshFunctions[i][j].a = (RealT*)MALLOC(nnStruct->dimension * sizeof(RealT))));
}
}
// initialize the LSH functions
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
for(IntT j = 0; j < nnStruct->hfTuplesLength; j++){
// vector a
for(IntT d = 0; d < nnStruct->dimension; d++){
lshFunctions[i][j].a[d] = genGaussianRandom();
}
// b
lshFunctions[i][j].b = genUniformRandom(0, nnStruct->parameterW);
}
}
nnStruct->lshFunctions = lshFunctions;
}
// Initializes the fields of a R-near neighbors data structure except
// the hash tables for storing the buckets.
PRNearNeighborStructT initializePRNearNeighborFields(RNNParametersT algParameters, Int32T nPointsEstimate){
PRNearNeighborStructT nnStruct;
FAILIF(NULL == (nnStruct = (PRNearNeighborStructT)MALLOC(sizeof(RNearNeighborStructT))));
nnStruct->parameterR = algParameters.parameterR;
nnStruct->parameterR2 = algParameters.parameterR2;
nnStruct->useUfunctions = algParameters.useUfunctions;
nnStruct->parameterK = algParameters.parameterK;
if (!algParameters.useUfunctions) {
// Use normal <g> functions.
nnStruct->parameterL = algParameters.parameterL;
nnStruct->nHFTuples = algParameters.parameterL;
nnStruct->hfTuplesLength = algParameters.parameterK;
}else{
// Use <u> hash functions; a <g> function is a pair of 2 <u> functions.
nnStruct->parameterL = algParameters.parameterL;
nnStruct->nHFTuples = algParameters.parameterM;
nnStruct->hfTuplesLength = algParameters.parameterK / 2;
}
nnStruct->parameterT = algParameters.parameterT;
nnStruct->dimension = algParameters.dimension;
nnStruct->parameterW = algParameters.parameterW;
nnStruct->nPoints = 0;
nnStruct->pointsArraySize = nPointsEstimate;
FAILIF(NULL == (nnStruct->points = (PPointT*)MALLOC(nnStruct->pointsArraySize * sizeof(PPointT))));
// create the hash functions
initHashFunctions(nnStruct);
// init fields that are used only in operations ("temporary" variables for operations).
// init the vector <pointULSHVectors> and the vector
// <precomputedHashesOfULSHs>
FAILIF(NULL == (nnStruct->pointULSHVectors = (Uns32T**)MALLOC(nnStruct->nHFTuples * sizeof(Uns32T*))));
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
FAILIF(NULL == (nnStruct->pointULSHVectors[i] = (Uns32T*)MALLOC(nnStruct->hfTuplesLength * sizeof(Uns32T))));
}
FAILIF(NULL == (nnStruct->precomputedHashesOfULSHs = (Uns32T**)MALLOC(nnStruct->nHFTuples * sizeof(Uns32T*))));
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
FAILIF(NULL == (nnStruct->precomputedHashesOfULSHs[i] = (Uns32T*)MALLOC(N_PRECOMPUTED_HASHES_NEEDED * sizeof(Uns32T))));
}
// init the vector <reducedPoint>
FAILIF(NULL == (nnStruct->reducedPoint = (RealT*)MALLOC(nnStruct->dimension * sizeof(RealT))));
// init the vector <nearPoints>
nnStruct->sizeMarkedPoints = nPointsEstimate;
FAILIF(NULL == (nnStruct->markedPoints = (BooleanT*)MALLOC(nnStruct->sizeMarkedPoints * sizeof(BooleanT))));
for(IntT i = 0; i < nnStruct->sizeMarkedPoints; i++){
nnStruct->markedPoints[i] = FALSE;
}
// init the vector <nearPointsIndeces>
FAILIF(NULL == (nnStruct->markedPointsIndeces = (Int32T*)MALLOC(nnStruct->sizeMarkedPoints * sizeof(Int32T))));
nnStruct->reportingResult = TRUE;
return nnStruct;
}
// Constructs a new empty R-near-neighbor data structure.
PRNearNeighborStructT initLSH(RNNParametersT algParameters, Int32T nPointsEstimate){
ASSERT(algParameters.typeHT == HT_LINKED_LIST || algParameters.typeHT == HT_STATISTICS);
PRNearNeighborStructT nnStruct = initializePRNearNeighborFields(algParameters, nPointsEstimate);
// initialize second level hashing (bucket hashing)
FAILIF(NULL == (nnStruct->hashedBuckets = (PUHashStructureT*)MALLOC(nnStruct->parameterL * sizeof(PUHashStructureT))));
Uns32T *mainHashA = NULL, *controlHash1 = NULL;
BooleanT uhashesComputedAlready = FALSE;
for(IntT i = 0; i < nnStruct->parameterL; i++){
nnStruct->hashedBuckets[i] = newUHashStructure(algParameters.typeHT, nPointsEstimate, nnStruct->parameterK, uhashesComputedAlready, mainHashA, controlHash1, NULL);
uhashesComputedAlready = TRUE;
}
return nnStruct;
}
void preparePointAdding(PRNearNeighborStructT nnStruct, PUHashStructureT uhash, PPointT point);
// Construct PRNearNeighborStructT given the data set <dataSet> (all
// the points <dataSet> will be contained in the resulting DS).
// Currenly only type HT_HYBRID_CHAINS is supported for this
// operation.
PRNearNeighborStructT initLSH_WithDataSet(RNNParametersT algParameters, Int32T nPoints, PPointT *dataSet){
ASSERT(algParameters.typeHT == HT_HYBRID_CHAINS);
ASSERT(dataSet != NULL);
ASSERT(USE_SAME_UHASH_FUNCTIONS);
PRNearNeighborStructT nnStruct = initializePRNearNeighborFields(algParameters, nPoints);
// Set the fields <nPoints> and <points>.
nnStruct->nPoints = nPoints;
for(Int32T i = 0; i < nPoints; i++){
nnStruct->points[i] = dataSet[i];
}
// initialize second level hashing (bucket hashing)
FAILIF(NULL == (nnStruct->hashedBuckets = (PUHashStructureT*)MALLOC(nnStruct->parameterL * sizeof(PUHashStructureT))));
Uns32T *mainHashA = NULL, *controlHash1 = NULL;
PUHashStructureT modelHT = newUHashStructure(HT_LINKED_LIST, nPoints, nnStruct->parameterK, FALSE, mainHashA, controlHash1, NULL);
Uns32T **(precomputedHashesOfULSHs[nnStruct->nHFTuples]);
for(IntT l = 0; l < nnStruct->nHFTuples; l++){
FAILIF(NULL == (precomputedHashesOfULSHs[l] = (Uns32T**)MALLOC(nPoints * sizeof(Uns32T*))));
for(IntT i = 0; i < nPoints; i++){
FAILIF(NULL == (precomputedHashesOfULSHs[l][i] = (Uns32T*)MALLOC(N_PRECOMPUTED_HASHES_NEEDED * sizeof(Uns32T))));
}
}
for(IntT i = 0; i < nPoints; i++){
preparePointAdding(nnStruct, modelHT, dataSet[i]);
for(IntT l = 0; l < nnStruct->nHFTuples; l++){
for(IntT h = 0; h < N_PRECOMPUTED_HASHES_NEEDED; h++){
precomputedHashesOfULSHs[l][i][h] = nnStruct->precomputedHashesOfULSHs[l][h];
}
}
}
//DPRINTF("Allocated memory(modelHT and precomputedHashesOfULSHs just a.): %d\n", totalAllocatedMemory);
// Initialize the counters for defining the pair of <u> functions used for <g> functions.
IntT firstUComp = 0;
IntT secondUComp = 1;
for(IntT i = 0; i < nnStruct->parameterL; i++){
// build the model HT.
for(IntT p = 0; p < nPoints; p++){
// Add point <dataSet[p]> to modelHT.
if (!nnStruct->useUfunctions) {
// Use usual <g> functions (truly independent; <g>s are precisly
// <u>s).
addBucketEntry(modelHT, 1, precomputedHashesOfULSHs[i][p], NULL, p);
} else {
// Use <u> functions (<g>s are pairs of <u> functions).
addBucketEntry(modelHT, 2, precomputedHashesOfULSHs[firstUComp][p], precomputedHashesOfULSHs[secondUComp][p], p);
}
}
//ASSERT(nAllocatedGBuckets <= nPoints);
//ASSERT(nAllocatedBEntries <= nPoints);
// compute what is the next pair of <u> functions.
secondUComp++;
if (secondUComp == nnStruct->nHFTuples) {
firstUComp++;
secondUComp = firstUComp + 1;
}
// copy the model HT into the actual (packed) HT. copy the uhash function too.
nnStruct->hashedBuckets[i] = newUHashStructure(algParameters.typeHT, nPoints, nnStruct->parameterK, TRUE, mainHashA, controlHash1, modelHT);
// clear the model HT for the next iteration.
clearUHashStructure(modelHT);
}
freeUHashStructure(modelHT, FALSE); // do not free the uhash functions since they are used by nnStruct->hashedBuckets[i]
// freeing precomputedHashesOfULSHs
for(IntT l = 0; l < nnStruct->nHFTuples; l++){
for(IntT i = 0; i < nPoints; i++){
FREE(precomputedHashesOfULSHs[l][i]);
}
FREE(precomputedHashesOfULSHs[l]);
}
return nnStruct;
}
// // Packed version (static).
// PRNearNeighborStructT buildPackedLSH(RealT R, BooleanT useUfunctions, IntT k, IntT LorM, RealT successProbability, IntT dim, IntT T, Int32T nPoints, PPointT *points){
// ASSERT(points != NULL);
// PRNearNeighborStructT nnStruct = initializePRNearNeighborFields(R, useUfunctions, k, LorM, successProbability, dim, T, nPoints);
// // initialize second level hashing (bucket hashing)
// FAILIF(NULL == (nnStruct->hashedBuckets = (PUHashStructureT*)MALLOC(nnStruct->parameterL * sizeof(PUHashStructureT))));
// Uns32T *mainHashA = NULL, *controlHash1 = NULL;
// PUHashStructureT modelHT = newUHashStructure(HT_STATISTICS, nPoints, nnStruct->parameterK, FALSE, mainHashA, controlHash1, NULL);
// for(IntT i = 0; i < nnStruct->parameterL; i++){
// // build the model HT.
// for(IntT p = 0; p < nPoints; p++){
// // addBucketEntry(modelHT, );
// }
// // copy the model HT into the actual (packed) HT.
// nnStruct->hashedBuckets[i] = newUHashStructure(HT_PACKED, nPointsEstimate, nnStruct->parameterK, TRUE, mainHashA, controlHash1, modelHT);
// // clear the model HT for the next iteration.
// clearUHashStructure(modelHT);
// }
// return nnStruct;
// }
// Optimizes the nnStruct (non-agressively, i.e., without changing the
// parameters).
void optimizeLSH(PRNearNeighborStructT nnStruct){
ASSERT(nnStruct != NULL);
PointsListEntryT *auxList = NULL;
for(IntT i = 0; i < nnStruct->parameterL; i++){
optimizeUHashStructure(nnStruct->hashedBuckets[i], auxList);
}
FREE(auxList);
}
// Frees completely all the memory occupied by the <nnStruct>
// structure.
void freePRNearNeighborStruct(PRNearNeighborStructT nnStruct){
if (nnStruct == NULL){
return;
}
if (nnStruct->points != NULL) {
free(nnStruct->points);
}
if (nnStruct->lshFunctions != NULL) {
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
free(nnStruct->lshFunctions[i]);
}
free(nnStruct->lshFunctions);
}
if (nnStruct->precomputedHashesOfULSHs != NULL) {
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
free(nnStruct->precomputedHashesOfULSHs[i]);
}
free(nnStruct->precomputedHashesOfULSHs);
}
freeUHashStructure(nnStruct->hashedBuckets[0], TRUE);
for(IntT i = 1; i < nnStruct->parameterL; i++){
freeUHashStructure(nnStruct->hashedBuckets[i], FALSE);
}
free(nnStruct->hashedBuckets);
if (nnStruct->pointULSHVectors != NULL){
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
free(nnStruct->pointULSHVectors[i]);
}
free(nnStruct->pointULSHVectors);
}
if (nnStruct->reducedPoint != NULL){
free(nnStruct->reducedPoint);
}
if (nnStruct->markedPoints != NULL){
free(nnStruct->markedPoints);
}
if (nnStruct->markedPointsIndeces != NULL){
free(nnStruct->markedPointsIndeces);
}
}
// If <reportingResult> == FALSe, no points are reported back in a
// <get> function. In particular any point that is found in the bucket
// is considered to be outside the R-ball of the query point. If
// <reportingResult> == TRUE, then the structure behaves normally.
void setResultReporting(PRNearNeighborStructT nnStruct, BooleanT reportingResult){
ASSERT(nnStruct != NULL);
nnStruct->reportingResult = reportingResult;
}
// Compute the value of a hash function u=lshFunctions[gNumber] (a
// vector of <hfTuplesLength> LSH functions) in the point <point>. The
// result is stored in the vector <vectorValue>. <vectorValue> must be
// already allocated (and have space for <hfTuplesLength> Uns32T-words).
inline void computeULSH(PRNearNeighborStructT nnStruct, IntT gNumber, RealT *point, Uns32T *vectorValue){
CR_ASSERT(nnStruct != NULL);
CR_ASSERT(point != NULL);
CR_ASSERT(vectorValue != NULL);
for(IntT i = 0; i < nnStruct->hfTuplesLength; i++){
RealT value = 0;
for(IntT d = 0; d < nnStruct->dimension; d++){
value += point[d] * nnStruct->lshFunctions[gNumber][i].a[d];
}
vectorValue[i] = (Uns32T)(FLOOR_INT32((value + nnStruct->lshFunctions[gNumber][i].b) / nnStruct->parameterW) /*- MIN_INT32T*/);
}
}
inline void preparePointAdding(PRNearNeighborStructT nnStruct, PUHashStructureT uhash, PPointT point){
ASSERT(nnStruct != NULL);
ASSERT(uhash != NULL);
ASSERT(point != NULL);
// Pi: if 'R' is small, just leave the point as it is to avoid division by 0 problem.
if ( nnStruct->parameterR < Pi_EPSILON /* better be the machine epsilon */ ) {
for(IntT d = 0; d < nnStruct->dimension; d++){
nnStruct->reducedPoint[d] = point->coordinates[d];
}
} else {
for(IntT d = 0; d < nnStruct->dimension; d++){
nnStruct->reducedPoint[d] = point->coordinates[d] / nnStruct->parameterR; // Pi: ==>inf if 'R'==0; ==> all vectors are hashed into a same bucket ==> O(dn^2), instead of O(dn^\rho\logn), query time!
}
}
// Compute all ULSH functions.
TIMEV_START(timeComputeULSH);
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
computeULSH(nnStruct, i, nnStruct->reducedPoint, nnStruct->pointULSHVectors[i]);
}
// Compute data for <precomputedHashesOfULSHs>.
if (USE_SAME_UHASH_FUNCTIONS) {
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
precomputeUHFsForULSH(uhash, nnStruct->pointULSHVectors[i], nnStruct->hfTuplesLength, nnStruct->precomputedHashesOfULSHs[i]);
}
}
TIMEV_END(timeComputeULSH);
}
inline void batchAddRequest(PRNearNeighborStructT nnStruct, IntT i, IntT &firstIndex, IntT &secondIndex, PPointT point){
// Uns32T *(gVector[4]);
// if (!nnStruct->useUfunctions) {
// // Use usual <g> functions (truly independent).
// gVector[0] = nnStruct->pointULSHVectors[i];
// gVector[1] = nnStruct->precomputedHashesOfULSHs[i];
// addBucketEntry(nnStruct->hashedBuckets[firstIndex], gVector, 1, point);
// } else {
// // Use <u> functions (<g>s are pairs of <u> functions).
// gVector[0] = nnStruct->pointULSHVectors[firstIndex];
// gVector[1] = nnStruct->pointULSHVectors[secondIndex];
// gVector[2] = nnStruct->precomputedHashesOfULSHs[firstIndex];
// gVector[3] = nnStruct->precomputedHashesOfULSHs[secondIndex];
// // compute what is the next pair of <u> functions.
// secondIndex++;
// if (secondIndex == nnStruct->nHFTuples) {
// firstIndex++;
// secondIndex = firstIndex + 1;
// }
// addBucketEntry(nnStruct->hashedBuckets[i], gVector, 2, point);
// }
}
// Adds a new point to the LSH data structure, that is for each
// i=0..parameterL-1, the point is added to the bucket defined by
// function g_i=lshFunctions[i].
void addNewPointToPRNearNeighborStruct(PRNearNeighborStructT nnStruct, PPointT point){
ASSERT(nnStruct != NULL);
ASSERT(point != NULL);
ASSERT(nnStruct->reducedPoint != NULL);
ASSERT(!nnStruct->useUfunctions || nnStruct->pointULSHVectors != NULL);
ASSERT(nnStruct->hashedBuckets[0]->typeHT == HT_LINKED_LIST || nnStruct->hashedBuckets[0]->typeHT == HT_STATISTICS);
nnStruct->points[nnStruct->nPoints] = point;
nnStruct->nPoints++;
preparePointAdding(nnStruct, nnStruct->hashedBuckets[0], point);
// Initialize the counters for defining the pair of <u> functions used for <g> functions.
IntT firstUComp = 0;
IntT secondUComp = 1;
TIMEV_START(timeBucketIntoUH);
for(IntT i = 0; i < nnStruct->parameterL; i++){
if (!nnStruct->useUfunctions) {
// Use usual <g> functions (truly independent; <g>s are precisly
// <u>s).
addBucketEntry(nnStruct->hashedBuckets[i], 1, nnStruct->precomputedHashesOfULSHs[i], NULL, nnStruct->nPoints - 1);
} else {
// Use <u> functions (<g>s are pairs of <u> functions).
addBucketEntry(nnStruct->hashedBuckets[i], 2, nnStruct->precomputedHashesOfULSHs[firstUComp], nnStruct->precomputedHashesOfULSHs[secondUComp], nnStruct->nPoints - 1);
// compute what is the next pair of <u> functions.
secondUComp++;
if (secondUComp == nnStruct->nHFTuples) {
firstUComp++;
secondUComp = firstUComp + 1;
}
}
//batchAddRequest(nnStruct, i, firstUComp, secondUComp, point);
}
TIMEV_END(timeBucketIntoUH);
// Check whether the vectors <nearPoints> & <nearPointsIndeces> is still big enough.
if (nnStruct->nPoints > nnStruct->sizeMarkedPoints) {
nnStruct->sizeMarkedPoints = 2 * nnStruct->nPoints;
FAILIF(NULL == (nnStruct->markedPoints = (BooleanT*)REALLOC(nnStruct->markedPoints, nnStruct->sizeMarkedPoints * sizeof(BooleanT))));
for(IntT i = 0; i < nnStruct->sizeMarkedPoints; i++){
nnStruct->markedPoints[i] = FALSE;
}
FAILIF(NULL == (nnStruct->markedPointsIndeces = (Int32T*)REALLOC(nnStruct->markedPointsIndeces, nnStruct->sizeMarkedPoints * sizeof(Int32T))));
}
}
// Returns TRUE iff |p1-p2|_2^2 <= threshold
inline BooleanT isDistanceSqrLeq(IntT dimension, PPointT p1, PPointT p2, RealT threshold){
RealT result = 0;
nOfDistComps++;
//TIMEV_START(timeDistanceComputation);
for (IntT i = 0; i < dimension; i++){
RealT temp = p1->coordinates[i] - p2->coordinates[i];
result += SQR(temp);
if (result > threshold){
TIMEV_END(timeDistanceComputation);
return 0;
}
}
//TIMEV_END(timeDistanceComputation);
//return result <= threshold;
return 1;
}
// // Returns TRUE iff |p1-p2|_2^2 <= threshold
// inline BooleanT isDistanceSqrLeq(IntT dimension, PPointT p1, PPointT p2, RealT threshold){
// RealT result = 0;
// nOfDistComps++;
// //TIMEV_START(timeDistanceComputation);
// for (IntT i = 0; i < dimension; i++){
// result += p1->coordinates[i] * p2->coordinates[i];
// }
// //TIMEV_END(timeDistanceComputation);
// return p1->sqrLength + p2->sqrLength - 2 * result <= threshold;
// }
// Returns the list of near neighbors of the point <point> (with a
// certain success probability). Near neighbor is defined as being a
// point within distance <parameterR>. Each near neighbor from the
// data set is returned is returned with a certain probability,
// dependent on <parameterK>, <parameterL>, and <parameterT>. The
// returned points are kept in the array <result>. If result is not
// allocated, it will be allocated to at least some minimum size
// (RESULT_INIT_SIZE). If number of returned points is bigger than the
// size of <result>, then the <result> is resized (to up to twice the
// number of returned points). The return value is the number of
// points found.
Int32T getNearNeighborsFromPRNearNeighborStruct(PRNearNeighborStructT nnStruct, PPointT query, PPointT *(&result), Int32T &resultSize){
ASSERT(nnStruct != NULL);
ASSERT(query != NULL);
ASSERT(nnStruct->reducedPoint != NULL);
ASSERT(!nnStruct->useUfunctions || nnStruct->pointULSHVectors != NULL);
PPointT point = query;
if (result == NULL){
resultSize = RESULT_INIT_SIZE;
FAILIF(NULL == (result = (PPointT*)MALLOC(resultSize * sizeof(PPointT))));
}
preparePointAdding(nnStruct, nnStruct->hashedBuckets[0], point);
Uns32T precomputedHashesOfULSHs[nnStruct->nHFTuples][N_PRECOMPUTED_HASHES_NEEDED];
for(IntT i = 0; i < nnStruct->nHFTuples; i++){
for(IntT j = 0; j < N_PRECOMPUTED_HASHES_NEEDED; j++){
precomputedHashesOfULSHs[i][j] = nnStruct->precomputedHashesOfULSHs[i][j];
}
}
TIMEV_START(timeTotalBuckets);
BooleanT oldTimingOn = timingOn;
if (noExpensiveTiming) {
timingOn = FALSE;
}
// Initialize the counters for defining the pair of <u> functions used for <g> functions.
IntT firstUComp = 0;
IntT secondUComp = 1;
Int32T nNeighbors = 0;// the number of near neighbors found so far.
Int32T nMarkedPoints = 0;// the number of marked points
for(IntT i = 0; i < nnStruct->parameterL; i++){
TIMEV_START(timeGetBucket);
GeneralizedPGBucket gbucket;
if (!nnStruct->useUfunctions) {
// Use usual <g> functions (truly independent; <g>s are precisly
// <u>s).
gbucket = getGBucket(nnStruct->hashedBuckets[i], 1, precomputedHashesOfULSHs[i], NULL);
} else {
// Use <u> functions (<g>s are pairs of <u> functions).
gbucket = getGBucket(nnStruct->hashedBuckets[i], 2, precomputedHashesOfULSHs[firstUComp], precomputedHashesOfULSHs[secondUComp]);
// compute what is the next pair of <u> functions.
secondUComp++;
if (secondUComp == nnStruct->nHFTuples) {
firstUComp++;
secondUComp = firstUComp + 1;
}
}
TIMEV_END(timeGetBucket);
PGBucketT bucket;
TIMEV_START(timeCycleBucket);
switch (nnStruct->hashedBuckets[i]->typeHT){
case HT_LINKED_LIST:
bucket = gbucket.llGBucket;
if (bucket != NULL){
// circle through the bucket and add to <result> the points that are near.
PBucketEntryT bucketEntry = &(bucket->firstEntry);
//TIMEV_START(timeCycleProc);
while (bucketEntry != NULL){
//TIMEV_END(timeCycleProc);
//ASSERT(bucketEntry->point != NULL);
//TIMEV_START(timeDistanceComputation);
Int32T candidatePIndex = bucketEntry->pointIndex;
PPointT candidatePoint = nnStruct->points[candidatePIndex];
if (isDistanceSqrLeq(nnStruct->dimension, point, candidatePoint, nnStruct->parameterR2) && nnStruct->reportingResult){
//TIMEV_END(timeDistanceComputation);
if (nnStruct->markedPoints[candidatePIndex] == FALSE) {
//TIMEV_START(timeResultStoring);
// a new R-NN point was found (not yet in <result>).
if (nNeighbors >= resultSize){
// run out of space => resize the <result> array.
resultSize = 2 * resultSize;
result = (PPointT*)REALLOC(result, resultSize * sizeof(PPointT));
}
result[nNeighbors] = candidatePoint;
nnStruct->markedPointsIndeces[nNeighbors] = candidatePIndex;
nnStruct->markedPoints[candidatePIndex] = TRUE; // do not include more points with the same index
nNeighbors++;
//TIMEV_END(timeResultStoring);
}
}else{
//TIMEV_END(timeDistanceComputation);
}
//TIMEV_START(timeCycleProc);
bucketEntry = bucketEntry->nextEntry;
}
//TIMEV_END(timeCycleProc);
}
break;
case HT_STATISTICS:
ASSERT(FALSE); // HT_STATISTICS not supported anymore
// if (gbucket.linkGBucket != NULL && gbucket.linkGBucket->indexStart != INDEX_START_EMPTY){
// Int32T position;
// PointsListEntryT *pointsList = nnStruct->hashedBuckets[i]->bucketPoints.pointsList;
// position = gbucket.linkGBucket->indexStart;
// // circle through the bucket and add to <result> the points that are near.
// while (position != INDEX_START_EMPTY){
// PPointT candidatePoint = pointsList[position].point;
// if (isDistanceSqrLeq(nnStruct->dimension, point, candidatePoint, nnStruct->parameterR2) && nnStruct->reportingResult){
// if (nnStruct->nearPoints[candidatePoint->index] == FALSE) {
// // a new R-NN point was found (not yet in <result>).
// if (nNeighbors >= resultSize){
// // run out of space => resize the <result> array.
// resultSize = 2 * resultSize;
// result = (PPointT*)REALLOC(result, resultSize * sizeof(PPointT));
// }
// result[nNeighbors] = candidatePoint;
// nNeighbors++;
// nnStruct->nearPoints[candidatePoint->index] = TRUE; // do not include more points with the same index
// }
// }
// // Int32T oldP = position;
// position = pointsList[position].nextPoint;
// // ASSERT(position == INDEX_START_EMPTY || position == oldP + 1);
// }
// }
break;
case HT_HYBRID_CHAINS:
if (gbucket.hybridGBucket != NULL){
PHybridChainEntryT hybridPoint = gbucket.hybridGBucket;
Uns32T offset = 0;
if (hybridPoint->point.bucketLength == 0){
// there are overflow points in this bucket.
offset = 0;
for(IntT j = 0; j < N_FIELDS_PER_INDEX_OF_OVERFLOW; j++){
offset += ((Uns32T)((hybridPoint + 1 + j)->point.bucketLength) << (j * N_BITS_FOR_BUCKET_LENGTH));
}
}
Uns32T index = 0;
BooleanT done = FALSE;
while(!done){
if (index == MAX_NONOVERFLOW_POINTS_PER_BUCKET){
//CR_ASSERT(hybridPoint->point.bucketLength == 0);
index = index + offset;
}
Int32T candidatePIndex = (hybridPoint + index)->point.pointIndex;
CR_ASSERT(candidatePIndex >= 0 && candidatePIndex < nnStruct->nPoints);
done = (hybridPoint + index)->point.isLastPoint == 1 ? TRUE : FALSE;
index++;
if (nnStruct->markedPoints[candidatePIndex] == FALSE){
// mark the point first.
nnStruct->markedPointsIndeces[nMarkedPoints] = candidatePIndex;
nnStruct->markedPoints[candidatePIndex] = TRUE; // do not include more points with the same index
nMarkedPoints++;
PPointT candidatePoint = nnStruct->points[candidatePIndex];
if (isDistanceSqrLeq(nnStruct->dimension, point, candidatePoint, nnStruct->parameterR2) && nnStruct->reportingResult){
//if (nnStruct->markedPoints[candidatePIndex] == FALSE) {
// a new R-NN point was found (not yet in <result>).
//TIMEV_START(timeResultStoring);
if (nNeighbors >= resultSize){
// run out of space => resize the <result> array.
resultSize = 2 * resultSize;
result = (PPointT*)REALLOC(result, resultSize * sizeof(PPointT));
}
result[nNeighbors] = candidatePoint;
nNeighbors++;
//TIMEV_END(timeResultStoring);
//nnStruct->markedPointsIndeces[nMarkedPoints] = candidatePIndex;
//nnStruct->markedPoints[candidatePIndex] = TRUE; // do not include more points with the same index
//nMarkedPoints++;
//}
}
}else{
// the point was already marked (& examined)
}
}
}
break;
default:
ASSERT(FALSE);
}
TIMEV_END(timeCycleBucket);
}
timingOn = oldTimingOn;
TIMEV_END(timeTotalBuckets);
// we need to clear the array nnStruct->nearPoints for the next query.
for(Int32T i = 0; i < nMarkedPoints; i++){
ASSERT(nnStruct->markedPoints[nnStruct->markedPointsIndeces[i]] == TRUE);
nnStruct->markedPoints[nnStruct->markedPointsIndeces[i]] = FALSE;
}
return nNeighbors;
}
| 39.024902 | 203 | 0.691967 | [
"vector",
"model"
] |
e1960f28a35b4e1bd78fa5d55191f11bd0ffb8fd | 475 | hpp | C++ | include/pybind11-numpy-example/pybind11-numpy-example.hpp | lkeegan/pybind11-numpy-example | 2420f24c772640eab68b2c216c3693da403bba96 | [
"MIT"
] | 1 | 2021-10-13T14:59:22.000Z | 2021-10-13T14:59:22.000Z | include/pybind11-numpy-example/pybind11-numpy-example.hpp | lkeegan/pybind11-numpy-example | 2420f24c772640eab68b2c216c3693da403bba96 | [
"MIT"
] | 2 | 2021-06-29T09:14:52.000Z | 2021-10-13T14:27:05.000Z | include/pybind11-numpy-example/pybind11-numpy-example.hpp | lkeegan/pybind11-numpy-example | 2420f24c772640eab68b2c216c3693da403bba96 | [
"MIT"
] | 2 | 2021-07-01T15:32:18.000Z | 2021-10-13T14:11:56.000Z | #pragma once
#include <numeric>
#include <vector>
namespace pybind11numpyexample {
/** @brief Helper function that returns a vector of given size and type
*
* @tparam T The type of element
* @param size The size of the vector to return
* @returns a vector of given size and type
*/
template <typename T> std::vector<T> make_vector(std::size_t size) {
std::vector<T> v(size, 0);
std::iota(v.begin(), v.end(), 0);
return v;
}
} // namespace pybind11numpyexample
| 22.619048 | 71 | 0.698947 | [
"vector"
] |
e198c203063f46552a42974a76604cbb0fb72842 | 1,287 | cpp | C++ | src/models/metasprite/framesetfile-serializer.cpp | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 13 | 2016-05-02T09:00:42.000Z | 2020-11-07T11:21:07.000Z | src/models/metasprite/framesetfile-serializer.cpp | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 3 | 2016-09-28T13:36:29.000Z | 2020-12-22T12:22:43.000Z | src/models/metasprite/framesetfile-serializer.cpp | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 1 | 2016-05-08T09:26:01.000Z | 2016-05-08T09:26:01.000Z | /*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2021, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "framesetfile-serializer.h"
using namespace UnTech::Xml;
namespace UnTech::MetaSprite {
const EnumMap<FrameSetFile::FrameSetType> frameSetTypeMap = {
{ "unknown", FrameSetFile::FrameSetType::UNKNOWN },
{ "metasprite", FrameSetFile::FrameSetType::METASPRITE },
{ "spriteimporter", FrameSetFile::FrameSetType::SPRITE_IMPORTER },
};
void readFrameSetFile(const XmlTag& tag, std::vector<FrameSetFile>& frameSets)
{
assert(tag.name == "frameset");
frameSets.emplace_back();
FrameSetFile& fs = frameSets.back();
fs.filename = tag.getAttributeFilename("src");
if (tag.hasAttribute("type")) {
fs.type = tag.getAttributeEnum("type", frameSetTypeMap);
}
else {
fs.setTypeFromExtension();
}
}
void writeFrameSetFiles(XmlWriter& xml, const std::vector<FrameSetFile>& frameSets)
{
for (const auto& fs : frameSets) {
xml.writeTag("frameset");
xml.writeTagAttributeFilename("src", fs.filename);
xml.writeTagAttributeEnum("type", fs.type, frameSetTypeMap);
xml.writeCloseTag();
}
}
}
| 26.8125 | 83 | 0.686869 | [
"vector"
] |
e19b04ccb5178165d2fbcfd345da5ed53421cfd1 | 8,686 | cpp | C++ | Firmware/Marlin/src/lcd/menu/menu_bed_leveling.cpp | M1dn1ghtN1nj4/UnifiedFirmware | 510ef8f4145dcbae1caced5e391c3888e6022b00 | [
"Info-ZIP"
] | 6 | 2020-12-04T21:55:04.000Z | 2022-02-02T20:49:45.000Z | Firmware/Marlin/src/lcd/menu/menu_bed_leveling.cpp | M1dn1ghtN1nj4/UnifiedFirmware | 510ef8f4145dcbae1caced5e391c3888e6022b00 | [
"Info-ZIP"
] | 24 | 2020-12-25T05:00:51.000Z | 2021-04-20T00:56:50.000Z | Firmware/Marlin/src/lcd/menu/menu_bed_leveling.cpp | M1dn1ghtN1nj4/UnifiedFirmware | 510ef8f4145dcbae1caced5e391c3888e6022b00 | [
"Info-ZIP"
] | 3 | 2021-05-01T15:13:41.000Z | 2022-02-11T01:15:30.000Z | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
//
// Bed Leveling Menus
//
#include "../../inc/MarlinConfigPre.h"
#if ENABLED(LCD_BED_LEVELING)
#include "menu_item.h"
#include "../../module/planner.h"
#include "../../feature/bedlevel/bedlevel.h"
#if HAS_BED_PROBE && DISABLED(BABYSTEP_ZPROBE_OFFSET)
#include "../../module/probe.h"
#endif
#if HAS_GRAPHICAL_TFT
#include "../tft/touch.h"
#include "../tft/tft.h"
#endif
#if EITHER(PROBE_MANUALLY, MESH_BED_LEVELING)
#include "../../module/motion.h"
#include "../../gcode/queue.h"
//
// Motion > Level Bed handlers
//
static uint8_t manual_probe_index;
// LCD probed points are from defaults
constexpr uint8_t total_probe_points = TERN(AUTO_BED_LEVELING_3POINT, 3, GRID_MAX_POINTS);
//
// Bed leveling is done. Wait for G29 to complete.
// A flag is used so that this can release control
// and allow the command queue to be processed.
//
// When G29 finishes the last move:
// - Raise Z to the "manual probe height"
// - Don't return until done.
//
// ** This blocks the command queue! **
//
void _lcd_level_bed_done() {
if (!ui.wait_for_move) {
#if MANUAL_PROBE_HEIGHT > 0 && DISABLED(MESH_BED_LEVELING)
// Display "Done" screen and wait for moves to complete
line_to_z(MANUAL_PROBE_HEIGHT);
ui.synchronize(GET_TEXT(MSG_LEVEL_BED_DONE));
#endif
ui.goto_previous_screen_no_defer();
ui.completion_feedback();
}
if (ui.should_draw()) MenuItem_static::draw(LCD_HEIGHT >= 4, GET_TEXT(MSG_LEVEL_BED_DONE));
ui.refresh(LCDVIEW_CALL_REDRAW_NEXT);
}
void _lcd_level_goto_next_point();
//
// Step 7: Get the Z coordinate, click goes to the next point or exits
//
void _lcd_level_bed_get_z() {
if (ui.use_click()) {
//
// Save the current Z position and move
//
// If done...
if (++manual_probe_index >= total_probe_points) {
//
// The last G29 records the point and enables bed leveling
//
ui.wait_for_move = true;
ui.goto_screen(_lcd_level_bed_done);
#if ENABLED(MESH_BED_LEVELING)
queue.inject_P(PSTR("G29 S2"));
#elif ENABLED(PROBE_MANUALLY)
queue.inject_P(PSTR("G29 V1"));
#endif
}
else
_lcd_level_goto_next_point();
return;
}
//
// Encoder knob or keypad buttons adjust the Z position
//
if (ui.encoderPosition) {
const float z = current_position.z + float(int32_t(ui.encoderPosition)) * (MESH_EDIT_Z_STEP);
line_to_z(constrain(z, -(LCD_PROBE_Z_RANGE) * 0.5f, (LCD_PROBE_Z_RANGE) * 0.5f));
ui.refresh(LCDVIEW_CALL_REDRAW_NEXT);
ui.encoderPosition = 0;
}
//
// Draw on first display, then only on Z change
//
if (ui.should_draw()) {
const float v = current_position.z;
MenuEditItemBase::draw_edit_screen(GET_TEXT(MSG_MOVE_Z), ftostr43sign(v + (v < 0 ? -0.0001f : 0.0001f), '+'));
}
}
//
// Step 6: Display "Next point: 1 / 9" while waiting for move to finish
//
void _lcd_level_bed_moving() {
if (ui.should_draw()) {
char msg[10];
sprintf_P(msg, PSTR("%i / %u"), int(manual_probe_index + 1), total_probe_points);
MenuEditItemBase::draw_edit_screen(GET_TEXT(MSG_LEVEL_BED_NEXT_POINT), msg);
}
ui.refresh(LCDVIEW_CALL_NO_REDRAW);
if (!ui.wait_for_move) ui.goto_screen(_lcd_level_bed_get_z);
}
//
// Step 5: Initiate a move to the next point
//
void _lcd_level_goto_next_point() {
ui.goto_screen(_lcd_level_bed_moving);
// G29 Records Z, moves, and signals when it pauses
ui.wait_for_move = true;
#if ENABLED(MESH_BED_LEVELING)
queue.inject_P(manual_probe_index ? PSTR("G29 S2") : PSTR("G29 S1"));
#elif ENABLED(PROBE_MANUALLY)
queue.inject_P(PSTR("G29 V1"));
#endif
}
//
// Step 4: Display "Click to Begin", wait for click
// Move to the first probe position
//
void _lcd_level_bed_homing_done() {
if (ui.should_draw()) {
MenuItem_static::draw(1, GET_TEXT(MSG_LEVEL_BED_WAITING));
// Color UI needs a control to detect a touch
TERN_(HAS_GRAPHICAL_TFT, touch.add_control(CLICK, 0, 0, TFT_WIDTH, TFT_HEIGHT));
}
if (ui.use_click()) {
manual_probe_index = 0;
_lcd_level_goto_next_point();
}
}
//
// Step 3: Display "Homing XYZ" - Wait for homing to finish
//
void _lcd_level_bed_homing() {
_lcd_draw_homing();
if (all_axes_homed()) ui.goto_screen(_lcd_level_bed_homing_done);
}
#if ENABLED(PROBE_MANUALLY)
extern bool g29_in_progress;
#endif
//
// Step 2: Continue Bed Leveling...
//
void _lcd_level_bed_continue() {
ui.defer_status_screen();
set_all_unhomed();
ui.goto_screen(_lcd_level_bed_homing);
queue.inject_P(G28_STR);
}
#endif // PROBE_MANUALLY || MESH_BED_LEVELING
#if ENABLED(MESH_EDIT_MENU)
inline void refresh_planner() {
set_current_from_steppers_for_axis(ALL_AXES);
sync_plan_position();
}
void menu_edit_mesh() {
static uint8_t xind, yind; // =0
START_MENU();
BACK_ITEM(MSG_BED_LEVELING);
EDIT_ITEM(uint8, MSG_MESH_X, &xind, 0, GRID_MAX_POINTS_X - 1);
EDIT_ITEM(uint8, MSG_MESH_Y, &yind, 0, GRID_MAX_POINTS_Y - 1);
EDIT_ITEM_FAST(float43, MSG_MESH_EDIT_Z, &Z_VALUES(xind, yind), -(LCD_PROBE_Z_RANGE) * 0.5, (LCD_PROBE_Z_RANGE) * 0.5, refresh_planner);
END_MENU();
}
#endif // MESH_EDIT_MENU
/**
* Step 1: Bed Level entry-point
*
* << Motion
* Auto Home (if homing needed)
* Leveling On/Off (if data exists, and homed)
* Fade Height: --- (Req: ENABLE_LEVELING_FADE_HEIGHT)
* Mesh Z Offset: --- (Req: MESH_BED_LEVELING)
* Z Probe Offset: --- (Req: HAS_BED_PROBE, Opt: BABYSTEP_ZPROBE_OFFSET)
* Level Bed >
* Level Corners > (if homed)
* Load Settings (Req: EEPROM_SETTINGS)
* Save Settings (Req: EEPROM_SETTINGS)
*/
void menu_bed_leveling() {
const bool is_homed = all_axes_known(),
is_valid = leveling_is_valid();
START_MENU();
BACK_ITEM(MSG_MOTION);
// Auto Home if not using manual probing
#if NONE(PROBE_MANUALLY, MESH_BED_LEVELING)
if (!is_homed) GCODES_ITEM(MSG_AUTO_HOME, G28_STR);
#endif
// Level Bed
#if EITHER(PROBE_MANUALLY, MESH_BED_LEVELING)
// Manual leveling uses a guided procedure
SUBMENU(MSG_LEVEL_BED, _lcd_level_bed_continue);
#else
// Automatic leveling can just run the G-code
GCODES_ITEM(MSG_LEVEL_BED, is_homed ? PSTR("G29") : PSTR("G28\nG29"));
#endif
#if ENABLED(MESH_EDIT_MENU)
if (is_valid) SUBMENU(MSG_EDIT_MESH, menu_edit_mesh);
#endif
// Homed and leveling is valid? Then leveling can be toggled.
if (is_homed && is_valid) {
bool show_state = planner.leveling_active;
EDIT_ITEM(bool, MSG_BED_LEVELING, &show_state, _lcd_toggle_bed_leveling);
}
// Z Fade Height
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
// Shadow for editing the fade height
editable.decimal = planner.z_fade_height;
EDIT_ITEM_FAST(float3, MSG_Z_FADE_HEIGHT, &editable.decimal, 0, 100, []{ set_z_fade_height(editable.decimal); });
#endif
//
// Mesh Bed Leveling Z-Offset
//
#if ENABLED(MESH_BED_LEVELING)
EDIT_ITEM(float43, MSG_BED_Z, &mbl.z_offset, -1, 1);
#endif
#if ENABLED(BABYSTEP_ZPROBE_OFFSET)
SUBMENU(MSG_ZPROBE_ZOFFSET, lcd_babystep_zoffset);
#elif HAS_BED_PROBE
EDIT_ITEM(LCD_Z_OFFSET_TYPE, MSG_ZPROBE_ZOFFSET, &probe.offset.z, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX);
#endif
#if ENABLED(LEVEL_BED_CORNERS)
SUBMENU(MSG_LEVEL_CORNERS, _lcd_level_bed_corners);
#endif
#if ENABLED(EEPROM_SETTINGS)
ACTION_ITEM(MSG_LOAD_EEPROM, ui.load_settings);
ACTION_ITEM(MSG_STORE_EEPROM, ui.store_settings);
#endif
END_MENU();
}
#endif // LCD_BED_LEVELING
| 29.147651 | 140 | 0.677527 | [
"mesh",
"3d"
] |
e19dc14dbc6635b771e943bafaecc92026f3e693 | 3,290 | cpp | C++ | Source/Core/ScreenCapture/ScreenshotHelper.cpp | zenden2k/image-uploader | 6cf2b3385039f0a000afa86f0ce80706aeb98226 | [
"Apache-2.0"
] | 107 | 2015-03-13T08:58:26.000Z | 2022-03-14T02:56:36.000Z | Source/Core/ScreenCapture/ScreenshotHelper.cpp | zenden2k/image-uploader | 6cf2b3385039f0a000afa86f0ce80706aeb98226 | [
"Apache-2.0"
] | 285 | 2015-03-12T23:08:54.000Z | 2022-02-20T15:22:31.000Z | Source/Core/ScreenCapture/ScreenshotHelper.cpp | zenden2k/image-uploader | 6cf2b3385039f0a000afa86f0ce80706aeb98226 | [
"Apache-2.0"
] | 40 | 2015-03-14T13:37:08.000Z | 2021-08-15T05:58:10.000Z | #include "ScreenshotHelper.h"
#include <dwmapi.h>
#include "Func/WinUtils.h"
namespace ScreenshotHelper {
std::vector<RECT> monitorsRects;
BOOL getActualWindowRect(HWND hWnd, RECT* res, bool maximizedFix) {
BOOL isEnabled = false;
if (S_OK == DwmIsCompositionEnabled(&isEnabled)) {
if (isEnabled) {
if (S_OK == DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, res, sizeof(RECT))) {
if (maximizedFix)
*res = maximizedWindowFix(hWnd, *res);
return TRUE;
}
}
}
return GetWindowRect(hWnd, res);
}
RECT maximizedWindowFix(HWND handle, RECT windowRect) {
RECT res = windowRect;
if (isWindowMaximized(handle)) {
RECT screenRect = screenFromRectangle(windowRect);
if (windowRect.left < screenRect.left) {
windowRect.right -= (screenRect.left - windowRect.left) /** 2*/;
windowRect.left = screenRect.left;
}
if (windowRect.top < screenRect.top) {
windowRect.bottom -= (screenRect.top - windowRect.top) /** 2*/;
windowRect.top = screenRect.top;
}
IntersectRect(&res, &windowRect, &screenRect);
// windowRect.Intersect(screenRect);
}
return res;
}
bool isWindowMaximized(HWND handle) {
WINDOWPLACEMENT wp;
memset(&wp, 0, sizeof(WINDOWPLACEMENT));
wp.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(handle, &wp)) {
return wp.showCmd == static_cast<UINT>(SW_MAXIMIZE);
}
return false;
}
RECT screenFromRectangle(RECT rc) {
monitorsRects.clear();
EnumDisplayMonitors(nullptr, nullptr, monitorEnumProc, 0);
int max = 0;
size_t iMax = 0;
for (size_t i = 0; i < monitorsRects.size(); i++) {
CRect Bounds = monitorsRects[i];
Bounds.IntersectRect(&Bounds, &rc);
if (Bounds.Width() * Bounds.Height() > max) {
max = Bounds.Width() * Bounds.Height();
iMax = i;
}
// result.UnionRect(result,Bounds);
}
return monitorsRects[iMax];
}
BOOL CALLBACK monitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
if (lprcMonitor) {
monitorsRects.push_back(*lprcMonitor);
}
return TRUE;
}
HRGN getWindowRegion(HWND wnd) {
RECT WndRect;
getActualWindowRect(wnd, &WndRect);
CRgn WindowRgn;
WindowRgn.CreateRectRgnIndirect(&WndRect);
if (::GetWindowRgn(wnd, WindowRgn) != ERROR) {
// WindowRegion.GetRgnBox( &WindowRect);
WindowRgn.OffsetRgn(WndRect.left, WndRect.top);
}
return WindowRgn.Detach();
}
HRGN getWindowVisibleRegion(HWND wnd) {
CRgn winReg;
CRect result;
if (!(GetWindowLong(wnd, GWL_STYLE) & WS_CHILD)) {
winReg = getWindowRegion(wnd);
return winReg.Detach();
}
getActualWindowRect(wnd, &result);
while (GetWindowLong(wnd, GWL_STYLE) & WS_CHILD) {
wnd = GetParent(wnd);
RECT rc;
if (GetClientRect(wnd, &rc)) {
MapWindowPoints(wnd, 0, reinterpret_cast<POINT*>(&rc), 2);
// parentRgn.CreateRectRgnIndirect(&rc);
}
result.IntersectRect(&result, &rc);
}
winReg.CreateRectRgnIndirect(&result);
return winReg.Detach();
}
}
| 28.859649 | 102 | 0.621581 | [
"vector"
] |
e1a3326472753e4270e5b4264ebd60a778be5003 | 45,764 | cpp | C++ | src/auto_referee/src/auto_referee.cpp | SaligiaR/simatch | a295a39500518ec220fa511ebfb2b50daab84b4e | [
"Apache-2.0"
] | 60 | 2016-09-17T13:18:03.000Z | 2021-12-20T01:19:49.000Z | src/auto_referee/src/auto_referee.cpp | SaligiaR/simatch | a295a39500518ec220fa511ebfb2b50daab84b4e | [
"Apache-2.0"
] | 13 | 2016-09-09T14:40:34.000Z | 2022-03-08T08:10:44.000Z | src/auto_referee/src/auto_referee.cpp | SaligiaR/simatch | a295a39500518ec220fa511ebfb2b50daab84b4e | [
"Apache-2.0"
] | 56 | 2016-09-09T14:49:53.000Z | 2022-03-26T15:02:54.000Z | #include "auto_referee.h"
#include <iostream>
#ifdef USE_NCURSES
#include <ncurses.h>
#define OUTINFO printw
#define OUTERROR printw
#else
#define OUTINFO ROS_INFO
#define OUTERROR ROS_ERROR
#define KEY_UP '5'
#define KEY_DOWN '2'
#define KEY_LEFT '1'
#define KEY_RIGHT '3'
#endif
#define WAIT_SECS_STOP 2 // after 'STOP' command is received, wait how many seconds before next command is sent
#define WAIT_SECS_PREGAME 4 // after pre-game command, such as free-kick, is received, wait how many seconds before next command is sent
using namespace std;
//zdx_note;for sendingoff and sendingback justice
int n2_isvalid_flag =1;
int n3_isvalid_flag =1;
int n4_isvalid_flag =1;
int n5_isvalid_flag =1;
int r2_isvalid_flag =1;
int r3_isvalid_flag =1;
int r4_isvalid_flag =1;
int r5_isvalid_flag =1;
// Model info in world reference frame;
// Unit -- length: cm, velocity: cm/s, ori: rad, w: rad/s
auto_referee::auto_referee(int start_id)
{
#ifdef USE_NCURSES
// ncurses initialization
initscr();
cbreak(); // one-character-a-time
keypad(stdscr, TRUE); // capture special keys
nodelay(stdscr, TRUE); // non-blocking input
noecho(); // no echo
scrollok(stdscr, TRUE); // automatic scroll screen
OUTINFO("start auto referee\n");
#endif
lastTouchBallTeam_ = NONE_TEAM;
start_team_ = start_id;
cyan_score_ = 0;
magenta_score_ = 0;
currentCmd_ = STOPROBOT;
nextCmd_ = STOPROBOT;
dribble_id_ = -1;
last_dribble_id_ = -1;
robot_initpos_ = DPoint(0.0, 0.0);
ball_resetpos_ = DPoint(0.0, 0.0);
ModelStatesCB_flag_ = false;
kickoff_flg_ = false;
cyan_info_.reserve(OUR_TEAM);
magenta_info_.reserve(OUR_TEAM);
rosnode_ = new ros::NodeHandle();
rosnode_->param("/cyan/prefix", cyan_prefix_, std::string("nubot"));
rosnode_->param("/magenta/prefix", magenta_prefix_, std::string("rival"));
rosnode_->param("/football/name", ball_name_, std::string("football") );
/** ROS publishers **/
cyan_pub_ = rosnode_->advertise<nubot_common::CoachInfo>("/"+cyan_prefix_+"/receive_from_coach", 100);
magenta_pub_ = rosnode_->advertise<nubot_common::CoachInfo>("/"+magenta_prefix_+"/receive_from_coach", 100);
setMS_pub_ = rosnode_->advertise<gazebo_msgs::ModelState>("/gazebo/set_model_state", 100);
//zdx_note
cyan_sending_off_pub = rosnode_->advertise<nubot_common::SendingOff>("/"+cyan_prefix_+"/redcard/chatter", 100);
magenta_sending_off_pub = rosnode_->advertise<nubot_common::SendingOff>("/"+magenta_prefix_+"/redcard/chatter", 100);
/** ROS subscribers using custom callback queues and a thread **/
ros::SubscribeOptions so1 = ros::SubscribeOptions::create<gazebo_msgs::ContactsState>(
"/football/bumper_states", 100, boost::bind(&auto_referee::contactCallback ,this,_1),
ros::VoidPtr(), &message_queue_);
bumper_sub_ = rosnode_->subscribe(so1);
ros::SubscribeOptions so2 = ros::SubscribeOptions::create<gazebo_msgs::ModelStates>(
"/gazebo/model_states", 100, boost::bind(&auto_referee::msCallback ,this,_1),
ros::VoidPtr(), &message_queue_);
gazebo_sub_ = rosnode_->subscribe(so2);
// bumper_sub_ = rosnode_->subscribe("/football/bumper_states", 10, &auto_referee::contactCallback, this);
// gazebo_sub_ = rosnode_->subscribe("/gazebo/model_states", 10, &auto_referee::msCallback, this);
/** ROS sercice client **/
// setMS_client_ = rosnode_->serviceClient<gazebo_msgs::SetModelState>("/gazebo/set_model_state");
/** ROS service server using custom callback queues and a thread **/
/** IMPORTATN: use a custom queue and a thread to process service calls to avoid deadlock **/
ros::AdvertiseServiceOptions aso1 = ros::AdvertiseServiceOptions::create<nubot_common::DribbleId>(
"DribbleId", boost::bind(&auto_referee::dribbleService, this, _1, _2),
ros::VoidPtr(), &service_queue_);
dribble_server_ = rosnode_->advertiseService(aso1);
/** Custom Callback Queue Thread. Use threads to process message and service callback queue **/
service_callback_queue_thread_ = boost::thread(boost::bind(&auto_referee::service_queue_thread, this));
message_callback_queue_thread_ = boost::thread(boost::bind( &auto_referee::message_queue_thread,this ));
/** timer process **/
loop_timer_ = rosnode_->createTimer(ros::Duration(LOOP_PERIOD), &auto_referee::loopControl, this);
createRecord();
// send the first game start command
if(start_team_ == CYAN_TEAM || start_team_ == MAGENTA_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = (start_team_==CYAN_TEAM) ? OUR_KICKOFF : OPP_KICKOFF;
kickoff_flg_ = true;
}
}
auto_referee::~auto_referee()
{
#ifdef USE_NCURSES
endwin(); // restore the terminal settings.
#endif
message_queue_.clear();
service_queue_.clear();
message_queue_.disable();
service_queue_.disable();
rosnode_->shutdown();
message_callback_queue_thread_.join();
service_callback_queue_thread_.join();
record_.close();
delete rosnode_;
}
void auto_referee::loopControl(const ros::TimerEvent &event)
{
msgCB_lock_.lock();
srvCB_lock_.lock();
#if 1
ModelStatesCB_flag_ = true;
static int err_count = 0;
if(!isManualControl()) // not manual control
{
if(ros::ok())
{
if(ModelStatesCB_flag_) // available to get the model states
{
if(currentCmd_ == STOPROBOT)
{
if(waittime(WAIT_SECS_STOP))
{
setBallPos(ball_resetpos_.x_, ball_resetpos_.y_);
sendGameCommand(nextCmd_);
}
}
else if(currentCmd_ == STARTROBOT)
{
// detect in-play faults
R1and2_isDribbleFault();
R3_isBallOutOrGoal();
R4_isOppGoalOrPenaltyArea();
}
else if( currentCmd_!=PARKINGROBOT) // pre-game commands, such as free-kick, drop-ball, etc.
{
// detect set-play faults
if(waittime(WAIT_SECS_PREGAME))
{
//if(!R5_isTooCloseToBall())
sendGameCommand(STARTROBOT);
}
else
{
if(ball_state_.pos.distance(ball_resetpos_) > 10.0) // prevent the ball from being kicked away
setBallPos(ball_resetpos_.x_, ball_resetpos_.y_);
}
}
}
else
{
err_count++;
if(err_count> 5.0/LOOP_PERIOD) // model state flag is not valid for 5 secs
{
OUTINFO("Err: model states NOT received. Has Gazebo started yet?\n");
err_count = 0;
}
}
}
else
OUTINFO("Err: ros::ok() is false.\n");
}
#else
test();
#endif
srvCB_lock_.unlock();
msgCB_lock_.unlock();
}
bool auto_referee::isManualControl()
{
#ifdef USE_NCURSES
static bool isManual = false;
static int pos_dif = 10;
int ch;
if( (ch=getch()) != ERR) // user input
{
if(ch == ' ')
{
isManual = !isManual;
if(isManual)
{
sendGameCommand(STOPROBOT);
writeRecord("\nEnter the MANUAL mode. Press h or H for help!\n");
}
else
{
sendGameCommand(STARTROBOT);
writeRecord("\nQuit the MANUAL mode!\n");
}
}
if(isManual)
{
switch(ch)
{
case 'h':
case 'H':
printManualHelp();
break;
case 'k':
sendGameCommand(OUR_KICKOFF);
break;
case 'K':
sendGameCommand(OPP_KICKOFF);
break;
case 't':
sendGameCommand(OUR_THROWIN);
break;
case 'T':
sendGameCommand(OPP_THROWIN);
break;
case 'g':
sendGameCommand(OUR_GOALKICK);
break;
case 'G':
sendGameCommand(OPP_GOALKICK);
break;
case 'c':
sendGameCommand(OUR_CORNERKICK);
break;
case 'C':
sendGameCommand(OPP_CORNERKICK);
break;
case 'f':
sendGameCommand(OUR_FREEKICK);
break;
case 'F':
sendGameCommand(OPP_FREEKICK);
break;
case 'p':
sendGameCommand(OUR_PENALTY);
break;
case 'P':
sendGameCommand(OPP_PENALTY);
break;
case 'd':
sendGameCommand(DROPBALL);
break;
case KEY_UP:
setBallPos(ball_state_.pos.x_, ball_state_.pos.y_ + pos_dif);
break;
case KEY_DOWN:
setBallPos(ball_state_.pos.x_, ball_state_.pos.y_ - pos_dif);
break;
case KEY_LEFT:
setBallPos(ball_state_.pos.x_ - pos_dif, ball_state_.pos.y_);
break;
case KEY_RIGHT:
setBallPos(ball_state_.pos.x_ + pos_dif, ball_state_.pos.y_);
break;
//zdx_note
case '2':
pub_sendingoff_flag.TeamName = "NuBot2";
pub_sendingoff_flag.TeamInfo = 0;
pub_sendingoff_flag.PlayerNum = 2;
pub_sendingoff_flag.id_maxvel_isvalid = 2;
n2_isvalid_flag ++;
if(n2_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 12;
n2_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '3':
pub_sendingoff_flag.TeamName = "NuBot3";
pub_sendingoff_flag.TeamInfo = 0;
pub_sendingoff_flag.PlayerNum = 3;
pub_sendingoff_flag.id_maxvel_isvalid =3;
n3_isvalid_flag ++;
if(n3_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 13;
n3_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '4':
pub_sendingoff_flag.TeamName = "NuBot4";
pub_sendingoff_flag.TeamInfo = 0;
pub_sendingoff_flag.PlayerNum = 4;
pub_sendingoff_flag.id_maxvel_isvalid =4;
n4_isvalid_flag ++;
if(n4_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 14;
n4_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '5':
pub_sendingoff_flag.TeamName = "NuBot5";
pub_sendingoff_flag.TeamInfo = 0;
pub_sendingoff_flag.PlayerNum = 5;
pub_sendingoff_flag.id_maxvel_isvalid =5;
n5_isvalid_flag ++;
if(n5_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 15;
n5_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '6':
pub_sendingoff_flag.TeamName = "rival2";
pub_sendingoff_flag.id_maxvel_isvalid =2;
pub_sendingoff_flag.TeamInfo = 1;
pub_sendingoff_flag.PlayerNum = 2;
r2_isvalid_flag ++;
if(r2_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 12;
r2_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
magenta_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '7':
pub_sendingoff_flag.TeamName = "rival3";
pub_sendingoff_flag.id_maxvel_isvalid =3;
pub_sendingoff_flag.TeamInfo = 1;
pub_sendingoff_flag.PlayerNum = 3;
r3_isvalid_flag ++;
if(r3_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 13;
r3_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
magenta_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '8':
pub_sendingoff_flag.TeamName = "rival4";
pub_sendingoff_flag.id_maxvel_isvalid =4;
pub_sendingoff_flag.TeamInfo = 1;
pub_sendingoff_flag.PlayerNum = 4;
r4_isvalid_flag ++;
if(r4_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 14;
r4_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
magenta_sending_off_pub.publish(pub_sendingoff_flag);
break;
case '9':
pub_sendingoff_flag.TeamName = "rival5";
pub_sendingoff_flag.id_maxvel_isvalid =5;
pub_sendingoff_flag.TeamInfo = 1;
pub_sendingoff_flag.PlayerNum = 5;
r5_isvalid_flag ++;
if(r5_isvalid_flag >=3)
{
pub_sendingoff_flag.id_maxvel_isvalid = 15;
r5_isvalid_flag = 1;
}
cyan_sending_off_pub.publish(pub_sendingoff_flag);
magenta_sending_off_pub.publish(pub_sendingoff_flag);
break;
//
default:
break;
}
}
}
if(isManual)
return true;
else
return false;
#else
return false;
#endif
}
void auto_referee::printManualHelp()
{
OUTINFO("You could also use the arrow key to control the movement of the ball or press the keys as follow to send game commands.\n\n");
OUTINFO(" cyan magenta \n");
OUTINFO("kick-off k K \n");
OUTINFO("throw-in t T \n");
OUTINFO("goal-kick g G \n");
OUTINFO("corner-kick c C \n");
OUTINFO("free-kick f F \n");
OUTINFO("penalty p P \n");
OUTINFO("drop-ball d d \n");
OUTINFO("sending0ff/back 2/3/4/5 6/7/8/9 \n");
OUTINFO("stop/start space space \n");
OUTINFO("\n");
OUTINFO("Press h or H to get this help message\n");
}
void auto_referee::msCallback(const gazebo_msgs::ModelStates::ConstPtr &msg)
{
msgCB_lock_.lock();
ModelStatesCB_flag_ = true;
int num = msg->name.size();
cyan_info_.clear();
magenta_info_.clear();
// Model info in world reference frame;
// Unit -- length: cm, velocity: cm/s, ori: rad, w: rad/s
for(int i=0; i<num;i++)
{
std::string name = msg->name[i];
gazebo::math::Quaternion qua(msg->pose[i].orientation.w, msg->pose[i].orientation.x,
msg->pose[i].orientation.y, msg->pose[i].orientation.z);
ModelState ms;
ms.name = msg->name[i];
ms.pos.x_ = msg->pose[i].position.x * M2CM_CONVERSION;
ms.pos.y_ = msg->pose[i].position.y * M2CM_CONVERSION;
ms.pos_z = msg->pose[i].position.z * M2CM_CONVERSION;
ms.ori = qua.GetYaw();
ms.vel.x_ = msg->twist[i].linear.x * M2CM_CONVERSION;
ms.vel.y_ = msg->twist[i].linear.y * M2CM_CONVERSION;
ms.w = msg->twist[i].angular.z;
if(name.find(cyan_prefix_) != std::string::npos)
{
ms.id = atoi( ms.name.substr(cyan_prefix_.size()).c_str() );
cyan_info_.push_back(ms);
}
else if(name.find(magenta_prefix_) != std::string::npos)
{
ms.id = atoi( ms.name.substr(magenta_prefix_.size()).c_str() );
ms.ori = ms.ori > 0.0 ? (ms.ori - M_PI) : (ms.ori + M_PI); // since rival models' body frame is flipped
magenta_info_.push_back(ms);
}
else if(name.find(ball_name_) != std::string::npos)
ball_state_ = ms;
}
msgCB_lock_.unlock();
}
void auto_referee::contactCallback(const gazebo_msgs::ContactsState::ConstPtr &msg)
{
msgCB_lock_.lock();
static int tmpTeam = NONE_TEAM;
contacts_ = *msg;
for(int i =0; i<contacts_.states.size();i++)
{
std::string coll = contacts_.states[i].collision2_name;
std::size_t cyan_found = coll.find(cyan_prefix_);
std::size_t magenta_found = coll.find(magenta_prefix_);
if(cyan_found != std::string::npos)
tmpTeam = CYAN_TEAM;
else if(magenta_found != std::string::npos)
tmpTeam = MAGENTA_TEAM;
}
if(dribble_id_ == -1) // it means no robot is dribbling the ball;
lastTouchBallTeam_ = tmpTeam;
else
{
if(dribble_id_ <= 5)
lastTouchBallTeam_ = CYAN_TEAM;
else
lastTouchBallTeam_ = MAGENTA_TEAM;
}
msgCB_lock_.unlock();
}
bool auto_referee::dribbleService(nubot_common::DribbleId::Request &req,
nubot_common::DribbleId::Response &res)
{
srvCB_lock_.lock();
dribble_id_ = req.AgentId;
if(dribble_id_ != -1) // it means a robot is dribbling the ball
{
if(dribble_id_ <= 5)
lastTouchBallTeam_ = CYAN_TEAM;
else
lastTouchBallTeam_ = MAGENTA_TEAM;
}
srvCB_lock_.unlock();
return true;
}
int auto_referee::R1and2_isDribbleFault()
{
int rtnv = 0; // return value
if(dribble_id_ != -1) // it means the ball is dribbled by a robot
{
if(dribble_id_ <= 5)
getModelState(CYAN_TEAM, dribble_id_, track_ms_);
else
getModelState(MAGENTA_TEAM, dribble_id_-5, track_ms_);
if(last_dribble_id_ != dribble_id_)
{
robot_initpos_ = track_ms_.pos;//ball_state_.pos;
}
if(R1_isDribble3m())
rtnv = 1;
// if(R2_isDribbleCrossField())
// rtnv = 2;
}
last_dribble_id_ = dribble_id_;
return rtnv;
}
bool auto_referee::R1_isDribble3m()
{
if(robot_initpos_.distance(track_ms_.pos) > 300)
{
ball_resetpos_ = getBallRstPtNotInPenalty(ball_state_.pos);
sendGameCommand(STOPROBOT);
nextCmd_ = (lastTouchBallTeam_==CYAN_TEAM)? OPP_FREEKICK : OUR_FREEKICK;
writeRecord(track_ms_.name+" dribbles more than 300 cm");
OUTINFO("robot init pos:[%.1f, %.1f], pos:[%.1f, %.1f]\n", robot_initpos_.x_, robot_initpos_.y_,
track_ms_.pos.x_, track_ms_.pos.y_);
return true;
}
else
return false;
}
/*
bool auto_referee::R2_isDribbleCrossField()
{
// Don't check this rule when kickoff, after this, always check this rule;
if(sgn(ball_initpos_.x_) != sgn(ball_state_.pos.x_) && sgn(ball_initpos_.x_) != 0)
{
if(!kickoff_flg_)
{
ball_resetpos_ = ball_state_.pos;
OUTINFO("rest pt:%.1f %.1f\n",ball_resetpos_.x_, ball_resetpos_.y_);
sendGameCommand(STOPROBOT);
nextCmd_ = (lastTouchBallTeam_==CYAN_TEAM)? OPP_FREEKICK : OUR_FREEKICK;
writeRecord(track_ms_.name+" dribbles across the field");
return true;
}
else
{
kickoff_flg_ = false;
return false;
}
}
else
return false;
}
*/
bool auto_referee::R4_isOppGoalOrPenaltyArea()
{
int cyan_num1=0, magen_num1=0, cyan_num2=0, magen_num2=0;
for(ModelState ms : cyan_info_)
{
if(ms.id != 1) // not consider the goal keeper
{
if(fieldinfo_.isOppGoal(ms.pos) || fieldinfo_.isOurGoal(ms.pos) ||
isOurGoalPoleArea(ms.pos) || isOppGoalPoleArea(ms.pos))
{
ball_resetpos_ = getBallRstPtNotInPenalty(ball_state_.pos);
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_FREEKICK;
writeRecord(ms.name+" in the goal/goal_pole area!");
return true;
}
if(fieldinfo_.isOurPenalty(ms.pos))
cyan_num1++;
if(fieldinfo_.isOppPenalty(ms.pos))
cyan_num2++;
if(cyan_num1 >=2 || cyan_num2 >= 2) // if two or more robots are in penalty areas, then they violate the rule
{
ball_resetpos_ = getBallRstPtNotInPenalty(ball_state_.pos);
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_FREEKICK;
writeRecord("two or more cyan robots in the penalty area!");
return true;
}
}
}
for(ModelState ms : magenta_info_)
{
if(ms.id != 1) // not consider the goal keeper
{
if(fieldinfo_.isOppGoal(ms.pos) || fieldinfo_.isOurGoal(ms.pos) ||
isOurGoalPoleArea(ms.pos) || isOppGoalPoleArea(ms.pos))
{
ball_resetpos_ = getBallRstPtNotInPenalty(ball_state_.pos);
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_FREEKICK;
writeRecord(ms.name+" in the goal/goal_pole area!");
return true;
}
if(fieldinfo_.isOurPenalty(ms.pos))
magen_num1++;
if(fieldinfo_.isOppPenalty(ms.pos))
magen_num2++;
if(magen_num1 >=2 || magen_num2>=2) // if two or more robots are in penalty areas, then they violate the rule
{
ball_resetpos_ = getBallRstPtNotInPenalty(ball_state_.pos);
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_FREEKICK;
writeRecord("two or more magenta robots in the penalty area!");
return true;
}
}
}
return false;
}
bool auto_referee::R5_isTooCloseToBall()
{
if(currentCmd_ == OUR_THROWIN || currentCmd_ == OUR_GOALKICK || currentCmd_ == OUR_CORNERKICK || currentCmd_ == OUR_FREEKICK) // refered as 4-type-kick
{
int count=0;
for(ModelState ms : magenta_info_)
{
if( !fieldinfo_.isOppPenalty(ms.pos) && ball_state_.pos.distance(ms.pos)<300.0)
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the 4-type-kick positioning rule");
return true;
}
}
for(ModelState ms : cyan_info_)
{
if(ball_state_.pos.distance(ms.pos)<200.0)
count++;
if(count>1)
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the 4-type-kick positioning rule");
return true;
}
}
}
else if(currentCmd_ == OPP_THROWIN || currentCmd_ == OPP_GOALKICK || currentCmd_ == OPP_CORNERKICK || currentCmd_ == OPP_FREEKICK)
{
int count=0;
for(ModelState ms : cyan_info_)
{
if( !fieldinfo_.isOurPenalty(ms.pos) && ball_state_.pos.distance(ms.pos)<300.0)
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the 4-type-kick positioning rule");
return true;
}
}
for(ModelState ms : magenta_info_)
{
if(ball_state_.pos.distance(ms.pos)<200.0)
count++;
if(count>1)
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the 4-type-kick positioning rule");
return true;
}
}
}
else if(currentCmd_ == OUR_KICKOFF)
{
int count=0;
for(ModelState ms : cyan_info_)
{
if( !(fieldinfo_.isOurField(ms.pos) && ball_state_.pos.distance(ms.pos)>200.0) )
count++;
if(count > 1) // only the robot taking the kcik could violate the rule; but now more than 1 robot violate the rule;
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the kick-off positioning rule");
return true;
}
}
for(ModelState ms : magenta_info_)
{
if( !(fieldinfo_.isOppField(ms.pos) && ball_state_.pos.distance(ms.pos)>300.0) )
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the kick-off positioning rule");
return true;
}
}
}
else if(currentCmd_ == OPP_KICKOFF)
{
int count=0;
for(ModelState ms : magenta_info_)
{
if( !(fieldinfo_.isOurField(ms.pos) && ball_state_.pos.distance(ms.pos)>200.0) )
count++;
if(count > 1) // only the robot taking the kcik could violate the rule; but now more than 1 robot violate the rule;
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the kick-off positioning rule");
return true;
}
}
for(ModelState ms : cyan_info_)
{
if( !(fieldinfo_.isOppField(ms.pos) && ball_state_.pos.distance(ms.pos)>300.0) )
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the kick-off positioning rule");
return true;
}
}
}
else if(currentCmd_ == DROPBALL)
{
for(ModelState ms : magenta_info_)
{
if( !fieldinfo_.isOppPenalty(ms.pos) && ball_state_.pos.distance(ms.pos)<100.0)
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the drop-ball positioning rule");
return true;
}
}
for(ModelState ms : cyan_info_)
{
if( !fieldinfo_.isOurPenalty(ms.pos) && ball_state_.pos.distance(ms.pos)<100.0)
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the drop-ball positioning rule");
return true;
}
}
}
else if(currentCmd_ == OUR_PENALTY )
{
int count=0;
for(ModelState ms : magenta_info_)
{
if(ms.id != 1)
{
if( fieldinfo_.isOppPenalty(ms.pos) || fieldinfo_.isOurPenalty(ms.pos) || ball_state_.pos.distance(ms.pos)<300.0)
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the penalty-kick positioning rule");
return true;
}
}
}
for(ModelState ms : cyan_info_)
{
if(ms.id != 1)
{
if(ball_state_.pos.distance(ms.pos)<300.0)
count++;
if(fieldinfo_.isOppPenalty(ms.pos) || fieldinfo_.isOurPenalty(ms.pos) || count>1)
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the penalty-kick positioning rule");
return true;
}
}
}
}
else if(currentCmd_ == OPP_PENALTY)
{
int count=0;
for(ModelState ms : cyan_info_)
{
if(ms.id != 1)
{
if( fieldinfo_.isOppPenalty(ms.pos) || fieldinfo_.isOurPenalty(ms.pos) || ball_state_.pos.distance(ms.pos)<300.0)
{
sendGameCommand(STOPROBOT);
writeRecord("cyan violates the penalty-kick positioning rule");
return true;
}
}
}
for(ModelState ms : magenta_info_)
{
if(ms.id != 1)
{
if(ball_state_.pos.distance(ms.pos)<300.0)
count++;
if(fieldinfo_.isOppPenalty(ms.pos) || fieldinfo_.isOurPenalty(ms.pos) || count>1)
{
sendGameCommand(STOPROBOT);
writeRecord("magenta violates the penalty-kick positioning rule");
return true;
}
}
}
}
R4_isOppGoalOrPenaltyArea(); // check if violates rule 4
return false;
}
bool auto_referee::R3_isBallOutOrGoal()
{
static std::string s;
if( fieldinfo_.isOutBorder(LEFTBORDER, ball_state_.pos) )
{
OUTINFO("LEFT out pos:%f %f %f\n",ball_state_.pos.x_, ball_state_.pos.y_, ball_state_.pos_z);
if(fabs(ball_state_.pos.y_) < fieldinfo_.ourGoal_[GOAL_UPPER].y_-BALL_RADIUS && fabs(ball_state_.pos_z) < GOAL_HEIGHT-BALL_RADIUS
&& ball_state_.pos.x_>-FIELD_LENGTH/2.0 - GOALPOST_WIDTH) // magenta goals
{
if(currentCmd_ != OUR_KICKOFF) // prevent the code from going into again
{
sendGameCommand(STOPROBOT);
magenta_score_++;
nextCmd_ = OUR_KICKOFF;
ball_resetpos_ = DPoint(0.0, 0.0);
s="Cyan : Magenta ["+ std::to_string(cyan_score_)+" : "+ std::to_string(magenta_score_) +"]\t Magenta goals. ";
writeRecord(s);
}
return true;
}
else // ball out
{
if(lastTouchBallTeam_ == CYAN_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_CORNERKICK;
ball_resetpos_ = (ball_state_.pos.distance(LU_CORNER) < ball_state_.pos.distance(LD_CORNER))?
LU_CORNER : LD_CORNER;
writeRecord("Cyan collides ball out");
}
else if(lastTouchBallTeam_ == MAGENTA_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_GOALKICK;
ball_resetpos_ = (ball_state_.pos.distance(LU_RSTPT) < ball_state_.pos.distance(LD_RSTPT))?
LU_RSTPT : LD_RSTPT;
writeRecord("Magenta collides ball out");
}
else
{
sendGameCommand(STOPROBOT);
nextCmd_ = DROPBALL;
ball_resetpos_ = DPoint(0.0, 0.0);
writeRecord("Cannot determine cyan or magenta collides ball out");
}
return true;
}
}
else if(fieldinfo_.isOutBorder(RIGHTBORDER, ball_state_.pos))
{
OUTINFO("RIGHT out pos:%f %f %f\n",ball_state_.pos.x_, ball_state_.pos.y_, ball_state_.pos_z);
if(fabs(ball_state_.pos.y_) < fieldinfo_.ourGoal_[GOAL_UPPER].y_-BALL_RADIUS && fabs(ball_state_.pos_z) < GOAL_HEIGHT-BALL_RADIUS
&& ball_state_.pos.x_<FIELD_LENGTH/2.0 + GOALPOST_WIDTH) // cyan goals
{
if(currentCmd_ != OPP_KICKOFF) // prevent the code from going into again
{
sendGameCommand(STOPROBOT);
cyan_score_++;
nextCmd_ = OPP_KICKOFF;
ball_resetpos_ = DPoint(0.0, 0.0);
s="Cyan : Magenta ["+ std::to_string(cyan_score_)+" : "+ std::to_string(magenta_score_) +"]\t Cyan goals. ";
writeRecord(s);
}
return true;
}
else // ball out
{
if(lastTouchBallTeam_ == CYAN_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_GOALKICK;
ball_resetpos_ = (ball_state_.pos.distance(RU_RSTPT) < ball_state_.pos.distance(RD_RSTPT))?
RU_RSTPT : RD_RSTPT;
writeRecord("Cyan collides ball out");
}
else if(lastTouchBallTeam_ == MAGENTA_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_CORNERKICK;
ball_resetpos_ = (ball_state_.pos.distance(RU_CORNER) < ball_state_.pos.distance(RD_CORNER))?
RU_CORNER : RD_CORNER;
writeRecord("Magenta collides ball out");
}
else
{
sendGameCommand(STOPROBOT);
nextCmd_ = DROPBALL;
ball_resetpos_ = DPoint(0.0, 0.0);
writeRecord("Cannot determine cyan or magenta collides ball out");
}
return true;
}
}
else if(fieldinfo_.isOutBorder(UPBORDER, ball_state_.pos))
{
OUTINFO("UP out pos:%f %f %f\n",ball_state_.pos.x_, ball_state_.pos.y_, ball_state_.pos_z);
ball_resetpos_ = DPoint(ball_state_.pos.x_, fieldinfo_.yline_[0]-30.0);
if(lastTouchBallTeam_ == CYAN_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_THROWIN;
writeRecord("Cyan collides ball out");
}
else if(lastTouchBallTeam_ == MAGENTA_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_THROWIN;
writeRecord("Magenta collides ball out");
}
else
{
sendGameCommand(STOPROBOT);
nextCmd_ = DROPBALL;
writeRecord("Cannot determine cyan or magenta collides ball out");
}
return true;
}
else if(fieldinfo_.isOutBorder(DOWNBORDER, ball_state_.pos))
{
OUTINFO("DOWN out pos:%f %f %f\n",ball_state_.pos.x_, ball_state_.pos.y_, ball_state_.pos_z);
ball_resetpos_ = DPoint(ball_state_.pos.x_, fieldinfo_.yline_[5]+30.0);
if(lastTouchBallTeam_ == CYAN_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OPP_THROWIN;
writeRecord("Cyan collides ball out");
}
else if(lastTouchBallTeam_ == MAGENTA_TEAM)
{
sendGameCommand(STOPROBOT);
nextCmd_ = OUR_THROWIN;
writeRecord("Magenta collides ball out");
}
else
{
sendGameCommand(STOPROBOT);
nextCmd_ = DROPBALL;
writeRecord("Cannot determine cyan or magenta collides ball out");
}
return true;
}
return false;
}
bool auto_referee::isGoal()
{
static std::string s;
if(fieldinfo_.isOutBorder(LEFTBORDER, ball_state_.pos) && fabs(ball_state_.pos.y_) < fieldinfo_.ourGoal_[GOAL_UPPER].y_-BALL_RADIUS
&& fabs(ball_state_.pos_z) < GOAL_HEIGHT-BALL_RADIUS) // magenta goals
{
if(currentCmd_ != OUR_KICKOFF) // prevent the code from going into again
{
sendGameCommand(STOPROBOT);
magenta_score_++;
nextCmd_ = OUR_KICKOFF;
ball_resetpos_ = DPoint(0.0, 0.0);
s="Cyan : Magenta ["+ std::to_string(cyan_score_)+" : "+ std::to_string(magenta_score_) +"]\t Magenta goals. ";
writeRecord(s);
}
std::cout<<fieldinfo_.ourGoal_[GOAL_UPPER].x_<<std::endl;
return true;
}
else if(fieldinfo_.isOutBorder(RIGHTBORDER, ball_state_.pos) && fabs(ball_state_.pos.y_) < fieldinfo_.ourGoal_[GOAL_UPPER].y_ - BALL_RADIUS
&& fabs(ball_state_.pos_z) < GOAL_HEIGHT-BALL_RADIUS) // cyan goals
{
if(currentCmd_ != OPP_KICKOFF) // prevent the code from going into again
{
sendGameCommand(STOPROBOT);
cyan_score_++;
nextCmd_ = OPP_KICKOFF;
ball_resetpos_ = DPoint(0.0, 0.0);
s="Cyan : Magenta ["+ std::to_string(cyan_score_)+" : "+ std::to_string(magenta_score_) +"]\t Cyan goals. ";
writeRecord(s);
}
return true;
}
return false;
}
bool auto_referee::isOurGoalPoleArea(DPoint world_pt)
{
if(world_pt.x_ < -FIELD_LENGTH/2.0 && world_pt.x_ > -FIELD_LENGTH/2.0 - GOALPOST_WIDTH &&
world_pt.y_ < GOALPOST_LEN/2.0 && world_pt.y_ > -GOALPOST_LEN/2.0)
return true;
else
return false;
}
bool auto_referee::isOppGoalPoleArea(DPoint world_pt)
{
if(world_pt.x_ > FIELD_LENGTH/2.0 && world_pt.x_ < FIELD_LENGTH/2.0 + GOALPOST_WIDTH &&
world_pt.y_ < GOALPOST_LEN/2.0 && world_pt.y_ > -GOALPOST_LEN/2.0)
return true;
else
return false;
}
bool auto_referee::setBallPos(double x, double y)
{
#if 0
gazebo_msgs::SetModelState ms;
ms.request.model_state.model_name = ball_name_;
ms.request.model_state.pose.position.x = x * CM2M_CONVERSION;
ms.request.model_state.pose.position.y = y * CM2M_CONVERSION;
ms.request.model_state.pose.position.z = 0.12;
ms.request.model_state.twist.linear.x = 0.0;
ms.request.model_state.twist.linear.y = 0.0;
ms.request.model_state.twist.linear.z = 0.0;
ms.request.model_state.twist.angular.x = 0.0;
ms.request.model_state.twist.angular.y = 0.0;
ms.request.model_state.twist.angular.z = 0.0;
if(setMS_client_.call(ms))
return true;
else
return false;
#else
gazebo_msgs::ModelState ms;
ms.model_name = ball_name_;
ms.pose.position.x = x * CM2M_CONVERSION;
ms.pose.position.y = y * CM2M_CONVERSION;
ms.pose.position.z = 0.12;
for(int i=0; i<2; i++) // send serveral times to make sure the message is received
setMS_pub_.publish(ms);
#endif
}
DPoint auto_referee::getBallRstPtNotInPenalty(DPoint ball_pos)
{
if(!fieldinfo_.isOppPenalty(ball_pos) && !fieldinfo_.isOurPenalty(ball_pos))
return ball_pos;
else if(fieldinfo_.isOppPenalty(ball_pos))
return (ball_pos.distance(RU_RSTPT) < ball_pos.distance(RD_RSTPT))?
RU_RSTPT : RD_RSTPT;
else if(fieldinfo_.isOurPenalty(ball_pos))
return (ball_pos.distance(LU_RSTPT) < ball_pos.distance(LD_RSTPT))?
LU_RSTPT : LD_RSTPT;
}
bool auto_referee::getModelState(int which_team, int id, ModelState &ms)
{
if(which_team == CYAN_TEAM)
{
for(ModelState mss : cyan_info_)
if(id == mss.id)
ms = mss;
return true;
}
else if(which_team == MAGENTA_TEAM)
{
for(ModelState mss : magenta_info_)
if(id == mss.id)
ms = mss;
return true;
}
else
OUTINFO("Please specify an appropriate team\n");
return false;
}
void auto_referee::sendGameCommand(int id)
{
static int PreCyanMode = id, PreMagentaMode = id;
cyan_coach_info_.MatchMode = id;
switch (id)
{
case STOPROBOT:
magenta_gameCmd_.MatchMode = id;
writeRecord("(cmd) STOP");
break;
case STARTROBOT:
magenta_gameCmd_.MatchMode = id;
writeRecord("(cmd) START");
break;
case PARKINGROBOT:
magenta_gameCmd_.MatchMode = id;
writeRecord("(cmd) PARKING");
break;
case OUR_KICKOFF:
magenta_gameCmd_.MatchMode = OPP_KICKOFF;
writeRecord("(cmd) CYAN KICKOFF");
break;
case OPP_KICKOFF:
magenta_gameCmd_.MatchMode = OUR_KICKOFF;
writeRecord("(cmd) MAGENTA KICKOFF");
break;
case OUR_THROWIN:
magenta_gameCmd_.MatchMode = OPP_THROWIN;
writeRecord("(cmd) CYAN THROWIN");
break;
case OPP_THROWIN:
magenta_gameCmd_.MatchMode = OUR_THROWIN;
writeRecord("(cmd) MAGENTA THROWIN");
break;
case OUR_GOALKICK:
magenta_gameCmd_.MatchMode = OPP_GOALKICK;
writeRecord("(cmd) CYAN GOALKICK");
break;
case OPP_GOALKICK:
magenta_gameCmd_.MatchMode = OUR_GOALKICK;
writeRecord("(cmd) MAGENTA GOALKICK");
break;
case OUR_CORNERKICK:
magenta_gameCmd_.MatchMode = OPP_CORNERKICK;
writeRecord("(cmd) CYAN CORNERKICK");
break;
case OPP_CORNERKICK:
magenta_gameCmd_.MatchMode = OUR_CORNERKICK;
writeRecord("(cmd) MAGENTA CORNERKICK");
break;
case OUR_FREEKICK:
magenta_gameCmd_.MatchMode = OPP_FREEKICK;
writeRecord("(cmd) CYAN FREEKICK");
break;
case OPP_FREEKICK:
magenta_gameCmd_.MatchMode = OUR_FREEKICK;
writeRecord("(cmd) MAGENTA FREEKICK");
break;
case OUR_PENALTY:
writeRecord("(cmd) CYAN PENALTY");
magenta_gameCmd_.MatchMode = OPP_PENALTY;
break;
case OPP_PENALTY:
magenta_gameCmd_.MatchMode = OUR_PENALTY;
writeRecord("(cmd) MAGENTA PENALTY");
break;
case DROPBALL:
magenta_gameCmd_.MatchMode = id;
writeRecord("(cmd) DROPBALL");
break;
default:
magenta_gameCmd_.MatchMode = STOPROBOT;
writeRecord("(cmd) STOP");
break;
}
cyan_coach_info_.MatchType = PreCyanMode;
magenta_gameCmd_.MatchType = PreMagentaMode;
//zdx_note write solid here, should be modify, according to the coach's message. 2020.11.07
//cyan_coach_info_.idA = 1;
//cyan_coach_info_.idB = 169;
cyan_coach_info_.angleA = 450;
cyan_coach_info_.angleB = 10;
//cyan_coach_info_.kickforce = 77;
magenta_gameCmd_.angleA = 450;
magenta_gameCmd_.angleB = 10;
//zdx_note end.
PreCyanMode = cyan_coach_info_.MatchMode;
PreMagentaMode = magenta_gameCmd_.MatchMode;
currentCmd_ = id;
for(int i=0; i<5; i++) // send serveral times to make sure the message is received
{
cyan_pub_.publish(cyan_coach_info_);
magenta_pub_.publish(magenta_gameCmd_);
}
}
bool auto_referee::waittime(double sec)
{
static int count=0;
if(count < sec/LOOP_PERIOD) // wait 5 secs
{
count++;
return false;
}
else
{
count = 0;
return true;
}
}
bool auto_referee::createRecord()
{
std::string filename, dirname("record/");
filename = dirname + cyan_prefix_ + "-" + magenta_prefix_ + "(" + getSysTime() + ").txt";
boost::filesystem::path dir(dirname);
if(!(boost::filesystem::exists(dir)))
if (boost::filesystem::create_directory(dir))
OUTINFO("Successfully create directory: %s!\n", dir.c_str());
record_.open(filename);
if(record_.is_open())
{
OUTINFO("Successfully create file: %s!\n", filename.c_str());
return true;
}
else
{
OUTINFO("Failed create file: %s!\n", filename.c_str());
return false;
}
}
std::string auto_referee::getSysTime(std::string format)
{
static int size = 50;
time_t now=time(NULL); // get time now
char buffer[size];
buffer[0] = '\0';
if (now != -1)
strftime(buffer, size, format.c_str(), localtime(&now));
return std::string(buffer);
}
void auto_referee::writeRecord(string s)
{
std::string ss = "[" + getSysTime("%T") + "] " +s + "\n";
record_<<ss;
OUTINFO("%s\n", s.c_str());
}
int auto_referee::sgn(double x)
{
if(gazebo::math::equal(x, 0.0, 10.0)) // error: +-10 cm
return 0;
else if(x < 0.0)
return -1;
else
return 1;
}
void auto_referee::service_queue_thread()
{
static const double timeout = 0.01;
while(rosnode_->ok())
service_queue_.callAvailable(ros::WallDuration(timeout));
}
void auto_referee::message_queue_thread()
{
static const double timeout = 0.01;
while (rosnode_->ok())
message_queue_.callAvailable(ros::WallDuration(timeout));
}
void auto_referee::test()
{
#if 0
for(ModelState ms : cyan_info_)
OUTINFO("cyan_info:\n\tname:%s,\t id:%d\n \tpos:[%.0f, %.0f](cm), ori:%.0f(deg)\n \tvel:[%.0f,%.0f](cm/s), w:%.0f(deg/s)\n",
ms.name.c_str(), ms.id, ms.pos.x_, ms.pos.y_, ms.ori*RAD2DEG, ms.vel.x_, ms.vel.y_, ms.w*RAD2DEG);
for(ModelState ms : magenta_info_)
OUTINFO("magenta_info:\n\tname:%s,\t id:%d\n \tpos:[%.0f, %.0f](cm), ori:%.0f(deg)\n \tvel:[%.0f,%.0f](cm/s), w:%.0f(deg/s)\n",
ms.name.c_str(), ms.id, ms.pos.x_, ms.pos.y_, ms.ori*RAD2DEG, ms.vel.x_, ms.vel.y_, ms.w*RAD2DEG);
#endif
#if 0
//detectBallOut();
detectGoal();
#endif
#if 0
sendGameCommand(OUR_PENALTY);
R5_isTooCloseToBall();
#endif
OUTINFO("id:%d", dribble_id_);
if(lastTouchBallTeam_ == CYAN_TEAM)
OUTINFO("CYAN\n");
else if(lastTouchBallTeam_ == MAGENTA_TEAM)
OUTINFO("MAGENTA\n");
else
OUTINFO("NONE\n");
}
int main(int argc, char **argv)
{
int id = 0;
if(argc >=2)
id = atoi(argv[1]);
else if(argc < 2 || (id!=CYAN_TEAM && id!=MAGENTA_TEAM))
{
cout<<"Please specify who kicks off. "<<CYAN_TEAM<<" for cyan; "<<MAGENTA_TEAM<<" for magenta"<<endl;
return -1;
}
ros::init(argc,argv,"auto_referee");
ros::Time::init();
auto_referee ref(id);
ros::spin();
return 0;
}
| 34.409023 | 157 | 0.556158 | [
"model",
"solid"
] |
e1a4175687e1d96a9bb8f68cf6aff750e40f26f8 | 18,978 | cc | C++ | test/common/upstream/cluster_discovery_manager_test.cc | VMAJSTER/envoy | bd0ec3d14bc2c6159ee9fafe76355f9607b5c9f7 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:23:12.000Z | 2022-03-02T14:23:12.000Z | test/common/upstream/cluster_discovery_manager_test.cc | VMAJSTER/envoy | bd0ec3d14bc2c6159ee9fafe76355f9607b5c9f7 | [
"Apache-2.0"
] | 153 | 2021-10-04T04:32:48.000Z | 2022-03-31T04:22:40.000Z | test/common/upstream/cluster_discovery_manager_test.cc | VMAJSTER/envoy | bd0ec3d14bc2c6159ee9fafe76355f9607b5c9f7 | [
"Apache-2.0"
] | 1 | 2019-07-09T21:09:57.000Z | 2019-07-09T21:09:57.000Z | #include <functional>
#include <list>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "envoy/upstream/cluster_manager.h"
#include "source/common/common/cleanup.h"
#include "source/common/upstream/cluster_discovery_manager.h"
#include "test/mocks/upstream/thread_local_cluster.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Upstream {
namespace {
class TestClusterUpdateCallbacksHandle : public ClusterUpdateCallbacksHandle,
RaiiListElement<ClusterUpdateCallbacks*> {
public:
TestClusterUpdateCallbacksHandle(ClusterUpdateCallbacks& cb,
std::list<ClusterUpdateCallbacks*>& parent)
: RaiiListElement<ClusterUpdateCallbacks*>(parent, &cb) {}
};
class TestClusterLifecycleCallbackHandler : public ClusterLifecycleCallbackHandler {
public:
// Upstream::ClusterLifecycleCallbackHandler
ClusterUpdateCallbacksHandlePtr addClusterUpdateCallbacks(ClusterUpdateCallbacks& cb) override {
return std::make_unique<TestClusterUpdateCallbacksHandle>(cb, update_callbacks_);
}
void invokeClusterAdded(ThreadLocalCluster& cluster) {
for (auto& cb : update_callbacks_) {
cb->onClusterAddOrUpdate(cluster);
}
}
std::list<ClusterUpdateCallbacks*> update_callbacks_;
};
enum class Action {
InvokePrevious,
InvokeSelf,
InvokeNext,
InvokeLast,
InvokeOther,
ProcessFoo,
ProcessBar,
DestroyPrevious,
DestroySelf,
DestroyNext,
DestroyOther,
AddNewToFoo,
};
const char* actionToString(Action action) {
switch (action) {
case Action::InvokePrevious:
return "invoke previous";
case Action::InvokeSelf:
return "invoke self";
case Action::InvokeNext:
return "invoke next";
case Action::InvokeLast:
return "invoke last";
case Action::InvokeOther:
return "invoke other";
case Action::ProcessFoo:
return "process foo";
case Action::ProcessBar:
return "process bar";
case Action::DestroyPrevious:
return "destroy previous";
case Action::DestroySelf:
return "destroy self";
case Action::DestroyNext:
return "destroy next";
case Action::DestroyOther:
return "destroy other";
case Action::AddNewToFoo:
return "add new to foo";
}
return "invalid action";
}
std::ostream& operator<<(std::ostream& os, Action action) {
os << actionToString(action);
return os;
}
enum class OtherActionsExecution {
AfterFirstAction,
WithinFirstAction,
};
struct ActionsParameter {
ActionsParameter(std::vector<Action> actions, std::vector<std::string> called_callbacks,
OtherActionsExecution other_actions_execution)
: actions_(std::move(actions)), called_callbacks_(std::move(called_callbacks)),
other_actions_execution_(other_actions_execution) {}
std::vector<Action> actions_;
std::vector<std::string> called_callbacks_;
OtherActionsExecution other_actions_execution_;
};
std::ostream& operator<<(std::ostream& os, const ActionsParameter& param) {
const char* prefix = "";
const char* first_separator = ", ";
if (param.other_actions_execution_ == OtherActionsExecution::WithinFirstAction) {
prefix = "during ";
first_separator = ": ";
}
os << prefix << param.actions_.front() << first_separator
<< absl::StrJoin(param.actions_.begin() + 1, param.actions_.end(), ", ",
absl::StreamFormatter())
<< " => " << absl::StrJoin(param.called_callbacks_, ", ");
return os;
}
class ActionExecutor {
public:
ActionExecutor()
: cdm_("test_thread", lifecycle_handler_), previous_(addCallback("foo", "previous")),
self_(addCallback("foo", "self")), next_(addCallback("foo", "next")),
last_(addCallback("foo", "last")), other_(addCallback("bar", "other")) {}
void setSelfCallback(std::function<void()> self_callback) {
self_callback_ = std::move(self_callback);
}
void execute(Action action) {
switch (action) {
case Action::InvokePrevious:
useInvoker(previous_.invoker_);
break;
case Action::InvokeSelf:
useInvoker(self_.invoker_);
break;
case Action::InvokeNext:
useInvoker(next_.invoker_);
break;
case Action::InvokeLast:
useInvoker(last_.invoker_);
break;
case Action::InvokeOther:
useInvoker(other_.invoker_);
break;
case Action::ProcessFoo:
processClusterName("foo");
break;
case Action::ProcessBar:
processClusterName("bar");
break;
case Action::DestroyPrevious:
previous_.handle_ptr_.reset();
break;
case Action::DestroySelf:
self_.handle_ptr_.reset();
break;
case Action::DestroyNext:
next_.handle_ptr_.reset();
break;
case Action::DestroyOther:
other_.handle_ptr_.reset();
break;
case Action::AddNewToFoo:
std::string callback_name = "new" + std::to_string(new_.size());
new_.emplace_back(addCallback("foo", std::move(callback_name)));
break;
}
}
ClusterDiscoveryManager::AddedCallbackData addCallback(std::string cluster_name,
std::string callback_name) {
return cdm_.addCallback(
std::move(cluster_name),
std::make_unique<ClusterDiscoveryCallback>(
[this, callback_name = std::move(callback_name)](ClusterDiscoveryStatus) {
// we ignore the status, it's a thing that always comes from outside the manager
bool is_self = callback_name == "self";
called_callbacks_.push_back(std::move(callback_name));
if (is_self && self_callback_) {
self_callback_();
}
}));
}
void processClusterName(std::string name) {
auto cluster = NiceMock<MockThreadLocalCluster>();
cluster.cluster_.info_->name_ = std::move(name);
lifecycle_handler_.invokeClusterAdded(cluster);
}
void useInvoker(ClusterDiscoveryManager::CallbackInvoker& invoker) {
invoker.invokeCallback(ClusterDiscoveryStatus::Available);
}
TestClusterLifecycleCallbackHandler lifecycle_handler_;
ClusterDiscoveryManager cdm_;
std::vector<std::string> called_callbacks_;
ClusterDiscoveryManager::AddedCallbackData previous_, self_, next_, last_, other_;
std::vector<ClusterDiscoveryManager::AddedCallbackData> new_;
std::function<void()> self_callback_;
};
class ActionExecutorTest : public testing::TestWithParam<ActionsParameter> {
public:
void runTest() {
auto& [actions, expected_result, other_actions_execution] = GetParam();
ASSERT_FALSE(actions.empty());
switch (other_actions_execution) {
case OtherActionsExecution::AfterFirstAction:
for (auto action : actions) {
executor_.execute(action);
}
break;
case OtherActionsExecution::WithinFirstAction:
executor_.setSelfCallback([this, begin = actions.begin() + 1, end = actions.end()]() {
for (auto it = begin; it != end; ++it) {
executor_.execute(*it);
}
});
executor_.execute(actions.front());
break;
}
EXPECT_EQ(executor_.called_callbacks_, expected_result);
}
ActionExecutor executor_;
};
std::vector<ActionsParameter> all_actions = {
// invoke self twice in a row; expect it to be called once
ActionsParameter({Action::InvokeSelf, Action::InvokeSelf}, {"self"},
OtherActionsExecution::AfterFirstAction),
// invoke self then other; expect them to be called normally
ActionsParameter({Action::InvokeSelf, Action::InvokeOther}, {"self", "other"},
OtherActionsExecution::AfterFirstAction),
// invoke self then process foo; since self was already called, processing foo should not call
// it again
ActionsParameter({Action::InvokeSelf, Action::ProcessFoo}, {"self", "previous", "next", "last"},
OtherActionsExecution::AfterFirstAction),
// invoke self then process bar; expect them to be called normally
ActionsParameter({Action::InvokeSelf, Action::ProcessBar}, {"self", "other"},
OtherActionsExecution::AfterFirstAction),
// invoke self then destroy self; expect destroying to be a noop instead of corrupting things
// (this is mostly for address sanitizer)
ActionsParameter({Action::InvokeSelf, Action::DestroySelf}, {"self"},
OtherActionsExecution::AfterFirstAction),
// process foo then invoke self; since self was called as a part of processing foo, invoke
// should be a noop
ActionsParameter({Action::ProcessFoo, Action::InvokeSelf}, {"previous", "self", "next", "last"},
OtherActionsExecution::AfterFirstAction),
// process foo twice; expect the callbacks to be called once
ActionsParameter({Action::ProcessFoo, Action::ProcessFoo}, {"previous", "self", "next", "last"},
OtherActionsExecution::AfterFirstAction),
// process foo then bar; expect the callbacks to be called normally
ActionsParameter({Action::ProcessFoo, Action::ProcessBar},
{"previous", "self", "next", "last", "other"},
OtherActionsExecution::AfterFirstAction),
// process foo then destroy self; expect destroying to be a noop instead of corrupting things
// (this is mostly for address sanitizer)
ActionsParameter({Action::ProcessFoo, Action::DestroySelf},
{"previous", "self", "next", "last"}, OtherActionsExecution::AfterFirstAction),
// destroy self then invoke self; expect the invoke to be a noop
ActionsParameter({Action::DestroySelf, Action::InvokeSelf}, {},
OtherActionsExecution::AfterFirstAction),
// destroy self then process foo; expect all callbacks but self to be invoked
ActionsParameter({Action::DestroySelf, Action::ProcessFoo}, {"previous", "next", "last"},
OtherActionsExecution::AfterFirstAction),
// destroy self twice; expect the second destroying to be a noop instead of corrupting things
// (this is mostly for address sanitizer)
ActionsParameter({Action::DestroySelf, Action::DestroySelf}, {},
OtherActionsExecution::AfterFirstAction),
// when invoking self, invoke self; expect the second invoke to be a noop
ActionsParameter({Action::InvokeSelf, Action::InvokeSelf}, {"self"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, destroy self; expect the second destroying to be a noop instead of
// corrupting things (this is mostly for address sanitizer)
ActionsParameter({Action::InvokeSelf, Action::DestroySelf}, {"self"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, process foo; expect all callbacks but self to be invoked, since self was
// already invoked
ActionsParameter({Action::InvokeSelf, Action::ProcessFoo}, {"self", "previous", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, process bar; expect the callbacks to be called normally
ActionsParameter({Action::InvokeSelf, Action::ProcessBar}, {"self", "other"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, invoke previous; expect the invoke to be a noop, because previous has
// already been called and done
ActionsParameter({Action::ProcessFoo, Action::InvokePrevious},
{"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, invoke self; expect the invoke to be a noop, because self is being
// called right now
ActionsParameter({Action::ProcessFoo, Action::InvokeSelf}, {"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, invoke next; expect next to be called once (with the invoke), while
// calling it during the process should become a noop
ActionsParameter({Action::ProcessFoo, Action::InvokeNext}, {"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, invoke last; expect last to be called out of order
ActionsParameter({Action::ProcessFoo, Action::InvokeLast}, {"previous", "self", "last", "next"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, process foo; expect the second process to be a noop
ActionsParameter({Action::ProcessFoo, Action::ProcessFoo}, {"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, process bar; expect the callbacks to be called normally, but bar
// callbacks should be called before the rest of foo callbacks
ActionsParameter({Action::ProcessFoo, Action::ProcessBar},
{"previous", "self", "other", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, destroy self; expect the second destroying to be a noop (since self is
// being called at the moment), instead of corrupting things (this is mostly for address
// sanitizer)
ActionsParameter({Action::ProcessFoo, Action::DestroySelf},
{"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, destroy next; expect next callback to be skipped
ActionsParameter({Action::ProcessFoo, Action::DestroyNext}, {"previous", "self", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, add a new callback to foo; expect the new callback to be not invoked
// (could be invoked with a follow-up process)
ActionsParameter({Action::ProcessFoo, Action::AddNewToFoo},
{"previous", "self", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, invoke previous and process foo; expect the process to call only next and
// last
ActionsParameter({Action::InvokeSelf, Action::InvokePrevious, Action::ProcessFoo},
{"self", "previous", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, invoke next and process foo; expect process to call only previous and
// last
ActionsParameter({Action::InvokeSelf, Action::InvokeNext, Action::ProcessFoo},
{"self", "next", "previous", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, invoke other invoke last, and process bar; expect the process to be a
// noop (invoking last for visibility of the noop)
ActionsParameter(
{Action::InvokeSelf, Action::InvokeOther, Action::InvokeLast, Action::ProcessBar},
{"self", "other", "last"}, OtherActionsExecution::WithinFirstAction),
// when invoking self, process foo then invoke previous; expect the process to skip self (as
// it's being called at the moment) and invoking previous to be a noop (called during the
// process)
ActionsParameter({Action::InvokeSelf, Action::ProcessFoo, Action::InvokePrevious},
{"self", "previous", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, process foo then invoke previous; expect the process to skip self (as
// it's being called at the moment) and invoking previous to be a noop (called during the
// process)
ActionsParameter({Action::InvokeSelf, Action::ProcessFoo, Action::DestroyPrevious},
{"self", "previous", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, destroy previous and process foo; expect self and previous to be skipped
// when processing
ActionsParameter({Action::InvokeSelf, Action::DestroyPrevious, Action::ProcessFoo},
{"self", "next", "last"}, OtherActionsExecution::WithinFirstAction),
// when invoking self, destroy other and process bar; expect the process to be a noop
ActionsParameter({Action::InvokeSelf, Action::DestroyOther, Action::ProcessBar}, {"self"},
OtherActionsExecution::WithinFirstAction),
// when invoking self, add new callback to foo and process foo; expect self to be skipped, but
// new to be called along with the rest of the callbacks
ActionsParameter({Action::InvokeSelf, Action::AddNewToFoo, Action::ProcessFoo},
{"self", "previous", "next", "last", "new0"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, add new callback to foo, process foo then invoke other; expect the
// second process to call only the new callback, then first process to resume with the rest of
// the callbacks (the other callback is added to see the split between two processes)
ActionsParameter(
{Action::ProcessFoo, Action::AddNewToFoo, Action::ProcessFoo, Action::InvokeOther},
{"previous", "self", "new0", "other", "next", "last"},
OtherActionsExecution::WithinFirstAction),
// when processing foo, add new to foo and destroy next; expect the new callback to be not
// called, same for the next callback
ActionsParameter({Action::ProcessFoo, Action::AddNewToFoo, Action::DestroyNext},
{"previous", "self", "last"}, OtherActionsExecution::WithinFirstAction),
// when processing foo, destroy next and try to invoke next;
// expect the invoke to be noop, and processing to not call the
// next callback
ActionsParameter({Action::ProcessFoo, Action::DestroyNext, Action::InvokeNext},
{"previous", "self", "last"}, OtherActionsExecution::WithinFirstAction),
};
class ClusterDiscoveryTest : public ActionExecutorTest {};
INSTANTIATE_TEST_SUITE_P(ClusterDiscoveryTestActions, ClusterDiscoveryTest,
testing::ValuesIn(all_actions));
TEST_P(ClusterDiscoveryTest, TestActions) { runTest(); }
class ClusterDiscoveryManagerMiscTest : public testing::Test {
public:
ClusterDiscoveryManagerMiscTest() = default;
ActionExecutor executor_;
};
// Test the the discovery in progress value is correct.
TEST_F(ClusterDiscoveryManagerMiscTest, TestDiscoveryInProgressValue) {
// previous is first callback added to foo
EXPECT_FALSE(executor_.previous_.discovery_in_progress_);
// self, next and last callbacks are follow-up callbacks in foo
EXPECT_TRUE(executor_.self_.discovery_in_progress_);
EXPECT_TRUE(executor_.next_.discovery_in_progress_);
EXPECT_TRUE(executor_.last_.discovery_in_progress_);
// other is first callback added to bar
EXPECT_FALSE(executor_.other_.discovery_in_progress_);
}
} // namespace
} // namespace Upstream
} // namespace Envoy
| 42.361607 | 100 | 0.680736 | [
"vector"
] |
e1a49ffb4eb9fd862c1aa6b315356d7dee1e92cb | 1,015 | cpp | C++ | acmicpc/8984.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/8984.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/8984.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <algorithm>
#include <vector>
#include <tuple>
using namespace std;
#define MAX 100001
int n, l, u, v;
vector<int> t, d;
vector<tuple<int, int, int>> st;
long long dpT[MAX], dpD[MAX];
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> n >> l;
for (int i=0; i<n; ++i) {
cin >> u >> v;
st.push_back({u, v, abs(u-v)+l});
t.push_back(u);
d.push_back(v);
}
sort(st.begin(), st.end());
sort(t.begin(), t.end());
sort(d.begin(), d.end());
t.erase(unique(t.begin(), t.end()), t.end());
d.erase(unique(d.begin(), d.end()), d.end());
long long ans = 0;
for (int i=0; i<n; ++i) {
auto x = lower_bound(t.begin(), t.end(), get<0>(st[i])) - t.begin();
auto y = lower_bound(d.begin(), d.end(), get<1>(st[i])) - d.begin();
long long retT = max(dpT[x], dpD[y] + get<2>(st[i]));
long long retD = max(dpD[y], dpT[x] + get<2>(st[i]));
dpT[x] = retT;
dpD[y] = retD;
ans = max({ans, dpT[x], dpD[y]});
}
cout << ans << '\n';
return 0;
}
| 19.901961 | 70 | 0.552709 | [
"vector"
] |
e1ad5804f0f2b6acdfdf311ff7045049301e6668 | 15,548 | cpp | C++ | thrift/lib/cpp/server/test/AggregatorClientTest.cpp | jesboat/fbthrift | 7d8e1dcec59024e526e6768d3d4a66f6c4abe5ac | [
"Apache-2.0"
] | 1 | 2015-11-05T18:31:38.000Z | 2015-11-05T18:31:38.000Z | thrift/lib/cpp/server/test/AggregatorClientTest.cpp | jesboat/fbthrift | 7d8e1dcec59024e526e6768d3d4a66f6c4abe5ac | [
"Apache-2.0"
] | null | null | null | thrift/lib/cpp/server/test/AggregatorClientTest.cpp | jesboat/fbthrift | 7d8e1dcec59024e526e6768d3d4a66f6c4abe5ac | [
"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.
*/
/**
* Test aggregation client for TNonblockingServer servers
* Suppose to send requests to the multiple servers
* aggregate responses
*/
#include <thrift/lib/cpp/server/test/AggregatorUtilTest.h>
#include "common/client_mgmt/TAsyncClientPool.h"
#include "common/client_mgmt/ThriftAggregatorInterface.h"
#include "common/network/NetworkUtil.h"
#include "common/process/CheckPointProfiler.h"
using std::cout;
using std::cerr;
using std::endl;
using std::pair;
using std::string;
using std::vector;
using std::shared_ptr;
using boost::lexical_cast;
using namespace apache::thrift::async;
using namespace facebook::common::client_mgmt;
using namespace facebook::network;
using facebook::CheckPointProfiler;
const size_t kNumOfRounds = 10000;
const int kMaxPolicyTimeout = 10000; // 500 msec
const size_t kOneWayCallDelayUs = 100;
void cleanup(int signo) {
fprintf(stderr, "term on signal %d\n", signo);
exit(0);
}
static void responseAggregator(
const vector<shared_ptr<StructResponse> >& responses,
const vector<pair<int, string> >& errors,
StructResponse* result) {
CHECK(result);
// and concate strings
for (size_t i = 0 ; i < responses.size() && i < errors.size(); ++i) {
if (errors[i].first) {
LOG(ERROR) << "aggregation error for leaf #" << i <<
" - " << errors[i].second;
continue;
}
addResponse(result, *responses[i].get());
}
}
static void s_threadFunction(int threadId,
int numServers,
TAsyncClientPool<AggregatorTestCobClient>& pool,
int* stopFlag,
int* startFlag,
bool oneWayCalls) {
while (*startFlag == 0) {
sleep(1);
}
LOG(INFO) << "Testing two ways, one argument aggregation...";
for (size_t rounds = 0; rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>
aggregatorSendRecv( pool,
&AggregatorTestCobClient::recv_sendStructRecvStruct
);
StructRequest request;
randomData(&request);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendStructRecvStruct,
std::placeholders::_1,
std::placeholders::_2,
std::cref(request));
// prepare aggregate results
StructResponse ethalon, aggregated;
zeroResponse(&aggregated);
zeroResponse(ðalon);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::AggrFunc
aggrCob = std::bind(&responseAggregator,
std::placeholders::_1,
std::placeholders::_2,
&aggregated
);
aggregatorSendRecv.sendRecvAndAggr(fSend, &aggrCob);
// prepare ethalon
for (uint16_t index = 0; index < numServers; ++index) {
addRequest(ðalon, request);
}
CHECK(equalResult(ethalon, aggregated));
}
LOG(INFO) << "Testing one way, one argument aggregation...";
for (size_t rounds = 0; oneWayCalls && rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface<AggregatorTestCobClient>
aggregatorSendRecv(pool);
StructRequest request;
randomData(&request);
ThriftAggregatorInterface<AggregatorTestCobClient>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendStructNoRecv,
std::placeholders::_1,
std::placeholders::_2,
std::cref(request));
if (!aggregatorSendRecv.sendRecvAndAggr(fSend)) {
LOG(ERROR) << "Test failed!";
}
usleep(kOneWayCallDelayUs);
}
LOG(INFO) << "Testing two ways, multiple arguments aggregation...";
for (size_t rounds = 0; rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>
aggregatorSendRecv( pool,
&AggregatorTestCobClient::recv_sendMultiParamsRecvStruct
);
StructRequest request;
randomData(&request);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendMultiParamsRecvStruct,
std::placeholders::_1,
std::placeholders::_2,
request.i32Val,
request.i64Val,
request.doubleVal,
request.stringVal,
std::cref(request));
// prepare aggregate results
StructResponse aggregated, ethalon;
zeroResponse(&aggregated);
zeroResponse(ðalon);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::AggrFunc
aggrCob = std::bind(&responseAggregator,
std::placeholders::_1,
std::placeholders::_2,
&aggregated
);
if (!aggregatorSendRecv.sendRecvAndAggr(fSend, &aggrCob)) {
LOG(ERROR) << "Test failed!";
}
// prepare ethalon
for (uint16_t index = 0; index < numServers; ++index) {
addRequest(ðalon, request.i32Val,
request.i64Val,
request.doubleVal,
request.stringVal,
request);
}
CHECK(equalResult(ethalon, aggregated));
}
LOG(INFO) << "Testing one way, multiple argument aggregation...";
for (size_t rounds = 0; oneWayCalls && rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface<AggregatorTestCobClient>
aggregatorSendRecv(pool);
StructRequest request;
defaultData(&request);
ThriftAggregatorInterface<AggregatorTestCobClient>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendMultiParamsNoRecv,
std::placeholders::_1,
std::placeholders::_2,
request.i32Val,
request.i64Val,
request.doubleVal,
request.stringVal,
std::cref(request));
if (!aggregatorSendRecv.sendRecvAndAggr(fSend)) {
LOG(ERROR) << "Test failed!";
}
usleep(kOneWayCallDelayUs);
}
LOG(INFO) << "Testing two ways, no arguments aggregation...";
for (size_t rounds = 0; rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>
aggregatorSendRecv( pool,
&AggregatorTestCobClient::recv_noSendRecvStruct
);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::noSendRecvStruct,
std::placeholders::_1,
std::placeholders::_2
);
// prepare aggregate results
StructRequest request;
defaultData(&request);
StructResponse aggregated, ethalon;
zeroResponse(&aggregated);
zeroResponse(ðalon);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::AggrFunc
aggrCob = std::bind(&responseAggregator,
std::placeholders::_1,
std::placeholders::_2,
&aggregated
);
if (!aggregatorSendRecv.sendRecvAndAggr(fSend, &aggrCob)) {
LOG(ERROR) << "Test failed!";
}
// prepare ethalon
for (uint16_t index = 0; index < numServers; ++index) {
addRequest(ðalon, request);
}
CHECK(equalResult(ethalon, aggregated));
}
LOG(INFO) << "Testing one way, no arguments aggregation...";
for (size_t rounds = 0; oneWayCalls && rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface<AggregatorTestCobClient>
aggregatorSendRecv(pool);
ThriftAggregatorInterface<AggregatorTestCobClient>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::noSendNoRecv,
std::placeholders::_1,
std::placeholders::_2);
if (!aggregatorSendRecv.sendRecvAndAggr(fSend)) {
LOG(ERROR) << "Test failed!";
}
usleep(kOneWayCallDelayUs);
}
// ---------------- asynchronous methods ------------
LOG(INFO) << "Async testing two ways, one argument aggregation...";
for (size_t rounds = 0; rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>
aggregatorSendRecv( pool,
&AggregatorTestCobClient::recv_sendStructRecvStruct
);
StructRequest request;
randomData(&request);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendStructRecvStruct,
std::placeholders::_1,
std::placeholders::_2,
std::cref(request));
// prepare aggregate results
StructResponse ethalon, aggregated;
zeroResponse(&aggregated);
zeroResponse(ðalon);
ThriftAggregatorInterface< AggregatorTestCobClient,
StructResponse>::AggrFunc
aggrCob = std::bind(&responseAggregator,
std::placeholders::_1,
std::placeholders::_2,
&aggregated
);
aggregatorSendRecv.sendRecvAndAggrAsync(fSend, &aggrCob);
// pump events
pool.waitForCompletion();
// prepare ethalon
for (uint16_t index = 0; index < numServers; ++index) {
addRequest(ðalon, request);
}
CHECK(equalResult(ethalon, aggregated));
}
LOG(INFO) << "Async testing one way, one argument aggregation...";
for (size_t rounds = 0; oneWayCalls && rounds < kNumOfRounds; ++rounds) {
// construct aggregator object
ThriftAggregatorInterface<AggregatorTestCobClient>
aggregatorSendRecv(pool);
StructRequest request;
randomData(&request);
ThriftAggregatorInterface<AggregatorTestCobClient>::SendFunc
fSend = std::bind(&AggregatorTestCobClient::sendStructNoRecv,
std::placeholders::_1,
std::placeholders::_2,
std::cref(request));
if (!aggregatorSendRecv.sendRecvAndAggrAsync(fSend)) {
LOG(ERROR) << "Test failed!";
}
// pump events
pool.waitForCompletion();
usleep(kOneWayCallDelayUs);
}
*stopFlag = 1;
}
int main(int argc, char**argv) {
if (argc != 6) {
cerr << "usage: " << argv[0]
<< " {first_port} {#servers} {#threads} {IP} {OneWayCalls}" << endl;
return 1;
}
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
::srandom(::random() + now.tv_nsec + now.tv_sec + getpid());
signal(SIGINT, cleanup);
shared_ptr<PosixThreadFactory> threadFactory(new PosixThreadFactory());
shared_ptr<TBinaryProtocolFactory> protocolFactory(
new TBinaryProtocolFactory());
// -- use pool to make aggregated calls
uint16_t first_port = lexical_cast<uint16_t>(argv[1]);
uint16_t numServers = lexical_cast<uint16_t>(argv[2]);
uint16_t numThreads = lexical_cast<uint16_t>(argv[3]);
string IP = argv[4];
string hostIpPort = IP.empty() ?
NetworkUtil::getLocalIPv4() :
IP;
uint16_t oneWayCalls = lexical_cast<uint16_t>(argv[5]);
// -- initialize client pool from command line parameters
TEventBaseManager ebm;
TAsyncClientPool<AggregatorTestCobClient> pool(&ebm);
Policy* policy = pool.getPolicy();
policy->setConnTimeout(kMaxPolicyTimeout);
policy->setSendTimeout(kMaxPolicyTimeout);
policy->setRecvTimeout(kMaxPolicyTimeout);
// -- use pool to make aggregated calls
for (uint16_t index = 0; index < numServers; ++index) {
// name of group
string groupName = "Group#" + lexical_cast<string>(index);
Group* group = pool.getGroup(groupName, true);
// host IP:port
string hostIpPort = IP.empty() ?
NetworkUtil::getLocalIPv4() :
IP;
hostIpPort += ":";
hostIpPort += lexical_cast<string>(first_port + index);
group->createHost(hostIpPort);
}
std::vector<std::shared_ptr<Thread> > proccessThreads;
std::vector<int> completedFlags;
completedFlags.resize(numThreads, 0);
std::vector<int> startFlags;
startFlags.resize(numThreads, 0);
LOG(INFO) << "Starting threads";
// - start processing threads
for (int index = 0; index < numThreads; ++index) {
std::shared_ptr<FunctionRunner> procRunner(new FunctionRunner(
std::bind(s_threadFunction, index, numServers, std::ref(pool),
&completedFlags[index], &startFlags[index],
oneWayCalls != 0)));
proccessThreads.push_back(threadFactory->newThread(procRunner));
proccessThreads.back()->start();
}
CP_START("", "");
FOR_EACH(startFlag, startFlags) {
*startFlag = 1;
}
while (true) {
int completed = 0;
FOR_EACH(completedFlag, completedFlags) {
completed += *completedFlag;
}
if (completed == numThreads) {
break;
}
sleep(1);
}
LOG(INFO) << "Joining threads";
for (std::vector<std::shared_ptr<Thread> >::iterator
processingThread = proccessThreads.begin();
processingThread != proccessThreads.end();
++processingThread) {
(*processingThread)->join();
}
proccessThreads.clear();
return 0;
}
| 33.508621 | 77 | 0.590623 | [
"object",
"vector"
] |
e1b1895b0e960b570e5e23bfd40fe80e3ee0bae9 | 591 | cpp | C++ | adventofcode2021/7.cpp | marcinbiegun/exercises | 36ad942e8d40d6471136326a3f6d09285bbd90aa | [
"MIT"
] | 1 | 2018-12-11T14:09:14.000Z | 2018-12-11T14:09:14.000Z | adventofcode2021/7.cpp | marcinbiegun/exercises | 36ad942e8d40d6471136326a3f6d09285bbd90aa | [
"MIT"
] | null | null | null | adventofcode2021/7.cpp | marcinbiegun/exercises | 36ad942e8d40d6471136326a3f6d09285bbd90aa | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "./utils.cpp"
#include "./7lib.cpp"
int main() {
std::string inputString = getInputString("7input.txt");
std::vector<std::string> inputNumbers = splitString(inputString, ',');
std::vector<int> numbers;
for (auto inputNumber : inputNumbers) {
auto [numberOk, number] = safeStrToInt(inputNumber);
if (numberOk)
numbers.push_back(number);
}
Day7 computor(numbers);
uint64_t result = computor.ComputeResult();
std::cout << "The result is: " << result << std::endl;
return 0;
} | 26.863636 | 74 | 0.631134 | [
"vector"
] |
e1b98295eabd034ea20f2b96d5483dd395e84359 | 16,891 | cpp | C++ | src/test/RunLengthEncodeGPU_test.cpp | robertmaynard/nvcomp | 0af45c303eda4aa77235cba8d2e7b7c0b019208c | [
"BSD-3-Clause"
] | 256 | 2020-08-03T17:40:07.000Z | 2022-03-30T15:43:10.000Z | src/test/RunLengthEncodeGPU_test.cpp | robertmaynard/nvcomp | 0af45c303eda4aa77235cba8d2e7b7c0b019208c | [
"BSD-3-Clause"
] | 44 | 2020-08-11T06:04:23.000Z | 2022-03-30T23:34:44.000Z | src/test/RunLengthEncodeGPU_test.cpp | robertmaynard/nvcomp | 0af45c303eda4aa77235cba8d2e7b7c0b019208c | [
"BSD-3-Clause"
] | 49 | 2020-08-04T16:03:32.000Z | 2022-03-24T10:15:02.000Z | /*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * 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 NVIDIA CORPORATION 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 ``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.
*/
#define CATCH_CONFIG_MAIN
#include "../../tests/catch.hpp"
#include "RunLengthEncodeGPU.h"
#include "common.h"
#include "nvcomp.hpp"
#include "cuda_runtime.h"
#include <cstdlib>
#ifndef CUDA_RT_CALL
#define CUDA_RT_CALL(call) \
{ \
cudaError_t cudaStatus = call; \
if (cudaSuccess != cudaStatus) { \
fprintf( \
stderr, \
"ERROR: CUDA RT call \"%s\" in line %d of file %s failed with %s " \
"(%d).\n", \
#call, \
__LINE__, \
__FILE__, \
cudaGetErrorString(cudaStatus), \
cudaStatus); \
abort(); \
} \
}
#endif
using namespace nvcomp;
/******************************************************************************
* HELPER FUNCTIONS ***********************************************************
*****************************************************************************/
namespace
{
template <typename T>
__global__ void toGPU(
T* const output,
T const* const input,
size_t const num,
cudaStream_t stream)
{
CUDA_RT_CALL(cudaMemcpyAsync(
output, input, num * sizeof(T), cudaMemcpyHostToDevice, stream));
}
template <typename T>
__global__ void fromGPU(
T* const output,
T const* const input,
size_t const num,
cudaStream_t stream)
{
CUDA_RT_CALL(cudaMemcpyAsync(
output, input, num * sizeof(T), cudaMemcpyDeviceToHost, stream));
}
template <typename T, typename V>
void compressAsyncTestRandom(const size_t n)
{
T *input, *inputHost;
size_t const numBytes = n * sizeof(*input);
CUDA_RT_CALL(cudaMalloc((void**)&input, numBytes));
CUDA_RT_CALL(cudaMallocHost((void**)&inputHost, n * sizeof(*inputHost)));
float const totalGB = numBytes / (1024.0 * 1024.0 * 1024.0);
cudaStream_t stream;
CUDA_RT_CALL(cudaStreamCreate(&stream));
std::srand(0);
T last = 0;
for (size_t i = 0; i < n; ++i) {
if (std::rand() % 3 == 0) {
last = std::rand() % 1024;
}
inputHost[i] = last;
}
toGPU(input, inputHost, n, stream);
T *outputValues, *outputValuesHost;
V *outputCounts, *outputCountsHost;
CUDA_RT_CALL(cudaMalloc((void**)&outputValues, sizeof(*outputValues) * n));
CUDA_RT_CALL(cudaMalloc((void**)&outputCounts, sizeof(*outputCounts) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputValuesHost, sizeof(*outputValuesHost) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputCountsHost, sizeof(*outputCountsHost) * n));
void* workspace;
const size_t maxNum = 2 * n;
size_t const workspaceSize = RunLengthEncodeGPU::requiredWorkspaceSize(
maxNum, TypeOf<T>(), TypeOf<V>());
CUDA_RT_CALL(cudaMalloc((void**)&workspace, workspaceSize));
// create on device inputs
size_t* numInDevice;
size_t* numOutDevice;
T** outputValuesPtr;
V** outputCountsPtr;
CUDA_RT_CALL(cudaMalloc((void**)&numInDevice, sizeof(*numInDevice)));
CUDA_RT_CALL(cudaMalloc((void**)&numOutDevice, sizeof(*numOutDevice)));
CUDA_RT_CALL(cudaMalloc((void**)&outputValuesPtr, sizeof(*outputValuesPtr)));
CUDA_RT_CALL(cudaMalloc((void**)&outputCountsPtr, sizeof(*outputCountsPtr)));
CUDA_RT_CALL(cudaMemcpy(
numInDevice, &n, sizeof(*numInDevice), cudaMemcpyHostToDevice));
CUDA_RT_CALL(cudaMemcpy(
outputValuesPtr,
&outputValues,
sizeof(outputValues),
cudaMemcpyHostToDevice));
CUDA_RT_CALL(cudaMemcpy(
outputCountsPtr,
&outputCounts,
sizeof(outputCounts),
cudaMemcpyHostToDevice));
cudaEvent_t start, stop;
CUDA_RT_CALL(cudaEventCreate(&start));
CUDA_RT_CALL(cudaEventCreate(&stop));
CUDA_RT_CALL(cudaEventRecord(start, stream));
RunLengthEncodeGPU::compressDownstream(
workspace,
workspaceSize,
TypeOf<T>(),
reinterpret_cast<void**>(outputValuesPtr),
TypeOf<V>(),
reinterpret_cast<void**>(outputCountsPtr),
numOutDevice,
input,
numInDevice,
maxNum,
stream);
CUDA_RT_CALL(cudaEventRecord(stop, stream));
CUDA_RT_CALL(cudaStreamSynchronize(stream));
float time;
CUDA_RT_CALL(cudaEventElapsedTime(&time, start, stop));
size_t numOut;
CUDA_RT_CALL(cudaMemcpy(
&numOut, numOutDevice, sizeof(numOut), cudaMemcpyDeviceToHost));
fromGPU(outputValuesHost, outputValues, numOut, stream);
fromGPU(outputCountsHost, outputCounts, numOut, stream);
CUDA_RT_CALL(cudaStreamSynchronize(stream));
CUDA_RT_CALL(cudaStreamDestroy(stream));
CUDA_RT_CALL(cudaFree(outputValues));
CUDA_RT_CALL(cudaFree(outputCounts));
CUDA_RT_CALL(cudaFree(outputValuesPtr));
CUDA_RT_CALL(cudaFree(outputCountsPtr));
CUDA_RT_CALL(cudaFree(numOutDevice));
CUDA_RT_CALL(cudaFree(numInDevice));
// compute RLE on host
std::vector<T> expectedValues{inputHost[0]};
std::vector<V> expectedCounts{1};
for (size_t i = 1; i < n; ++i) {
if (inputHost[i] == expectedValues.back()) {
++expectedCounts.back();
} else {
expectedValues.emplace_back(inputHost[i]);
expectedCounts.emplace_back(1);
}
}
REQUIRE(expectedCounts.size() == numOut);
// verify output
for (size_t i = 0; i < expectedCounts.size(); ++i) {
if (!(expectedValues[i] == outputValuesHost[i]
&& expectedCounts[i] == outputCountsHost[i])) {
std::cerr << "i = " << i << " exp " << (int64_t)expectedCounts[i] << ":"
<< (int64_t)expectedValues[i] << " act "
<< (int64_t)outputCountsHost[i] << ":"
<< (int64_t)outputValuesHost[i] << std::endl;
}
CHECK(expectedValues[i] == outputValuesHost[i]);
CHECK(expectedCounts[i] == outputCountsHost[i]);
}
CUDA_RT_CALL(cudaFreeHost(outputValuesHost));
CUDA_RT_CALL(cudaFreeHost(outputCountsHost));
CUDA_RT_CALL(cudaFree(input));
CUDA_RT_CALL(cudaFreeHost(inputHost));
}
} // namespace
/******************************************************************************
* UNIT TEST ******************************************************************
*****************************************************************************/
TEST_CASE("compress_10Million_Test", "[small]")
{
size_t const n = 10000000;
using T = int32_t;
using V = uint32_t;
T *input, *inputHost;
size_t const numBytes = n * sizeof(*input);
CUDA_RT_CALL(cudaMalloc((void**)&input, numBytes));
CUDA_RT_CALL(cudaMallocHost((void**)&inputHost, n * sizeof(*inputHost)));
float const totalGB = numBytes / (1024.0 * 1024.0 * 1024.0);
cudaStream_t stream;
CUDA_RT_CALL(cudaStreamCreate(&stream));
std::srand(0);
T last = 0;
for (size_t i = 0; i < n; ++i) {
if (std::rand() % 3 == 0) {
last = std::rand() % 1024;
}
inputHost[i] = last;
}
toGPU(input, inputHost, n, stream);
T *outputValues, *outputValuesHost;
V *outputCounts, *outputCountsHost;
CUDA_RT_CALL(cudaMalloc((void**)&outputValues, sizeof(*outputValues) * n));
CUDA_RT_CALL(cudaMalloc((void**)&outputCounts, sizeof(*outputCounts) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputValuesHost, sizeof(*outputValuesHost) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputCountsHost, sizeof(*outputCountsHost) * n));
size_t* numOutDevice;
CUDA_RT_CALL(cudaMalloc((void**)&numOutDevice, sizeof(*numOutDevice)));
void* workspace;
size_t const workspaceSize
= RunLengthEncodeGPU::requiredWorkspaceSize(n, TypeOf<T>(), TypeOf<V>());
CUDA_RT_CALL(cudaMalloc((void**)&workspace, workspaceSize));
cudaEvent_t start, stop;
CUDA_RT_CALL(cudaEventCreate(&start));
CUDA_RT_CALL(cudaEventCreate(&stop));
CUDA_RT_CALL(cudaEventRecord(start, stream));
size_t numOut = 0;
RunLengthEncodeGPU::compress(
workspace,
workspaceSize,
TypeOf<T>(),
outputValues,
TypeOf<V>(),
outputCounts,
numOutDevice,
input,
n,
stream);
CUDA_RT_CALL(cudaEventRecord(stop, stream));
CUDA_RT_CALL(cudaStreamSynchronize(stream));
CUDA_RT_CALL(cudaMemcpy(
&numOut, numOutDevice, sizeof(numOut), cudaMemcpyDeviceToHost));
float time;
CUDA_RT_CALL(cudaEventElapsedTime(&time, start, stop));
fromGPU(outputValuesHost, outputValues, numOut, stream);
fromGPU(outputCountsHost, outputCounts, numOut, stream);
CUDA_RT_CALL(cudaStreamSynchronize(stream));
CUDA_RT_CALL(cudaStreamDestroy(stream));
CUDA_RT_CALL(cudaFree(outputValues));
CUDA_RT_CALL(cudaFree(outputCounts));
// compute RLE on host
std::vector<T> expectedValues{inputHost[0]};
std::vector<V> expectedCounts{1};
for (size_t i = 1; i < n; ++i) {
if (inputHost[i] == expectedValues.back()) {
++expectedCounts.back();
} else {
expectedValues.emplace_back(inputHost[i]);
expectedCounts.emplace_back(1);
}
}
REQUIRE(expectedCounts.size() == numOut);
// verify output
for (size_t i = 0; i < expectedCounts.size(); ++i) {
CHECK(expectedValues[i] == outputValuesHost[i]);
CHECK(expectedCounts[i] == outputCountsHost[i]);
}
CUDA_RT_CALL(cudaFreeHost(outputValuesHost));
CUDA_RT_CALL(cudaFreeHost(outputCountsHost));
CUDA_RT_CALL(cudaFree(input));
CUDA_RT_CALL(cudaFreeHost(inputHost));
}
TEST_CASE("compressDownstream_10kUniform_Test", "[small]")
{
using T = int32_t;
using V = uint32_t;
size_t const n = 10000;
T *input, *inputHost;
size_t const numBytes = n * sizeof(*input);
CUDA_RT_CALL(cudaMalloc((void**)&input, numBytes));
CUDA_RT_CALL(cudaMallocHost((void**)&inputHost, n * sizeof(*inputHost)));
float const totalGB = numBytes / (1024.0 * 1024.0 * 1024.0);
cudaStream_t stream;
CUDA_RT_CALL(cudaStreamCreate(&stream));
T last = 37;
for (size_t i = 0; i < n; ++i) {
inputHost[i] = last;
}
toGPU(input, inputHost, n, stream);
T *outputValues, *outputValuesHost;
V *outputCounts, *outputCountsHost;
CUDA_RT_CALL(cudaMalloc((void**)&outputValues, sizeof(*outputValues) * n));
CUDA_RT_CALL(cudaMalloc((void**)&outputCounts, sizeof(*outputCounts) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputValuesHost, sizeof(*outputValuesHost) * n));
CUDA_RT_CALL(
cudaMallocHost((void**)&outputCountsHost, sizeof(*outputCountsHost) * n));
void* workspace;
const size_t maxNum = 2 * n;
const size_t workspaceSize = RunLengthEncodeGPU::requiredWorkspaceSize(
maxNum, TypeOf<T>(), TypeOf<V>());
CUDA_RT_CALL(cudaMalloc((void**)&workspace, workspaceSize));
// create on device inputs
size_t* numInDevice;
size_t* numOutDevice;
T** outputValuesPtr;
V** outputCountsPtr;
CUDA_RT_CALL(cudaMalloc((void**)&numInDevice, sizeof(*numInDevice)));
CUDA_RT_CALL(cudaMalloc((void**)&numOutDevice, sizeof(*numOutDevice)));
CUDA_RT_CALL(cudaMalloc((void**)&outputValuesPtr, sizeof(*outputValuesPtr)));
CUDA_RT_CALL(cudaMalloc((void**)&outputCountsPtr, sizeof(*outputCountsPtr)));
CUDA_RT_CALL(cudaMemcpy(
numInDevice, &n, sizeof(*numInDevice), cudaMemcpyHostToDevice));
CUDA_RT_CALL(cudaMemcpy(
outputValuesPtr,
&outputValues,
sizeof(outputValues),
cudaMemcpyHostToDevice));
CUDA_RT_CALL(cudaMemcpy(
outputCountsPtr,
&outputCounts,
sizeof(outputCounts),
cudaMemcpyHostToDevice));
cudaEvent_t start, stop;
CUDA_RT_CALL(cudaEventCreate(&start));
CUDA_RT_CALL(cudaEventCreate(&stop));
CUDA_RT_CALL(cudaEventRecord(start, stream));
RunLengthEncodeGPU::compressDownstream(
workspace,
workspaceSize,
TypeOf<T>(),
reinterpret_cast<void**>(outputValuesPtr),
TypeOf<V>(),
reinterpret_cast<void**>(outputCountsPtr),
numOutDevice,
input,
numInDevice,
maxNum,
stream);
CUDA_RT_CALL(cudaEventRecord(stop, stream));
CUDA_RT_CALL(cudaStreamSynchronize(stream));
float time;
CUDA_RT_CALL(cudaEventElapsedTime(&time, start, stop));
size_t numOut;
CUDA_RT_CALL(cudaMemcpy(
&numOut, numOutDevice, sizeof(numOut), cudaMemcpyDeviceToHost));
fromGPU(outputValuesHost, outputValues, numOut, stream);
fromGPU(outputCountsHost, outputCounts, numOut, stream);
CUDA_RT_CALL(cudaStreamSynchronize(stream));
CUDA_RT_CALL(cudaStreamDestroy(stream));
CUDA_RT_CALL(cudaFree(outputValues));
CUDA_RT_CALL(cudaFree(outputCounts));
CUDA_RT_CALL(cudaFree(outputValuesPtr));
CUDA_RT_CALL(cudaFree(outputCountsPtr));
CUDA_RT_CALL(cudaFree(numOutDevice));
CUDA_RT_CALL(cudaFree(numInDevice));
// compute RLE on host
std::vector<T> expectedValues{inputHost[0]};
std::vector<V> expectedCounts{1};
for (size_t i = 1; i < n; ++i) {
if (inputHost[i] == expectedValues.back()) {
++expectedCounts.back();
} else {
expectedValues.emplace_back(inputHost[i]);
expectedCounts.emplace_back(1);
}
}
REQUIRE(expectedCounts.size() == numOut);
// verify output
for (size_t i = 0; i < expectedCounts.size(); ++i) {
if (!(expectedValues[i] == outputValuesHost[i]
&& expectedCounts[i] == outputCountsHost[i])) {
std::cerr << "i = " << i << " exp " << expectedCounts[i] << ":"
<< expectedValues[i] << " act " << outputCountsHost[i] << ":"
<< outputValuesHost[i] << std::endl;
}
CHECK(expectedValues[i] == outputValuesHost[i]);
CHECK(expectedCounts[i] == outputCountsHost[i]);
}
CUDA_RT_CALL(cudaFreeHost(outputValuesHost));
CUDA_RT_CALL(cudaFreeHost(outputCountsHost));
CUDA_RT_CALL(cudaFree(input));
CUDA_RT_CALL(cudaFreeHost(inputHost));
}
TEST_CASE("compressDownstream_10k_16bit_count_Test", "[small]")
{
const size_t n = 10003;
compressAsyncTestRandom<uint8_t, uint16_t>(n);
compressAsyncTestRandom<int8_t, uint16_t>(n);
compressAsyncTestRandom<uint16_t, uint16_t>(n);
compressAsyncTestRandom<int16_t, uint16_t>(n);
compressAsyncTestRandom<int32_t, uint16_t>(n);
compressAsyncTestRandom<uint32_t, uint16_t>(n);
compressAsyncTestRandom<int64_t, uint16_t>(n);
compressAsyncTestRandom<uint64_t, uint16_t>(n);
}
TEST_CASE("compressDownstream_10k_64bit_count_Test", "[small]")
{
const size_t n = 10003;
compressAsyncTestRandom<uint8_t, uint64_t>(n);
compressAsyncTestRandom<int8_t, uint64_t>(n);
compressAsyncTestRandom<uint16_t, uint64_t>(n);
compressAsyncTestRandom<int16_t, uint64_t>(n);
compressAsyncTestRandom<int32_t, uint64_t>(n);
compressAsyncTestRandom<uint32_t, uint64_t>(n);
compressAsyncTestRandom<int64_t, uint64_t>(n);
compressAsyncTestRandom<uint64_t, uint64_t>(n);
}
TEST_CASE("compressDownstream_1024_32bit_count_Test", "[small]")
{
for (size_t n = 512; n < 2048; ++n) {
compressAsyncTestRandom<int32_t, uint16_t>(n);
}
}
| 32.234733 | 80 | 0.644189 | [
"vector"
] |
e1bd64c6d7745e00d515f20fc1540f8e22985418 | 17,392 | cpp | C++ | Samples/EmbeddedSamples/Micro AV Media Browser/MediaBrowserPPC/MediaBrowserPPCDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | null | null | null | Samples/EmbeddedSamples/Micro AV Media Browser/MediaBrowserPPC/MediaBrowserPPCDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | null | null | null | Samples/EmbeddedSamples/Micro AV Media Browser/MediaBrowserPPC/MediaBrowserPPCDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | 1 | 2019-02-22T19:57:30.000Z | 2019-02-22T19:57:30.000Z | /*
Copyright 2006 - 2011 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "MediaBrowserPPC.h"
#include "MediaBrowserPPCDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern "C"
{
#include "MSCPControlPoint.h"
#include "ILibParsers.h"
#include "MmsCp.h"
#include "MyString.h"
}
#define NULL_FREE(x) free(x); x = NULL
DWORD WINAPI MediaControlPointStart(LPVOID args);
void DisplayDeviceList();
struct MMSCP_BrowseArgs *ArgsBrowseMetadata, *ArgsBrowseDirectChildren;
void* chain;
char *ZeroString = "0";
char *StarString = "*";
char *EmptyString = "";
const int MaxObjects = 100;
char *FilterString = "dc:title,dc:creator,upnp:class,res";
char *SortString = "";//+dc:creator,+dc:title";
bool ExitFlag = false;
CMediaBrowserPPCDlg* MainDialog = NULL;
struct UPnPDevice* devices[32];
struct UPnPDevice *MediaListCurrentDevice = NULL;
char* MediaListCurrentContainer = NULL;
struct MMSCP_ResultsList *MediaResultList = NULL;
int *IPAddressList = NULL;
int IPAddressListLen = 0;
/////////////////////////////////////////////////////////////////////////////
// CMediaBrowserPPCDlg dialog
CMediaBrowserPPCDlg::CMediaBrowserPPCDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMediaBrowserPPCDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMediaBrowserPPCDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMediaBrowserPPCDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMediaBrowserPPCDlg)
DDX_Control(pDX, IDC_MEDIASTATIC3, m_MediaText3);
DDX_Control(pDX, IDC_MEDIASTATIC2, m_MediaText2);
DDX_Control(pDX, IDC_MEDIASTATIC1, m_MediaText1);
DDX_Control(pDX, IDC_COMBOMEDIAPATH, m_MediaCombo);
DDX_Control(pDX, IDC_MEDIALIST, m_MediaList);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMediaBrowserPPCDlg, CDialog)
//{{AFX_MSG_MAP(CMediaBrowserPPCDlg)
ON_WM_SIZE()
ON_COMMAND(ID_FILE_EXIT, OnFileExit)
ON_COMMAND(ID_FILE_MOVEBACK, OnFileMoveback)
ON_COMMAND(ID_FILE_MOVEFORWARD, OnFileMoveforward)
ON_COMMAND(ID_FILE_MOVETOSERVERLIST, OnFileMovetoserverlist)
ON_WM_CLOSE()
ON_NOTIFY(NM_DBLCLK, IDC_MEDIALIST, OnDblclkMedialist)
ON_CBN_SELCHANGE(IDC_COMBOMEDIAPATH, OnSelchangeCombomediapath)
ON_NOTIFY(LVN_ITEMCHANGED, IDC_MEDIALIST, OnItemchangedMedialist)
ON_NOTIFY(LVN_KEYDOWN, IDC_MEDIALIST, OnKeydownMedialist)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMediaBrowserPPCDlg message handlers
BOOL CMediaBrowserPPCDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CenterWindow(GetDesktopWindow()); // center to the hpc screen
// Extra initialization here
CCeCommandBar *pCommandBar = (CCeCommandBar*)m_pWndEmptyCB;
pCommandBar->InsertMenuBar(IDR_MAINMENU);
CImageList* MediaImageList = new CImageList();
MediaImageList->Create(16,16,0,8,8);
CBitmap b1;
b1.LoadBitmap(IDB_DEVICE2BITMAP);
MediaImageList->Add(&b1,RGB(0,0,0));
b1.DeleteObject();
b1.LoadBitmap(IDB_FOLDER1BITMAP);
MediaImageList->Add(&b1,RGB(0,0,0));
b1.DeleteObject();
b1.LoadBitmap(IDB_FOLDER1BITMAP);
MediaImageList->Add(&b1,RGB(0,0,0));
b1.DeleteObject();
b1.LoadBitmap(IDB_METHODBITMAP);
MediaImageList->Add(&b1,RGB(0,0,0));
b1.DeleteObject();
m_MediaList.SetImageList(MediaImageList,LVSIL_SMALL);
memset(devices,0,sizeof(void*)*32);
this->m_MediaList.InsertItem(0,TEXT("Searching..."),-1);
this->m_MediaCombo.AddString(TEXT("Servers"));
this->m_MediaCombo.SetCurSel(0);
MainDialog = this;
CreateThread(NULL,0,&MediaControlPointStart,NULL,0,NULL);
return TRUE; // return TRUE unless you set the focus to a control
}
void CMediaBrowserPPCDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if (m_MediaList.GetSafeHwnd() != 0)
{
RECT clientRect;
this->GetClientRect(&clientRect);
clientRect.top += 20;
clientRect.bottom -= 42;
m_MediaList.MoveWindow(&clientRect,false);
clientRect.left += 2;
clientRect.right -= 2;
clientRect.top = clientRect.bottom + 2;
clientRect.bottom = clientRect.top + 13;
this->m_MediaText1.MoveWindow(&clientRect,false);
clientRect.bottom += 13;
clientRect.top += 13;
this->m_MediaText2.MoveWindow(&clientRect,false);
clientRect.bottom += 13;
clientRect.top += 13;
this->m_MediaText3.MoveWindow(&clientRect,false);
this->GetClientRect(&clientRect);
clientRect.bottom = 20;
this->m_MediaCombo.MoveWindow(&clientRect,false);
this->Invalidate(false);
}
}
void DisplayMediaInfo(struct UPnPDevice *device)
{
wchar_t str[402];
Utf8ToWide((wchar_t*)str,device->FriendlyName,200);
MainDialog->m_MediaText1.SetWindowText((wchar_t*)str);
Utf8ToWide((wchar_t*)str,device->ManufacturerName,200);
MainDialog->m_MediaText2.SetWindowText((wchar_t*)str);
Utf8ToWide((wchar_t*)str,device->ModelDescription,200);
MainDialog->m_MediaText3.SetWindowText((wchar_t*)str);
}
void DisplayMediaInfo(struct MMSCP_MediaObject* object)
{
wchar_t str[2048];
struct MMSCP_MediaResource* res;
Utf8ToWide((wchar_t*)str,object->Title,100);
MainDialog->m_MediaText1.SetWindowText((wchar_t*)str);
Utf8ToWide((wchar_t*)str,object->Creator,100);
MainDialog->m_MediaText2.SetWindowText((wchar_t*)str);
res = MMSCP_SelectBestIpNetworkResource(object, "http-get:*:*:*", IPAddressList, IPAddressListLen);
if (res != NULL)
{
Utf8ToWide((wchar_t*)str, res->Uri, 100);
MainDialog->m_MediaText3.SetWindowText(str);
}
else
{
MainDialog->m_MediaText3.SetWindowText(TEXT(""));
}}
void DisplayMediaInfo()
{
MainDialog->m_MediaText1.SetWindowText(TEXT(""));
MainDialog->m_MediaText2.SetWindowText(TEXT(""));
MainDialog->m_MediaText3.SetWindowText(TEXT(""));
}
char* CopyThisIfNotThat(char *copyThis, const char *ifNotThat)
{
int len;
char *retVal = NULL;
if (copyThis != NULL)
{
if (copyThis != ifNotThat)
{
if (ifNotThat != NULL)
{
len = (int) strlen(copyThis);
retVal = (char*) malloc(len+1);
strcpy(retVal, copyThis);
}
}
else
{
retVal = copyThis;
}
}
return retVal;
}
struct MMSCP_BrowseArgs* CreateBrowseArgs(char *objectID, enum MMSCP_Enum_BrowseFlag browseFlag, char *filter, unsigned int startingIndex, unsigned int requestedCount, char *sortCriteria)
{
struct MMSCP_BrowseArgs* retVal;
retVal = (struct MMSCP_BrowseArgs*) malloc (sizeof(struct MMSCP_BrowseArgs));
memset(retVal, 0, sizeof(struct MMSCP_BrowseArgs));
retVal->ObjectID = CopyThisIfNotThat(objectID, ZeroString);
retVal->BrowseFlag = browseFlag;
if (browseFlag == MMSCP_BrowseFlag_Metadata)
{
retVal->Filter = CopyThisIfNotThat(filter, StarString);
retVal->SortCriteria = CopyThisIfNotThat(sortCriteria, EmptyString);
}
else
{
retVal->Filter = CopyThisIfNotThat(filter, FilterString);
retVal->SortCriteria = CopyThisIfNotThat(sortCriteria, SortString);
}
retVal->StartingIndex = 0;
retVal->RequestedCount = MaxObjects;
return retVal;
}
void DestroyBrowseArgs(struct MMSCP_BrowseArgs* args)
{
if (args->ObjectID != ZeroString) { NULL_FREE(args->ObjectID); }
if ((args->Filter != FilterString) && (args->Filter != StarString)) {NULL_FREE(args->Filter);}
if ((args->SortCriteria != EmptyString) && (args->SortCriteria != SortString)) {NULL_FREE(args->SortCriteria);}
memset(args, 0, sizeof(struct MMSCP_BrowseArgs));
NULL_FREE(args);
}
void DisplayMediaList(char* container)
{
wchar_t str[202];
MainDialog->m_MediaList.ShowWindow(SW_HIDE);
if (container == NULL || MediaListCurrentDevice == NULL)
{
DisplayMediaInfo();
int i,j;
bool d = false;
MainDialog->m_MediaList.DeleteAllItems();
for(i=0;i<32;i++)
{
if (devices[i] != NULL)
{
Utf8ToWide((wchar_t*)str,devices[i]->FriendlyName,100);
j = MainDialog->m_MediaList.InsertItem(0xFF,(wchar_t*)str,0);
MainDialog->m_MediaList.SetItemData(j,(int)devices[i]);
d = true;
}
}
if (d == false) MainDialog->m_MediaList.InsertItem(0,TEXT("Searching..."),-1);
MediaListCurrentContainer = NULL;
}
else
{
DisplayMediaInfo();
struct UPnPService* service;
service = MSCPGetService_ContentDirectory(MediaListCurrentDevice);
if (service == NULL) return;
DestroyBrowseArgs(ArgsBrowseDirectChildren);
ArgsBrowseDirectChildren = CreateBrowseArgs(container, MMSCP_BrowseFlag_Children, FilterString, 0, MaxObjects, SortString);
MMSCP_Invoke_Browse(service, ArgsBrowseDirectChildren);
MainDialog->m_MediaList.DeleteAllItems();
MainDialog->m_MediaList.InsertItem(0,TEXT("Loading..."),-1);
MediaListCurrentContainer = container;
}
MainDialog->m_MediaList.ShowWindow(SW_SHOWNA);
}
void ServerAddedRemoved(struct UPnPDevice *device, int added)
{
int i;
if (added != 0)
{
for(i=0;i<32;i++)
{
if (devices[i] == NULL) {devices[i] = device;break;}
}
}
else
{
for(i=0;i<32;i++)
{
if (devices[i] == device) {devices[i] = NULL;break;}
}
if (MediaListCurrentDevice == device) MainDialog->OnFileMovetoserverlist();
}
if (IPAddressList != NULL)
{
free (IPAddressList);
IPAddressList = NULL;
}
IPAddressListLen = ILibGetLocalIPAddressList(&IPAddressList);
if (MediaListCurrentDevice == NULL) DisplayMediaList(NULL);
}
void Result_Browse(void *serviceObj, struct MMSCP_BrowseArgs *args, int errorCode, struct MMSCP_ResultsList *results)
{
int j;
MMSCP_MediaObject* object;
MainDialog->m_MediaList.DeleteAllItems();
wchar_t str[202];
if (MediaResultList != NULL)
{
MMSCP_DestroyResultsList(MediaResultList);
MediaResultList = NULL;
}
if (errorCode != 0)
{
MainDialog->m_MediaList.InsertItem(0,TEXT("Error"),0);
return;
}
if (results == NULL || results->NumberReturned == 0)
{
MainDialog->m_MediaList.InsertItem(0,TEXT("Empty Container"),-1);
return;
}
object = results->FirstObject;
MediaResultList = results;
MainDialog->m_MediaList.ShowWindow(SW_HIDE);
while(object != NULL)
{
Utf8ToWide((wchar_t*)str,object->Title,100);
if (object->MediaClass & MMSCP_CLASS_MASK_CONTAINER)
{
j = MainDialog->m_MediaList.InsertItem(0xFF,(wchar_t*)str,2);
MainDialog->m_MediaList.SetItemData(j,(int)object);
}
else
{
j = MainDialog->m_MediaList.InsertItem(0xFF,(wchar_t*)str,3);
MainDialog->m_MediaList.SetItemData(j,(int)object);
}
object = object->Next;
}
MainDialog->m_MediaList.ShowWindow(SW_SHOWNA);
}
DWORD WINAPI MediaControlPointStart(LPVOID args)
{
chain = ILibCreateChain();
ArgsBrowseMetadata = CreateBrowseArgs(ZeroString, MMSCP_BrowseFlag_Metadata, StarString, 0, 0, EmptyString);
ArgsBrowseDirectChildren = CreateBrowseArgs(ZeroString, MMSCP_BrowseFlag_Children, FilterString, 0, MaxObjects, SortString);
MMSCP_Init(chain, &Result_Browse, &ServerAddedRemoved);
ILibStartChain(chain);
if (IPAddressList != NULL)
{
free (IPAddressList);
IPAddressList = NULL;
}
if (MediaResultList != NULL)
{
MMSCP_DestroyResultsList(MediaResultList);
MediaResultList = NULL;
}
DestroyBrowseArgs(ArgsBrowseMetadata);
DestroyBrowseArgs(ArgsBrowseDirectChildren);
while (MainDialog->m_MediaCombo.GetCount() > 1)
{
free((char*)MainDialog->m_MediaCombo.GetItemData(1));
MainDialog->m_MediaCombo.DeleteString(1);
}
ExitFlag = true;
PostMessage(MainDialog->GetSafeHwnd(),WM_CLOSE,0,0);
return 0;
}
void CMediaBrowserPPCDlg::OnFileExit()
{
this->DestroyWindow();
}
void CMediaBrowserPPCDlg::OnFileMoveback()
{
int i = MainDialog->m_MediaCombo.GetCount();
if (i == CB_ERR || i < 2) return;
i -= 2;
char* ID = (char*)MainDialog->m_MediaCombo.GetItemData(i);
while (MainDialog->m_MediaCombo.GetCount() > (i+1))
{
free((char*)MainDialog->m_MediaCombo.GetItemData(i+1));
MainDialog->m_MediaCombo.DeleteString(i+1);
}
MainDialog->m_MediaCombo.SetCurSel(i);
if (ID == NULL)
{
OnFileMovetoserverlist();
}
else
{
DisplayMediaList(ID);
}
}
void CMediaBrowserPPCDlg::OnFileMoveforward()
{
LRESULT result;
OnDblclkMedialist(NULL,&result);
}
void CMediaBrowserPPCDlg::OnFileMovetoserverlist()
{
if (MediaResultList != NULL)
{
MMSCP_DestroyResultsList(MediaResultList);
MediaResultList = NULL;
}
MediaListCurrentDevice = NULL;
DisplayMediaList(NULL);
}
void CMediaBrowserPPCDlg::OnClose()
{
if (ExitFlag == true)
{
CDialog::OnClose();
}
else
{
ILibStopChain(chain);
}
}
void CMediaBrowserPPCDlg::OnDblclkMedialist(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 0;
struct UPnPDevice *device;
struct UPnPService* service;
struct MMSCP_MediaObject* object;
wchar_t str[202];
POSITION pos = m_MediaList.GetFirstSelectedItemPosition();
if (pos == NULL) return;
if (MediaListCurrentContainer == NULL)
{
int index = m_MediaList.GetNextSelectedItem(pos);
device = (struct UPnPDevice*)m_MediaList.GetItemData(index);
if (device == NULL) return;
service = MSCPGetService_ContentDirectory(device);
if (service == NULL) return;
DestroyBrowseArgs(ArgsBrowseDirectChildren);
ArgsBrowseDirectChildren = CreateBrowseArgs("0", MMSCP_BrowseFlag_Children, FilterString, 0, MaxObjects, SortString);
MMSCP_Invoke_Browse(service, ArgsBrowseDirectChildren);
MediaListCurrentDevice = device;
MediaListCurrentContainer = "0";
MainDialog->m_MediaList.DeleteAllItems();
MainDialog->m_MediaList.InsertItem(0,TEXT("Loading..."),-1);
Utf8ToWide((wchar_t*)str,device->FriendlyName,100);
int i = this->m_MediaCombo.AddString((wchar_t*)str);
char* identifier = (char*)malloc(2);
strcpy(identifier,"0");
this->m_MediaCombo.SetItemData(i,(DWORD_PTR)identifier);
this->m_MediaCombo.SetCurSel(i);
DisplayMediaInfo();
}
else
{
int index = m_MediaList.GetNextSelectedItem(pos);
object = (struct MMSCP_MediaObject*)m_MediaList.GetItemData(index);
if (object == NULL || (object->MediaClass & MMSCP_CLASS_MASK_CONTAINER) == 0) return;
service = MSCPGetService_ContentDirectory(MediaListCurrentDevice);
DestroyBrowseArgs(ArgsBrowseDirectChildren);
ArgsBrowseDirectChildren = CreateBrowseArgs(object->ID, MMSCP_BrowseFlag_Children, FilterString, 0, MaxObjects, SortString);
MMSCP_Invoke_Browse(service, ArgsBrowseDirectChildren);
MediaListCurrentContainer = object->ID;
MainDialog->m_MediaList.DeleteAllItems();
MainDialog->m_MediaList.InsertItem(0,TEXT("Loading..."),-1);
Utf8ToWide((wchar_t*)str,object->Title,100);
int i = this->m_MediaCombo.AddString((wchar_t*)str);
char* identifier = (char*)malloc(strlen(object->ID)+1);
strcpy(identifier,object->ID);
this->m_MediaCombo.SetItemData(i,(DWORD_PTR)identifier);
this->m_MediaCombo.SetCurSel(i);
DisplayMediaInfo();
}
}
void CMediaBrowserPPCDlg::OnSelchangeCombomediapath()
{
int i = MainDialog->m_MediaCombo.GetCurSel();
if (i == CB_ERR) return;
char* ID = (char*)MainDialog->m_MediaCombo.GetItemData(i);
while (MainDialog->m_MediaCombo.GetCount() > (i+1))
{
free((char*)MainDialog->m_MediaCombo.GetItemData(i+1));
MainDialog->m_MediaCombo.DeleteString(i+1);
}
if (ID == NULL)
{
OnFileMovetoserverlist();
}
else
{
DisplayMediaList(ID);
}
}
void CMediaBrowserPPCDlg::OnItemchangedMedialist(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
*pResult = 0;
struct UPnPDevice *device;
struct MMSCP_MediaObject* object;
POSITION pos = m_MediaList.GetFirstSelectedItemPosition();
if (pos == NULL) return;
if (MediaListCurrentContainer == NULL)
{
int index = m_MediaList.GetNextSelectedItem(pos);
device = (struct UPnPDevice*)m_MediaList.GetItemData(index);
if (device == NULL) return;
DisplayMediaInfo(device);
}
else
{
int index = m_MediaList.GetNextSelectedItem(pos);
object = (struct MMSCP_MediaObject*)m_MediaList.GetItemData(index);
if (object == NULL) return;
DisplayMediaInfo(object);
}
}
void CMediaBrowserPPCDlg::OnKeydownMedialist(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);
*pResult = 0;
WORD key = pLVKeyDow->wVKey;
if (key == 37)
{
OnFileMoveback();
}
else
if (key == 39)
{
OnFileMoveforward();
}
}
| 27.694268 | 188 | 0.709752 | [
"object"
] |
e1c009836d701f993b130c35e79cbadd8937e605 | 4,768 | cpp | C++ | source/core/ad-manager/AdClickPredictor.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | 18 | 2015-04-20T03:40:36.000Z | 2020-01-09T08:43:07.000Z | source/core/ad-manager/AdClickPredictor.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | null | null | null | source/core/ad-manager/AdClickPredictor.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | 7 | 2015-02-01T13:53:35.000Z | 2020-07-07T15:45:36.000Z | /*
* AdCliclPredictor.cpp
*/
#include "AdClickPredictor.h"
#include <dirent.h>
#include <stdio.h>
#include <fstream>
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <glog/logging.h>
#include <boost/filesystem.hpp>
namespace sf1r
{
void AdClickPredictor::init(const std::string& path)
{
predictor_.reset(new AdPredictorType(0, 400, 450, 0.08));
dataPath_ = path + "/data/";
modelPath_ = path + "/model/predictor.bin";
boost::filesystem::create_directories(path + "/model");
boost::filesystem::create_directories(dataPath_ + "backup");
load();
}
void AdClickPredictor::stop()
{
}
bool AdClickPredictor::preProcess()
{
//use copy constructor
learner_.reset(new AdPredictorType(*predictor_));
return true;
}
//Train model with named file
bool AdClickPredictor::trainFromFile(const std::string& filename)
{
LOG(INFO) << "training from file: " << filename << std::endl;
std::string oldname = dataPath_ + filename;
std::ifstream fin(oldname.c_str());
std::string str;
bool click = false;
while ( getline(fin, str) )
{
//parse log
//LOG(INFO) << "str: " << str << std::endl;
std::vector<std::string> elems;
std::vector<std::pair<std::string, std::string> > knowledge;
boost::split(elems, str, boost::is_any_of(" "));
std::vector<std::string>::iterator it, end;
end = elems.end(); end--;
if ( *end == "0" )
click = false;
else if ( *end == "1" )
click = true;
else
{
LOG(INFO) << "Unknown Log Format : " << str << std::endl;
continue;
}
for (it = elems.begin(); it != end; it++ )
{
std::vector<std::string> assignment;
boost::split(assignment, *it, boost::is_any_of(":"));
if ( assignment.size() != 2 )
{
LOG(INFO) << "Unknown Log Format : " << str << std::endl;
continue;
}
knowledge.push_back(std::make_pair(assignment[0], assignment[1]));
}
//learn
learner_->update(knowledge, click);
}
std::string newname = dataPath_ + "backup/" + filename;
//move the current file to the backup data path
if ( rename(oldname.c_str(), newname.c_str()) != 0 )
{
LOG(INFO) << "Rename File Error: " << oldname << std::endl;
}
return true;
}
bool AdClickPredictor::train()
{
// Obtain all the data files under the dataPath_
DIR *dp;
struct dirent *dirp;
if ( (dp = opendir(dataPath_.c_str())) == NULL )
{
LOG(ERROR) << "opendir error: " << dataPath_ << std::endl;
return false;
}
while ( (dirp = readdir(dp)) != NULL )
{
if ( (strcmp(dirp->d_name, ".") == 0) || (strcmp(dirp->d_name, "..") == 0))
continue;
if ( dirp->d_type == DT_DIR )
continue;
std::string filename(dirp->d_name);
LOG(INFO) << "Train AdClickPredictor from file: " << dirp->d_name << std::endl;
//Training model with the current data file
trainFromFile(filename);
}
return true;
}
bool AdClickPredictor::postProcess()
{
//LOG(INFO) << "postProcess after training " << std::endl;
std::ofstream ofs(modelPath_.c_str(), std::ios_base::binary);
if (!ofs)
{
LOG(ERROR) << "failed openning file " << modelPath_ << std::endl;
return false;
}
try
{
learner_->save_binary(ofs);
}
catch(const std::exception& e)
{
LOG(ERROR) << "exception in writing file " << e.what()
<< ", path: " << modelPath_ << std::endl;
return false;
}
writeLock lock(rwMutex_);
predictor_ = learner_;
learner_.reset();
return true;
}
void AdClickPredictor::save()
{
readLock lock(rwMutex_);
std::ofstream ofs(modelPath_.c_str(), std::ios_base::binary);
if (!ofs)
{
LOG(ERROR) << "failed openning file " << modelPath_ << std::endl;
return;
}
try
{
predictor_->save_binary(ofs);
}
catch(const std::exception& e)
{
LOG(ERROR) << "exception in writing file " << e.what()
<< ", path: " << modelPath_ << std::endl;
}
}
bool AdClickPredictor::load()
{
std::ifstream ifs(modelPath_.c_str(), std::ios_base::binary);
if (!ifs)
return false;
try
{
writeLock lock(rwMutex_);
predictor_->load_binary(ifs);
}
catch(const std::exception& e)
{
LOG(ERROR) << "exception in read file: " << e.what()
<< ", path: " << modelPath_ << std::endl;
return false;
}
return true;
}
} //namespace sf1r
| 23.959799 | 87 | 0.553062 | [
"vector",
"model"
] |
e1c753a852b4ee6bcfaceff344480d0fd52a4274 | 6,873 | cc | C++ | src/libxtp/forces.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | src/libxtp/forces.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | src/libxtp/forces.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2018 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <votca/xtp/forces.h>
#include <boost/format.hpp>
#include "votca/xtp/statefilter.h"
namespace votca {
namespace xtp {
using std::flush;
void Forces::Initialize(tools::Property &options) {
std::vector<std::string> choices = {"forward", "central"};
_force_method = options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(".method", choices);
_noisy_output = options.ifExistsReturnElseReturnDefault<bool>(".noisy", false);
if ((_force_method == "forward") || (_force_method == "central")) {
_displacement = options.ifExistsReturnElseReturnDefault<double>(".displacement", 0.001); // Angstrom
}
_displacement*=tools::conv::ang2bohr;
// check for force removal options
choices = {"total", "none"};
std::string _force_removal = options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(".removal", choices);
if (_force_removal == "total") _remove_total_force = true;
_natoms = _orbitals.QMAtoms().size();
_forces =Eigen::MatrixX3d::Zero(_natoms,3);
return;
}
void Forces::Calculate(double energy) {
ctp::TLogLevel ReportLevel = _pLog->getReportLevel(); // backup report level
if ( ! _noisy_output ){
_pLog->setReportLevel(ctp::logERROR); // go silent for force calculations
}
std::vector<QMAtom*>& atoms=_orbitals.QMAtoms();
for (unsigned atom_index=0;atom_index<atoms.size();atom_index++) {
if ( _noisy_output ){
CTP_LOG(ctp::logINFO, *_pLog) << "FORCES--DEBUG working on atom " << atom_index<< flush;
}
Eigen::Vector3d atom_force=Eigen::Vector3d::Zero();
// Calculate Force on this atom
if (_force_method == "forward") atom_force=NumForceForward(energy, atom_index);
if (_force_method == "central") atom_force=NumForceCentral(energy, atom_index);
_forces.row(atom_index)=atom_force.transpose();
}
_pLog->setReportLevel(ReportLevel); //
if (_remove_total_force) RemoveTotalForce();
return;
}
void Forces::Report() const{
CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(" ---- FORCES (Hartree/Bohr) ")).str() << flush;
CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(" %1$s differences ") % _force_method).str() << flush;
CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(" displacement %1$1.4f Angstrom ") % (_displacement*tools::conv::bohr2ang)).str() << flush;
CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(" Atom\t x\t y\t z ")).str() << flush;
for (unsigned _i = 0; _i < _forces.rows(); _i++) {
CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(" %1$4d %2$+1.4f %3$+1.4f %4$+1.4f")
% _i % _forces(_i, 0) % _forces(_i, 1) % _forces(_i, 2)).str() << flush;
}
return;
}
/* Calculate forces on an atom numerically by forward differences */
Eigen::Vector3d Forces::NumForceForward(double energy,int atom_index) {
Eigen::Vector3d force=Eigen::Vector3d::Zero();
// get this atoms's current coordinates
QMAtom* atom= _orbitals.QMAtoms()[atom_index];
const tools::vec current_pos =atom->getPos();
for (unsigned i_cart = 0; i_cart < 3; i_cart++) {
tools::vec displacement_vec(0, 0, 0);
displacement_vec[i_cart]=_displacement;
// update the coordinate
tools::vec pos_displaced = current_pos + displacement_vec;
atom->setPos(pos_displaced);
_gwbse_engine.ExcitationEnergies(_orbitals);
double energy_displaced = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));
force(i_cart) = (energy - energy_displaced) / _displacement;
atom->setPos(current_pos); // restore original coordinate into segment
} // Cartesian directions
return force;
}
/* Calculate forces on atoms numerically by central differences */
Eigen::Vector3d Forces::NumForceCentral(double energy,int atom_index) {
QMAtom* atom= _orbitals.QMAtoms()[atom_index];
const tools::vec current_pos =atom->getPos();
Eigen::Vector3d force=Eigen::Vector3d::Zero();
for (unsigned i_cart = 0; i_cart < 3; i_cart++) {
if ( _noisy_output ){
CTP_LOG(ctp::logINFO, *_pLog) << "FORCES--DEBUG Cartesian component " << i_cart << flush;
}
tools::vec displacement_vec(0, 0, 0);
displacement_vec[i_cart]=_displacement;
// update the coordinate
tools::vec pos_displaced = current_pos + displacement_vec;
atom->setPos(pos_displaced);
_gwbse_engine.ExcitationEnergies(_orbitals);
double energy_displaced_plus = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));
// update the coordinate
pos_displaced = current_pos - displacement_vec;
atom->setPos(pos_displaced);
_gwbse_engine.ExcitationEnergies(_orbitals);
double energy_displaced_minus = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));
force(i_cart) = 0.5 * (energy_displaced_minus - energy_displaced_plus) / _displacement;
atom->setPos(current_pos); // restore original coordinate into orbital
}
return force;
}
void Forces::RemoveTotalForce() {
Eigen::Vector3d total_force = _forces.colwise().sum();
for (unsigned i_atom = 0; i_atom < _natoms; i_atom++) {
_forces.row(i_atom)-=total_force/double(_natoms);
}
return;
}
}
}
| 46.755102 | 160 | 0.585334 | [
"vector"
] |
e1cbde6f76eed3f167d705099831ec15e39106ba | 1,770 | cpp | C++ | Src/Source/ColorView.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | Src/Source/ColorView.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | Src/Source/ColorView.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | /*****************************************************************
* Copyright (c) 2005 Tim de Jong, Brent Miszalski *
* *
* All rights reserved. *
* Distributed under the terms of the MIT License. *
*****************************************************************/
#ifndef COLOR_VIEW_H
#include "ColorView.h"
#endif
#include <be/interface/Point.h>
ColorView::ColorView(BRect frame)
: BView(frame,"colorView",B_FOLLOW_NONE,B_WILL_DRAW)
{
m_bitmap = new BBitmap(Bounds(),B_RGB32,true);
m_bitmap->Lock();
m_bitmapView = new BView(Bounds(),"view",B_FOLLOW_NONE, B_WILL_DRAW);
m_bitmap->AddChild(m_bitmapView);
m_bitmap->Unlock();
}
ColorView::~ColorView()
{
// delete bitmap;
// delete bView;
}
void ColorView::SetColor(rgb_color color)
{
m_color = color;
}
void ColorView::Draw(BRect drawRect)
{
Render();
}
void ColorView::Render()
{
m_bitmap->Lock();
BRect bitmapBounds = m_bitmap->Bounds();
m_bitmapView->SetHighColor(m_color);
m_bitmapView->FillRect(bitmapBounds);
m_bitmapView->SetHighColor(tint_color(m_color,B_LIGHTEN_2_TINT));
m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.top), BPoint(bitmapBounds.left,bitmapBounds.bottom));
m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.top), BPoint(bitmapBounds.right,bitmapBounds.top));
m_bitmapView->SetHighColor(tint_color(m_color,B_DARKEN_2_TINT));
m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.bottom), BPoint(bitmapBounds.right,bitmapBounds.bottom));
m_bitmapView->StrokeLine(BPoint(bitmapBounds.right,bitmapBounds.top), BPoint(bitmapBounds.right,bitmapBounds.bottom));
m_bitmapView->Sync();
DrawBitmapAsync(m_bitmap, Bounds(), Bounds());
Flush();
Sync();
m_bitmap->Unlock();
}
| 29.5 | 121 | 0.681921 | [
"render"
] |
e1cd3ca0a0a3fe60256ed7b96b9d9242d6657c2a | 3,308 | cpp | C++ | Program/InstanceCVRPLIB.cpp | chkwon/HGS-CVRP | cab306d2b25269c57e58acbb7b1f8a6c54491b76 | [
"MIT"
] | null | null | null | Program/InstanceCVRPLIB.cpp | chkwon/HGS-CVRP | cab306d2b25269c57e58acbb7b1f8a6c54491b76 | [
"MIT"
] | null | null | null | Program/InstanceCVRPLIB.cpp | chkwon/HGS-CVRP | cab306d2b25269c57e58acbb7b1f8a6c54491b76 | [
"MIT"
] | null | null | null | //
// Created by chkwon on 3/22/22.
//
#include <fstream>
#include <cmath>
#include "InstanceCVRPLIB.h"
InstanceCVRPLIB::InstanceCVRPLIB(std::string pathToInstance, bool isRoundingInteger = true)
{
std::string content, content2, content3;
double serviceTimeData = 0.;
// Read INPUT dataset
std::ifstream inputFile(pathToInstance);
if (inputFile.is_open())
{
getline(inputFile, content);
getline(inputFile, content);
getline(inputFile, content);
for (inputFile >> content ; content != "NODE_COORD_SECTION" ; inputFile >> content)
{
if (content == "DIMENSION") { inputFile >> content2 >> nbClients; nbClients--; } // Need to substract the depot from the number of nodes
else if (content == "EDGE_WEIGHT_TYPE") inputFile >> content2 >> content3;
else if (content == "CAPACITY") inputFile >> content2 >> vehicleCapacity;
else if (content == "DISTANCE") { inputFile >> content2 >> durationLimit; isDurationConstraint = true; }
else if (content == "SERVICE_TIME") inputFile >> content2 >> serviceTimeData;
else throw std::string("Unexpected data in input file: " + content);
}
if (nbClients <= 0) throw std::string("Number of nodes is undefined");
if (vehicleCapacity == 1.e30) throw std::string("Vehicle capacity is undefined");
x_coords = std::vector<double>(nbClients + 1);
y_coords = std::vector<double>(nbClients + 1);
demands = std::vector<double>(nbClients + 1);
service_time = std::vector<double>(nbClients + 1);
// Reading node coordinates
// depot must be the first element
// - i = 0 in the for-loop below, or
// - node_number = 1 in the .vrp file
// customers are
// - i = 1, 2, ..., nbClients in the for-loop below, or
// - node_number = 2, 3, ..., nb_Clients in the .vrp file
int node_number;
for (int i = 0; i <= nbClients; i++)
{
inputFile >> node_number >> x_coords[i] >> y_coords[i];
if (node_number != i + 1) throw std::string("The node numbering is not in order.");
}
// Reading demand information
inputFile >> content;
if (content != "DEMAND_SECTION") throw std::string("Unexpected data in input file: " + content);
for (int i = 0; i <= nbClients; i++)
{
inputFile >> content >> demands[i];
service_time[i] = (i == 0) ? 0. : serviceTimeData ;
}
// Calculating 2D Euclidean Distance
dist_mtx = std::vector < std::vector< double > >(nbClients + 1, std::vector <double>(nbClients + 1));
for (int i = 0; i <= nbClients; i++)
{
for (int j = 0; j <= nbClients; j++)
{
dist_mtx[i][j] = std::sqrt(
(x_coords[i] - x_coords[j]) * (x_coords[i] - x_coords[j])
+ (y_coords[i] - y_coords[j]) * (y_coords[i] - y_coords[j])
);
if (isRoundingInteger) dist_mtx[i][j] = round(dist_mtx[i][j]);
}
}
// Reading depot information (in all current instances the depot is represented as node 1, the program will return an error otherwise)
inputFile >> content >> content2 >> content3 >> content3;
if (content != "DEPOT_SECTION") throw std::string("Unexpected data in input file: " + content);
if (content2 != "1") throw std::string("Expected depot index 1 instead of " + content2);
if (content3 != "EOF") throw std::string("Unexpected data in input file: " + content3);
}
else
throw std::string("Impossible to open instance file: " + pathToInstance);
}
| 38.917647 | 139 | 0.658404 | [
"vector"
] |
e1ce1aae23664e916d5e235250904f70645d8e1f | 8,067 | hpp | C++ | ScannerBit/include/gambit/ScannerBit/scanners/postprocessor_2.0.0/postprocessor.hpp | patscott/gambit_1.4 | a50537419918089effc207e8b206489a5cfd2258 | [
"Unlicense"
] | 1 | 2019-01-21T19:59:18.000Z | 2019-01-21T19:59:18.000Z | ScannerBit/include/gambit/ScannerBit/scanners/postprocessor_2.0.0/postprocessor.hpp | patscott/gambit_1.2 | 19d8ffbe58e1622542eef6c48790fb1a8cf6dd0b | [
"Unlicense"
] | 4 | 2019-10-06T14:03:41.000Z | 2020-08-06T11:53:54.000Z | ScannerBit/include/gambit/ScannerBit/scanners/postprocessor_2.0.0/postprocessor.hpp | patscott/gambit_1.4 | a50537419918089effc207e8b206489a5cfd2258 | [
"Unlicense"
] | null | null | null | // GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// "Postprocessing" scanner plugin.
/// Header file
///
/// *********************************************
///
/// Authors (add name and date if you modify):
///
/// \author Ben Farmer
/// (b.farmer@imperial.ac.uk)
/// \date 2018, Sep
///
/// *********************************************
#include "gambit/ScannerBit/scanner_plugin.hpp"
#include "gambit/ScannerBit/scanners/postprocessor_2.0.0/chunks.hpp"
#ifndef __postprocessor_2_0_0_hpp__
#define __postprocessor_2_0_0_hpp__
namespace Gambit
{
/// Forward declaration
namespace Printers
{
class BaseBaseReader;
}
namespace PostProcessor
{
/// @{ Helper functions for performing resume related tasks
/// Answer queries as to whether a given dataset index has been postprocessed in a previous run or not
bool point_done(const ChunkSet done_chunks, size_t index);
/// Get 'effective' start and end positions for a processing batch
/// i.e. simply divides up an integer into the most even parts possible
/// over a given number of processes
Chunk get_effective_chunk(const std::size_t total_length, const unsigned int rank, const unsigned int numtasks);
/// Compute start/end indices for a given rank process, given previous "done_chunk" data.
Chunk get_my_chunk(const std::size_t dset_length, const ChunkSet& done_chunks, const int rank, const int numtasks);
/// Read through resume data files and reconstruct which chunks of points have already been processed
ChunkSet get_done_points(Gambit::Printers::BaseBaseReader& filebase);
/// Simplify a ChunkSet by merging chunks which overlap.
ChunkSet merge_chunks(const ChunkSet&);
// This chunk signals that the run is finished.
const Chunk stopchunk = Chunk(0,0);
/// Write resume data files
/// These specify which chunks of points have been processed during this run
void record_done_points(const ChunkSet& done_chunks, const Chunk& mydone, const std::string& filebase, unsigned int rank, unsigned int size);
// Gather a bunch of ints from all processes (COLLECTIVE OPERATION)
#ifdef WITH_MPI
std::vector<int> allgather_int(int myval, GMPI::Comm& comm);
#endif
/// @}
/// Options object for PPDriver
/// See matching options in PPDriver class for description
struct PPOptions
{
std::set<std::string> all_params;
std::set<std::string> data_labels;
std::set<std::string> data_labels_copy;
std::vector<std::string> add_to_logl;
std::vector<std::string> subtract_from_logl;
std::map<std::string,std::string> renaming_scheme;
std::map<std::string,double> cut_less_than;
std::map<std::string,double> cut_greater_than;
bool discard_points_outside_cuts;
std::size_t update_interval;
bool discard_old_logl;
std::string logl_purpose_name;
std::string reweighted_loglike_name;
std::string root;
unsigned int numtasks;
unsigned int rank;
std::size_t chunksize;
#ifdef WITH_MPI
GMPI::Comm* comm;
PPOptions() : comm(NULL) {}
#endif
};
/// Driver class to handle the actual postprocessing tasks
class PPDriver
{
public:
PPDriver();
PPDriver(Printers::BaseBaseReader* const, Printers::BaseBasePrinter* const, Scanner::like_ptr const, const PPOptions&);
void check_settings();
int run_main_loop(const Chunk& mychunks);
bool get_ModelParameters(std::unordered_map<std::string, double>& outputMap);
Chunk get_new_chunk();
void set_done_chunks(const ChunkSet& done_chunks);
unsigned long long next_point_index();
unsigned long long get_total_length();
// Message tags
static const int REDIST_REQ = 0;
private:
/// Safe accessors for pointer data
Printers::BaseBaseReader& getReader();
Printers::BaseBasePrinter& getPrinter();
Scanner::like_ptr getLogLike();
/// The reader object in use for the scan
Printers::BaseBaseReader* reader;
/// The printer for the primary output stream of the scan
Printers::BaseBasePrinter* printer;
/// The likelihood container plugin
Scanner::like_ptr LogLike;
/// Names of new output to be printed, i.e. output labels not present in the input file.
std::set<std::string> new_params;
/// Models required by the scan
std::map<std::string,std::vector<std::string>> req_models;
/// Map to retrieve the "model::parameter" version of the parameter name
std::map<std::string,std::map<std::string,std::string>> longname;
/// Total length of input dataset
unsigned long long total_length;
/// Next point scheduled to be distributed for processing
unsigned long long next_point;
/// Size of chunks to distribute to worker processes
unsigned long long chunksize;
/// Chunks describing the points that can be auto-skipped (because they have been processed previously)
ChunkSet done_chunks;
/// Names of all output that the primary printer knows about at startup (things GAMBIT plans to print from the likelihood loop)
std::set<std::string> all_params;
/// Labels of all output datasets
std::set<std::string> data_labels;
/// Labels of output datasets to be copied
std::set<std::string> data_labels_copy;
/// List of likelihoods in old output to be added to the newly computed likelihood
std::vector<std::string> add_to_logl;
/// List of likelihoods in old output to be subtracted from the newly computed likelihood
std::vector<std::string> subtract_from_logl;
/// Map for renaming old datasets in the new output
/// Keys are "in_label", values are "out_label"
std::map<std::string,std::string> renaming_scheme;
/// Cut maps, for selecting only points in the input
/// datasets which pass certain criteria.
/// Keys are "in_label", values are the cut boundaries.
std::map<std::string,double> cut_less_than;
std::map<std::string,double> cut_greater_than;
/// Flag to throw away points that don't pass the cuts (rather than copying them un-processed)
bool discard_points_outside_cuts;
/// Number of iterations between progress reports. '0' means no updates
std::size_t update_interval;
/// Allow old likelihood components to be overwritten by newly calculated values?
bool discard_old_logl;
/// Label assigned to the output of the likelihood container
std::string logl_purpose_name;
/// The label to assign to the results of add_to_like and subtract_from_like operations.
std::string reweighted_loglike_name;
/// Flag to trigger unique behaviour on first loop
bool firstloop;
/// Path to save resume files
std::string root;
/// MPI variables (set manually rather than inferred, to allow for "virtual rank" settings
unsigned int numtasks;
unsigned int rank;
#ifdef WITH_MPI
GMPI::Comm* comm;
#endif
};
}
}
#endif
//o.all_params
//o.data_labels
//o.data_labels_copy
//o.add_to_logl
//o.subtract_from_logl
//o.renaming_scheme
//o.cut_less_than
//o.cut_greater_than
//o.discard_points_outside_cuts
//o.update_interval
//o.numtasks
//o.rank
//
| 36.337838 | 147 | 0.624768 | [
"object",
"vector",
"model"
] |
e1d4ddb8775ab90780eb84d1dff0d199ee9053c6 | 1,645 | hpp | C++ | infra/stream/StdVectorOutputStream.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 54 | 2019-04-02T14:42:54.000Z | 2022-03-20T23:02:19.000Z | infra/stream/StdVectorOutputStream.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 32 | 2019-03-26T06:57:29.000Z | 2022-03-25T00:04:44.000Z | infra/stream/StdVectorOutputStream.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 20 | 2019-03-25T15:49:49.000Z | 2022-03-20T23:02:22.000Z | #ifndef INFRA_STD_VECTOR_OUTPUT_STREAM_HPP
#define INFRA_STD_VECTOR_OUTPUT_STREAM_HPP
#include "infra/stream/OutputStream.hpp"
#include "infra/util/WithStorage.hpp"
#include <vector>
namespace infra
{
class StdVectorOutputStreamWriter
: public StreamWriter
{
public:
using WithStorage = infra::WithStorage<StdVectorOutputStreamWriter, std::vector<uint8_t>>;
explicit StdVectorOutputStreamWriter(std::vector<uint8_t>& vector, std::size_t saveSize = 1024);
public:
virtual void Insert(ConstByteRange range, StreamErrorPolicy& errorPolicy) override;
std::size_t Available() const override;
virtual std::size_t ConstructSaveMarker() const override;
virtual std::size_t GetProcessedBytesSince(std::size_t marker) const override;
virtual infra::ByteRange SaveState(std::size_t marker) override;
virtual void RestoreState(infra::ByteRange range) override;
virtual infra::ByteRange Overwrite(std::size_t marker) override;
private:
std::vector<uint8_t>& vector;
std::size_t saveSize;
std::vector<std::vector<uint8_t>> savedState;
};
class StdVectorOutputStream
: public DataOutputStream::WithWriter<StdVectorOutputStreamWriter>
{
public:
using WithStorage = infra::WithStorage<DataOutputStream::WithWriter<StdVectorOutputStreamWriter>, std::vector<uint8_t>>;
StdVectorOutputStream(std::vector<uint8_t>& vector);
StdVectorOutputStream(std::vector<uint8_t>& vector, const SoftFail&);
StdVectorOutputStream(std::vector<uint8_t>& vector, const NoFail&);
};
}
#endif
| 35.76087 | 128 | 0.722796 | [
"vector"
] |
e1d68a892fe767e8cf0cd02bf3fe5745d9b286f9 | 6,855 | cpp | C++ | src/cpp/main/main.cpp | javabird25/PyGmod | 9bbf3b985548b258182c6f25f02617c712642e9d | [
"MIT"
] | 26 | 2018-11-27T16:40:30.000Z | 2022-01-27T12:37:34.000Z | src/cpp/main/main.cpp | javabird25/PyGmod | 9bbf3b985548b258182c6f25f02617c712642e9d | [
"MIT"
] | 9 | 2019-05-05T22:00:00.000Z | 2021-01-18T13:43:21.000Z | src/cpp/main/main.cpp | javabird25/PyGmod | 9bbf3b985548b258182c6f25f02617c712642e9d | [
"MIT"
] | 4 | 2019-05-05T18:10:35.000Z | 2022-01-18T14:42:31.000Z | // Third stage of PyGmod init.
// This binary module initializes Python and creates subinterpreters for each realm.
#include <fstream>
#include <filesystem>
#ifdef __linux__
#include <dlfcn.h> // For dlopen workaround
#endif
#include <GarrysMod/Lua/Interface.h>
#include "Console.hpp"
#include "_luastack.hpp"
#include "luapyobject.hpp"
#include "lua2py_interop.hpp"
#include "realms.hpp"
#include "interpreter_states.hpp"
#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)
using namespace GarrysMod::Lua;
using std::to_string;
// Declaration of interpreter states in "interpreter_states.hpp"
PyThreadState *clientInterp = nullptr, *serverInterp = nullptr;
bool isFileExists(const char *path) {
std::ifstream file(path);
return file.good();
}
class SetupFailureException : public std::exception {
const char *message;
public:
SetupFailureException(const char *message) : message(message) {}
SetupFailureException(string message) : message(message.c_str()) {}
const char *what() {
return this->message;
}
};
void setPythonHomeAndPath(Console &cons) {
std::filesystem::path pythonHome = std::filesystem::current_path() / "garrysmod" / "pygmod" / "stdlib";
if (!std::filesystem::exists(pythonHome))
throw SetupFailureException("Python standard library directory (garrysmod/pygmod/stdlib) not found.");
std::wstring homeWString = pythonHome.wstring();
const wchar_t* homeWChar = homeWString.c_str();
Py_SetPythonHome(homeWChar);
// Choosing an OS-specific symbol to separate paths in PYTHONPATH
#ifdef _WIN32
const std::wstring os_pathsep = L";";
#else
const std::wstring os_pathsep = L":";
#endif
// PYTHONPATH = PYTHONHOME (*.py modules)
// + PYTHONHOME/lib-dynload (binary modules)
// + PYTHONHOME/site-packages (pip packages)
// + ./garrysmod/pygmod (PyGmod modules)
std::filesystem::path libDynloadPath = pythonHome / "lib-dynload";
std::filesystem::path sitePackagesPath = pythonHome / "site-packages";
std::wstring pathWString = homeWString + os_pathsep
+ libDynloadPath.wstring() + os_pathsep
+ sitePackagesPath.wstring() + os_pathsep
+ (std::filesystem::current_path() / "garrysmod" / "pygmod").wstring();
const wchar_t* pathWChar = pathWString.c_str();
Py_SetPath(pathWChar);
}
// Preloads libpygmod.so to help Python binary modules find Py_* symbols on Linux.
// It's required because for some bizarre reason binary modules don't have
// libpython3.X.so as their dynamic link dependency.
void doDlopenWorkaround() {
#ifdef __linux__
const char *soName = "libpython" TO_STRING(PYTHON_VERSION) ".so.1.0";
if(!dlopen(soName, RTLD_LAZY | RTLD_GLOBAL))
throw SetupFailureException((string("Couldn't load ") + soName + ", which must be at GarrysMod/bin."));
#endif
}
// Schedules the initialization of _luastack module.
void appendLuastackToInittab() {
if (PyImport_AppendInittab("_luastack", PyInit__luastack) == -1)
throw SetupFailureException("PyImport_AppendInittab(\"_luastack\") failed");
}
// Initializes the _luastack module by calling its init() function.
void initLuastack(Console &cons, ILuaBase *ptr) {
createLuaPyObjectMetatable(ptr);
PyObject *luastackModule = PyImport_ImportModule("_luastack"); // import _luastack
if (!luastackModule) {
PyErr_Print();
throw SetupFailureException("Couldn't import or find _luastack module.");
}
PyObject *initFunc = PyObject_GetAttrString(luastackModule, "init"); // initFunc = _luastack.init
Py_DECREF(PyObject_CallFunction(initFunc, "n", reinterpret_cast<Py_ssize_t>(ptr))); // initFunc(ILuaBase memory address)
Py_DECREF(initFunc);
Py_DECREF(luastackModule);
}
// Redirects the Python stdout and stderr to "pygmod.log" for debugging errors which prevent Garry's Mod IO from working.
void redirectIOToLogFile() {
PyRun_SimpleString("import sys; sys.stdout = sys.stderr = sys.__stdout__ = sys.__stderr__ = open('pygmod.log', 'w+')");
}
void initPython(Console &cons) {
setPythonHomeAndPath(cons);
doDlopenWorkaround();
appendLuastackToInittab();
Py_Initialize();
}
int finalize(lua_State*);
// Registers a hook which calls finalize() on game shutdown, so we have a chance to properly
// finalize Python.
void registerShutdownHook(lua_State *state) {
LUA->PushSpecial(SPECIAL_GLOB);
LUA->GetField(-1, "hook");
LUA->GetField(-1, "Add");
LUA->PushString("ShutDown");
LUA->PushString("PyGmod early shutdown routine");
LUA->PushCFunction(finalize);
LUA->Call(3, 0);
LUA->Pop(2); // "hook" table, _G
}
// PyGmod main init routine which may throw SetupFailureException.
// This exception is handled at pygmod_run, the function just below.
void pygmodRunThrowing(Console& cons, lua_State *state) {
cons.log("Binary module loaded");
Realm currentRealm = getCurrentRealm(state);
if (serverInterp == nullptr && clientInterp == nullptr) {
initPython(cons);
}
if (currentRealm == SERVER) {
serverInterp = PyThreadState_Get(); // Saving the server subinterpreter for later use
} else { // Client
// If we should have interpreters for both realms...
if (serverInterp != nullptr) {
// Creating a subinterpreter for client and immediately swapping to it
clientInterp = Py_NewInterpreter();
PyThreadState_Swap(clientInterp);
} else {
clientInterp = PyThreadState_Get();
}
}
cons.log("Python initialized!");
redirectIOToLogFile();
initLuastack(cons, LUA);
if (PyErr_Occurred()) {
PyErr_Print();
throw SetupFailureException("Internal Python error occurred");
}
extendLua(LUA);
cons.log("Lua2Python Lua extensions loaded");
registerShutdownHook(state);
cons.log("Shutdown hook registered");
PyRun_SimpleString("from pygmod import _loader; _loader.main()"); // See python/loader.py
if (PyErr_Occurred()) {
PyErr_Print();
throw SetupFailureException("Exception occurred after an attempt to call _loader.main()");
}
}
// Main init routine.
DLL_EXPORT int pygmod_run(lua_State *state) {
Console cons(LUA); // Creating a Console object for printing to the Garry's Mod console
try {
pygmodRunThrowing(cons, state);
} catch (SetupFailureException e) {
cons.error(e.what());
}
return 0;
}
int finalize(lua_State *state) { // TODO: rewrite
Console cons(LUA); // Creating a Console object for printing to the Garry's Mod console
cons.log("Binary module shutting down.");
Realm currentRealm = getCurrentRealm(state);
auto currentInterp = currentRealm == CLIENT ? clientInterp : serverInterp;
PyThreadState_Swap(currentInterp);
if (currentRealm == CLIENT && serverInterp == nullptr || currentRealm == SERVER && clientInterp == nullptr)
Py_FinalizeEx();
else
Py_EndInterpreter(currentInterp);
if (currentRealm == CLIENT)
clientInterp = nullptr;
else
serverInterp = nullptr;
cons.log("Python finalized!");
return 0;
}
| 31.30137 | 122 | 0.727644 | [
"object"
] |
e1dad4985732e3d8707b76bee2a4409d6feb55dd | 4,502 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcDistanceExpression.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 426 | 2015-04-12T10:00:46.000Z | 2022-03-29T11:03:02.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcDistanceExpression.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 124 | 2015-05-15T05:51:00.000Z | 2022-02-09T15:25:12.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcDistanceExpression.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 214 | 2015-05-06T07:30:37.000Z | 2022-03-26T16:14:04.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcBoolean.h"
#include "ifcpp/IFC4/include/IfcDistanceExpression.h"
#include "ifcpp/IFC4/include/IfcLengthMeasure.h"
#include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h"
#include "ifcpp/IFC4/include/IfcStyledItem.h"
// ENTITY IfcDistanceExpression
IfcDistanceExpression::IfcDistanceExpression( int id ) { m_entity_id = id; }
shared_ptr<BuildingObject> IfcDistanceExpression::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcDistanceExpression> copy_self( new IfcDistanceExpression() );
if( m_DistanceAlong ) { copy_self->m_DistanceAlong = dynamic_pointer_cast<IfcLengthMeasure>( m_DistanceAlong->getDeepCopy(options) ); }
if( m_OffsetLateral ) { copy_self->m_OffsetLateral = dynamic_pointer_cast<IfcLengthMeasure>( m_OffsetLateral->getDeepCopy(options) ); }
if( m_OffsetVertical ) { copy_self->m_OffsetVertical = dynamic_pointer_cast<IfcLengthMeasure>( m_OffsetVertical->getDeepCopy(options) ); }
if( m_OffsetLongitudinal ) { copy_self->m_OffsetLongitudinal = dynamic_pointer_cast<IfcLengthMeasure>( m_OffsetLongitudinal->getDeepCopy(options) ); }
if( m_AlongHorizontal ) { copy_self->m_AlongHorizontal = dynamic_pointer_cast<IfcBoolean>( m_AlongHorizontal->getDeepCopy(options) ); }
return copy_self;
}
void IfcDistanceExpression::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCDISTANCEEXPRESSION" << "(";
if( m_DistanceAlong ) { m_DistanceAlong->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_OffsetLateral ) { m_OffsetLateral->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_OffsetVertical ) { m_OffsetVertical->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_OffsetLongitudinal ) { m_OffsetLongitudinal->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_AlongHorizontal ) { m_AlongHorizontal->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcDistanceExpression::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; }
const std::wstring IfcDistanceExpression::toString() const { return L"IfcDistanceExpression"; }
void IfcDistanceExpression::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 5 ){ std::stringstream err; err << "Wrong parameter count for entity IfcDistanceExpression, expecting 5, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_DistanceAlong = IfcLengthMeasure::createObjectFromSTEP( args[0], map );
m_OffsetLateral = IfcLengthMeasure::createObjectFromSTEP( args[1], map );
m_OffsetVertical = IfcLengthMeasure::createObjectFromSTEP( args[2], map );
m_OffsetLongitudinal = IfcLengthMeasure::createObjectFromSTEP( args[3], map );
m_AlongHorizontal = IfcBoolean::createObjectFromSTEP( args[4], map );
}
void IfcDistanceExpression::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
IfcGeometricRepresentationItem::getAttributes( vec_attributes );
vec_attributes.emplace_back( std::make_pair( "DistanceAlong", m_DistanceAlong ) );
vec_attributes.emplace_back( std::make_pair( "OffsetLateral", m_OffsetLateral ) );
vec_attributes.emplace_back( std::make_pair( "OffsetVertical", m_OffsetVertical ) );
vec_attributes.emplace_back( std::make_pair( "OffsetLongitudinal", m_OffsetLongitudinal ) );
vec_attributes.emplace_back( std::make_pair( "AlongHorizontal", m_AlongHorizontal ) );
}
void IfcDistanceExpression::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
IfcGeometricRepresentationItem::getAttributesInverse( vec_attributes_inverse );
}
void IfcDistanceExpression::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcGeometricRepresentationItem::setInverseCounterparts( ptr_self_entity );
}
void IfcDistanceExpression::unlinkFromInverseCounterparts()
{
IfcGeometricRepresentationItem::unlinkFromInverseCounterparts();
}
| 60.026667 | 238 | 0.771657 | [
"vector",
"model"
] |
e1de9fc2cba2454271b716911d7c672ea438fa5a | 58 | cpp | C++ | benchmarks/logical_or/strict_specialization.erb.cpp | ldionne/mpl11 | 927d4339edc0c0cc41fb65ced2bf19d26bcd4a08 | [
"BSL-1.0"
] | 80 | 2015-03-09T03:19:12.000Z | 2022-03-04T06:44:12.000Z | benchmarks/logical_or/strict_specialization.erb.cpp | ldionne/mpl11 | 927d4339edc0c0cc41fb65ced2bf19d26bcd4a08 | [
"BSL-1.0"
] | 1 | 2021-07-27T22:37:43.000Z | 2021-08-06T17:42:07.000Z | benchmarks/logical_or/strict_specialization.erb.cpp | ldionne/mpl11 | 927d4339edc0c0cc41fb65ced2bf19d26bcd4a08 | [
"BSL-1.0"
] | 8 | 2015-01-28T00:18:57.000Z | 2021-08-06T03:00:49.000Z | <%= render('_main.erb', which: 'strict_specialization') %> | 58 | 58 | 0.689655 | [
"render"
] |
e1e111dd27ecf2153b48e04689a5bfe4ec151797 | 766 | cc | C++ | Code/1970-sorting-the-sentence.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/1970-sorting-the-sentence.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/1970-sorting-the-sentence.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
string sortSentence(string s) {
vector<string> v(10);
for (int i = 0; i < 10; i++) {
v[i] = "";
}
string tmp = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
continue;
}
if (s[i] > '0' && s[i] <= '9') {
int index = s[i] - '0';
v[index] = tmp;
tmp = "";
} else {
tmp += s[i];
}
}
string result = "" + v[1];
for (int i = 2; i < 10; i++) {
if (v[i] == "") {
return result;
}
result += " ";
result += v[i];
}
return result;
}
}; | 24.709677 | 44 | 0.28329 | [
"vector"
] |
e1e1373e16e008a02be4ee83cfb07a5109d40bc2 | 4,701 | cpp | C++ | Source/menu/GUIMain.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | 16 | 2021-08-03T07:44:15.000Z | 2022-01-17T15:14:17.000Z | Source/menu/GUIMain.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | 1 | 2021-08-03T23:36:55.000Z | 2021-08-04T03:01:36.000Z | Source/menu/GUIMain.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | null | null | null | #include <algorithm>
#include <string>
#include <GL/glew.h>
#include <GL/wgl.h>
#include <GL/wglext.h>
#include <GL/gl.h>
#include <GLFW/glfw3.h>
#include "Version.h"
#include "common/Graphics.h"
#include "gameplay/PlayScreenMarathon.h"
#include "gameplay/PlayScreenSprint.h"
#include "gameplay/PlayScreenUltra.h"
#include "gameplay/PlayScreenZone.h"
#include "menu/GUISelectStage.h"
#include "settings/GUISettings.h"
#include "menu/GUIMain.h"
using namespace std::string_literals;
std::array<std::string, 6> GUIMain::menuEntryNames = {
"ZONE"s, "MARATHON"s, "SPRINT"s, "ULTRA"s,
"SETTINGS"s, "EXIT"s
};
std::array<std::string, 4> GUIMain::configurationFolderNames = {
"Assets/Configurations/Zone"s,
"Assets/Configurations/Marathon"s,
"Assets/Configurations/Sprint"s,
"Assets/Configurations/Ultra"s,
};
GUIMain::GUIMain(
const std::shared_ptr<GUI> &parent,
CommonResources &commonResources
): GUI(parent, commonResources) {}
void GUIMain::init() {
fadeTime = -500;
}
void GUIMain::render(const long timePassed) {
if (fadeTime < 0)
fadeTime = std::min(0l, fadeTime + timePassed);
else if (fadeTime != 0) {
fadeTime = std::max(0l, fadeTime - timePassed);
if (fadeTime == 0) {
processOption();
return;
}
}
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
manager->set2DUniform();
const float
screenWidth
= (float)manager->screenWidth / manager->screenHeight,
horizontalCenter = screenWidth / 2;
commonResources.font.render(
"Tetrec"s, horizontalCenter, 0.7, 0,
0.15, 0.5, true, 0, 1, 0, false, 0, {1, 1, 1, 1}
);
for (int i = 0; i != 6; i++) renderMenuEntry(i);
commonResources.font.render(
VERSION_STRING,
screenWidth - 0.05, 0.05, 0, 0.02, 1, true, 0, 1, 0, false, 0,
{1, 1, 1, 0.5f}
);
// Fade.
if (fadeTime != 0) {
manager->set2D(true);
glDisable(GL_TEXTURE_2D);
glColor4f(
0, 0, 0,
fadeTime < 0 ? fadeTime/-500.f : 1 + fadeTime/-500.f
);
glBegin(GL_QUADS);
glVertex2f(1, 1);
glVertex2f(0, 1);
glVertex2f(0, 0);
glVertex2f(1, 0);
glEnd();
}
}
void GUIMain::renderMenuEntry(const int index) {
const bool selected = selectedIndex == index;
const float horizontalCenter
= (float)manager->screenWidth / manager->screenHeight / 2;
const float halfWidth = commonResources.font.render(
menuEntryNames[index], horizontalCenter, 0.5 - 0.05*index, 0,
0.03, 0.5, true, 0, 1, 0, false, 0,
{1, 1, 1, selected ? 1.f : 0.7f}
) / 2;
if (selected) {
const float lineY = 0.49 - 0.05*index;
glLineWidth(2);
glDisable(GL_TEXTURE_2D);
glBegin(GL_LINE_STRIP);
glColor4f(1, 1, 1, 0);
glVertex2f(horizontalCenter + halfWidth*1.5, lineY);
glColor4f(1, 1, 1, 1);
glVertex2f(horizontalCenter + halfWidth, lineY);
glVertex2f(horizontalCenter - halfWidth, lineY);
glColor4f(1, 1, 1, 0);
glVertex2f(horizontalCenter - halfWidth*1.5, lineY);
glEnd();
glEnable(GL_TEXTURE_2D);
}
}
void GUIMain::onKeyPressed(const int key) {
if (fadeTime == 0) switch (key) {
case GLFW_KEY_DOWN:
selectedIndex = (selectedIndex + 1) % 6;
playSound(commonResources.selectSound);
break;
case GLFW_KEY_UP:
selectedIndex = (selectedIndex + 5) % 6;
playSound(commonResources.selectSound);
break;
case GLFW_KEY_ENTER:
fadeTime = 500;
playSound(commonResources.enterSound);
break;
}
}
void GUIMain::processOption() {
if (selectedIndex < 4) {
selectStageScreen = std::make_shared<GUISelectStage>(
manager->currentGUI, commonResources,
menuEntryNames[selectedIndex],
configurationFolderNames[selectedIndex]
);
manager->openGUI(selectStageScreen);
return;
}
switch (selectedIndex) {
case 4:
manager->openGUI(std::make_shared<GUISettings>(
manager->currentGUI, commonResources
));
break;
case 5:
glfwSetWindowShouldClose(manager->window, GLFW_TRUE);
break;
}
}
void GUIMain::notify() {
switch (selectedIndex) {
case 0:
manager->openGUI(std::make_shared<PlayScreenZone>(
manager->currentGUI->parent, commonResources,
selectStageScreen->getStageFileName()
));
break;
case 1:
manager->openGUI(std::make_shared<PlayScreenMarathon>(
manager->currentGUI->parent, commonResources,
selectStageScreen->getStageFileName()
));
break;
case 2:
manager->openGUI(std::make_shared<PlayScreenSprint>(
manager->currentGUI->parent, commonResources,
selectStageScreen->getStageFileName()
));
break;
case 3:
manager->openGUI(std::make_shared<PlayScreenUltra>(
manager->currentGUI->parent, commonResources,
selectStageScreen->getStageFileName()
));
break;
}
selectStageScreen = nullptr;
} | 25.274194 | 64 | 0.697298 | [
"render"
] |
e1e3d4d5443706f05654f67f7a3250f2b689195d | 29,648 | hpp | C++ | src/parser/def/def/defrReader.hpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/parser/def/def/defrReader.hpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/parser/def/def/defrReader.hpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | // *****************************************************************************
// *****************************************************************************
// Copyright 2013-2016, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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.
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: icftcm $
// $Revision: #10 $
// $Date: 2016/12/04 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#ifndef DEFRREADER_H
#define DEFRREADER_H
#include <stdarg.h>
#include "defiKRDefs.hpp"
#include "defiDefs.hpp"
#include "defiUser.hpp"
#include "util/io_manager.h"
#define DEF_MSGS 4013
#define CBMAX 150 // Number of callbacks.
BEGIN_LEFDEF_PARSER_NAMESPACE
using IOManager = open_edi::util::IOManager;
// An enum describing all of the types of reader callbacks.
typedef enum {
defrUnspecifiedCbkType = 0,
defrDesignStartCbkType,
defrTechNameCbkType,
defrPropCbkType,
defrPropDefEndCbkType,
defrPropDefStartCbkType,
defrFloorPlanNameCbkType,
defrArrayNameCbkType,
defrUnitsCbkType,
defrDividerCbkType,
defrBusBitCbkType,
defrSiteCbkType,
defrComponentStartCbkType,
defrComponentCbkType,
defrComponentEndCbkType,
defrNetStartCbkType,
defrNetCbkType,
defrNetNameCbkType,
defrNetNonDefaultRuleCbkType,
defrNetSubnetNameCbkType,
defrNetEndCbkType,
defrPathCbkType,
defrVersionCbkType,
defrVersionStrCbkType,
defrComponentExtCbkType,
defrPinExtCbkType,
defrViaExtCbkType,
defrNetConnectionExtCbkType,
defrNetExtCbkType,
defrGroupExtCbkType,
defrScanChainExtCbkType,
defrIoTimingsExtCbkType,
defrPartitionsExtCbkType,
defrHistoryCbkType,
defrDieAreaCbkType,
defrCanplaceCbkType,
defrCannotOccupyCbkType,
defrPinCapCbkType,
defrDefaultCapCbkType,
defrStartPinsCbkType,
defrPinCbkType,
defrPinEndCbkType,
defrRowCbkType,
defrTrackCbkType,
defrGcellGridCbkType,
defrViaStartCbkType,
defrViaCbkType,
defrViaEndCbkType,
defrRegionStartCbkType,
defrRegionCbkType,
defrRegionEndCbkType,
defrSNetStartCbkType,
defrSNetCbkType,
defrSNetPartialPathCbkType,
defrSNetWireCbkType,
defrSNetEndCbkType,
defrGroupsStartCbkType,
defrGroupNameCbkType,
defrGroupMemberCbkType,
defrGroupCbkType,
defrGroupsEndCbkType,
defrAssertionsStartCbkType,
defrAssertionCbkType,
defrAssertionsEndCbkType,
defrConstraintsStartCbkType,
defrConstraintCbkType,
defrConstraintsEndCbkType,
defrScanchainsStartCbkType,
defrScanchainCbkType,
defrScanchainsEndCbkType,
defrIOTimingsStartCbkType,
defrIOTimingCbkType,
defrIOTimingsEndCbkType,
defrFPCStartCbkType,
defrFPCCbkType,
defrFPCEndCbkType,
defrTimingDisablesStartCbkType,
defrTimingDisableCbkType,
defrTimingDisablesEndCbkType,
defrPartitionsStartCbkType,
defrPartitionCbkType,
defrPartitionsEndCbkType,
defrPinPropStartCbkType,
defrPinPropCbkType,
defrPinPropEndCbkType,
defrBlockageStartCbkType,
defrBlockageCbkType,
defrBlockageEndCbkType,
defrSlotStartCbkType,
defrSlotCbkType,
defrSlotEndCbkType,
defrFillStartCbkType,
defrFillCbkType,
defrFillEndCbkType,
defrCaseSensitiveCbkType,
defrNonDefaultStartCbkType,
defrNonDefaultCbkType,
defrNonDefaultEndCbkType,
defrStylesStartCbkType,
defrStylesCbkType,
defrStylesEndCbkType,
defrExtensionCbkType,
// NEW CALLBACK - If you are creating a new callback, you must add
// a unique item to this enum for each callback routine. When the
// callback is called in def.y you have to supply this enum item
// as an argument in the call.
defrComponentMaskShiftLayerCbkType,
defrDesignEndCbkType
} defrCallbackType_e;
// Declarations of function signatures for each type of callback.
// These declarations are type-safe when compiling with ANSI C
// or C++; you will only be able to register a function pointer
// with the correct signature for a given type of callback.
//
// Each callback function is expected to return 0 if successful.
// A non-zero return code will cause the reader to abort.
//
// The defrDesignStart and defrDesignEnd callback is only called once.
// Other callbacks may be called multiple times, each time with a different
// set of data.
//
// For each callback, the Def API will make the callback to the
// function supplied by the client, which should either make a copy
// of the Def object, or store the data in the client's own data structures.
// The Def API will delete or reuse each object after making the callback,
// so the client should not keep a pointer to it.
//
// All callbacks pass the user data pointer provided in defrRead()
// or defrSetUserData() back to the client; this can be used by the
// client to obtain access to the rest of the client's data structures.
//
// The user data pointer is obtained using defrGetUserData() immediately
// prior to making each callback, so the client is free to change the
// user data on the fly if necessary.
//
// Callbacks with the same signature are passed a callback type
// parameter, which allows an application to write a single callback
// function, register that function for multiple callbacks, then
// switch based on the callback type to handle the appropriate type of
// data.
// A declaration of the signature of all callbacks that return nothing.
typedef int (*defrVoidCbkFnType) (defrCallbackType_e, void* v, defiUserData);
// A declaration of the signature of all callbacks that return a string.
typedef int (*defrStringCbkFnType) (defrCallbackType_e, const char *string, defiUserData);
// A declaration of the signature of all callbacks that return a integer.
typedef int (*defrIntegerCbkFnType) (defrCallbackType_e, int number, defiUserData);
// A declaration of the signature of all callbacks that return a double.
typedef int (*defrDoubleCbkFnType) (defrCallbackType_e, double number, defiUserData);
// A declaration of the signature of all callbacks that return a defiProp.
typedef int (*defrPropCbkFnType) (defrCallbackType_e, defiProp *prop, defiUserData);
// A declaration of the signature of all callbacks that return a defiSite.
typedef int (*defrSiteCbkFnType) (defrCallbackType_e, defiSite *site, defiUserData);
// A declaration of the signature of all callbacks that return a defComponent.
typedef int (*defrComponentCbkFnType) (defrCallbackType_e, defiComponent *comp, defiUserData);
// A declaration of the signature of all callbacks that return a defComponentMaskShiftLayer.
typedef int (*defrComponentMaskShiftLayerCbkFnType) (defrCallbackType_e, defiComponentMaskShiftLayer *comp, defiUserData);
// A declaration of the signature of all callbacks that return a defNet.
typedef int (*defrNetCbkFnType) (defrCallbackType_e, defiNet *net, defiUserData);
// A declaration of the signature of all callbacks that return a defPath.
typedef int (*defrPathCbkFnType) (defrCallbackType_e, defiPath *path, defiUserData);
// A declaration of the signature of all callbacks that return a defiBox.
typedef int (*defrBoxCbkFnType) (defrCallbackType_e, defiBox *box, defiUserData);
// A declaration of the signature of all callbacks that return a defiPinCap.
typedef int (*defrPinCapCbkFnType) (defrCallbackType_e, defiPinCap *pincap, defiUserData);
// A declaration of the signature of all callbacks that return a defiPin.
typedef int (*defrPinCbkFnType) (defrCallbackType_e, defiPin *pin, defiUserData);
// A declaration of the signature of all callbacks that return a defiRow.
typedef int (*defrRowCbkFnType) (defrCallbackType_e, defiRow *row, defiUserData);
// A declaration of the signature of all callbacks that return a defiTrack.
typedef int (*defrTrackCbkFnType) (defrCallbackType_e, defiTrack *track, defiUserData);
// A declaration of the signature of all callbacks that return a defiGcellGrid.
typedef int (*defrGcellGridCbkFnType) (defrCallbackType_e, defiGcellGrid *grid, defiUserData);
// A declaration of the signature of all callbacks that return a defiVia.
typedef int (*defrViaCbkFnType) (defrCallbackType_e, defiVia *, defiUserData);
// A declaration of the signature of all callbacks that return a defiRegion.
typedef int (*defrRegionCbkFnType) (defrCallbackType_e, defiRegion *, defiUserData);
// A declaration of the signature of all callbacks that return a defiGroup.
typedef int (*defrGroupCbkFnType) (defrCallbackType_e, defiGroup *, defiUserData);
// A declaration of the signature of all callbacks that return a defiAssertion.
typedef int (*defrAssertionCbkFnType) (defrCallbackType_e, defiAssertion *, defiUserData);
// A declaration of the signature of all callbacks that return a defiScanChain.
typedef int (*defrScanchainCbkFnType) (defrCallbackType_e, defiScanchain *, defiUserData);
// A declaration of the signature of all callbacks that return a defiIOTiming.
typedef int (*defrIOTimingCbkFnType) (defrCallbackType_e, defiIOTiming *, defiUserData);
// A declaration of the signature of all callbacks that return a defiFPC.
typedef int (*defrFPCCbkFnType) (defrCallbackType_e, defiFPC *, defiUserData);
// A declaration of the signature of all callbacks that return a defiTimingDisable.
typedef int (*defrTimingDisableCbkFnType) (defrCallbackType_e, defiTimingDisable *, defiUserData);
// A declaration of the signature of all callbacks that return a defiPartition.
typedef int (*defrPartitionCbkFnType) (defrCallbackType_e, defiPartition *, defiUserData);
// A declaration of the signature of all callbacks that return a defiPinProp.
typedef int (*defrPinPropCbkFnType) (defrCallbackType_e, defiPinProp *, defiUserData);
// A declaration of the signature of all callbacks that return a defiBlockage.
typedef int (*defrBlockageCbkFnType) (defrCallbackType_e, defiBlockage *, defiUserData);
// A declaration of the signature of all callbacks that return a defiSlot.
typedef int (*defrSlotCbkFnType) (defrCallbackType_e, defiSlot *, defiUserData);
// A declaration of the signature of all callbacks that return a defiFill.
typedef int (*defrFillCbkFnType) (defrCallbackType_e, defiFill *, defiUserData);
// A declaration of the signature of all callbacks that return a defiNonDefault.
typedef int (*defrNonDefaultCbkFnType) (defrCallbackType_e, defiNonDefault *, defiUserData);
// A declaration of the signature of all callbacks that return a defiStyles.
typedef int (*defrStylesCbkFnType) (defrCallbackType_e, defiStyles *, defiUserData);
// NEW CALLBACK - Each callback must return user data, enum, and
// OUR-DATA item. We must define a callback function type for
// each type of OUR-DATA. Some routines return a string, some
// return an integer, and some return a pointer to a class.
// If you create a new class, then you must create a new function
// type here to return that class to the user.
// The reader initialization. Must be called before defrRead().
extern int defrInit ();
extern int defrInitSession (int startSession = 1);
// obsoleted now.
extern int defrReset ();
//Sets all parser memory into init state.
extern int defrClear();
// Change the comment character in the DEF file. The default
// is '#'
extern void defrSetCommentChar (char c);
// Functions to call to set specific actions in the parser.
extern void defrSetAddPathToNet ();
extern void defrSetAllowComponentNets ();
extern int defrGetAllowComponentNets ();
extern void defrSetCaseSensitivity (int caseSense);
// Functions to keep track of callbacks that the user did not
// supply. Normally all parts of the DEF file that the user
// does not supply a callback for will be ignored. These
// routines tell the parser count the DEF constructs that are
// present in the input file, but did not trigger a callback.
// This should help you find any "important" DEF constructs that
// you are ignoring.
extern void defrSetRegisterUnusedCallbacks ();
extern void defrPrintUnusedCallbacks (FILE* log);
// Obsoleted now.
extern int defrReleaseNResetMemory ();
// This function clear session data.
extern void defrClearSession();
// The main reader function.
// The file should already be opened. This requirement allows
// the reader to be used with stdin or a pipe. The file name
// is only used for error messages.
extern int defrRead (IOManager &io_manager,
const char *fileName,
defiUserData userData,
int case_sensitive);
// Set/get the client-provided user data. defi doesn't look at
// this data at all, it simply passes the opaque defiUserData pointer
// back to the application with each callback. The client can
// change the data at any time, and it will take effect on the
// next callback. The defi reader and writer maintain separate
// user data pointers.
extern void defrSetUserData (defiUserData);
extern defiUserData defrGetUserData ();
// Functions to call to register a callback function or get the function
//pointer after it has been registered.
//
// Register one function for all callbacks with the same signature
extern void defrSetArrayNameCbk (defrStringCbkFnType);
extern void defrSetAssertionCbk (defrAssertionCbkFnType);
extern void defrSetAssertionsStartCbk (defrIntegerCbkFnType);
extern void defrSetAssertionsEndCbk (defrVoidCbkFnType);
extern void defrSetBlockageCbk (defrBlockageCbkFnType);
extern void defrSetBlockageStartCbk (defrIntegerCbkFnType);
extern void defrSetBlockageEndCbk (defrVoidCbkFnType);
extern void defrSetBusBitCbk (defrStringCbkFnType);
extern void defrSetCannotOccupyCbk (defrSiteCbkFnType);
extern void defrSetCanplaceCbk (defrSiteCbkFnType);
extern void defrSetCaseSensitiveCbk (defrIntegerCbkFnType);
extern void defrSetComponentCbk (defrComponentCbkFnType);
extern void defrSetComponentExtCbk (defrStringCbkFnType);
extern void defrSetComponentStartCbk (defrIntegerCbkFnType);
extern void defrSetComponentEndCbk (defrVoidCbkFnType);
extern void defrSetConstraintCbk (defrAssertionCbkFnType);
extern void defrSetConstraintsStartCbk (defrIntegerCbkFnType);
extern void defrSetConstraintsEndCbk (defrVoidCbkFnType);
extern void defrSetDefaultCapCbk (defrIntegerCbkFnType);
extern void defrSetDesignCbk (defrStringCbkFnType);
extern void defrSetDesignEndCbk (defrVoidCbkFnType);
extern void defrSetDieAreaCbk (defrBoxCbkFnType);
extern void defrSetDividerCbk (defrStringCbkFnType);
extern void defrSetExtensionCbk (defrStringCbkFnType);
extern void defrSetFillCbk (defrFillCbkFnType);
extern void defrSetFillStartCbk (defrIntegerCbkFnType);
extern void defrSetFillEndCbk (defrVoidCbkFnType);
extern void defrSetFPCCbk (defrFPCCbkFnType);
extern void defrSetFPCStartCbk (defrIntegerCbkFnType);
extern void defrSetFPCEndCbk (defrVoidCbkFnType);
extern void defrSetFloorPlanNameCbk (defrStringCbkFnType);
extern void defrSetGcellGridCbk (defrGcellGridCbkFnType);
extern void defrSetGroupNameCbk (defrStringCbkFnType);
extern void defrSetGroupMemberCbk (defrStringCbkFnType);
extern void defrSetComponentMaskShiftLayerCbk (defrComponentMaskShiftLayerCbkFnType);
extern void defrSetGroupCbk (defrGroupCbkFnType);
extern void defrSetGroupExtCbk (defrStringCbkFnType);
extern void defrSetGroupsStartCbk (defrIntegerCbkFnType);
extern void defrSetGroupsEndCbk (defrVoidCbkFnType);
extern void defrSetHistoryCbk (defrStringCbkFnType);
extern void defrSetIOTimingCbk (defrIOTimingCbkFnType);
extern void defrSetIOTimingsStartCbk (defrIntegerCbkFnType);
extern void defrSetIOTimingsEndCbk (defrVoidCbkFnType);
extern void defrSetIoTimingsExtCbk (defrStringCbkFnType);
extern void defrSetNetCbk (defrNetCbkFnType);
extern void defrSetNetNameCbk (defrStringCbkFnType);
extern void defrSetNetNonDefaultRuleCbk (defrStringCbkFnType);
extern void defrSetNetConnectionExtCbk (defrStringCbkFnType);
extern void defrSetNetExtCbk (defrStringCbkFnType);
extern void defrSetNetPartialPathCbk (defrNetCbkFnType);
extern void defrSetNetSubnetNameCbk (defrStringCbkFnType);
extern void defrSetNetStartCbk (defrIntegerCbkFnType);
extern void defrSetNetEndCbk (defrVoidCbkFnType);
extern void defrSetNonDefaultCbk (defrNonDefaultCbkFnType);
extern void defrSetNonDefaultStartCbk (defrIntegerCbkFnType);
extern void defrSetNonDefaultEndCbk (defrVoidCbkFnType);
extern void defrSetPartitionCbk (defrPartitionCbkFnType);
extern void defrSetPartitionsExtCbk (defrStringCbkFnType);
extern void defrSetPartitionsStartCbk (defrIntegerCbkFnType);
extern void defrSetPartitionsEndCbk (defrVoidCbkFnType);
extern void defrSetPathCbk (defrPathCbkFnType);
extern void defrSetPinCapCbk (defrPinCapCbkFnType);
extern void defrSetPinCbk (defrPinCbkFnType);
extern void defrSetPinExtCbk (defrStringCbkFnType);
extern void defrSetPinPropCbk (defrPinPropCbkFnType);
extern void defrSetPinPropStartCbk (defrIntegerCbkFnType);
extern void defrSetPinPropEndCbk (defrVoidCbkFnType);
extern void defrSetPropCbk (defrPropCbkFnType);
extern void defrSetPropDefEndCbk (defrVoidCbkFnType);
extern void defrSetPropDefStartCbk (defrVoidCbkFnType);
extern void defrSetRegionCbk (defrRegionCbkFnType);
extern void defrSetRegionStartCbk (defrIntegerCbkFnType);
extern void defrSetRegionEndCbk (defrVoidCbkFnType);
extern void defrSetRowCbk (defrRowCbkFnType);
extern void defrSetSNetCbk (defrNetCbkFnType);
extern void defrSetSNetStartCbk (defrIntegerCbkFnType);
extern void defrSetSNetEndCbk (defrVoidCbkFnType);
extern void defrSetSNetPartialPathCbk (defrNetCbkFnType);
extern void defrSetSNetWireCbk (defrNetCbkFnType);
extern void defrSetScanChainExtCbk (defrStringCbkFnType);
extern void defrSetScanchainCbk (defrScanchainCbkFnType);
extern void defrSetScanchainsStartCbk (defrIntegerCbkFnType);
extern void defrSetScanchainsEndCbk (defrVoidCbkFnType);
extern void defrSetSiteCbk (defrSiteCbkFnType);
extern void defrSetSlotCbk (defrSlotCbkFnType);
extern void defrSetSlotStartCbk (defrIntegerCbkFnType);
extern void defrSetSlotEndCbk (defrVoidCbkFnType);
extern void defrSetStartPinsCbk (defrIntegerCbkFnType);
extern void defrSetStylesCbk (defrStylesCbkFnType);
extern void defrSetStylesStartCbk (defrIntegerCbkFnType);
extern void defrSetStylesEndCbk (defrVoidCbkFnType);
extern void defrSetPinEndCbk (defrVoidCbkFnType);
extern void defrSetTechnologyCbk (defrStringCbkFnType);
extern void defrSetTimingDisableCbk (defrTimingDisableCbkFnType);
extern void defrSetTimingDisablesStartCbk (defrIntegerCbkFnType);
extern void defrSetTimingDisablesEndCbk (defrVoidCbkFnType);
extern void defrSetTrackCbk (defrTrackCbkFnType);
extern void defrSetUnitsCbk (defrDoubleCbkFnType);
extern void defrSetVersionCbk (defrDoubleCbkFnType);
extern void defrSetVersionStrCbk (defrStringCbkFnType);
extern void defrSetViaCbk (defrViaCbkFnType);
extern void defrSetViaExtCbk (defrStringCbkFnType);
extern void defrSetViaStartCbk (defrIntegerCbkFnType);
extern void defrSetViaEndCbk (defrVoidCbkFnType);
// NEW CALLBACK - For each new callback you create, you must
// create a routine that allows the user to set it. Add the
// setting routines here.
//Set all of the callbacks that have not yet been set to the following
//function. This is especially useful if you want to check to see
//if you forgot anything.
extern void defrUnsetCallbacks ();
// Functions to call to unregister a callback function.
extern void defrUnsetArrayNameCbk ();
extern void defrUnsetAssertionCbk ();
extern void defrUnsetAssertionsStartCbk ();
extern void defrUnsetAssertionsEndCbk ();
extern void defrUnsetBlockageCbk ();
extern void defrUnsetBlockageStartCbk ();
extern void defrUnsetBlockageEndCbk ();
extern void defrUnsetBusBitCbk ();
extern void defrUnsetCannotOccupyCbk ();
extern void defrUnsetCanplaceCbk ();
extern void defrUnsetCaseSensitiveCbk ();
extern void defrUnsetComponentCbk ();
extern void defrUnsetComponentExtCbk ();
extern void defrUnsetComponentStartCbk ();
extern void defrUnsetComponentEndCbk ();
extern void defrUnsetConstraintCbk ();
extern void defrUnsetConstraintsStartCbk ();
extern void defrUnsetConstraintsEndCbk ();
extern void defrUnsetDefaultCapCbk ();
extern void defrUnsetDesignCbk ();
extern void defrUnsetDesignEndCbk ();
extern void defrUnsetDieAreaCbk ();
extern void defrUnsetDividerCbk ();
extern void defrUnsetExtensionCbk ();
extern void defrUnsetFillCbk ();
extern void defrUnsetFillStartCbk ();
extern void defrUnsetFillEndCbk ();
extern void defrUnsetFPCCbk ();
extern void defrUnsetFPCStartCbk ();
extern void defrUnsetFPCEndCbk ();
extern void defrUnsetFloorPlanNameCbk ();
extern void defrUnsetGcellGridCbk ();
extern void defrUnsetGroupCbk ();
extern void defrUnsetGroupExtCbk ();
extern void defrUnsetGroupMemberCbk ();
extern void defrUnsetComponentMaskShiftLayerCbk ();
extern void defrUnsetGroupNameCbk ();
extern void defrUnsetGroupsStartCbk ();
extern void defrUnsetGroupsEndCbk ();
extern void defrUnsetHistoryCbk ();
extern void defrUnsetIOTimingCbk ();
extern void defrUnsetIOTimingsStartCbk ();
extern void defrUnsetIOTimingsEndCbk ();
extern void defrUnsetIOTimingsExtCbk ();
extern void defrUnsetNetCbk ();
extern void defrUnsetNetNameCbk ();
extern void defrUnsetNetNonDefaultRuleCbk ();
extern void defrUnsetNetConnectionExtCbk ();
extern void defrUnsetNetExtCbk ();
extern void defrUnsetNetPartialPathCbk ();
extern void defrUnsetNetSubnetNameCbk ();
extern void defrUnsetNetStartCbk ();
extern void defrUnsetNetEndCbk ();
extern void defrUnsetNonDefaultCbk ();
extern void defrUnsetNonDefaultStartCbk ();
extern void defrUnsetNonDefaultEndCbk ();
extern void defrUnsetPartitionCbk ();
extern void defrUnsetPartitionsExtCbk ();
extern void defrUnsetPartitionsStartCbk ();
extern void defrUnsetPartitionsEndCbk ();
extern void defrUnsetPathCbk ();
extern void defrUnsetPinCapCbk ();
extern void defrUnsetPinCbk ();
extern void defrUnsetPinEndCbk ();
extern void defrUnsetPinExtCbk ();
extern void defrUnsetPinPropCbk ();
extern void defrUnsetPinPropStartCbk ();
extern void defrUnsetPinPropEndCbk ();
extern void defrUnsetPropCbk ();
extern void defrUnsetPropDefEndCbk ();
extern void defrUnsetPropDefStartCbk ();
extern void defrUnsetRegionCbk ();
extern void defrUnsetRegionStartCbk ();
extern void defrUnsetRegionEndCbk ();
extern void defrUnsetRowCbk ();
extern void defrUnsetScanChainExtCbk ();
extern void defrUnsetScanchainCbk ();
extern void defrUnsetScanchainsStartCbk ();
extern void defrUnsetScanchainsEndCbk ();
extern void defrUnsetSiteCbk ();
extern void defrUnsetSlotCbk ();
extern void defrUnsetSlotStartCbk ();
extern void defrUnsetSlotEndCbk ();
extern void defrUnsetSNetWireCbk ();
extern void defrUnsetSNetCbk ();
extern void defrUnsetSNetStartCbk ();
extern void defrUnsetSNetEndCbk ();
extern void defrUnsetSNetPartialPathCbk ();
extern void defrUnsetStartPinsCbk ();
extern void defrUnsetStylesCbk ();
extern void defrUnsetStylesStartCbk ();
extern void defrUnsetStylesEndCbk ();
extern void defrUnsetTechnologyCbk ();
extern void defrUnsetTimingDisableCbk ();
extern void defrUnsetTimingDisablesStartCbk ();
extern void defrUnsetTimingDisablesEndCbk ();
extern void defrUnsetTrackCbk ();
extern void defrUnsetUnitsCbk ();
extern void defrUnsetVersionCbk ();
extern void defrUnsetVersionStrCbk ();
extern void defrUnsetViaCbk ();
extern void defrUnsetViaExtCbk ();
extern void defrUnsetViaStartCbk ();
extern void defrUnsetViaEndCbk ();
// Routine to set all unused callbacks. This is useful for checking
//to see if you missed something.
extern void defrSetUnusedCallbacks (defrVoidCbkFnType func);
// Return the current line number in the input file.
extern int defrLineNumber ();
extern long long defrLongLineNumber ();
// Routine to set the message logging routine for errors
#ifndef DEFI_LOG_FUNCTION
typedef void (*DEFI_LOG_FUNCTION) (const char*);
#endif
extern void defrSetLogFunction(DEFI_LOG_FUNCTION);
// Routine to set the message logging routine for warnings
#ifndef DEFI_WARNING_LOG_FUNCTION
typedef void (*DEFI_WARNING_LOG_FUNCTION) (const char*);
#endif
extern void defrSetWarningLogFunction(DEFI_WARNING_LOG_FUNCTION);
// Routine to set the message logging routine for errors
// Used in re-enterable environment.
#ifndef DEFI_LOG_FUNCTION
typedef void (*DEFI_CONTEXT_LOG_FUNCTION) (defiUserData userData, const char*);
#endif
extern void defrSetContextLogFunction(DEFI_CONTEXT_LOG_FUNCTION);
// Routine to set the message logging routine for warnings
// Used in re-enterable environment.
#ifndef DEFI_WARNING_LOG_FUNCTION
typedef void (*DEFI_CONTEXT_WARNING_LOG_FUNCTION) (defiUserData userData, const char*);
#endif
extern void defrSetContextWarningLogFunction(DEFI_CONTEXT_WARNING_LOG_FUNCTION);
// Routine to set the user defined malloc routine
typedef void* (*DEFI_MALLOC_FUNCTION) (size_t);
extern void defrSetMallocFunction(DEFI_MALLOC_FUNCTION);
// Routine to set the user defined realloc routine
typedef void* (*DEFI_REALLOC_FUNCTION) (void*, size_t);
extern void defrSetReallocFunction(DEFI_REALLOC_FUNCTION);
// Routine to set the user defined free routine
typedef void (*DEFI_FREE_FUNCTION) (void *);
extern void defrSetFreeFunction(DEFI_FREE_FUNCTION);
// Routine to set the line number of the file that is parsing routine (takes int)
typedef void (*DEFI_LINE_NUMBER_FUNCTION) (int);
extern void defrSetLineNumberFunction(DEFI_LINE_NUMBER_FUNCTION);
// Routine to set the line number of the file that is parsing routine (takes long long)
typedef void (*DEFI_LONG_LINE_NUMBER_FUNCTION) (long long);
extern void defrSetLongLineNumberFunction(DEFI_LONG_LINE_NUMBER_FUNCTION);
// Routine to set the line number of the file that is parsing routine (takes int)
// Used in re-enterable environment.
typedef void (*DEFI_CONTEXT_LINE_NUMBER_FUNCTION) (defiUserData userData, int);
extern void defrSetContextLineNumberFunction(DEFI_CONTEXT_LINE_NUMBER_FUNCTION);
// Routine to set the line number of the file that is parsing routine (takes long long
// Used in re-enterable environment.
typedef void (*DEFI_CONTEXT_LONG_LINE_NUMBER_FUNCTION) (defiUserData userData, long long);
extern void defrSetContextLongLineNumberFunction(DEFI_CONTEXT_LONG_LINE_NUMBER_FUNCTION);
// Set the number of lines before calling the line function callback routine
// Default is 10000
extern void defrSetDeltaNumberLines (int);
// Routine to set the read function
typedef size_t (*DEFI_READ_FUNCTION) (FILE*, char*, size_t);
extern void defrSetReadFunction(DEFI_READ_FUNCTION);
extern void defrUnsetReadFunction ();
// Routine to set the defrWarning.log to open as append instead for write
// New in 5.7
extern void defrSetOpenLogFileAppend ();
extern void defrUnsetOpenLogFileAppend ();
// Routine to set the magic comment found routine
typedef void (*DEFI_MAGIC_COMMENT_FOUND_FUNCTION) ();
extern void defrSetMagicCommentFoundFunction(DEFI_MAGIC_COMMENT_FOUND_FUNCTION);
// Routine to set the magic comment string
extern void defrSetMagicCommentString(char *);
// Routine to disable string property value process, default it will process
// the value string
extern void defrDisablePropStrProcess ();
// Testing purposes only
extern void defrSetNLines(long long n);
// Routine to set the max number of warnings for a perticular section
extern void defrSetAssertionWarnings(int warn);
extern void defrSetBlockageWarnings(int warn);
extern void defrSetCaseSensitiveWarnings(int warn);
extern void defrSetComponentWarnings(int warn);
extern void defrSetConstraintWarnings(int warn);
extern void defrSetDefaultCapWarnings(int warn);
extern void defrSetGcellGridWarnings(int warn);
extern void defrSetIOTimingWarnings(int warn);
extern void defrSetNetWarnings(int warn);
extern void defrSetNonDefaultWarnings(int warn);
extern void defrSetPinExtWarnings(int warn);
extern void defrSetPinWarnings(int warn);
extern void defrSetRegionWarnings(int warn);
extern void defrSetRowWarnings(int warn);
extern void defrSetScanchainWarnings(int warn);
extern void defrSetSNetWarnings(int warn);
extern void defrSetStylesWarnings(int warn);
extern void defrSetTrackWarnings(int warn);
extern void defrSetUnitsWarnings(int warn);
extern void defrSetVersionWarnings(int warn);
extern void defrSetViaWarnings(int warn);
// Handling output messages
extern void defrDisableParserMsgs(int nMsg, int* msgs);
extern void defrEnableParserMsgs(int nMsg, int* msgs);
extern void defrEnableAllMsgs();
extern void defrSetTotalMsgLimit(int totNumMsgs);
extern void defrSetLimitPerMsg(int msgId, int numMsg);
// Return codes for the user callbacks.
//The user should return one of these values.
#define PARSE_OK 0 // continue parsing
#define STOP_PARSE 1 // stop parsing with no error message
#define PARSE_ERROR 2 // stop parsing, print an error message
// Add this alias to the list for the parser
extern void defrAddAlias (const char* key,
const char* value,
int marked);
END_LEFDEF_PARSER_NAMESPACE
USE_LEFDEF_PARSER_NAMESPACE
#endif
| 40.837466 | 122 | 0.794387 | [
"object"
] |
e1e711c7992ad8fed1660a0c3140bcacdf89e395 | 1,571 | cpp | C++ | test.cpp | nkyriazis/conversion_path | 108a8471477e851944940de214fa4338ae983c37 | [
"Apache-2.0"
] | null | null | null | test.cpp | nkyriazis/conversion_path | 108a8471477e851944940de214fa4338ae983c37 | [
"Apache-2.0"
] | null | null | null | test.cpp | nkyriazis/conversion_path | 108a8471477e851944940de214fa4338ae983c37 | [
"Apache-2.0"
] | null | null | null | #include "conversion.hpp"
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
struct A
{
};
struct B
{
};
struct C
{
};
struct D
{
};
struct E
{
};
struct F
{
};
B AtoB(A)
{
std::cout << __FUNCTION__ << std::endl;
return {};
}
C BtoC(B)
{
std::cout << __FUNCTION__ << std::endl;
return {};
}
D CtoD(C)
{
std::cout << __FUNCTION__ << std::endl;
return {};
}
E DtoE(D)
{
std::cout << __FUNCTION__ << std::endl;
return {};
}
F EtoF(E)
{
std::cout << __FUNCTION__ << std::endl;
return {};
}
F f = EtoF(DtoE(CtoD(BtoC(AtoB(A{})))));
int
main(int argc, char** argv)
{
try
{
auto f0 = [](A) -> B {
std::cout << "A->B" << std::endl;
return {};
};
auto f1 = [](B) -> C {
std::cout << "B->C" << std::endl;
return {};
};
auto f2 = [](C) -> D {
std::cout << "C->D" << std::endl;
return {};
};
auto f3 = [](D) -> E {
std::cout << "D->E" << std::endl;
return {};
};
auto f4 = [](E) -> F {
std::cout << "E->F" << std::endl;
return {};
};
auto f5 = [](A) -> F {
std::cout << "A->F" << std::endl;
return {};
};
conversion::convert<B>(A(), std::make_tuple(AtoB, BtoC, CtoD, DtoE, EtoF));
// convert<D>(B(), std::make_tuple(f0, f1, f2, f3, f4));
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
| 16.892473 | 83 | 0.423934 | [
"vector"
] |
e1eaf51e50627c1f45a60898914b9e404c0fd55a | 396 | cc | C++ | compiler/frontends/spar-rtl/getclassstring.cc | CvR42/timber-compiler | fcd35f78378dff111902052916f76adb037f2cf1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2018-04-21T00:43:16.000Z | 2019-03-14T03:22:08.000Z | compiler/frontends/spar-rtl/getclassstring.cc | CvR42/timber-compiler | fcd35f78378dff111902052916f76adb037f2cf1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | compiler/frontends/spar-rtl/getclassstring.cc | CvR42/timber-compiler | fcd35f78378dff111902052916f76adb037f2cf1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | // File: getclassstring.cc
#include <vnustypes.h>
#include <vnusstd.h>
#include <shape.h>
#include "getclassstring.h"
char *get_class_string( const VnusChar *nm, VnusInt len )
{
// TODO: do unicode translation.
size_t sz = (size_t) len;
char *res = (char *) malloc( sz+1 );
if( res == NULL ){
return NULL;
}
memcpy( res, nm, sz );
res[sz] = '\0';
return res;
}
| 19.8 | 57 | 0.606061 | [
"shape"
] |
e1ebb98c2b5b93f9d295adb5a1feb55feab1cec5 | 210,999 | cpp | C++ | inetcore/outlookexpress/inetcomm/imnxport/ixphttpm.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/outlookexpress/inetcomm/imnxport/ixphttpm.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/outlookexpress/inetcomm/imnxport/ixphttpm.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // --------------------------------------------------------------------------------
// Ixphttpm.cpp
// Copyright (c)1998 Microsoft Corporation, All Rights Reserved
// Greg Friedman
// --------------------------------------------------------------------------------
#include "pch.hxx"
#include "dllmain.h"
#include "ixphttpm.h"
#include "wininet.h"
#include "ocidl.h"
#include "Vstream.h"
#include "shlwapi.h"
#include "htmlstr.h"
#include "strconst.h"
#include "propfind.h"
#include "davparse.h"
#include "davstrs.h"
#include <ntverp.h>
#include <process.h>
#include "oleutil.h"
#include "ixputil.h"
#include <demand.h>
extern HRESULT HrGetLastError(void);
typedef struct tagHTTPERROR
{
DWORD dwHttpError;
HRESULT ixpResult;
} HTTPERROR, *LPHTTPERROR;
static const HTTPERROR c_rgHttpErrorMap[] =
{
{ HTTP_STATUS_USE_PROXY, IXP_E_HTTP_USE_PROXY },
{ HTTP_STATUS_BAD_REQUEST, IXP_E_HTTP_BAD_REQUEST },
{ HTTP_STATUS_DENIED, IXP_E_HTTP_UNAUTHORIZED },
{ HTTP_STATUS_FORBIDDEN, IXP_E_HTTP_FORBIDDEN },
{ HTTP_STATUS_NOT_FOUND, IXP_E_HTTP_NOT_FOUND },
{ HTTP_STATUS_BAD_METHOD, IXP_E_HTTP_METHOD_NOT_ALLOW },
{ HTTP_STATUS_NONE_ACCEPTABLE, IXP_E_HTTP_NOT_ACCEPTABLE },
{ HTTP_STATUS_PROXY_AUTH_REQ, IXP_E_HTTP_PROXY_AUTH_REQ },
{ HTTP_STATUS_REQUEST_TIMEOUT, IXP_E_HTTP_REQUEST_TIMEOUT },
{ HTTP_STATUS_CONFLICT, IXP_E_HTTP_CONFLICT },
{ HTTP_STATUS_GONE, IXP_E_HTTP_GONE },
{ HTTP_STATUS_LENGTH_REQUIRED, IXP_E_HTTP_LENGTH_REQUIRED },
{ HTTP_STATUS_PRECOND_FAILED, IXP_E_HTTP_PRECOND_FAILED },
{ HTTP_STATUS_SERVER_ERROR, IXP_E_HTTP_INTERNAL_ERROR },
{ HTTP_STATUS_NOT_SUPPORTED, IXP_E_HTTP_NOT_IMPLEMENTED },
{ HTTP_STATUS_BAD_GATEWAY, IXP_E_HTTP_BAD_GATEWAY },
{ HTTP_STATUS_SERVICE_UNAVAIL, IXP_E_HTTP_SERVICE_UNAVAIL },
{ HTTP_STATUS_GATEWAY_TIMEOUT, IXP_E_HTTP_GATEWAY_TIMEOUT },
{ HTTP_STATUS_VERSION_NOT_SUP, IXP_E_HTTP_VERS_NOT_SUP },
{ 425, IXP_E_HTTP_INSUFFICIENT_STORAGE }, // obsolete out of storage error
{ 507, IXP_E_HTTP_INSUFFICIENT_STORAGE }, // preferred out of storage error
{ ERROR_INTERNET_OUT_OF_HANDLES, E_OUTOFMEMORY },
{ ERROR_INTERNET_TIMEOUT, IXP_E_TIMEOUT },
{ ERROR_INTERNET_NAME_NOT_RESOLVED, IXP_E_CANT_FIND_HOST },
{ ERROR_INTERNET_CANNOT_CONNECT, IXP_E_FAILED_TO_CONNECT },
{ HTTP_STATUS_NOT_MODIFIED, IXP_E_HTTP_NOT_MODIFIED},
};
#define FAIL_ABORT \
if (WasAborted()) \
{ \
hr = TrapError(IXP_E_USER_CANCEL); \
goto exit; \
} \
else
#define FAIL_EXIT_STREAM_WRITE(stream, psz) \
if (FAILED(hr = stream.Write(psz, lstrlen(psz), NULL))) \
goto exit; \
else
#define FAIL_EXIT(hr) \
if (FAILED(hr)) \
goto exit; \
else
#define FAIL_CREATEWND \
if (!m_hwnd && !CreateWnd()) \
{ \
hr = TrapError(E_OUTOFMEMORY); \
goto exit; \
} \
else
// these arrays describe element stack states, and are used to asses
// the current state of the element stack
static const HMELE c_rgPropFindPropStatStack[] =
{
HMELE_DAV_MULTISTATUS,
HMELE_DAV_RESPONSE,
HMELE_DAV_PROPSTAT
};
static const HMELE c_rgPropFindPropValueStack[] =
{
HMELE_DAV_MULTISTATUS,
HMELE_DAV_RESPONSE,
HMELE_DAV_PROPSTAT,
HMELE_DAV_PROP,
HMELE_UNKNOWN // wildcard
};
static const HMELE c_rgPropFindResponseStack[] =
{
HMELE_DAV_MULTISTATUS,
HMELE_DAV_RESPONSE
};
static const HMELE c_rgMultiStatusResponseChildStack[] =
{
HMELE_DAV_MULTISTATUS,
HMELE_DAV_RESPONSE,
HMELE_UNKNOWN
};
static const HMELE c_rgPropFindStatusStack[] =
{
HMELE_DAV_MULTISTATUS,
HMELE_DAV_RESPONSE,
HMELE_DAV_PROPSTAT,
HMELE_DAV_STATUS
};
// GET command
static const PFNHTTPMAILOPFUNC c_rgpfGet[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessGetResponse,
&CHTTPMailTransport::FinalizeRequest
};
// DELETE command
static const PFNHTTPMAILOPFUNC c_rgpfDelete[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::FinalizeRequest
};
// PROPPATCH command
static const PFNHTTPMAILOPFUNC c_rgpfnPropPatch[] =
{
&CHTTPMailTransport::GeneratePropPatchXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::FinalizeRequest
};
// MKCOL command
static const PFNHTTPMAILOPFUNC c_rgpfnMkCol[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCharsetLine,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessCreatedResponse,
&CHTTPMailTransport::ProcessLocationResponse,
&CHTTPMailTransport::FinalizeRequest
};
// COPY command
static const PFNHTTPMAILOPFUNC c_rgpfnCopy[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDestinationHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessCreatedResponse,
&CHTTPMailTransport::ProcessLocationResponse,
&CHTTPMailTransport::FinalizeRequest
};
// MOVE command
static const PFNHTTPMAILOPFUNC c_rgpfnMove[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDestinationHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessCreatedResponse,
&CHTTPMailTransport::ProcessLocationResponse,
&CHTTPMailTransport::FinalizeRequest
};
// BMOVE command (data applies to bcopy and bmove)
#define BCOPYMOVE_MAXRESPONSES 10
XP_BEGIN_SCHEMA(HTTPMAILBCOPYMOVE)
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_MSVALIDMSRESPONSECHILD, XPCDT_STRA, HTTPMAILBCOPYMOVE, pszHref)
XP_SCHEMA_COL(HMELE_DAV_LOCATION, XPCF_MSVALIDMSRESPONSECHILD, XPCDT_STRA, HTTPMAILBCOPYMOVE, pszLocation)
XP_SCHEMA_COL(HMELE_DAV_STATUS, XPCF_MSVALIDMSRESPONSECHILD, XPCDT_IXPHRESULT, HTTPMAILBCOPYMOVE, hrResult)
XP_END_SCHEMA
static const PFNHTTPMAILOPFUNC c_rgpfnBMove[] =
{
&CHTTPMailTransport::InitBCopyMove,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDestinationHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRequest
};
static const XMLPARSEFUNCS c_rgpfnBCopyMoveParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::BCopyMove_HandleText,
&CHTTPMailTransport::BCopyMove_EndChildren
};
// MemberInfo Data. There are four schemas associated with this command.
// The first three are used to build up the propfind request, and are
// not used to parse responses. The fourth is the combined schema that
// is used for parsing.
//
// THE FOURTH SCHEMA MUST BE KEPT IN SYNC WITH THE FIRST THREE TO
// GUARANTEE THAT RESPONSES WILL BE PARSED CORRECTLY.
#define MEMBERINFO_MAXRESPONSES 10
// common property schema - used only for building the request
XP_BEGIN_SCHEMA(HTTPMEMBERINFO_COMMON)
// common properties
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_PROPFINDHREF, XPCDT_STRA, HTTPMEMBERINFO, pszHref)
XP_SCHEMA_COL(HMELE_DAV_ISFOLDER, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fIsFolder)
XP_END_SCHEMA
// folder property schema - used only for building the request
XP_BEGIN_SCHEMA(HTTPMEMBERINFO_FOLDER)
XP_SCHEMA_COL(HMELE_DAV_DISPLAYNAME, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszDisplayName)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SPECIAL, XPFC_PROPFINDPROP, XPCDT_HTTPSPECIALFOLDER, HTTPMEMBERINFO, tySpecial)
XP_SCHEMA_COL(HMELE_DAV_HASSUBS, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fHasSubs)
XP_SCHEMA_COL(HMELE_DAV_NOSUBS, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fNoSubs)
XP_SCHEMA_COL(HMELE_HTTPMAIL_UNREADCOUNT, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwUnreadCount)
XP_SCHEMA_COL(HMELE_DAV_VISIBLECOUNT, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwVisibleCount)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SPECIAL, XPFC_PROPFINDPROP, XPCDT_HTTPSPECIALFOLDER, HTTPMEMBERINFO, tySpecial)
XP_END_SCHEMA
// message property schema - used only for building the request
XP_BEGIN_SCHEMA(HTTPMEMBERINFO_MESSAGE)
XP_SCHEMA_COL(HMELE_HTTPMAIL_READ, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fRead)
XP_SCHEMA_COL(HMELE_MAIL_HASATTACHMENT, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fHasAttachment)
XP_SCHEMA_COL(HMELE_MAIL_TO, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszTo)
XP_SCHEMA_COL(HMELE_MAIL_FROM, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszFrom)
XP_SCHEMA_COL(HMELE_MAIL_SUBJECT, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszSubject)
XP_SCHEMA_COL(HMELE_MAIL_DATE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszDate)
XP_SCHEMA_COL(HMELE_DAV_GETCONTENTLENGTH, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwContentLength)
XP_END_SCHEMA
// combined schema - used for parsing responses
XP_BEGIN_SCHEMA(HTTPMEMBERINFO)
// common properties
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_PROPFINDHREF, XPCDT_STRA, HTTPMEMBERINFO, pszHref)
XP_SCHEMA_COL(HMELE_DAV_ISFOLDER, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fIsFolder)
// folder properties
XP_SCHEMA_COL(HMELE_DAV_DISPLAYNAME, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszDisplayName)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SPECIAL, XPFC_PROPFINDPROP, XPCDT_HTTPSPECIALFOLDER, HTTPMEMBERINFO, tySpecial)
XP_SCHEMA_COL(HMELE_DAV_HASSUBS, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fHasSubs)
XP_SCHEMA_COL(HMELE_DAV_NOSUBS, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fNoSubs)
XP_SCHEMA_COL(HMELE_HTTPMAIL_UNREADCOUNT, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwUnreadCount)
XP_SCHEMA_COL(HMELE_DAV_VISIBLECOUNT, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwVisibleCount)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SPECIAL, XPFC_PROPFINDPROP, XPCDT_HTTPSPECIALFOLDER, HTTPMEMBERINFO, tySpecial)
// message properties
XP_SCHEMA_COL(HMELE_HTTPMAIL_READ, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fRead)
XP_SCHEMA_COL(HMELE_MAIL_HASATTACHMENT, XPFC_PROPFINDPROP, XPCDT_BOOL, HTTPMEMBERINFO, fHasAttachment)
XP_SCHEMA_COL(HMELE_MAIL_TO, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszTo)
XP_SCHEMA_COL(HMELE_MAIL_FROM, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszFrom)
XP_SCHEMA_COL(HMELE_MAIL_SUBJECT, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszSubject)
XP_SCHEMA_COL(HMELE_MAIL_DATE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPMEMBERINFO, pszDate)
XP_SCHEMA_COL(HMELE_DAV_GETCONTENTLENGTH, XPFC_PROPFINDPROP, XPCDT_DWORD, HTTPMEMBERINFO, dwContentLength)
XP_END_SCHEMA
static const XMLPARSEFUNCS c_rgpfnMemberInfoParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::MemberInfo_HandleText,
&CHTTPMailTransport::MemberInfo_EndChildren
};
static const PFNHTTPMAILOPFUNC c_rgpfnMemberInfo[] =
{
&CHTTPMailTransport::InitMemberInfo,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::RequireMultiStatus,
&CHTTPMailTransport::FinalizeRequest
};
// Operations which share MemberError-based responses (MarkRead, BDELETE)
#define MEMBERERROR_MAXRESPONSES 10
XP_BEGIN_SCHEMA(HTTPMEMBERERROR)
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_PROPFINDHREF, XPCDT_STRA, HTTPMEMBERERROR, pszHref)
XP_SCHEMA_COL(HMELE_DAV_STATUS, XPCF_MSVALIDMSRESPONSECHILD, XPCDT_IXPHRESULT, HTTPMEMBERERROR, hrResult)
XP_END_SCHEMA
static const XMLPARSEFUNCS c_rgpfnMemberErrorParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::MemberError_HandleText,
&CHTTPMailTransport::MemberError_EndChildren
};
static const PFNHTTPMAILOPFUNC c_rgpfnMarkRead[] =
{
&CHTTPMailTransport::InitMemberError,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRequest
};
// SendMessage
static const PFNHTTPMAILOPFUNC c_rgpfnSendMessage[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddContentTypeHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendPostRequest,
&CHTTPMailTransport::ProcessPostResponse,
&CHTTPMailTransport::FinalizeRequest
};
// RootProps
XP_BEGIN_SCHEMA(ROOTPROPS)
XP_SCHEMA_COL(HMELE_HOTMAIL_ADBAR, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszAdbar)
XP_SCHEMA_COL(HMELE_HTTPMAIL_CONTACTS, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszContacts)
XP_SCHEMA_COL(HMELE_HTTPMAIL_INBOX, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszInbox)
XP_SCHEMA_COL(HMELE_HTTPMAIL_OUTBOX, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszOutbox)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SENDMSG, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszSendMsg)
XP_SCHEMA_COL(HMELE_HTTPMAIL_SENTITEMS, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszSentItems)
XP_SCHEMA_COL(HMELE_HTTPMAIL_DELETEDITEMS, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszDeletedItems)
XP_SCHEMA_COL(HMELE_HTTPMAIL_DRAFTS, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszDrafts)
XP_SCHEMA_COL(HMELE_HTTPMAIL_MSGFOLDERROOT, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszMsgFolderRoot)
XP_SCHEMA_COL(HMELE_HOTMAIL_MAXPOLLINGINTERVAL, XPFC_PROPFINDPROP, XPCDT_DWORD, ROOTPROPS, dwMaxPollingInterval)
XP_SCHEMA_COL(HMELE_HOTMAIL_SIG, XPFC_PROPFINDPROP, XPCDT_STRA, ROOTPROPS, pszSig)
XP_END_SCHEMA
static const XMLPARSEFUNCS c_rgpfnRootPropsParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::RootProps_HandleText,
&CHTTPMailTransport::RootProps_EndChildren
};
static const PFNHTTPMAILOPFUNC c_rgpfnRootProps[] =
{
&CHTTPMailTransport::InitRootProps,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRootProps
};
static const PFNHTTPMAILOPFUNC c_rgpfnPost[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddContentTypeHeader,
&CHTTPMailTransport::AddCharsetLine,
&CHTTPMailTransport::SendPostRequest,
//&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessPostResponse,
&CHTTPMailTransport::FinalizeRequest
};
static const PFNHTTPMAILOPFUNC c_rgpfnPut[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCharsetLine,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessPostResponse,
&CHTTPMailTransport::FinalizeRequest
};
// ListContacts Data
#define LISTCONTACTS_MAXRESPONSES 10
XP_BEGIN_SCHEMA(HTTPCONTACTID)
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_PROPFINDHREF, XPCDT_STRA, HTTPCONTACTID, pszHref)
XP_SCHEMA_COL(HMELE_DAV_ID, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTID, pszId)
XP_SCHEMA_COL(HMELE_CONTACTS_GROUP, XPFC_PROPFINDPROP, XPCDT_HTTPCONTACTTYPE, HTTPCONTACTID, tyContact)
XP_SCHEMA_COL(HMELE_HOTMAIL_MODIFIED, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTID, pszModified)
XP_END_SCHEMA
static const PFNHTTPMAILOPFUNC c_rgpfnListContacts[] =
{
&CHTTPMailTransport::InitListContacts,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::RequireMultiStatus,
&CHTTPMailTransport::FinalizeRequest
};
static const XMLPARSEFUNCS c_rgpfnListContactsParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::ListContacts_HandleText,
&CHTTPMailTransport::ListContacts_EndChildren
};
// ContactInfo Data
#define CONTACTINFO_MAXRESPONSES 10
XP_BEGIN_SCHEMA(HTTPCONTACTINFO)
XP_SCHEMA_COL(HMELE_DAV_HREF, XPCF_PROPFINDHREF, XPCDT_STRA, HTTPCONTACTINFO, pszHref)
XP_SCHEMA_COL(HMELE_DAV_ID, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszId)
XP_SCHEMA_COL(HMELE_CONTACTS_GROUP, XPFC_PROPFINDPROP, XPCDT_HTTPCONTACTTYPE, HTTPCONTACTINFO, tyContact)
XP_SCHEMA_COL(HMELE_HOTMAIL_MODIFIED, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszModified)
XP_SCHEMA_COL(HMELE_CONTACTS_CN, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszDisplayName)
XP_SCHEMA_COL(HMELE_CONTACTS_GIVENNAME, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszGivenName)
XP_SCHEMA_COL(HMELE_CONTACTS_SN, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszSurname)
XP_SCHEMA_COL(HMELE_CONTACTS_NICKNAME, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszNickname)
XP_SCHEMA_COL(HMELE_CONTACTS_MAIL, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszEmail)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMESTREET, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomeStreet)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMECITY, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomeCity)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMESTATE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomeState)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMEPOSTALCODE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomePostalCode)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMECOUNTRY, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomeCountry)
XP_SCHEMA_COL(HMELE_CONTACTS_O, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszCompany)
XP_SCHEMA_COL(HMELE_CONTACTS_STREET, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkStreet)
XP_SCHEMA_COL(HMELE_CONTACTS_L, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkCity)
XP_SCHEMA_COL(HMELE_CONTACTS_ST, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkState)
XP_SCHEMA_COL(HMELE_CONTACTS_POSTALCODE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkPostalCode)
XP_SCHEMA_COL(HMELE_CONTACTS_FRIENDLYCOUNTRYNAME, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkCountry)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMEPHONE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomePhone)
XP_SCHEMA_COL(HMELE_CONTACTS_HOMEFAX, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszHomeFax)
XP_SCHEMA_COL(HMELE_CONTACTS_TELEPHONENUMBER, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkPhone)
XP_SCHEMA_COL(HMELE_CONTACTS_FACSIMILETELEPHONENUMBER, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszWorkFax)
XP_SCHEMA_COL(HMELE_CONTACTS_MOBILE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszMobilePhone)
XP_SCHEMA_COL(HMELE_CONTACTS_OTHERTELEPHONE, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszOtherPhone)
XP_SCHEMA_COL(HMELE_CONTACTS_BDAY, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszBday)
XP_SCHEMA_COL(HMELE_CONTACTS_PAGER, XPFC_PROPFINDPROP, XPCDT_STRA, HTTPCONTACTINFO, pszPager)
XP_END_SCHEMA
static const XMLPARSEFUNCS c_rgpfnContactInfoParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::ContactInfo_HandleText,
&CHTTPMailTransport::ContactInfo_EndChildren
};
static const PFNHTTPMAILOPFUNC c_rgpfnContactInfo[] =
{
&CHTTPMailTransport::InitContactInfo,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRequest
};
// PostContact Data
static const PFNHTTPMAILOPFUNC c_rgpfnPostContact[] =
{
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessPostContactResponse,
&CHTTPMailTransport::InitListContacts,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRequest
};
static const XMLPARSEFUNCS c_rgpfnPostOrPatchContactParse[] =
{
&CHTTPMailTransport::CreateElement,
&CHTTPMailTransport::PostOrPatchContact_HandleText,
&CHTTPMailTransport::PostOrPatchContact_EndChildren
};
// PatchContact data
static const PFNHTTPMAILOPFUNC c_rgpfnPatchContact[] =
{
&CHTTPMailTransport::GeneratePropPatchXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessPatchContactResponse,
&CHTTPMailTransport::InitListContacts,
&CHTTPMailTransport::GeneratePropFindXML,
&CHTTPMailTransport::OpenRequest,
&CHTTPMailTransport::AddDepthHeader,
&CHTTPMailTransport::AddCommonHeaders,
&CHTTPMailTransport::SendRequest,
&CHTTPMailTransport::ProcessXMLResponse,
&CHTTPMailTransport::FinalizeRequest
};
// special folders
typedef struct tagHTTPSPECIALFOLDER
{
const WCHAR *pwcName;
ULONG ulLen;
HTTPMAILSPECIALFOLDER tyFolder;
} HTTPSPECIALFOLDER, *LPHTTPSPECIALFOLDER;
static const HTTPSPECIALFOLDER c_rgpfnSpecialFolder[] =
{
{ DAV_STR_LEN(InboxSpecialFolder), HTTPMAIL_SF_INBOX },
{ DAV_STR_LEN(DeletedItemsSpecialFolder), HTTPMAIL_SF_DELETEDITEMS },
{ DAV_STR_LEN(DraftsSpecialFolder), HTTPMAIL_SF_DRAFTS },
{ DAV_STR_LEN(OutboxSpecialFolder), HTTPMAIL_SF_OUTBOX },
{ DAV_STR_LEN(SentItemsSpecialFolder), HTTPMAIL_SF_SENTITEMS },
{ DAV_STR_LEN(ContactsSpecialFolder), HTTPMAIL_SF_CONTACTS },
{ DAV_STR_LEN(CalendarSpecialFolder), HTTPMAIL_SF_CALENDAR },
{ DAV_STR_LEN(MsnPromoSpecialFolder), HTTPMAIL_SF_MSNPROMO },
{ DAV_STR_LEN(BulkMailSpecialFolder), HTTPMAIL_SF_BULKMAIL },
};
#define VALIDSTACK(rg) ValidStack(rg, ARRAYSIZE(rg))
static const char s_szHTTPMailWndClass[] = "HTTPMailWndClass";
// Notification messages used to communicate between the async thread
// and the window proc
#define SPM_HTTPMAIL_STATECHANGED (WM_USER + 1)
#define SPM_HTTPMAIL_SENDRESPONSE (WM_USER + 2)
#define SPM_HTTPMAIL_LOGONPROMPT (WM_USER + 3)
#define SPM_HTTPMAIL_GETPARENTWINDOW (WM_USER + 4)
// --------------------------------------------------------------------------------
// static functions
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_HrCrackUrl
// --------------------------------------------------------------------------------
HRESULT HrCrackUrl(
LPSTR pszUrl,
LPSTR *ppszHost,
LPSTR *ppszPath,
INTERNET_PORT *pPort)
{
URL_COMPONENTS uc;
char szHost[INTERNET_MAX_HOST_NAME_LENGTH];
char szPath[INTERNET_MAX_PATH_LENGTH];
if (NULL == pszUrl)
return E_INVALIDARG;
if (ppszHost)
*ppszHost = NULL;
if (ppszPath)
*ppszPath = NULL;
if (pPort)
*pPort = INTERNET_INVALID_PORT_NUMBER;
ZeroMemory(&uc, sizeof(URL_COMPONENTS));
uc.dwStructSize = sizeof(URL_COMPONENTS);
uc.lpszHostName = szHost;
uc.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
uc.lpszUrlPath = szPath;
uc.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
if (!InternetCrackUrl(pszUrl, NULL, 0, &uc))
return E_INVALIDARG;
// validate the protocol
if (INTERNET_SCHEME_HTTP != uc.nScheme && INTERNET_SCHEME_HTTPS != uc.nScheme)
return E_INVALIDARG;
// copy the response data
if (ppszHost)
{
*ppszHost = PszDupA(uc.lpszHostName);
if (!*ppszHost)
return E_OUTOFMEMORY;
}
if (ppszPath)
{
*ppszPath = PszDupA(uc.lpszUrlPath);
if (!*ppszPath)
{
SafeMemFree(*ppszHost);
return E_OUTOFMEMORY;
}
}
if (pPort)
*pPort = uc.nPort;
return S_OK;
}
// --------------------------------------------------------------------------------
// Utility functions
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// HttpErrorToIxpResult
// --------------------------------------------------------------------------------
HRESULT HttpErrorToIxpResult(DWORD dwHttpError)
{
for (DWORD dw = 0; dw < ARRAYSIZE(c_rgHttpErrorMap); dw++)
{
if (c_rgHttpErrorMap[dw].dwHttpError == dwHttpError)
return c_rgHttpErrorMap[dw].ixpResult;
}
return E_FAIL;
}
// --------------------------------------------------------------------------------
// HrParseHTTPStatus
// --------------------------------------------------------------------------------
HRESULT HrParseHTTPStatus(LPSTR pszStatusStr, DWORD *pdwStatus)
{
LPSTR psz;
LPSTR pszEnd;
char chSaved;
if (!pszStatusStr || !pdwStatus)
return E_INVALIDARG;
*pdwStatus = 0;
// status is of the form "HTTP/1.1 200 OK"
psz = PszSkipWhiteA(pszStatusStr);
if ('\0' == *psz)
return E_INVALIDARG;
psz = PszScanToWhiteA(psz);
if ('\0' == *psz)
return E_INVALIDARG;
psz = PszSkipWhiteA(psz);
if ('\0' == *psz)
return E_INVALIDARG;
// psz now points at the numeric component
pszEnd = PszScanToWhiteA(psz);
if ('\0' == *psz)
return E_INVALIDARG;
// temporarily modify the string in place
chSaved = *pszEnd;
*pszEnd = '\0';
*pdwStatus = StrToInt(psz);
*pszEnd = chSaved;
return S_OK;
}
// --------------------------------------------------------------------------------
// HrGetStreamSize
// --------------------------------------------------------------------------------
static HRESULT HrGetStreamSize(LPSTREAM pstm, ULONG *pcb)
{
// Locals
HRESULT hr=S_OK;
ULARGE_INTEGER uliPos = {0,0};
LARGE_INTEGER liOrigin = {0,0};
// Seek
hr = pstm->Seek(liOrigin, STREAM_SEEK_END, &uliPos);
if (FAILED(hr))
goto error;
// set size
*pcb = uliPos.LowPart;
error:
// Done
return hr;
}
// --------------------------------------------------------------------------------
// HrAddPropFindProps
// --------------------------------------------------------------------------------
HRESULT HrAddPropFindProps(IPropFindRequest *pRequest, const HMELE *rgEle, DWORD cEle)
{
HRESULT hr;
HMELE ele;
for (DWORD i = 0; i < cEle; ++i)
{
ele = rgEle[i];
hr = pRequest->AddProperty(
rgHTTPMailDictionary[ele].dwNamespaceID,
const_cast<char *>(rgHTTPMailDictionary[ele].pszName));
if (FAILED(hr))
goto exit;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// HrAddPropFindSchemaProps
// --------------------------------------------------------------------------------
HRESULT HrAddPropFindSchemaProps(
IPropFindRequest *pRequest,
const XPCOLUMN *prgCols,
DWORD cCols)
{
HRESULT hr = S_OK;
HMELE ele;
for (DWORD i = 0; i < cCols; i++)
{
if (!!(prgCols[i].dwFlags & XPCF_PFREQUEST))
{
hr = pRequest->AddProperty(
rgHTTPMailDictionary[prgCols[i].ele].dwNamespaceID,
rgHTTPMailDictionary[prgCols[i].ele].pszName);
if (FAILED(hr))
goto exit;
}
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// _HrGenerateRfc821Stream
// --------------------------------------------------------------------------------
HRESULT _HrGenerateRfc821Stream(LPCSTR pszFrom,
LPHTTPTARGETLIST pTargets,
IStream **ppRfc821Stream)
{
HRESULT hr = S_OK;
IStream *pStream = NULL;
DWORD dw;
DWORD cbCloseTerm;
DWORD cbRcptTo;
IxpAssert(pszFrom);
IxpAssert(pTargets);
IxpAssert(ppRfc821Stream);
*ppRfc821Stream = NULL;
cbCloseTerm = lstrlen(c_szXMLCloseElementCRLF);
cbRcptTo = lstrlen(c_szRcptTo);
pStream = new CVirtualStream();
if (NULL == pStream)
{
hr = TraceResult(E_OUTOFMEMORY);
goto exit;
}
// write out 'mail from'
FAIL_EXIT_STREAM_WRITE((*pStream), c_szMailFrom);
FAIL_EXIT_STREAM_WRITE((*pStream), pszFrom);
FAIL_EXIT(hr = pStream->Write(c_szXMLCloseElementCRLF, cbCloseTerm, NULL));
// write out the 'rcpt to' lines
for (dw = 0; dw < pTargets->cTarget; ++dw)
{
FAIL_EXIT(hr = pStream->Write(c_szRcptTo, cbRcptTo, NULL));
FAIL_EXIT_STREAM_WRITE((*pStream), pTargets->prgTarget[dw]);
FAIL_EXIT(hr = pStream->Write(c_szXMLCloseElementCRLF, cbCloseTerm, NULL));
}
// append an extra crlf to the end of the stream
FAIL_EXIT_STREAM_WRITE((*pStream), c_szCRLF);
*ppRfc821Stream = pStream;
pStream = NULL;
exit:
SafeRelease(pStream);
return hr;
}
// --------------------------------------------------------------------------------
// _EscapeString
// --------------------------------------------------------------------------------
LPSTR _EscapeString(LPSTR pszIn)
{
CByteStream stream;
DWORD dwLen;
LPSTR pszLastNonEsc, pszNext, pszOut;
HRESULT hr;
if (NULL == pszIn)
return NULL;
pszLastNonEsc = pszIn;
pszNext = pszIn;
while (*pszNext)
{
switch (*pszNext)
{
case '<':
case '>':
case '&':
if (FAILED(hr = stream.Write(pszLastNonEsc, (ULONG) (pszNext - pszLastNonEsc), NULL)))
goto exit;
if (*pszNext == '<')
{
if (FAILED(hr = stream.Write(c_szEscLessThan, lstrlen(c_szEscLessThan), NULL)))
goto exit;
}
else if (*pszNext == '>')
{
if (FAILED(hr = stream.Write(c_szEscGreaterThan, lstrlen(c_szEscGreaterThan), NULL)))
goto exit;
}
else
{
if (FAILED(hr = stream.Write(c_szEscAmp, lstrlen(c_szEscAmp), NULL)))
goto exit;
}
pszLastNonEsc = CharNextExA(CP_ACP, pszNext, 0);
break;
}
pszNext = CharNextExA(CP_ACP, pszNext, 0);
}
if (FAILED(hr = stream.Write(pszLastNonEsc, (ULONG) (pszNext - pszLastNonEsc), NULL)))
goto exit;
FAIL_EXIT(hr = stream.HrAcquireStringA(&dwLen, (LPSTR *)&pszOut, ACQ_DISPLACE));
return pszOut;
exit:
return NULL;
}
const HMELE g_rgContactEle[] = {
HMELE_UNKNOWN,
HMELE_UNKNOWN,
HMELE_UNKNOWN,
HMELE_UNKNOWN,
HMELE_UNKNOWN,
HMELE_CONTACTS_GIVENNAME,
HMELE_CONTACTS_SN,
HMELE_CONTACTS_NICKNAME,
HMELE_CONTACTS_MAIL,
HMELE_CONTACTS_HOMESTREET,
HMELE_CONTACTS_HOMECITY,
HMELE_CONTACTS_HOMESTATE,
HMELE_CONTACTS_HOMEPOSTALCODE,
HMELE_CONTACTS_HOMECOUNTRY,
HMELE_CONTACTS_O,
HMELE_CONTACTS_STREET,
HMELE_CONTACTS_L,
HMELE_CONTACTS_ST,
HMELE_CONTACTS_POSTALCODE,
HMELE_CONTACTS_FRIENDLYCOUNTRYNAME,
HMELE_CONTACTS_HOMEPHONE,
HMELE_CONTACTS_HOMEFAX,
HMELE_CONTACTS_TELEPHONENUMBER,
HMELE_CONTACTS_FACSIMILETELEPHONENUMBER,
HMELE_CONTACTS_MOBILE,
HMELE_CONTACTS_OTHERTELEPHONE,
HMELE_CONTACTS_BDAY,
HMELE_CONTACTS_PAGER
};
#define CCHMAX_TAGBUFFER 128
HRESULT HrGeneratePostContactXML(LPHTTPCONTACTINFO pciInfo, LPVOID *ppvXML, DWORD *pdwLen)
{
HRESULT hr = S_OK;
CByteStream stream;
CDAVNamespaceArbiterImp dna;
DWORD dwIndex, dwSize = ARRAYSIZE(g_rgContactEle);
DWORD iBufferSize;
TCHAR szTagBuffer[CCHMAX_TAGBUFFER+1];
LPSTR *prgsz = (LPSTR*)pciInfo, pszEsc;
LPCSTR pszPropName;
*ppvXML = NULL;
*pdwLen = 0;
if (NULL == ppvXML)
return E_INVALIDARG;
// write the DAV header. we ALWAYS post using the windows-1252 code
// page for this release.
if (FAILED(hr = stream.Write(c_szXML1252Head, lstrlen(c_szXML1252Head), NULL)))
goto exit;
dna.m_rgbNsUsed[DAVNAMESPACE_CONTACTS] = TRUE;
dna.m_rgbNsUsed[DAVNAMESPACE_DAV] = TRUE;
// write out the contacts header
if (FAILED(hr = stream.Write(c_szContactHead, lstrlen(c_szContactHead), NULL)))
goto exit;
if (FAILED(hr = dna.WriteNamespaces(&stream)))
goto exit;
if (FAILED(hr = stream.Write(c_szXMLCloseElement, lstrlen(c_szXMLCloseElement), NULL)))
goto exit;
// [PaulHi] 3/11/99 Implementing WAB/HM group contact syncing
// Include the xml group tag if this is a group contact item
if (pciInfo->tyContact == HTTPMAIL_CT_GROUP)
{
if (FAILED(hr = stream.Write(c_szCRLFTab, lstrlen(c_szCRLFTab), NULL)))
goto exit;
if (FAILED(hr = stream.Write(c_szGroupSwitch, lstrlen(c_szGroupSwitch), NULL)))
goto exit;
}
for (dwIndex = 0; dwIndex < dwSize; dwIndex ++)
{
if (prgsz[dwIndex] && g_rgContactEle[dwIndex] != HMELE_UNKNOWN)
{
pszPropName = rgHTTPMailDictionary[g_rgContactEle[dwIndex]].pszName;
if (FAILED(hr = stream.Write(c_szOpenContactNamespace, lstrlen(c_szOpenContactNamespace), NULL)))
goto exit;
if (FAILED(hr = stream.Write(pszPropName, lstrlen(pszPropName), NULL)))
goto exit;
if (FAILED(hr = stream.Write(c_szXMLCloseElement, lstrlen(c_szXMLCloseElement), NULL)))
goto exit;
pszEsc = _EscapeString(prgsz[dwIndex]);
if (!pszEsc)
goto exit;
hr = stream.Write(pszEsc, lstrlen(pszEsc), NULL);
SafeMemFree(pszEsc);
if (FAILED(hr))
goto exit;
if (FAILED(hr = stream.Write(c_szCloseContactNamespace, lstrlen(c_szCloseContactNamespace), NULL)))
goto exit;
if (FAILED(hr = stream.Write(pszPropName, lstrlen(pszPropName), NULL)))
goto exit;
if (FAILED(hr = stream.Write(c_szXMLCloseElement, lstrlen(c_szXMLCloseElement), NULL)))
goto exit;
}
}
if (FAILED(hr = stream.Write(c_szContactTail, lstrlen(c_szContactTail), NULL)))
goto exit;
FAIL_EXIT(hr = stream.HrAcquireStringA(pdwLen, (LPSTR *)ppvXML, ACQ_DISPLACE));
exit:
return hr;
}
HRESULT HrCreatePatchContactRequest(LPHTTPCONTACTINFO pciInfo, IPropPatchRequest **ppRequest)
{
HRESULT hr = S_OK;
LPSTR *prgsz = (LPSTR*)pciInfo, pszEsc;
DWORD dwIndex, dwSize = ARRAYSIZE(g_rgContactEle);
CPropPatchRequest *pRequest = NULL;
*ppRequest = NULL;
pRequest = new CPropPatchRequest();
if (NULL == pRequest)
{
hr = E_OUTOFMEMORY;
goto exit;
}
// always specify windows-1252 encoding for this release
pRequest->SpecifyWindows1252Encoding(TRUE);
for (dwIndex = 0; dwIndex < dwSize; dwIndex ++)
{
if (g_rgContactEle[dwIndex] != HMELE_UNKNOWN)
{
if (prgsz[dwIndex])
{
// values with content are added. Empty strings are deleted. Null values are ignored.
if (*(prgsz[dwIndex]))
{
pszEsc = _EscapeString(prgsz[dwIndex]);
if (!pszEsc)
goto exit;
hr = pRequest->SetProperty(DAVNAMESPACE_CONTACTS, const_cast<char *>(rgHTTPMailDictionary[g_rgContactEle[dwIndex]].pszName), pszEsc);
SafeMemFree(pszEsc);
if (FAILED(hr))
goto exit;
}
else
{
if (FAILED(hr = pRequest->RemoveProperty(DAVNAMESPACE_CONTACTS, const_cast<char *>(rgHTTPMailDictionary[g_rgContactEle[dwIndex]].pszName))))
goto exit;
}
}
}
}
exit:
if (FAILED(hr))
SafeRelease(pRequest);
else
*ppRequest = pRequest;
return hr;
}
HRESULT HrGenerateSimpleBatchXML(
LPCSTR pszRootName,
LPHTTPTARGETLIST pTargets,
LPVOID *ppvXML,
DWORD *pdwLen)
{
HRESULT hr = S_OK;
CByteStream stream;
DWORD dwIndex;
DWORD dwHrefHeadLen, dwHrefTailLen;
IxpAssert(NULL != pszRootName);
IxpAssert(NULL != pTargets);
IxpAssert(pTargets->cTarget >= 1);
IxpAssert(NULL != pTargets->prgTarget);
IxpAssert(NULL != ppvXML);
IxpAssert(NULL != pdwLen);
dwHrefHeadLen = lstrlen(c_szHrefHead);
dwHrefTailLen = lstrlen(c_szHrefTail);
// write the DAV header
FAIL_EXIT_STREAM_WRITE(stream, c_szXMLHead);
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchHead1);
FAIL_EXIT_STREAM_WRITE(stream, pszRootName);
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchHead2);
FAIL_EXIT_STREAM_WRITE(stream, c_szTargetHead);
// write out the targets
for (dwIndex = 0; dwIndex < pTargets->cTarget; dwIndex++)
{
if (FAILED(hr = stream.Write(c_szHrefHead, dwHrefHeadLen, NULL)))
goto exit;
FAIL_EXIT_STREAM_WRITE(stream, pTargets->prgTarget[dwIndex]);
if (FAILED(hr = stream.Write(c_szHrefTail, dwHrefTailLen, NULL)))
goto exit;
}
FAIL_EXIT_STREAM_WRITE(stream, c_szTargetTail);
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchTail);
FAIL_EXIT_STREAM_WRITE(stream, pszRootName);
FAIL_EXIT_STREAM_WRITE(stream, c_szXMLCloseElement);
// take ownership of the bytestream
FAIL_EXIT(hr = stream.HrAcquireStringA(pdwLen, (LPSTR *)ppvXML, ACQ_DISPLACE));
exit:
return hr;
}
HRESULT HrGenerateMultiDestBatchXML(
LPCSTR pszRootName,
LPHTTPTARGETLIST pTargets,
LPHTTPTARGETLIST pDestinations,
LPVOID *ppvXML,
DWORD *pdwLen)
{
HRESULT hr = S_OK;
CByteStream stream;
DWORD dwIndex;
IxpAssert(NULL != pszRootName);
IxpAssert(NULL != pTargets);
IxpAssert(NULL != pDestinations);
IxpAssert(NULL != ppvXML);
IxpAssert(NULL != pdwLen);
// source and destination must have same count
if (pTargets->cTarget != pDestinations->cTarget)
return E_INVALIDARG;
*ppvXML = NULL;
*pdwLen = 0;
// write the DAV header
FAIL_EXIT_STREAM_WRITE(stream, c_szXMLHead);
// write the command header
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchHead1);
FAIL_EXIT_STREAM_WRITE(stream, pszRootName);
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchHead2);
// write out the targets
for (dwIndex = 0; dwIndex < pTargets->cTarget; dwIndex++)
{
IxpAssert(NULL != pTargets->prgTarget[dwIndex]);
if (NULL != pTargets->prgTarget[dwIndex])
{
FAIL_EXIT_STREAM_WRITE(stream, c_szTargetHead);
FAIL_EXIT_STREAM_WRITE(stream, c_szHrefHead);
FAIL_EXIT_STREAM_WRITE(stream, pTargets->prgTarget[dwIndex]);
FAIL_EXIT_STREAM_WRITE(stream, c_szHrefTail);
if (NULL != pDestinations->prgTarget[dwIndex])
{
FAIL_EXIT_STREAM_WRITE(stream, c_szDestHead);
FAIL_EXIT_STREAM_WRITE(stream, pDestinations->prgTarget[dwIndex]);
FAIL_EXIT_STREAM_WRITE(stream, c_szDestTail);
}
FAIL_EXIT_STREAM_WRITE(stream, c_szTargetTail);
}
}
FAIL_EXIT_STREAM_WRITE(stream, c_szBatchTail);
FAIL_EXIT_STREAM_WRITE(stream, pszRootName);
FAIL_EXIT_STREAM_WRITE(stream, c_szXMLCloseElement);
// take ownership of the byte stream
hr = stream.HrAcquireStringA(pdwLen, (LPSTR *)ppvXML, ACQ_DISPLACE);
exit:
return hr;
}
HRESULT HrCopyStringList(LPCSTR *rgszInList, LPCSTR **prgszOutList)
{
DWORD cStrings = 0;
HRESULT hr = S_OK;
LPCSTR pszCur;
DWORD i = 0;
IxpAssert(NULL != rgszInList);
IxpAssert(NULL != prgszOutList);
*prgszOutList = NULL;
// count the strings in the list
while (NULL != rgszInList[i++])
++cStrings;
// allocate the new list
if (!MemAlloc((void **)prgszOutList, (cStrings + 1) * sizeof(LPCSTR)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
// copy the strings over. if an allocation fails,
// stay in the loop and null out all of the slots
// that haven't been filled
for (i = 0; i <= cStrings; i++)
{
if (SUCCEEDED(hr) && NULL != rgszInList[i])
{
(*prgszOutList)[i] = PszDupA(rgszInList[i]);
if (NULL == (*prgszOutList)[i])
hr = E_OUTOFMEMORY;
}
else
(*prgszOutList)[i] = NULL;
}
if (FAILED(hr))
{
FreeStringList(*prgszOutList);
*prgszOutList = NULL;
}
exit:
return hr;
}
void FreeStringList(LPCSTR *rgszList)
{
DWORD i = 0;
IxpAssert(NULL != rgszList);
if (rgszList)
{
while (NULL != rgszList[i])
MemFree((void *)rgszList[i++]);
MemFree(rgszList);
}
}
// --------------------------------------------------------------------------------
// class CHTTPMailTransport
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CHTTPMailTransport
// --------------------------------------------------------------------------------
CHTTPMailTransport::CHTTPMailTransport(void) :
m_cRef(1),
m_fHasServer(FALSE),
m_fHasRootProps(FALSE),
m_fTerminating(FALSE),
m_status(IXP_DISCONNECTED),
m_hInternet(NULL),
m_hConnection(NULL),
m_pszUserAgent(NULL),
m_pLogFile(NULL),
m_pCallback(NULL),
m_pParser(NULL),
m_hwnd(NULL),
m_hevPendingCommand(NULL),
m_opPendingHead(NULL),
m_opPendingTail(NULL),
m_pszCurrentHost(NULL),
m_nCurrentPort(INTERNET_INVALID_PORT_NUMBER)
{
DWORD dwTempID;
HANDLE hThread = NULL;
InitializeCriticalSection(&m_cs);
ZeroMemory(&m_rServer, sizeof(INETSERVER));
ZeroMemory(&m_op, sizeof(HTTPMAILOPERATION));
ZeroMemory(&m_rootProps, sizeof(ROOTPROPS));
m_op.rResponse.command = HTTPMAIL_NONE;
m_hevPendingCommand = CreateEvent(NULL, TRUE, FALSE, NULL);
// Create the IO thread
hThread = CreateThread(NULL, 0, IOThreadFuncProxy, (LPVOID)this, 0, &dwTempID);
// We do not need to manipulate the IO Thread through its handle, so close it
// This will NOT terminate the thread
if (NULL != hThread)
{
CloseHandle(hThread);
}
DllAddRef();
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::~CHTTPMailTransport
// --------------------------------------------------------------------------------
CHTTPMailTransport::~CHTTPMailTransport(void)
{
IxpAssert(0 == m_cRef);
// Shouldn't be pending commands
IxpAssert(HTTPMAIL_NONE == m_op.rResponse.command);
IxpAssert(!m_opPendingHead);
IxpAssert(!m_opPendingTail);
IxpAssert(m_fTerminating);
// Destroy the critical sections
DeleteCriticalSection(&m_cs);
// Close the window
if ((NULL != m_hwnd) && (FALSE != IsWindow(m_hwnd)))
::SendMessage(m_hwnd, WM_CLOSE, 0, 0);
SafeMemFree(m_pszUserAgent);
CloseHandle(m_hevPendingCommand);
SafeMemFree(m_rootProps.pszAdbar);
SafeMemFree(m_rootProps.pszContacts);
SafeMemFree(m_rootProps.pszInbox);
SafeMemFree(m_rootProps.pszOutbox);
SafeMemFree(m_rootProps.pszSendMsg);
SafeMemFree(m_rootProps.pszSentItems);
SafeMemFree(m_rootProps.pszDeletedItems);
SafeMemFree(m_rootProps.pszDrafts);
SafeMemFree(m_rootProps.pszMsgFolderRoot);
SafeMemFree(m_rootProps.pszSig);
SafeMemFree(m_pszCurrentHost);
SafeRelease(m_pLogFile);
SafeRelease(m_pCallback);
SafeRelease(m_pParser);
SafeInternetCloseHandle(m_hInternet);
// BUGBUG: clean up window, thread and event, release buffers, etc
DllRelease();
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::HrConnectToHost
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::HrConnectToHost(
LPSTR pszHostName,
INTERNET_PORT nPort,
LPSTR pszUserName,
LPSTR pszPassword)
{
IxpAssert(m_hInternet);
// if a connection exists, determine if it is to the same host/port
// that the caller is specifying.
if (NULL != m_hConnection)
{
// if we are already connected to the correct host, return immediately
if (m_nCurrentPort == nPort && m_pszCurrentHost && (lstrcmp(pszHostName, m_pszCurrentHost) == 0))
return S_OK;
// if we are connected to the wrong server, close the existing connection
SafeInternetCloseHandle(m_hConnection);
SafeMemFree(m_pszCurrentHost);
m_nCurrentPort = INTERNET_INVALID_PORT_NUMBER;
}
// establish a connection to the specified server
m_hConnection = InternetConnect(
m_hInternet,
pszHostName,
nPort,
NULL, // user name
NULL, // password
INTERNET_SERVICE_HTTP, // service
0, // flags
reinterpret_cast<DWORD_PTR>(this)); // context
// what can cause this?
if (NULL == m_hConnection)
return E_OUTOFMEMORY;
// save the host name. don't bother checking for failure...we just won't reuse
// the connection next time through.
m_pszCurrentHost = PszDupA(pszHostName);
m_nCurrentPort = nPort;
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::DoLogonPrompt
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::DoLogonPrompt(void)
{
HRESULT hr = S_OK;
IHTTPMailCallback *pCallback = NULL;
EnterCriticalSection(&m_cs);
if (m_pCallback)
{
pCallback = m_pCallback;
pCallback->AddRef();
}
else
hr = E_FAIL;
LeaveCriticalSection(&m_cs);
if (pCallback)
{
hr = pCallback->OnLogonPrompt(&m_rServer, this);
pCallback->Release();
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::DoGetParentWindow
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::DoGetParentWindow(HWND *phwndParent)
{
HRESULT hr = S_OK;
IHTTPMailCallback *pCallback = NULL;
EnterCriticalSection(&m_cs);
if (m_pCallback)
{
pCallback = m_pCallback;
pCallback->AddRef();
}
else
hr = E_FAIL;
LeaveCriticalSection(&m_cs);
if (pCallback)
{
hr = pCallback->GetParentWindow(phwndParent);
pCallback->Release();
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CreateWnd
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::CreateWnd()
{
WNDCLASS wc;
IxpAssert(!m_hwnd);
if (m_hwnd)
return TRUE;
if (!GetClassInfo(g_hLocRes, s_szHTTPMailWndClass, &wc))
{
wc.style = 0;
wc.lpfnWndProc = CHTTPMailTransport::WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = g_hLocRes;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = s_szHTTPMailWndClass;
RegisterClass(&wc);
}
m_hwnd = CreateWindowEx(0,
s_szHTTPMailWndClass,
s_szHTTPMailWndClass,
WS_POPUP,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
g_hLocRes,
(LPVOID)this);
return (NULL != m_hwnd);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::DequeueNextOperation
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::DequeueNextOperation(void)
{
if (NULL == m_opPendingHead)
return FALSE;
IxpAssert(HTTPMAIL_NONE == m_op.rResponse.command);
IxpAssert(HTTPMAIL_NONE != m_opPendingHead->command);
m_op.rResponse.command = m_opPendingHead->command;
m_op.pfnState = m_opPendingHead->pfnState;
m_op.cState = m_opPendingHead->cState;
m_op.pszUrl = m_opPendingHead->pszUrl;
m_op.pszDestination = m_opPendingHead->pszDestination;
m_op.pszContentType = m_opPendingHead->pszContentType;
m_op.pvData = m_opPendingHead->pvData;
m_op.cbDataLen = m_opPendingHead->cbDataLen;
m_op.dwContext = m_opPendingHead->dwContext;
m_op.dwDepth = m_opPendingHead->dwDepth;
m_op.dwRHFlags = m_opPendingHead->dwRHFlags;
m_op.dwMIFlags = m_opPendingHead->dwMIFlags;
m_op.tyProp = m_opPendingHead->tyProp;
m_op.fBatch = m_opPendingHead->fBatch;
m_op.rgszAcceptTypes = m_opPendingHead->rgszAcceptTypes;
m_op.pPropFindRequest = m_opPendingHead->pPropFindRequest;
m_op.pPropPatchRequest = m_opPendingHead->pPropPatchRequest;
m_op.pParseFuncs = m_opPendingHead->pParseFuncs;
m_op.pHeaderStream = m_opPendingHead->pHeaderStream;
m_op.pBodyStream = m_opPendingHead->pBodyStream;
m_op.pszFolderTimeStamp = m_opPendingHead->pszFolderTimeStamp;
m_op.pszRootTimeStamp = m_opPendingHead->pszRootTimeStamp;
//m_op.pszFolderName = m_opPendingHead->pszFolderName;
LPHTTPQUEUEDOP pDelete = m_opPendingHead;
m_opPendingHead = m_opPendingHead->pNext;
if (NULL == m_opPendingHead)
m_opPendingTail = NULL;
MemFree(pDelete);
return TRUE;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FlushQueue
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FlushQueue(void)
{
// destroy any commands that are pending.
// REVIEW: these commands need to notify their callers
LPHTTPQUEUEDOP pOp = m_opPendingHead;
LPHTTPQUEUEDOP pNext;
while (pOp)
{
pNext = pOp->pNext;
SafeMemFree(pOp->pszUrl);
SafeMemFree(pOp->pszDestination);
if (pOp->pszContentType)
MemFree((void *)pOp->pszContentType);
SafeMemFree(pOp->pvData);
if (pOp->rgszAcceptTypes)
FreeStringList(pOp->rgszAcceptTypes);
SafeRelease(pOp->pPropFindRequest);
SafeRelease(pOp->pPropPatchRequest);
MemFree(pOp);
pOp = pNext;
}
m_opPendingHead = m_opPendingTail = NULL;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::TerminateIOThread
// --------------------------------------------------------------------------------
void CHTTPMailTransport::TerminateIOThread(void)
{
EnterCriticalSection(&m_cs);
// acquire a reference to the transport that will be owned
// by the io thread. the reference will be release when the
// io thread exits. this reference is not acquired when the
// thread is created, because it would prevent the transport
// from going away.
AddRef();
m_fTerminating = TRUE;
FlushQueue();
// signal the io thread to wake it.
SetEvent(m_hevPendingCommand);
LeaveCriticalSection(&m_cs);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::IOThreadFunc
// --------------------------------------------------------------------------------
DWORD CALLBACK CHTTPMailTransport::IOThreadFuncProxy(PVOID pv)
{
CHTTPMailTransport *pHTTPMail = (CHTTPMailTransport*)pv;
DWORD dwResult = S_OK;
IxpAssert(pHTTPMail);
// Initialize COM
if(S_OK == (dwResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)))
{
dwResult = pHTTPMail->IOThreadFunc();
//Bug #101165 -- MSXML needs notification to clean up per thread data.
CoUninitialize();
}
return dwResult;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::IOThreadFunc
// Called by IOThreadProxy to transition into an object method
// --------------------------------------------------------------------------------
DWORD CHTTPMailTransport::IOThreadFunc()
{
LPSTR pszVerb = NULL;
BOOL bQueueEmpty = FALSE;
// block until a command is pending.
while (WAIT_OBJECT_0 == WaitForSingleObject(m_hevPendingCommand, INFINITE))
{
if (IsTerminating())
break;
// Reset the event
ResetEvent(m_hevPendingCommand);
// unhook commands from the queue one at a time, and process them until
// the queue is empty
while (TRUE)
{
// dequeue the next operation
EnterCriticalSection(&m_cs);
IxpAssert(HTTPMAIL_NONE == m_op.rResponse.command);
bQueueEmpty = !DequeueNextOperation();
// if no commands left, break out of the loop and block
LeaveCriticalSection(&m_cs);
if (bQueueEmpty)
break;
DoOperation();
}
if (IsTerminating())
break;
}
IxpAssert(IsTerminating());
// TerminateIOThread acquired a reference that gets released here
Release();
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::WndProc
// --------------------------------------------------------------------------------
LRESULT CALLBACK CHTTPMailTransport::WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
CHTTPMailTransport *pThis = (CHTTPMailTransport*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
LRESULT lr = 0;
switch (msg)
{
case WM_NCCREATE:
IxpAssert(!pThis);
pThis = (CHTTPMailTransport*)((LPCREATESTRUCT)lParam)->lpCreateParams;
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LPARAM)pThis);
lr = DefWindowProc(hwnd, msg, wParam, lParam);
break;
case SPM_HTTPMAIL_SENDRESPONSE:
IxpAssert(pThis);
pThis->InvokeResponseCallback();
break;
case SPM_HTTPMAIL_LOGONPROMPT:
IxpAssert(pThis);
lr = pThis->DoLogonPrompt();
break;
case SPM_HTTPMAIL_GETPARENTWINDOW:
IxpAssert(pThis);
lr = pThis->DoGetParentWindow((HWND *)wParam);
break;
default:
lr = DefWindowProc(hwnd, msg, wParam, lParam);
break;
}
return lr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::Reset
// --------------------------------------------------------------------------------
void CHTTPMailTransport::Reset(void)
{
// REVIEW: this is incomplete. Should we be aborting the current command?
EnterCriticalSection(&m_cs);
SafeRelease(m_pLogFile);
SafeInternetCloseHandle(m_hConnection);
SafeInternetCloseHandle(m_hInternet);
SafeMemFree(m_pszUserAgent);
SafeRelease(m_pCallback);
m_status = IXP_DISCONNECTED;
m_fHasServer = FALSE;
ZeroMemory(&m_rServer, sizeof(INETSERVER));
LeaveCriticalSection(&m_cs);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::QueryInterface
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::QueryInterface(REFIID riid, LPVOID *ppv)
{
// Locals
HRESULT hr = S_OK;
// Validate params
if (NULL == ppv)
{
hr = TrapError(E_INVALIDARG);
goto exit;
}
// Initialize params
*ppv = NULL;
// IID_IUnknown
if (IID_IUnknown == riid)
*ppv = ((IUnknown *)(IHTTPMailTransport *)this);
// IID_IInternetTransport
else if (IID_IInternetTransport == riid)
*ppv = (IInternetTransport *)this;
// IID_IHTTPMailTransport
else if (IID_IHTTPMailTransport == riid)
*ppv = (IHTTPMailTransport *)this;
// IID_IXMLNodeFactory
else if (IID_IXMLNodeFactory == riid)
*ppv = (IXMLNodeFactory *)this;
else if (IID_IHTTPMailTransport2 == riid)
*ppv = (IHTTPMailTransport2 *)this;
// if not NULL, acquire a reference and return
if (NULL != *ppv)
{
((LPUNKNOWN)*ppv)->AddRef();
goto exit;
}
hr = TrapError(E_NOINTERFACE);
exit:
// Done
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AddRef
// --------------------------------------------------------------------------------
STDMETHODIMP_(ULONG) CHTTPMailTransport::AddRef(void)
{
return ++m_cRef;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::Release
// --------------------------------------------------------------------------------
STDMETHODIMP_(ULONG) CHTTPMailTransport::Release(void)
{
if (0 != --m_cRef)
return m_cRef;
// our refcount dropped to zero, and we aren't terminating,
// begin terminating
if (!IsTerminating())
{
TerminateIOThread();
return 1;
}
// if we were terminating, and our refCount dropped to zero,
// then the iothread has been unwound and we can safely exit.
delete this;
return 0;
}
// ----------------------------------------------------------------------------
// IInternetTransport methods
// ----------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// CHTTPMailTransport::Connect
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::Connect(LPINETSERVER pInetServer,
boolean fAuthenticate,
boolean fCommandLogging)
{
HRESULT hr = S_OK;
if (NULL == pInetServer || FIsEmptyA(pInetServer->szServerName))
return TrapError(E_INVALIDARG);
// Thread safety
EnterCriticalSection(&m_cs);
// not init
if (NULL == m_hInternet || NULL == m_pCallback)
{
hr = TrapError(IXP_E_NOT_INIT);
goto exit;
}
FAIL_CREATEWND;
// busy
if (IXP_DISCONNECTED != m_status || m_fHasServer)
{
hr = TrapError(IXP_E_ALREADY_CONNECTED);
goto exit;
}
// copy the server struct
CopyMemory(&m_rServer, pInetServer, sizeof(INETSERVER));
m_fHasServer = TRUE;
m_fHasRootProps = FALSE;
exit:
// ThreadSafety
LeaveCriticalSection(&m_cs);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::DropConnection
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::DropConnection(void)
{
// this function is called to stop any current and pending i/o
// Locals
HRESULT hr = S_OK;
BOOL fSendResponse;
EnterCriticalSection(&m_cs);
// flush any pending i/o from the queue
FlushQueue();
// if a command is being processed, mark it aborted and
// send a response if necessary. stay in the critical
// section to prevent the io thread from sending any
// notifications at the same time.
if (m_op.rResponse.command != HTTPMAIL_NONE)
{
m_op.fAborted = TRUE;
m_op.rResponse.fDone = TRUE;
}
Disconnect();
LeaveCriticalSection(&m_cs);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::Disconnect
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::Disconnect(void)
{
// Locals
HRESULT hr = S_OK;
// Thread safety
EnterCriticalSection(&m_cs);
if (NULL == m_hConnection)
{
hr = TrapError(IXP_E_NOT_INIT);
goto exit;
}
// Disconnecting
if (m_pCallback)
m_pCallback->OnStatus(IXP_DISCONNECTING, this);
SafeInternetCloseHandle(m_hConnection);
m_status = IXP_DISCONNECTED;
ZeroMemory(&m_rServer, sizeof(INETSERVER));
if (m_pCallback)
m_pCallback->OnStatus(IXP_DISCONNECTED, this);
// Close the window
if ((NULL != m_hwnd) && (FALSE != IsWindow(m_hwnd)))
::SendMessage(m_hwnd, WM_CLOSE, 0, 0);
m_hwnd = NULL;
m_fHasServer = FALSE;
exit:
// Thread safety
LeaveCriticalSection(&m_cs);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::IsState
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::IsState(IXPISSTATE isstate)
{
// Locals
HRESULT hr = S_OK;
// Thread safety
EnterCriticalSection(&m_cs);
switch(isstate)
{
// are we connected?
case IXP_IS_CONNECTED:
hr = (NULL == m_hConnection) ? S_FALSE : S_OK;
break;
// are we busy?
case IXP_IS_BUSY:
hr = (HTTPMAIL_NONE != m_op.rResponse.command) ? S_OK : S_FALSE;
break;
// are we ready
case IXP_IS_READY:
hr = (HTTPMAIL_NONE == m_op.rResponse.command) ? S_OK : S_FALSE;
break;
case IXP_IS_AUTHENTICATED:
// REVIEW
hr = S_OK;
break;
default:
IxpAssert(FALSE);
break;
}
// Thread safety
LeaveCriticalSection(&m_cs);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GetServerInfo
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::GetServerInfo(LPINETSERVER pInetServer)
{
// check params
if (NULL == pInetServer)
return TrapError(E_INVALIDARG);
// Thread safety
EnterCriticalSection(&m_cs);
// Copy server info
CopyMemory(pInetServer, &m_rServer, sizeof(INETSERVER));
// Thread safety
LeaveCriticalSection(&m_cs);
// Done
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GetIXPType
// --------------------------------------------------------------------------------
STDMETHODIMP_(IXPTYPE) CHTTPMailTransport::GetIXPType(void)
{
return IXP_HTTPMail;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InetServerFromAccount
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::InetServerFromAccount(IImnAccount *pAccount, LPINETSERVER pInetServer)
{
HRESULT hr = S_OK;
DWORD fAlwaysPromptPassword = FALSE;
// check params
if (NULL == pAccount || NULL == pInetServer)
return TrapError(E_INVALIDARG);
// ZeroInit
ZeroMemory(pInetServer, sizeof(INETSERVER));
// Get the account name
if (FAILED(hr = pAccount->GetPropSz(AP_ACCOUNT_NAME, pInetServer->szAccount, ARRAYSIZE(pInetServer->szAccount))))
{
hr = TrapError(IXP_E_INVALID_ACCOUNT);
goto exit;
}
// Get the RAS connectoid
if (FAILED(pAccount->GetPropSz(AP_RAS_CONNECTOID, pInetServer->szConnectoid, ARRAYSIZE(pInetServer->szConnectoid))))
*pInetServer->szConnectoid = '\0';
// Connection Type
Assert(sizeof(pInetServer->rasconntype) == sizeof(DWORD));
if (FAILED(pAccount->GetPropDw(AP_RAS_CONNECTION_TYPE, (DWORD *)&pInetServer->rasconntype)))
pInetServer->rasconntype = RAS_CONNECT_LAN;
// Get Server Name
hr = pAccount->GetPropSz(AP_HTTPMAIL_SERVER, pInetServer->szServerName, sizeof(pInetServer->szServerName));
if (FAILED(hr))
{
hr = TrapError(IXP_E_INVALID_ACCOUNT);
goto exit;
}
// Password
if (FAILED(pAccount->GetPropDw(AP_HTTPMAIL_PROMPT_PASSWORD, &fAlwaysPromptPassword)) || FALSE == fAlwaysPromptPassword)
pAccount->GetPropSz(AP_HTTPMAIL_PASSWORD, pInetServer->szPassword, sizeof(pInetServer->szPassword));
if (fAlwaysPromptPassword)
pInetServer->dwFlags |= ISF_ALWAYSPROMPTFORPASSWORD;
// Sicily
Assert(sizeof(pInetServer->fTrySicily) == sizeof(DWORD));
pAccount->GetPropDw(AP_HTTPMAIL_USE_SICILY, (DWORD *)&pInetServer->fTrySicily);
// User Name
pAccount->GetPropSz(AP_HTTPMAIL_USERNAME, pInetServer->szUserName, sizeof(pInetServer->szUserName));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::HandsOffCallback
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::HandsOffCallback(void)
{
// Locals
HRESULT hr = S_OK;
// Thread safety
EnterCriticalSection(&m_cs);
// No current callback
if (NULL == m_pCallback)
{
hr = TrapError(S_FALSE);
goto exit;
}
// Release it
SafeRelease(m_pCallback);
exit:
// Thread safety
LeaveCriticalSection(&m_cs);
// Done
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GetStatus
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::GetStatus(IXPSTATUS *pCurrentStatus)
{
if (NULL == pCurrentStatus)
return TrapError(E_INVALIDARG);
*pCurrentStatus = m_status;
return S_OK;
}
// ----------------------------------------------------------------------------
// IHTTPMailTransport methods
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// CHTTPMailTransport::GetProperty
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::GetProperty(
HTTPMAILPROPTYPE type,
LPSTR *ppszProp)
{
HRESULT hr = S_OK;
if (type <= HTTPMAIL_PROP_INVALID || type >= HTTPMAIL_PROP_LAST)
return E_INVALIDARG;
if (ppszProp)
*ppszProp = NULL;
if (!m_fHasRootProps || NULL == ppszProp)
{
IF_FAILEXIT(hr = QueueGetPropOperation(type));
}
switch (type)
{
case HTTPMAIL_PROP_ADBAR:
*ppszProp = PszDupA(m_rootProps.pszAdbar);
break;
case HTTPMAIL_PROP_CONTACTS:
*ppszProp = PszDupA(m_rootProps.pszContacts);
break;
case HTTPMAIL_PROP_INBOX:
*ppszProp = PszDupA(m_rootProps.pszInbox);
break;
case HTTPMAIL_PROP_OUTBOX:
*ppszProp = PszDupA(m_rootProps.pszOutbox);
break;
case HTTPMAIL_PROP_SENDMSG:
*ppszProp = PszDupA(m_rootProps.pszSendMsg);
break;
case HTTPMAIL_PROP_SENTITEMS:
*ppszProp = PszDupA(m_rootProps.pszSentItems);
break;
case HTTPMAIL_PROP_DELETEDITEMS:
*ppszProp = PszDupA(m_rootProps.pszDeletedItems);
break;
case HTTPMAIL_PROP_DRAFTS:
*ppszProp = PszDupA(m_rootProps.pszDrafts);
break;
case HTTPMAIL_PROP_MSGFOLDERROOT:
*ppszProp = PszDupA(m_rootProps.pszMsgFolderRoot);
break;
case HTTPMAIL_PROP_SIG:
*ppszProp = PszDupA(m_rootProps.pszSig);
break;
default:
hr = TrapError(E_INVALIDARG);
break;
}
if (SUCCEEDED(hr) && !*ppszProp)
hr = IXP_E_HTTP_ROOT_PROP_NOT_FOUND;
exit:
return hr;
}
HRESULT CHTTPMailTransport::QueueGetPropOperation(HTTPMAILPROPTYPE type)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp;
if (!m_fHasServer || NULL == m_rServer.szServerName)
{
hr = E_FAIL;
goto exit;
}
FAIL_CREATEWND;
// queue the getprop operation
if (FAILED(hr = AllocQueuedOperation(m_rServer.szServerName, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_GETPROP;
pOp->tyProp = type;
pOp->pfnState = c_rgpfnRootProps;
pOp->cState = ARRAYSIZE(c_rgpfnRootProps);
pOp->pParseFuncs = c_rgpfnRootPropsParse;
pOp->dwRHFlags = (RH_XMLCONTENTTYPE | RH_BRIEF);
QueueOperation(pOp);
hr = E_PENDING;
exit:
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::GetPropertyDw
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::GetPropertyDw(
HTTPMAILPROPTYPE type,
LPDWORD lpdwProp)
{
HRESULT hr = S_OK;
if (type <= HTTPMAIL_PROP_INVALID || type >= HTTPMAIL_PROP_LAST)
IF_FAILEXIT(hr = E_INVALIDARG);
if (lpdwProp)
*lpdwProp = 0;
if (!m_fHasRootProps || NULL == lpdwProp)
{
IF_FAILEXIT(hr = QueueGetPropOperation(type));
}
switch (type)
{
case HTTPMAIL_PROP_MAXPOLLINGINTERVAL:
*lpdwProp = m_rootProps.dwMaxPollingInterval;
break;
default:
hr = TrapError(E_INVALIDARG);
break;
}
exit:
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandGET
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandGET(LPCSTR pszUrl,
LPCSTR *rgszAcceptTypes,
BOOL fTranslate,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPCSTR *rgszAcceptTypesCopy = NULL;
if (NULL == pszUrl)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (NULL != rgszAcceptTypes)
{
hr = HrCopyStringList(rgszAcceptTypes, &rgszAcceptTypesCopy);
if (FAILED(hr))
goto exit;
}
if (FAILED(hr = AllocQueuedOperation(pszUrl, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_GET;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfGet;
pOp->cState = ARRAYSIZE(c_rgpfGet);
pOp->rgszAcceptTypes = rgszAcceptTypesCopy;
if (!fTranslate)
pOp->dwRHFlags = RH_TRANSLATEFALSE;
rgszAcceptTypesCopy = NULL;
QueueOperation(pOp);
exit:
if (NULL != rgszAcceptTypesCopy)
FreeStringList(rgszAcceptTypesCopy);
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandPUT
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandPUT(
LPCSTR pszPath,
LPVOID lpvData,
ULONG cbSize,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPCSTR pszLocalContentType = NULL;
LPVOID lpvCopy = NULL;
if (NULL == pszPath || NULL == lpvData || 0 == cbSize)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (!MemAlloc(&lpvCopy, cbSize))
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
CopyMemory(lpvCopy, lpvData, cbSize);
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_PUT;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnPut;
pOp->cState = ARRAYSIZE(c_rgpfnPut);
pOp->pvData = lpvCopy;
lpvCopy = NULL;
pOp->cbDataLen = cbSize;
QueueOperation(pOp);
exit:
SafeMemFree(lpvCopy);
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandPOST
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandPOST(
LPCSTR pszPath,
IStream *pStream,
LPCSTR pszContentType,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPCSTR pszLocalContentType = NULL;
if (NULL == pszPath || NULL == pStream)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (pszContentType)
{
pszLocalContentType = PszDupA(pszContentType);
if (NULL == pszLocalContentType)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
}
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_POST;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnPost;
pOp->cState = ARRAYSIZE(c_rgpfnPost);
pOp->pBodyStream = pStream;
pOp->pBodyStream->AddRef();
pOp->pszContentType = pszLocalContentType;
pszLocalContentType = NULL;
QueueOperation(pOp);
exit:
if (pszLocalContentType)
MemFree((void *)pszLocalContentType);
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandDELETE
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandDELETE(
LPCSTR pszPath,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_DELETE;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfDelete;
pOp->cState = ARRAYSIZE(c_rgpfDelete);
QueueOperation(pOp);
exit:
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandBDELETE
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandBDELETE(
LPCSTR pszPath,
LPHTTPTARGETLIST pBatchTargets,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPVOID pvXML = NULL;
DWORD dwXMLLen = 0;
if (NULL == pszPath || NULL == pBatchTargets)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = HrGenerateSimpleBatchXML(c_szDelete, pBatchTargets, &pvXML, &dwXMLLen)))
goto exit;
if (FAILED(hr = AllocQueuedOperation(pszPath, pvXML, dwXMLLen, &pOp, TRUE)))
goto exit;
pvXML = NULL;
pOp->command = HTTPMAIL_BDELETE;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfDelete;
pOp->cState = ARRAYSIZE(c_rgpfDelete);
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
QueueOperation(pOp);
exit:
SafeMemFree(pvXML);
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::CommandPROPFIND
// ----------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandPROPFIND(
LPCSTR pszPath,
IPropFindRequest *pRequest,
DWORD dwDepth,
DWORD dwContext)
{
if (NULL == pszPath || NULL == pRequest)
return TrapError(E_INVALIDARG);
return E_NOTIMPL;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandPROPPATCH
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandPROPPATCH(
LPCSTR pszUrl,
IPropPatchRequest *pRequest,
DWORD dwContext)
{
if (NULL == pszUrl || NULL == pRequest)
return TrapError(E_INVALIDARG);
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszUrl, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_PROPPATCH;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnPropPatch;
pOp->cState = ARRAYSIZE(c_rgpfnPropPatch);
pOp->pPropPatchRequest = pRequest;
pRequest->AddRef();
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandMKCOL
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::CommandMKCOL(LPCSTR pszUrl, DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszUrl)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszUrl, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_MKCOL;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnMkCol;
pOp->cState = ARRAYSIZE(c_rgpfnMkCol);
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandCOPY
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandCOPY(
LPCSTR pszPath,
LPCSTR pszDestination,
BOOL fAllowRename,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp;
LPSTR pszDupDestination = NULL;
if (NULL == pszPath || NULL == pszDestination)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
pszDupDestination = PszDupA(pszDestination);
if (NULL == pszDupDestination)
return TrapError(E_OUTOFMEMORY);
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_COPY;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnCopy;
pOp->cState = ARRAYSIZE(c_rgpfnCopy);
pOp->pszDestination = pszDupDestination;
pszDupDestination = NULL;
if (fAllowRename)
pOp->dwRHFlags = RH_ALLOWRENAME;
QueueOperation(pOp);
exit:
SafeMemFree(pszDupDestination);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandBCOPY
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandBCOPY(
LPCSTR pszSourceCollection,
LPHTTPTARGETLIST pTargets,
LPCSTR pszDestCollection,
LPHTTPTARGETLIST pDestinations,
BOOL fAllowRename,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPVOID pvXML = NULL;
DWORD dwXMLLen = 0;
LPSTR pszDupDestination = NULL;
if (NULL == pszSourceCollection || NULL == pTargets || NULL == pszDestCollection)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
pszDupDestination = PszDupA(pszDestCollection);
if (NULL == pszDupDestination)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (NULL == pDestinations)
hr = HrGenerateSimpleBatchXML(c_szCopy, pTargets, &pvXML, &dwXMLLen);
else
hr = HrGenerateMultiDestBatchXML(c_szCopy, pTargets, pDestinations, &pvXML, &dwXMLLen);
if (FAILED(hr))
goto exit;
if (FAILED(hr = AllocQueuedOperation(pszSourceCollection, pvXML, dwXMLLen, &pOp, TRUE)))
goto exit;
pvXML = NULL;
pOp->command = HTTPMAIL_BCOPY;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnBMove;
pOp->cState = ARRAYSIZE(c_rgpfnBMove);
pOp->pParseFuncs = c_rgpfnBCopyMoveParse;
pOp->pszDestination = pszDupDestination;
pszDupDestination = NULL;
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
if (fAllowRename)
pOp->dwRHFlags |= RH_ALLOWRENAME;
QueueOperation(pOp);
exit:
SafeMemFree(pvXML);
SafeMemFree(pszDupDestination);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandMOVE
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandMOVE(
LPCSTR pszPath,
LPCSTR pszDestination,
BOOL fAllowRename,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp;
LPSTR pszDupDestination = NULL;
if (NULL == pszPath || NULL == pszDestination)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
pszDupDestination = PszDupA(pszDestination);
if (NULL == pszDupDestination)
return TrapError(E_OUTOFMEMORY);
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_MOVE;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnMove;
pOp->cState = ARRAYSIZE(c_rgpfnMove);
pOp->pszDestination = pszDupDestination;
pszDupDestination = NULL;
if (fAllowRename)
pOp->dwRHFlags = RH_ALLOWRENAME;
QueueOperation(pOp);
exit:
SafeMemFree(pszDupDestination);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandBMOVE
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CommandBMOVE(
LPCSTR pszSourceCollection,
LPHTTPTARGETLIST pTargets,
LPCSTR pszDestCollection,
LPHTTPTARGETLIST pDestinations,
BOOL fAllowRename,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPVOID pvXML = NULL;
DWORD dwXMLLen = 0;
LPSTR pszDupDestination = NULL;
if (NULL == pszSourceCollection || NULL == pTargets || NULL == pszDestCollection)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
pszDupDestination = PszDupA(pszDestCollection);
if (NULL == pszDupDestination)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (NULL == pDestinations)
hr = HrGenerateSimpleBatchXML(c_szMove, pTargets, &pvXML, &dwXMLLen);
else
hr = HrGenerateMultiDestBatchXML(c_szMove, pTargets, pDestinations, &pvXML, &dwXMLLen);
if (FAILED(hr))
goto exit;
if (FAILED(hr = AllocQueuedOperation(pszSourceCollection, pvXML, dwXMLLen, &pOp, TRUE)))
goto exit;
pvXML = NULL;
pOp->command = HTTPMAIL_BMOVE;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnBMove;
pOp->cState = ARRAYSIZE(c_rgpfnBMove);
pOp->pParseFuncs = c_rgpfnBCopyMoveParse;
pOp->pszDestination = pszDupDestination;
pszDupDestination = NULL;
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
if (fAllowRename)
pOp->dwRHFlags |= RH_ALLOWRENAME;
QueueOperation(pOp);
exit:
SafeMemFree(pvXML);
SafeMemFree(pszDupDestination);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MemberInfo
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::MemberInfo(
LPCSTR pszPath,
MEMBERINFOFLAGS flags,
DWORD dwDepth,
BOOL fIncludeRoot,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_MEMBERINFO;
pOp->dwMIFlags = flags;
pOp->dwDepth = dwDepth;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnMemberInfo;
pOp->cState = ARRAYSIZE(c_rgpfnMemberInfo);
pOp->pParseFuncs = c_rgpfnMemberInfoParse;
pOp->dwRHFlags = (RH_BRIEF | RH_XMLCONTENTTYPE);
if (!fIncludeRoot)
pOp->dwRHFlags |= RH_NOROOT;
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FindFolders
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::FindFolders(LPCSTR pszPath, DWORD dwContext)
{
return E_NOTIMPL;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MarkRead
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::MarkRead(
LPCSTR pszPath,
LPHTTPTARGETLIST pTargets,
BOOL fMarkRead,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
CPropPatchRequest *pRequest = NULL;
LPSTR pszXML = NULL;
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
pRequest = new CPropPatchRequest();
if (NULL == pRequest)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (fMarkRead)
FAIL_EXIT(hr = pRequest->SetProperty(DAVNAMESPACE_HTTPMAIL, "read", "1"));
else
FAIL_EXIT(hr = pRequest->SetProperty(DAVNAMESPACE_HTTPMAIL, "read", "0"));
FAIL_EXIT(hr = pRequest->GenerateXML(pTargets, &pszXML));
FAIL_EXIT(hr = AllocQueuedOperation(pszPath, pszXML, lstrlen(pszXML), &pOp, TRUE));
pszXML = NULL;
pOp->command = HTTPMAIL_MARKREAD;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnMarkRead;
pOp->cState = ARRAYSIZE(c_rgpfnMarkRead);
pOp->pParseFuncs = c_rgpfnMemberErrorParse;
pOp->dwRHFlags = (RH_BRIEF | RH_XMLCONTENTTYPE);
if (pTargets && pTargets->cTarget > 0)
pOp->fBatch = TRUE;
QueueOperation(pOp);
exit:
SafeRelease(pRequest);
SafeMemFree(pszXML);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::SendMessage
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::SendMessage(LPCSTR pszPath,
LPCSTR pszFrom,
LPHTTPTARGETLIST pTargets,
BOOL fSaveInSent,
IStream *pMessageStream,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
IStream *pRfc821Stream = NULL;
if (NULL == pszPath ||
NULL == pszFrom ||
NULL == pTargets || pTargets->cTarget < 1 ||
NULL == pMessageStream)
return E_INVALIDARG;
FAIL_CREATEWND;
// build the rfc821 stream that will precede the mime message
FAIL_EXIT(hr = _HrGenerateRfc821Stream(pszFrom, pTargets, &pRfc821Stream));
FAIL_EXIT(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp));
pOp->command = HTTPMAIL_SENDMESSAGE;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnSendMessage;
pOp->cState = ARRAYSIZE(c_rgpfnSendMessage);
pOp->pHeaderStream = pRfc821Stream;
pRfc821Stream = NULL;
pOp->pBodyStream = pMessageStream;
if (NULL != pOp->pBodyStream)
pOp->pBodyStream->AddRef();
pOp->dwRHFlags = (RH_TRANSLATETRUE | RH_SMTPMESSAGECONTENTTYPE);
pOp->dwRHFlags |= (fSaveInSent ? RH_SAVEINSENTTRUE : RH_SAVEINSENTFALSE);
QueueOperation(pOp);
exit:
SafeRelease(pRfc821Stream);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ListContacts
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ListContacts(LPCSTR pszPath, DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_LISTCONTACTS;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnListContacts;
pOp->cState = ARRAYSIZE(c_rgpfnListContacts);
pOp->pParseFuncs = c_rgpfnListContactsParse;
pOp->dwDepth = 1;
pOp->dwRHFlags = (RH_NOROOT | RH_XMLCONTENTTYPE);
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ListContactInfos
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ListContactInfos(LPCSTR pszCollectionPath, DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszCollectionPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszCollectionPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_CONTACTINFO;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnContactInfo;
pOp->cState = ARRAYSIZE(c_rgpfnContactInfo);
pOp->pParseFuncs = c_rgpfnContactInfoParse;
pOp->dwDepth = 1;
pOp->dwRHFlags = (RH_NOROOT | RH_XMLCONTENTTYPE);
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ContactInfo
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ContactInfo(LPCSTR pszPath, DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_CONTACTINFO;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnContactInfo;
pOp->cState = ARRAYSIZE(c_rgpfnContactInfo);
pOp->pParseFuncs = c_rgpfnContactInfoParse;
pOp->dwDepth = 0;
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PostContact
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PostContact(LPCSTR pszPath,
LPHTTPCONTACTINFO pciInfo,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
LPVOID pvXML = NULL;
DWORD cb;
if (NULL == pciInfo)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = HrGeneratePostContactXML(pciInfo, &pvXML, &cb)))
goto exit;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->pvData = pvXML;
pOp->cbDataLen = cb;
pvXML = NULL;
pOp->command = HTTPMAIL_POSTCONTACT;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnPostContact;
pOp->cState = ARRAYSIZE(c_rgpfnPostContact);
pOp->dwDepth = 0;
pOp->dwRHFlags = (RH_XMLCONTENTTYPE | RH_TRANSLATEFALSE);
QueueOperation(pOp);
exit:
SafeMemFree(pvXML);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PatchContact
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PatchContact(LPCSTR pszPath,
LPHTTPCONTACTINFO pciInfo,
DWORD dwContext)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
IPropPatchRequest *pRequest = NULL;
if (NULL == pciInfo)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
if (FAILED(hr = HrCreatePatchContactRequest(pciInfo, &pRequest)))
goto exit;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_PATCHCONTACT;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnPatchContact;
pOp->cState = ARRAYSIZE(c_rgpfnPatchContact);
pOp->pPropPatchRequest = pRequest;
pRequest = NULL;
pOp->dwRHFlags = RH_XMLCONTENTTYPE;
QueueOperation(pOp);
exit:
SafeRelease(pRequest);
return hr;
}
// --------------------------------------------------------------------------------
// INodeFactory Methods
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// CHTTPMailTransport::NotifyEvent
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::NotifyEvent(IXMLNodeSource* pSource,
XML_NODEFACTORY_EVENT iEvt)
{
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::BeginChildren
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::BeginChildren(IXMLNodeSource* pSource, XML_NODE_INFO *pNodeInfo)
{
if (m_op.dwStackDepth <= ELE_STACK_CAPACITY)
m_op.rgEleStack[m_op.dwStackDepth - 1].fBeganChildren = TRUE;
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::EndChildren
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::EndChildren(
IXMLNodeSource* pSource,
BOOL fEmpty,
XML_NODE_INFO *pNodeInfo)
{
HRESULT hr = S_OK;
IxpAssert(HTTPMAIL_NONE != m_op.rResponse.command);
IxpAssert(NULL != m_op.pParseFuncs);
if (HTTPMAIL_NONE == m_op.rResponse.command || NULL == m_op.pParseFuncs)
{
hr = E_FAIL;
goto exit;
}
if (XML_ELEMENT == pNodeInfo->dwType)
hr = (this->*(m_op.pParseFuncs->pfnEndChildren))();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::Error
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::Error(IXMLNodeSource* pSource,
HRESULT hrErrorCode,
USHORT cNumRecs,
XML_NODE_INFO** apNodeInfo)
{
BSTR bstr = NULL;
if (NULL == m_op.rResponse.rIxpResult.pszResponse)
{
if (FAILED(pSource->GetErrorInfo(&bstr)))
goto exit;
HrBSTRToLPSZ(CP_ACP, bstr, &m_op.rResponse.rIxpResult.pszResponse);
}
exit:
if (NULL != bstr)
SysFreeString(bstr);
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CreateNode
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::CreateNode(
IXMLNodeSource* pSource,
PVOID pNodeParent,
USHORT cNumRecs,
XML_NODE_INFO** apNodeInfo)
{
HRESULT hr = S_OK;
LPPCDATABUFFER pTextBuffer = NULL;
CXMLNamespace *pBaseNamespace = m_op.pTopNamespace;
XML_NODE_INFO *pNodeInfo;
IxpAssert(HTTPMAIL_NONE != m_op.rResponse.command);
IxpAssert(NULL != m_op.pParseFuncs);
if (HTTPMAIL_NONE == m_op.rResponse.command || NULL == m_op.pParseFuncs)
{
hr = E_FAIL;
goto exit;
}
if (NULL == apNodeInfo || 0 == cNumRecs)
{
hr = E_INVALIDARG;
goto exit;
}
pNodeInfo = apNodeInfo[0];
switch (pNodeInfo->dwType)
{
case XML_ELEMENT:
if (cNumRecs > 1 && FAILED(hr = PushNamespaces(apNodeInfo, cNumRecs)))
goto exit;
hr = (this->*(m_op.pParseFuncs->pfnCreateElement))(pBaseNamespace, pNodeInfo->pwcText, pNodeInfo->ulLen, pNodeInfo->ulNsPrefixLen, pNodeInfo->fTerminal);
break;
case XML_PCDATA:
// we only parse element content...we don't care about attributes
if (InValidElementChildren())
{
// get the buffer
pTextBuffer = m_op.rgEleStack[m_op.dwStackDepth - 1].pTextBuffer;
// request one if we don't already have one
if (NULL == pTextBuffer)
{
if (FAILED(hr = _GetTextBuffer(&pTextBuffer)))
goto exit;
m_op.rgEleStack[m_op.dwStackDepth - 1].pTextBuffer = pTextBuffer;
}
hr = _AppendTextToBuffer(pTextBuffer, pNodeInfo->pwcText, pNodeInfo->ulLen);
goto exit;
}
break;
default:
break;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_HrThunkConnectionError
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_HrThunkConnectionError(void)
{
return _HrThunkConnectionError(m_op.dwHttpStatus);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_HrThunkConnectionError
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_HrThunkConnectionError(DWORD dwStatus)
{
IxpAssert(NULL == m_op.rResponse.rIxpResult.pszResponse);
IxpAssert(NULL == m_op.rResponse.rIxpResult.pszProblem);
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
m_op.rResponse.rIxpResult.hrResult = HttpErrorToIxpResult(dwStatus);
_GetRequestHeader(&m_op.rResponse.rIxpResult.pszResponse, HTTP_QUERY_STATUS_TEXT);
m_op.rResponse.rIxpResult.dwSocketError = GetLastError();
return _HrThunkResponse(TRUE);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_HrThunkResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_HrThunkResponse(BOOL fDone)
{
HRESULT hr = S_OK;
BOOL fSendResponse;
// Thread safety
EnterCriticalSection(&m_cs);
IxpAssert(HTTPMAIL_NONE != m_op.rResponse.command);
if (m_op.rResponse.fDone)
{
fSendResponse = FALSE;
}
else
{
fSendResponse = TRUE;
if (!fDone && WasAborted())
{
m_op.rResponse.rIxpResult.hrResult = IXP_E_USER_CANCEL;
m_op.rResponse.fDone = TRUE;
}
else
m_op.rResponse.fDone = fDone;
}
LeaveCriticalSection(&m_cs);
if (fSendResponse)
hr = (HRESULT) ::SendMessage(m_hwnd, SPM_HTTPMAIL_SENDRESPONSE, 0, NULL);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InvokeResponseCallback
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InvokeResponseCallback(void)
{
HRESULT hr = S_OK;
IHTTPMailCallback *pCallback = NULL;
EnterCriticalSection(&m_cs);
if (m_pCallback)
{
pCallback = m_pCallback;
pCallback->AddRef();
}
LeaveCriticalSection(&m_cs);
if (pCallback)
{
hr = pCallback->OnResponse(&m_op.rResponse);
pCallback->Release();
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitNew
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::InitNew(
LPCSTR pszUserAgent,
LPCSTR pszLogFilePath,
IHTTPMailCallback *pCallback)
{
HRESULT hr = S_OK;
if (NULL == pszUserAgent || NULL == pCallback)
return TrapError(E_INVALIDARG);
IxpAssert(NULL == m_hInternet);
// Thread Safety
EnterCriticalSection(&m_cs);
if (IXP_DISCONNECTED != m_status)
{
hr = TrapError(IXP_E_ALREADY_CONNECTED);
goto exit;
}
Reset();
m_pszUserAgent = PszDupA(pszUserAgent);
if (NULL == m_pszUserAgent)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
// open log file
if (pszLogFilePath)
CreateLogFile(g_hInst, pszLogFilePath, "HTTPMAIL", DONT_TRUNCATE, &m_pLogFile,
FILE_SHARE_READ | FILE_SHARE_WRITE);
m_pCallback = pCallback;
m_pCallback->AddRef();
m_hInternet = InternetOpen(m_pszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (NULL == m_hInternet)
{
hr = TrapError(IXP_E_SOCKET_INIT_ERROR);
goto exit;
}
// Install the callback ptr for the internet handle and all of its derived handles
//InternetSetStatusCallbackA(m_hInternet, StatusCallbackProxy);
exit:
LeaveCriticalSection(&m_cs);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::OnStatusCallback
// --------------------------------------------------------------------------------
void CHTTPMailTransport::OnStatusCallback(
HINTERNET hInternet,
DWORD dwInternetStatus,
LPVOID pvStatusInformation,
DWORD dwStatusInformationLength)
{
#if 0
// Locals
IXPSTATUS ixps;
EnterCriticalSection(&m_cs);
// if the status message is one of the defined IXPSTATUS messages,
// notify the callback.
if ((NULL != m_pCallback) && TranslateWinInetMsg(dwInternetStatus, &ixps))
m_pCallback->OnStatus(ixps, (IHTTPMailTransport *)this);
// for now, we just handle the request_complete message
if (INTERNET_STATUS_REQUEST_COMPLETE == dwInternetStatus)
HrCommandCompleted();
LeaveCriticalSection(&m_cs);
#endif
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::AllocQueuedOperation
// ----------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AllocQueuedOperation(
LPCSTR pszUrl,
LPVOID pvData,
ULONG cbDataLen,
LPHTTPQUEUEDOP *ppOp,
BOOL fAdoptData)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pTempOp = NULL;
if (!MemAlloc((void **)&pTempOp , sizeof(HTTPQUEUEDOP)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
ZeroMemory(pTempOp, sizeof(HTTPQUEUEDOP));
if (NULL != pszUrl)
{
pTempOp->pszUrl = PszDupA(pszUrl);
if (NULL == pTempOp->pszUrl)
{
hr = E_OUTOFMEMORY;
goto exit;
}
}
// can't have a length if data ptr is null
IxpAssert(!pvData || cbDataLen);
if (pvData)
{
if (!fAdoptData)
{
if (!MemAlloc((LPVOID*)&pTempOp->pvData, cbDataLen + 1))
{
hr = E_OUTOFMEMORY;
goto exit;
}
CopyMemory(pTempOp->pvData, pvData, cbDataLen);
((char *)pTempOp->pvData)[cbDataLen] = '\0';
}
else
pTempOp->pvData = pvData;
pTempOp->cbDataLen = cbDataLen;
}
*ppOp = pTempOp;
pTempOp = NULL;
exit:
if (pTempOp)
{
SafeMemFree(pTempOp->pszUrl);
if (!fAdoptData)
SafeMemFree(pTempOp->pvData);
MemFree(pTempOp);
}
return hr;
}
// ----------------------------------------------------------------------------
// CHTTPMailTransport::QueueOperation
// ----------------------------------------------------------------------------
void CHTTPMailTransport::QueueOperation(LPHTTPQUEUEDOP pOp)
{
// Thread safety
EnterCriticalSection(&m_cs);
if (m_opPendingTail)
m_opPendingTail->pNext = pOp;
else
{
// if there is no tail, there shouldn't be a head
IxpAssert(!m_opPendingHead);
m_opPendingHead = m_opPendingTail = pOp;
}
// signal the io thread
SetEvent(m_hevPendingCommand);
// Thread Safety
LeaveCriticalSection(&m_cs);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StatusCallbackProxy
// --------------------------------------------------------------------------------
void CHTTPMailTransport::StatusCallbackProxy(
HINTERNET hInternet,
DWORD dwContext,
DWORD dwInternetStatus,
LPVOID pvStatusInformation,
DWORD dwStatusInformationLength)
{
// Locals
CHTTPMailTransport *pHTTPMail = reinterpret_cast<CHTTPMailTransport *>(IntToPtr(dwContext));
IxpAssert(NULL != pHTTPMail);
if (NULL != pHTTPMail)
pHTTPMail->OnStatusCallback(hInternet, dwInternetStatus, pvStatusInformation, dwStatusInformationLength);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::DoOperation
// --------------------------------------------------------------------------------
void CHTTPMailTransport::DoOperation(void)
{
HRESULT hr = S_OK;
while (m_op.iState < m_op.cState)
{
hr = (this->*(m_op.pfnState[m_op.iState]))();
if (FAILED(hr))
break;
m_op.iState++;
}
if (!m_op.rResponse.fDone && FAILED(hr))
{
m_op.rResponse.rIxpResult.hrResult = hr;
_HrThunkResponse(TRUE);
}
FreeOperation();
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeOperation
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeOperation(void)
{
// Thread Safety
EnterCriticalSection(&m_cs);
SafeMemFree(m_op.pszUrl);
SafeMemFree(m_op.pszDestination);
if (m_op.pszContentType)
{
MemFree((void *)m_op.pszContentType);
m_op.pszContentType = NULL;
}
SafeMemFree(m_op.pvData);
SafeInternetCloseHandle(m_op.hRequest);
SafeRelease(m_op.pPropFindRequest);
SafeRelease(m_op.pPropPatchRequest);
if (NULL != m_op.rgszAcceptTypes)
FreeStringList(m_op.rgszAcceptTypes);
SafeRelease(m_op.pHeaderStream);
SafeRelease(m_op.pBodyStream);
if (m_op.pTextBuffer)
_FreeTextBuffer(m_op.pTextBuffer);
// Free the response
SafeMemFree(m_op.rResponse.rIxpResult.pszResponse);
SafeMemFree(m_op.rResponse.rIxpResult.pszProblem);
PopNamespaces(NULL);
// in the case of an error, the element stack can
// contain text buffers that need to be freed
for (DWORD i = 0; i < m_op.dwStackDepth; ++i)
{
if (NULL != m_op.rgEleStack[i].pTextBuffer)
_FreeTextBuffer(m_op.rgEleStack[i].pTextBuffer);
}
SafeMemFree(m_op.rResponse.rIxpResult.pszResponse);
switch (m_op.rResponse.command)
{
case HTTPMAIL_GET:
SafeMemFree(m_op.rResponse.rGetInfo.pvBody);
SafeMemFree(m_op.rResponse.rGetInfo.pszContentType);
break;
case HTTPMAIL_POST:
case HTTPMAIL_SENDMESSAGE:
SafeMemFree(m_op.rResponse.rPostInfo.pszLocation);
break;
case HTTPMAIL_COPY:
case HTTPMAIL_MOVE:
case HTTPMAIL_MKCOL:
SafeMemFree(m_op.rResponse.rCopyMoveInfo.pszLocation);
break;
case HTTPMAIL_BCOPY:
case HTTPMAIL_BMOVE:
SafeMemFree(m_op.rResponse.rBCopyMoveList.prgBCopyMove);
break;
case HTTPMAIL_MEMBERINFO:
FreeMemberInfoList();
SafeMemFree(m_op.rResponse.rMemberInfoList.prgMemberInfo);
SafeMemFree(m_op.pszRootTimeStamp);
SafeMemFree(m_op.pszFolderTimeStamp);
SafeMemFree(m_op.rResponse.rMemberInfoList.pszRootTimeStamp);
SafeMemFree(m_op.rResponse.rMemberInfoList.pszFolderTimeStamp);
break;
case HTTPMAIL_MARKREAD:
FreeMemberErrorList();
SafeMemFree(m_op.rResponse.rMemberErrorList.prgMemberError);
break;
case HTTPMAIL_LISTCONTACTS:
FreeContactIdList();
SafeMemFree(m_op.rResponse.rContactIdList.prgContactId);
break;
case HTTPMAIL_CONTACTINFO:
FreeContactInfoList();
SafeMemFree(m_op.rResponse.rContactInfoList.prgContactInfo);
break;
case HTTPMAIL_POSTCONTACT:
XP_FREE_STRUCT(HTTPCONTACTID, &m_op.rResponse.rPostContactInfo, NULL);
break;
case HTTPMAIL_PATCHCONTACT:
XP_FREE_STRUCT(HTTPCONTACTID, &m_op.rResponse.rPatchContactInfo, NULL);
break;
default:
break;
}
ZeroMemory(&m_op, sizeof(HTTPMAILOPERATION));
m_op.rResponse.command = HTTPMAIL_NONE;
// Thread Safety
LeaveCriticalSection(&m_cs);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_BindToStruct
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_BindToStruct(const WCHAR *pwcText,
ULONG ulLen,
const XPCOLUMN *prgCols,
DWORD cCols,
LPVOID pTarget,
BOOL *pfWasBound)
{
HRESULT hr = S_OK;
DWORD dwColIndex;
DWORD dwColFlags;
LPSTR *ppsz;
DWORD *pdw;
BOOL *pb;
HTTPMAILSPECIALFOLDER *ptySpecial;
HTTPMAILCONTACTTYPE *ptyContact;
HMELE ele;
HRESULT *phr;
if (pfWasBound)
*pfWasBound = FALSE;
// if the stack is overflowed, we definitely won't do anything with the text
if (m_op.dwStackDepth >= ELE_STACK_CAPACITY)
goto exit;
ele = m_op.rgEleStack[m_op.dwStackDepth - 1].ele;
for (dwColIndex = 0; dwColIndex < cCols; dwColIndex++)
{
if (ele == prgCols[dwColIndex].ele)
break;
}
if (dwColIndex >= cCols)
goto exit;
dwColFlags = prgCols[dwColIndex].dwFlags;
// the column may require validation of the element stack
if (!!(dwColFlags & XPCF_MSVALIDPROP))
{
if (!VALIDSTACK(c_rgPropFindPropValueStack))
goto exit;
}
else if (!!(dwColFlags & XPCF_MSVALIDMSRESPONSECHILD))
{
if (!VALIDSTACK(c_rgMultiStatusResponseChildStack))
goto exit;
}
if (dwColIndex < cCols)
{
switch (prgCols[dwColIndex].cdt)
{
case XPCDT_STRA:
ppsz = (LPSTR *)(((char *)pTarget) + prgCols[dwColIndex].offset);
SafeMemFree(*ppsz);
hr = AllocStrFromStrNW(pwcText, ulLen, ppsz);
break;
case XPCDT_DWORD:
pdw = (DWORD *)(((char *)pTarget) + prgCols[dwColIndex].offset);
*pdw = 0;
hr = StrNToDwordW(pwcText, ulLen, pdw);
break;
case XPCDT_BOOL:
pb = (BOOL *)(((char *)pTarget) + prgCols[dwColIndex].offset);
*pb = FALSE;
hr = StrNToBoolW(pwcText, ulLen, pb);
break;
case XPCDT_IXPHRESULT:
phr = (HRESULT *)(((char *)pTarget) + prgCols[dwColIndex].offset);
*phr = S_OK;
hr = StatusStrNToIxpHr(pwcText, ulLen, phr);
break;
case XPCDT_HTTPSPECIALFOLDER:
ptySpecial = (HTTPMAILSPECIALFOLDER *)(((char *)pTarget) + prgCols[dwColIndex].offset);
*ptySpecial = HTTPMAIL_SF_NONE;
hr = StrNToSpecialFolderW(pwcText, ulLen, ptySpecial);
break;
case XPCDT_HTTPCONTACTTYPE:
ptyContact = (HTTPMAILCONTACTTYPE *)(((char *)pTarget) + prgCols[dwColIndex].offset);
*ptyContact = HTTPMAIL_CT_CONTACT;
hr = StrNToContactTypeW(pwcText, ulLen, ptyContact);
break;
default:
IxpAssert(FALSE);
break;
}
if (FAILED(hr))
goto exit;
// set the bit in the flag word to indicate that this field
// has been set.
if (!(dwColFlags & XPCF_DONTSETFLAG))
m_op.dwPropFlags |= (1 << dwColIndex);
if (pfWasBound)
*pfWasBound = TRUE;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_FreeStruct
// --------------------------------------------------------------------------------
void CHTTPMailTransport::_FreeStruct(const XPCOLUMN *prgCols,
DWORD cCols,
LPVOID pTarget,
DWORD *pdwFlags)
{
DWORD dwFlags;
DWORD dwIndex = 0;
LPSTR *ppsz;
DWORD *pdw;
BOOL *pb;
HTTPMAILSPECIALFOLDER *ptySpecial;
HTTPMAILCONTACTTYPE *ptyContact;
HRESULT *phr;
if (NULL != pdwFlags)
{
dwFlags = *pdwFlags;
*pdwFlags = NOFLAGS;
}
else
dwFlags = 0xFFFFFFFF;
while (0 != dwFlags && dwIndex < cCols)
{
// test the low bit
if (!!(dwFlags & 0x00000001))
{
switch (prgCols[dwIndex].cdt)
{
case XPCDT_STRA:
ppsz = (LPSTR *)(((char *)pTarget) + prgCols[dwIndex].offset);
SafeMemFree(*ppsz);
break;
case XPCDT_DWORD:
pdw = (DWORD *)(((char *)pTarget) + prgCols[dwIndex].offset);
*pdw = 0;
break;
case XPCDT_BOOL:
pb = (BOOL *)(((char *)pTarget) + prgCols[dwIndex].offset);
*pb = FALSE;
break;
case XPCDT_IXPHRESULT:
phr = (HRESULT *)(((char *)pTarget) + prgCols[dwIndex].offset);
*phr = S_OK;
break;
case XPCDT_HTTPSPECIALFOLDER:
ptySpecial = (HTTPMAILSPECIALFOLDER *)(((char *)pTarget) + prgCols[dwIndex].offset);
*ptySpecial = HTTPMAIL_SF_NONE;
break;
case XPCDT_HTTPCONTACTTYPE:
ptyContact = (HTTPMAILCONTACTTYPE *)(((char *)pTarget) + prgCols[dwIndex].offset);
*ptyContact = HTTPMAIL_CT_CONTACT;
break;
default:
IxpAssert(FALSE);
break;
}
}
dwFlags >>= 1;
dwIndex++;
}
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_AppendTextToBuffer
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_AppendTextToBuffer(LPPCDATABUFFER pTextBuffer,
const WCHAR *pwcText,
ULONG ulLen)
{
HRESULT hr = S_OK;
ULONG ulNewCapacity = pTextBuffer->ulLen + ulLen;
IxpAssert(ulLen > 0);
// grow the buffer if necessary, and append the text
if (pTextBuffer->ulCapacity < ulNewCapacity)
{
if (!MemRealloc((void **)&(pTextBuffer->pwcText), sizeof(WCHAR) * ulNewCapacity))
{
hr = E_OUTOFMEMORY;
goto exit;
}
pTextBuffer->ulCapacity = ulNewCapacity;
}
// copy the new text over. special case the one-byte case to avoid
// calls to CopyMemory when we see one character entities
if (1 == ulLen)
{
pTextBuffer->pwcText[pTextBuffer->ulLen++] = *pwcText;
}
else
{
CopyMemory(&pTextBuffer->pwcText[pTextBuffer->ulLen], pwcText, sizeof(WCHAR) * ulLen);
pTextBuffer->ulLen += ulLen;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_AllocTextBuffer
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_AllocTextBuffer(LPPCDATABUFFER *ppTextBuffer)
{
HRESULT hr = S_OK;
IxpAssert(NULL != ppTextBuffer);
*ppTextBuffer = NULL;
if (!MemAlloc((void **)ppTextBuffer, sizeof(PCDATABUFFER)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
// allocate the buffer
if (!MemAlloc((void **)(&((*ppTextBuffer)->pwcText)), PCDATA_BUFSIZE * sizeof(WCHAR)))
{
MemFree(*ppTextBuffer);
*ppTextBuffer = NULL;
hr = E_OUTOFMEMORY;
goto exit;
}
(*ppTextBuffer)->ulLen = 0;
(*ppTextBuffer)->ulCapacity = PCDATA_BUFSIZE ;
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeTextBuffer
// --------------------------------------------------------------------------------
void CHTTPMailTransport::_FreeTextBuffer(LPPCDATABUFFER pTextBuffer)
{
if (pTextBuffer)
{
if (pTextBuffer->pwcText)
MemFree(pTextBuffer->pwcText);
MemFree(pTextBuffer);
}
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeMemberInfoList
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeMemberInfoList(void)
{
DWORD cInfo = m_op.rResponse.rMemberInfoList.cMemberInfo;
LPHTTPMEMBERINFO rgInfo = m_op.rResponse.rMemberInfoList.prgMemberInfo;
// free the completed infos
for (DWORD i = 0; i < cInfo; i++)
XP_FREE_STRUCT(HTTPMEMBERINFO, &rgInfo[i], NULL);
// free the partial info
if (m_op.dwPropFlags)
{
IxpAssert(cInfo < MEMBERINFO_MAXRESPONSES);
XP_FREE_STRUCT(HTTPMEMBERINFO, &rgInfo[cInfo], &m_op.dwPropFlags);
}
m_op.rResponse.rMemberInfoList.cMemberInfo= 0;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeMemberErrorList
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeMemberErrorList(void)
{
DWORD cInfo = m_op.rResponse.rMemberErrorList.cMemberError;
LPHTTPMEMBERERROR rgInfo = m_op.rResponse.rMemberErrorList.prgMemberError;
// free the completed infos
for (DWORD i = 0; i < cInfo; i++)
XP_FREE_STRUCT(HTTPMEMBERERROR, &rgInfo[i], NULL);
// free the partial info
if (m_op.dwPropFlags)
{
IxpAssert(cInfo < MEMBERERROR_MAXRESPONSES);
XP_FREE_STRUCT(HTTPMEMBERERROR, &rgInfo[cInfo], &m_op.dwPropFlags);
}
m_op.rResponse.rMemberErrorList.cMemberError = 0;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeContactIdList
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeContactIdList(void)
{
DWORD cId = m_op.rResponse.rContactIdList.cContactId;
LPHTTPCONTACTID rgId = m_op.rResponse.rContactIdList.prgContactId;
// free the completed ids
for (DWORD i = 0; i < cId; ++i)
XP_FREE_STRUCT(HTTPCONTACTID, &rgId[i], NULL);
// free the partial id
if (m_op.dwPropFlags)
{
IxpAssert(cId < LISTCONTACTS_MAXRESPONSES);
XP_FREE_STRUCT(HTTPCONTACTID, &rgId[cId], &m_op.dwPropFlags);
m_op.dwPropFlags = NOFLAGS;
}
m_op.rResponse.rContactIdList.cContactId = 0;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeContactInfoList
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeContactInfoList(void)
{
DWORD cInfo = m_op.rResponse.rContactInfoList.cContactInfo;
LPHTTPCONTACTINFO rgInfo = m_op.rResponse.rContactInfoList.prgContactInfo;
// free the completed ids
for (DWORD i = 0; i < cInfo; ++i)
XP_FREE_STRUCT(HTTPCONTACTINFO, &rgInfo[i], NULL);
// free the partial info
if (m_op.dwPropFlags)
{
IxpAssert(cInfo < CONTACTINFO_MAXRESPONSES);
XP_FREE_STRUCT(HTTPCONTACTINFO, &rgInfo[cInfo], &m_op.dwPropFlags);
}
m_op.rResponse.rContactInfoList.cContactInfo = 0;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FreeBCopyMoveList
// --------------------------------------------------------------------------------
void CHTTPMailTransport::FreeBCopyMoveList(void)
{
DWORD cInfo = m_op.rResponse.rBCopyMoveList.cBCopyMove;
LPHTTPMAILBCOPYMOVE rgInfo = m_op.rResponse.rBCopyMoveList.prgBCopyMove;
// free the completed records
for (DWORD i = 0; i < cInfo; ++i)
XP_FREE_STRUCT(HTTPMAILBCOPYMOVE, &rgInfo[i], NULL);
// free the partial info
if (m_op.dwPropFlags)
{
IxpAssert(cInfo < BCOPYMOVE_MAXRESPONSES);
XP_FREE_STRUCT(HTTPMAILBCOPYMOVE, &rgInfo[cInfo], &m_op.dwPropFlags);
}
m_op.rResponse.rBCopyMoveList.cBCopyMove = 0;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ValidStack
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::ValidStack(const HMELE *prgEle, DWORD cEle)
{
BOOL bResult = TRUE;
DWORD dw;
if (cEle != m_op.dwStackDepth)
{
bResult = FALSE;
goto exit;
}
IxpAssert(cEle <= ELE_STACK_CAPACITY);
for (dw = 0; dw < cEle; ++dw)
{
if (prgEle[dw] != HMELE_UNKNOWN && prgEle[dw] != m_op.rgEleStack[dw].ele)
{
bResult = FALSE;
goto exit;
}
}
exit:
return bResult;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PopNamespaces
// --------------------------------------------------------------------------------
void CHTTPMailTransport::PopNamespaces(CXMLNamespace *pBaseNamespace)
{
CXMLNamespace *pTemp;
while (pBaseNamespace != m_op.pTopNamespace)
{
IxpAssert(m_op.pTopNamespace);
pTemp = m_op.pTopNamespace->GetParent();
m_op.pTopNamespace->Release();
m_op.pTopNamespace = pTemp;
}
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PushNamespaces
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PushNamespaces(XML_NODE_INFO** apNodeInfo, USHORT cNumRecs)
{
HRESULT hr = S_OK;
CXMLNamespace *pNamespace = NULL;
for (USHORT i = 0; i < cNumRecs; ++i)
{
if (apNodeInfo[i]->dwType == XML_ATTRIBUTE && apNodeInfo[i]->dwSubType == XML_NS)
{
// better have at least one more record
IxpAssert(i < (cNumRecs - 1));
if (i < (cNumRecs - 1) && apNodeInfo[i + 1]->dwType == XML_PCDATA)
{
pNamespace = new CXMLNamespace();
if (!pNamespace)
{
hr = E_OUTOFMEMORY;
goto exit;
}
if (apNodeInfo[i]->ulLen != apNodeInfo[i]->ulNsPrefixLen)
{
if (FAILED(hr = pNamespace->SetPrefix(
&apNodeInfo[i]->pwcText[apNodeInfo[i]->ulNsPrefixLen + 1],
apNodeInfo[i]->ulLen - (apNodeInfo[i]->ulNsPrefixLen + 1))))
goto exit;
}
if (FAILED(hr = pNamespace->SetNamespace(apNodeInfo[i + 1]->pwcText, apNodeInfo[i + 1]->ulLen)))
goto exit;
pNamespace->SetParent(m_op.pTopNamespace);
if (m_op.pTopNamespace)
m_op.pTopNamespace->Release();
m_op.pTopNamespace = pNamespace;
pNamespace = NULL;
}
}
}
exit:
SafeRelease(pNamespace);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AllocStrFromStrW
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AllocStrFromStrNW(
const WCHAR *pwcText,
ULONG ulLen,
LPSTR *ppszAlloc)
{
HRESULT hr = S_OK;
DWORD iBufferSize;
DWORD iConvertedChars;
IxpAssert(NULL != ppszAlloc);
if (NULL == ppszAlloc)
return E_INVALIDARG;
*ppszAlloc = NULL;
// if pwcText is NULL, the result is null, but not an error
if (NULL == pwcText)
goto exit;
iBufferSize = WideCharToMultiByte(CP_ACP, 0, pwcText, ulLen, NULL, 0, NULL, NULL);
if (0 == iBufferSize)
{
m_op.rResponse.rIxpResult.uiServerError = GetLastError();
hr = TrapError(E_FAIL);
goto exit;
}
// allocate the buffer (add 1 to the size to allow for eos)
if (!MemAlloc((void **)ppszAlloc, iBufferSize + 1))
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
// convert the string
iConvertedChars = WideCharToMultiByte(CP_ACP, 0, pwcText, ulLen, *ppszAlloc, iBufferSize, NULL, NULL);
if (0 == iConvertedChars)
{
m_op.rResponse.rIxpResult.uiServerError = GetLastError();
hr = TrapError(E_FAIL);
goto exit;
}
IxpAssert(iConvertedChars == iBufferSize);
// terminate the new string
(*ppszAlloc)[iConvertedChars] = 0;
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StrNToDwordW
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::StrNToDwordW(const WCHAR *pwcText, ULONG ulLen, DWORD *pdw)
{
HRESULT hr = S_OK;
int i;
WCHAR wcBuf[32];
WCHAR *pwcUseBuf;
BOOL fFreeBuf = FALSE;
IxpAssert(NULL != pdw);
if (NULL == pdw)
return E_INVALIDARG;
*pdw = 0;
if (NULL == pwcText)
goto exit;
// decide whether to use a local buffer or an allocated buffer
if (ulLen < 32)
pwcUseBuf = wcBuf;
else
{
if (!MemAlloc((void **)&pwcUseBuf, (ulLen + 1) * sizeof(WCHAR)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
fFreeBuf = TRUE;
}
// copy the string over
CopyMemory(pwcUseBuf, pwcText, ulLen * sizeof(WCHAR));
pwcUseBuf[ulLen] = 0;
*pdw = StrToIntW(pwcUseBuf);
exit:
if (fFreeBuf)
MemFree(pwcUseBuf);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StrNToSpecialFolderW
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::StrNToSpecialFolderW(const WCHAR *pwcText,
ULONG ulLen,
HTTPMAILSPECIALFOLDER *ptySpecial)
{
HRESULT hr = S_OK;
if (NULL == ptySpecial)
return E_INVALIDARG;
*ptySpecial = HTTPMAIL_SF_UNRECOGNIZED;
if (NULL != pwcText && ulLen > 0)
{
for (DWORD dw = 0; dw < ARRAYSIZE(c_rgpfnSpecialFolder); dw++)
{
if (ulLen == c_rgpfnSpecialFolder[dw].ulLen)
{
if (0 == StrCmpNW(c_rgpfnSpecialFolder[dw].pwcName, pwcText, ulLen))
{
*ptySpecial = c_rgpfnSpecialFolder[dw].tyFolder;
break;
}
}
}
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StrNToContactTypeW
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::StrNToContactTypeW(const WCHAR *pwcText,
ULONG ulLen,
HTTPMAILCONTACTTYPE *ptyContact)
{
HRESULT hr = S_OK;
BOOL fGroup = FALSE;
IxpAssert(NULL != ptyContact);
if (NULL == ptyContact)
return E_INVALIDARG;
// for now, we treat the presence of the <group> element as an indication that
// the contact is a group
*ptyContact = HTTPMAIL_CT_GROUP;
#if 0
// for now, we treat the value as an integer-based bool
hr = StrNToBoolW(pwcText, ulLen, &fGroup);
// default is contact
*ptyContact = fGroup ? HTTPMAIL_CT_GROUP : HTTPMAIL_CT_CONTACT;
#endif
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StrNToBoolW
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::StrNToBoolW(const WCHAR *pwcText, DWORD ulLen, BOOL *pb)
{
HRESULT hr = S_OK;
DWORD dw;
IxpAssert(NULL != pb);
if (NULL == pb)
return E_INVALIDARG;
*pb = FALSE;
if (NULL == pwcText)
goto exit;
if (FAILED(hr = StrNToDwordW(pwcText, ulLen, &dw)))
goto exit;
if (dw != 0)
*pb = TRUE;
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::StatusStrNToIxpHr
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::StatusStrNToIxpHr(const WCHAR *pwcText, DWORD ulLen, HRESULT *phr)
{
HRESULT hr = S_OK;
DWORD dw;
LPSTR pszStatus = NULL;
DWORD dwStatus = 0;
IxpAssert(NULL != phr);
if (NULL == phr)
return E_INVALIDARG;
*phr = S_OK;
if (NULL == pwcText)
goto exit;
if (FAILED(hr = AllocStrFromStrNW(pwcText, ulLen, &pszStatus)) || NULL == pszStatus)
goto exit;
HrParseHTTPStatus(pszStatus, &dwStatus);
if (dwStatus < 200 || dwStatus > 299)
*phr = HttpErrorToIxpResult(dwStatus);
exit:
SafeMemFree(pszStatus);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CommandToVerb
// --------------------------------------------------------------------------------
LPSTR CHTTPMailTransport::CommandToVerb(HTTPMAILCOMMAND command)
{
LPSTR pszVerb = NULL;
// convert the command to a string
switch (command)
{
case HTTPMAIL_GET:
pszVerb = "GET";
break;
case HTTPMAIL_POST:
case HTTPMAIL_SENDMESSAGE:
pszVerb = "POST";
break;
case HTTPMAIL_PUT:
pszVerb = "PUT";
break;
case HTTPMAIL_GETPROP:
case HTTPMAIL_PROPFIND:
case HTTPMAIL_MEMBERINFO:
case HTTPMAIL_LISTCONTACTS:
case HTTPMAIL_CONTACTINFO:
pszVerb = "PROPFIND";
break;
case HTTPMAIL_MARKREAD:
if (m_op.fBatch)
pszVerb = "BPROPPATCH";
else
pszVerb = "PROPPATCH";
break;
case HTTPMAIL_MKCOL:
pszVerb = "MKCOL";
break;
case HTTPMAIL_COPY:
pszVerb = "COPY";
break;
case HTTPMAIL_BCOPY:
pszVerb = "BCOPY";
break;
case HTTPMAIL_MOVE:
pszVerb = "MOVE";
break;
case HTTPMAIL_BMOVE:
pszVerb = "BMOVE";
break;
case HTTPMAIL_PROPPATCH:
pszVerb = "PROPPATCH";
break;
case HTTPMAIL_DELETE:
pszVerb = "DELETE";
break;
case HTTPMAIL_BDELETE:
pszVerb = "BDELETE";
break;
case HTTPMAIL_POSTCONTACT:
// first post the contact, then do a propfind
if (NULL == m_op.rResponse.rPostContactInfo.pszHref)
pszVerb = "POST";
else
pszVerb = "PROPFIND";
break;
case HTTPMAIL_PATCHCONTACT:
// first patch the contact, then do a propfind
if (NULL == m_op.rResponse.rPatchContactInfo.pszHref)
pszVerb = "PROPPATCH";
else
pszVerb = "PROPFIND";
break;
default:
pszVerb = "";
IxpAssert(FALSE);
break;
}
return pszVerb;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::UpdateLogonInfo
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::UpdateLogonInfo(void)
{
// send the message synchronously
return (HRESULT) (::SendMessage(m_hwnd, SPM_HTTPMAIL_LOGONPROMPT, NULL, NULL));
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GetParentWindow
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::GetParentWindow(HWND *phwndParent)
{
// send the message synchronously
return (HRESULT) (::SendMessage(m_hwnd, SPM_HTTPMAIL_GETPARENTWINDOW, (WPARAM)phwndParent, NULL));
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ReadBytes
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::ReadBytes(LPSTR pszBuffer, DWORD cbBufferSize, DWORD *pcbBytesRead)
{
return InternetReadFile(m_op.hRequest, pszBuffer, cbBufferSize, pcbBytesRead);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_GetStatusCode
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::_GetStatusCode(DWORD *pdw)
{
IxpAssert(NULL != pdw);
DWORD dwStatusSize = sizeof(DWORD);
*pdw = 0;
return HttpQueryInfo(m_op.hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, pdw, &dwStatusSize, NULL);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_GetContentLength
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::_GetContentLength(DWORD *pdw)
{
IxpAssert(NULL != pdw);
DWORD dwLengthSize = sizeof(DWORD);
*pdw = 0;
return HttpQueryInfo(m_op.hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_CONTENT_LENGTH, pdw, &dwLengthSize, NULL);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_GetRequestHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_GetRequestHeader(LPSTR *ppszHeader, DWORD dwHeader)
{
HRESULT hr = S_OK;
DWORD dwSize = MAX_PATH;
LPSTR pszHeader = NULL;
Assert(NULL != ppszHeader);
*ppszHeader = NULL;
retry:
pszHeader = (LPSTR)ZeroAllocate(dwSize);
if (!pszHeader)
{
hr = E_OUTOFMEMORY;
goto exit;
}
if (!HttpQueryInfo(m_op.hRequest, dwHeader, pszHeader, &dwSize, NULL))
{
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
goto exit;
SafeMemFree(pszHeader);
goto retry;
}
*ppszHeader = pszHeader;
pszHeader = NULL;
exit:
SafeMemFree(pszHeader);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_AddRequestHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_AddRequestHeader(LPCSTR pszHeader)
{
HRESULT hr = S_OK;
if (!HttpAddRequestHeaders(m_op.hRequest, pszHeader, lstrlen(pszHeader), HTTP_ADDREQ_FLAG_ADD))
hr = HrGetLastError();
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_AuthCurrentRequest
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::_AuthCurrentRequest(DWORD dwStatus, BOOL fRetryAuth)
{
BOOL fResult = FALSE;
HRESULT hr;
// unused code to let wininet do the ui
#if 0
if (HTTP_STATUS_PROXY_AUTH_REQ == dwStatus || HTTP_STATUS_DENIED == dwStatus)
{
if (!fRequestedParent)
{
GetParentWindow(&hwndParent);
fRequestedParent = TRUE;
}
hr = InternetErrorDlg(hwndParent, m_op.hRequest, hr,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL);
if (ERROR_INTERNET_FORCE_RETRY == hr)
goto resend;
}
#endif
// TODO: should probably let wininet handle proxy auth errors
#if 0
case HTTP_STATUS_PROXY_AUTH_REQ: //Proxy Authentication Required
InternetSetOption(m_op.hRequest, INTERNET_OPTION_PROXY_USERNAME,
GetUserName(), strlen(GetUserName())+1);
InternetSetOption(m_op.hRequest, INTERNET_OPTION_PROXY_PASSWORD,
GetPassword(), strlen(GetPassword())+1);
break;
#endif
if (HTTP_STATUS_DENIED == dwStatus) //Server Authentication Required
{
if (fRetryAuth || (SUCCEEDED(hr = UpdateLogonInfo()) && S_FALSE != hr))
{
InternetSetOption(m_op.hRequest, INTERNET_OPTION_USERNAME,
GetUserName(), strlen(GetUserName())+1);
InternetSetOption(m_op.hRequest, INTERNET_OPTION_PASSWORD,
GetPassword(), strlen(GetPassword())+1);
fResult = TRUE;
}
}
return fResult;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_LogRequest
// --------------------------------------------------------------------------------
void CHTTPMailTransport::_LogRequest(LPVOID pvData, DWORD cbData)
{
HRESULT hr = S_OK;
CByteStream bs;
LPSTR pszCommand = CommandToVerb(m_op.rResponse.command);
LPSTR pszLogData = NULL;
Assert(NULL != m_pLogFile);
if (NULL == m_pLogFile)
return;
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT_STREAM_WRITE(bs, pszCommand);
FAIL_EXIT_STREAM_WRITE(bs, c_szSpace);
FAIL_EXIT_STREAM_WRITE(bs, m_op.pszUrl);
if (pvData && cbData)
{
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
if (FAILED(hr = bs.Write(pvData, cbData, NULL)))
goto exit;
}
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT(hr = bs.HrAcquireStringA(NULL, &pszLogData, ACQ_DISPLACE));
m_pLogFile->WriteLog(LOGFILE_TX, pszLogData);
exit:
SafeMemFree(pszLogData);
return;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_LogResponse
// --------------------------------------------------------------------------------
void CHTTPMailTransport::_LogResponse(LPVOID pvData, DWORD cbData)
{
HRESULT hr = S_OK;
CByteStream bs;
LPSTR pszHeaders = NULL;
LPSTR pszLogData = NULL;
Assert(NULL != m_pLogFile);
if (NULL == m_pLogFile || m_op.fLoggedResponse)
return;
FAIL_EXIT(_GetRequestHeader(&pszHeaders, HTTP_QUERY_RAW_HEADERS_CRLF));
if (pszHeaders)
{
// prefix with a CRLF
if ('\r' != pszHeaders[0])
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT_STREAM_WRITE(bs, pszHeaders);
}
if (pvData && cbData)
{
if (FAILED(hr = bs.Write(pvData, cbData, NULL)))
goto exit;
}
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT_STREAM_WRITE(bs, c_szCRLF);
FAIL_EXIT(hr = bs.HrAcquireStringA(NULL, &pszLogData, ACQ_DISPLACE));
m_pLogFile->WriteLog(LOGFILE_RX, pszLogData);
exit:
m_op.fLoggedResponse = TRUE;
SafeMemFree(pszHeaders);
SafeMemFree(pszLogData);
return;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::TranslateWinInetMsg
// --------------------------------------------------------------------------------
BOOL CHTTPMailTransport::TranslateWinInetMsg(
DWORD dwInternetStatus,
IXPSTATUS *pIxpStatus)
{
IxpAssert(NULL != pIxpStatus);
switch (dwInternetStatus)
{
case INTERNET_STATUS_RESOLVING_NAME:
*pIxpStatus = IXP_FINDINGHOST;
break;
case INTERNET_STATUS_CONNECTING_TO_SERVER:
*pIxpStatus = IXP_CONNECTING;
break;
case INTERNET_STATUS_CONNECTED_TO_SERVER:
*pIxpStatus = IXP_CONNECTED;
break;
case INTERNET_STATUS_CLOSING_CONNECTION:
*pIxpStatus = IXP_DISCONNECTING;
break;
case INTERNET_STATUS_CONNECTION_CLOSED:
*pIxpStatus = IXP_DISCONNECTED;
break;
case INTERNET_STATUS_REQUEST_COMPLETE:
*pIxpStatus = IXP_LAST;
break;
default:
// status codes that are not translated:
// INTERNET_STATUS_NAME_RESOLVED
// INTERNET_STATUS_SENDING_REQUEST
// INTERNET_STATUS_ REQUEST_SENT
// INTERNET_STATUS_RECEIVING_RESPONSE
// INTERNET_STATUS_RESPONSE_RECEIVED
// INTERNET_STATUS_REDIRECT
// INTERNET_STATUS_HANDLE_CREATED
// INTERNET_STATUS_HANDLE_CLOSING
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_CreateXMLParser
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_CreateXMLParser()
{
HRESULT hr = S_OK;
if (NULL == m_pParser)
{
// instantiate the xml document
hr = ::CoCreateInstance(CLSID_XMLParser,
NULL,
CLSCTX_INPROC_SERVER,
IID_IXMLParser,
reinterpret_cast<void **>(&m_pParser));
if (FAILED(hr))
goto exit;
if (FAILED(hr = m_pParser->SetFlags(XMLFLAG_FLOATINGAMP)))
goto exit;
}
hr = m_pParser->SetFactory(this);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::OpenRequest
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::OpenRequest(void)
{
LPSTR pszVerb = NULL;
HRESULT hr = S_OK;
LPSTR pszHostName = NULL;
LPSTR pszUrlPath = NULL;
INTERNET_PORT nPort;
LPSTR pszUserName = GetUserName();
LPSTR pszPassword = GetPassword();
if (NULL == pszUserName)
pszUserName = "";
if (NULL == pszPassword)
pszPassword = "";
// crack the url into component parts
if (FAILED(hr = HrCrackUrl(m_op.pszUrl, &pszHostName, &pszUrlPath, &nPort)))
{
TrapError(hr);
goto exit;
}
if (FAILED(hr = HrConnectToHost(pszHostName, nPort, pszUserName, NULL)))
{
TrapError(hr);
goto exit;
}
// We have to set the password and username on every connection. If we don't,
// and and incorrect password or username forces us to prompt the user, the
// newly entered data won't get used on subsequent requests
InternetSetOption(GetConnection(), INTERNET_OPTION_USERNAME, pszUserName, lstrlen(pszUserName) + 1);
InternetSetOption(GetConnection(), INTERNET_OPTION_PASSWORD, pszPassword, lstrlen(pszPassword) + 1);
FAIL_ABORT;
// convert the command to a verb string
pszVerb = CommandToVerb(m_op.rResponse.command);
// Open the HTTP request
m_op.hRequest = HttpOpenRequest(
GetConnection(),
pszVerb,
pszUrlPath,
NULL,
NULL,
m_op.rgszAcceptTypes,
INTERNET_FLAG_EXISTING_CONNECT |
INTERNET_FLAG_RELOAD |
INTERNET_FLAG_KEEP_CONNECTION,
0);
if (NULL == m_op.hRequest)
{
DWORD dwErr = GetLastError();
hr = E_FAIL;
}
exit:
SafeMemFree(pszHostName);
SafeMemFree(pszUrlPath);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::SendPostRequest
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::SendPostRequest(void)
{
HRESULT hr = S_OK;
INTERNET_BUFFERS buffers;
DWORD cbData;
ULONG cbRead;
ULONG cbWritten;
BOOL fResult;
CHAR localBuffer[HTTPMAIL_BUFSIZE];
LARGE_INTEGER liOrigin = {0,0};
DWORD dwBufferLength;
BOOL fSentData = FALSE;
BOOL fWillSend;
DWORD dwWinInetErr = 0;
BOOL fRetryAuth = FALSE;
// log the request, but don't log the request body
if (m_pLogFile)
_LogRequest(NULL, 0);
if (m_op.pHeaderStream)
{
if (FAILED(hr = HrGetStreamSize(m_op.pHeaderStream, &m_op.rResponse.rPostInfo.cbTotal)))
goto exit;
}
if (m_op.pBodyStream)
{
if (FAILED(hr = HrGetStreamSize(m_op.pBodyStream, &cbData)))
goto exit;
m_op.rResponse.rPostInfo.cbTotal += cbData;
}
buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
buffers.Next = NULL;
buffers.lpcszHeader = NULL;
buffers.dwHeadersLength = 0;
buffers.dwHeadersTotal = 0;
buffers.lpvBuffer = NULL;
buffers.dwBufferLength = 0;
buffers.dwBufferTotal = m_op.rResponse.rPostInfo.cbTotal;
buffers.dwOffsetLow = 0;
buffers.dwOffsetHigh = 0;
resend:
if (fSentData)
{
m_op.rResponse.rPostInfo.fResend = TRUE;
m_op.rResponse.rPostInfo.cbCurrent = 0;
_HrThunkResponse(FALSE);
m_op.rResponse.rPostInfo.fResend = FALSE;
FAIL_ABORT;
}
fResult = HttpSendRequestEx(m_op.hRequest, &buffers, NULL, 0, 0);
if (!fResult)
{
dwWinInetErr = GetLastError();
if (ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION == dwWinInetErr)
{
fRetryAuth = TRUE;
goto resend;
}
_HrThunkConnectionError(dwWinInetErr);
hr = E_FAIL;
goto exit;
}
// with some auth methods (e.g., NTLM), wininet will send a post request
// with a content length of 0, and will ignore calls to InternetWriteFile
// until the server sends a 100 (continue) response. wininet will then
// return ERROR_INTERNET_FORCE_RETRY to force a resend. we detect this
// case here so that we don't send a bunch of OnResponse progress notifications
// when no data is actually going out over the wire
// this constant isn't in the wininet headers as of 10/6/98!!
#ifndef INTERNET_OPTION_DETECT_POST_SEND
#define INTERNET_OPTION_DETECT_POST_SEND 71
#endif
dwBufferLength = sizeof(fWillSend);
if (!InternetQueryOption(m_op.hRequest, INTERNET_OPTION_DETECT_POST_SEND, &fWillSend, &dwBufferLength))
fWillSend = TRUE;
else
{
Assert(dwBufferLength == sizeof(BOOL));
}
if (fWillSend)
{
fSentData = TRUE;
if (m_op.pHeaderStream)
{
// rewind the stream
if (FAILED(hr = m_op.pHeaderStream->Seek(liOrigin, STREAM_SEEK_SET, NULL)))
goto exit;
while (TRUE)
{
if (FAILED(hr = m_op.pHeaderStream->Read(localBuffer, sizeof(localBuffer), &cbRead)))
goto exit;
if (0 == cbRead)
break;
fResult = InternetWriteFile(m_op.hRequest, localBuffer, cbRead, &cbWritten);
IxpAssert(!fResult || (cbRead == cbWritten));
if (!fResult)
{
_HrThunkConnectionError(GetLastError());
hr = E_FAIL;
goto exit;
}
m_op.rResponse.rPostInfo.cbIncrement = cbWritten;
m_op.rResponse.rPostInfo.cbCurrent += cbWritten;
_HrThunkResponse(FALSE);
m_op.rResponse.rPostInfo.cbIncrement = 0;
FAIL_ABORT;
}
}
if (m_op.pBodyStream)
{
// rewind the stream
if (FAILED(hr = m_op.pBodyStream->Seek(liOrigin, STREAM_SEEK_SET, NULL)))
goto exit;
while (TRUE)
{
if (FAILED(hr = m_op.pBodyStream->Read(localBuffer, sizeof(localBuffer), &cbRead)))
goto exit;
if (0 == cbRead)
break;
fResult = InternetWriteFile(m_op.hRequest, localBuffer, cbRead, &cbWritten);
IxpAssert(!fResult || (cbRead == cbWritten));
if (!fResult)
{
_HrThunkConnectionError(GetLastError());
hr = E_FAIL;
goto exit;
}
m_op.rResponse.rPostInfo.cbIncrement = cbWritten;
m_op.rResponse.rPostInfo.cbCurrent += cbWritten;
_HrThunkResponse(FALSE);
m_op.rResponse.rPostInfo.cbIncrement = 0;
FAIL_ABORT;
}
}
}
fResult = HttpEndRequest(m_op.hRequest, NULL, 0, 0);
if (!fResult)
{
if (ERROR_INTERNET_FORCE_RETRY == GetLastError())
goto resend;
_HrThunkConnectionError(GetLastError());
}
if (!_GetStatusCode(&m_op.dwHttpStatus))
{
_HrThunkConnectionError(GetLastError());
hr = E_FAIL;
goto exit;
}
if (_AuthCurrentRequest(m_op.dwHttpStatus, fRetryAuth))
{
fRetryAuth = FALSE;
goto resend;
}
if (!fResult)
{
_HrThunkConnectionError();
hr = E_FAIL;
goto exit;
}
// status codes not in the 200-299 range indicate an error
if (200 > m_op.dwHttpStatus || 299 < m_op.dwHttpStatus)
{
_HrThunkConnectionError();
hr = E_FAIL;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::SendRequest
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::SendRequest(void)
{
HRESULT hr = S_OK;
DWORD dwError;
BOOL bResult;
HWND hwndParent = NULL;
BOOL fRequestedParent = FALSE;
DWORD dwWinInetErr = 0;
BOOL fRetryAuth = FALSE;
// log the request, including the requets body
if (m_pLogFile)
_LogRequest(m_op.pvData, m_op.cbDataLen);
resend:
hr = S_OK;
bResult = HttpSendRequest(m_op.hRequest, NULL, 0L, m_op.pvData, m_op.cbDataLen);
if (!bResult)
{
dwWinInetErr = GetLastError();
if (ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION == dwWinInetErr)
{
fRetryAuth = TRUE;
goto resend;
}
_HrThunkConnectionError(dwWinInetErr);
hr = E_FAIL;
goto exit;
}
if (!_GetStatusCode(&m_op.dwHttpStatus))
{
_HrThunkConnectionError(GetLastError());
hr = E_FAIL;
goto exit;
}
if (_AuthCurrentRequest(m_op.dwHttpStatus, fRetryAuth))
{
fRetryAuth = FALSE;
goto resend;
}
// status codes not in the 200-299 range indicate an error
if (200 > m_op.dwHttpStatus|| 299 < m_op.dwHttpStatus)
{
_HrThunkConnectionError();
hr = E_FAIL;
goto exit;
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::RequireMultiStatus
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::RequireMultiStatus(void)
{
HRESULT hr = S_OK;
if (207 != m_op.dwHttpStatus)
{
_HrThunkConnectionError(ERROR_INTERNET_CANNOT_CONNECT);
hr = E_FAIL;
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FinalizeRequest
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::FinalizeRequest(void)
{
HRESULT hr = S_OK;
LPSTR pszTimestampHeader = NULL;
// log the response if it hasn't already been logged
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
if (HTTPMAIL_MEMBERINFO == m_op.rResponse.command)
{
// Get the headers and copy them. If we don't get timestamp header, its not a big deal. We don't report an error.
hr = _HrGetTimestampHeader(&pszTimestampHeader);
if (SUCCEEDED(hr))
{
// Get the Active timestamp
FAIL_EXIT(hr = _HrParseAndCopy(c_szActive, &m_op.rResponse.rMemberInfoList.pszFolderTimeStamp, pszTimestampHeader));
// Get RootTimeStamp which for some strange reason comes as Folders TimeStamp
// This call might fail for legitimate reasons. For Inbox list headers we do not get a RootTimeStamp.
// Hence we do not exit if we can't get root time stamp.
_HrParseAndCopy(c_szFolders, &m_op.rResponse.rMemberInfoList.pszRootTimeStamp, pszTimestampHeader);
SafeMemFree(pszTimestampHeader);
}
}
hr = _HrThunkResponse(TRUE);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessGetResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessGetResponse(void)
{
HRESULT hr = S_OK;
BOOL bRead;
DWORD cbReadBytes = 0;
// log the respnse, but don't log the response body
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
Assert(NULL == m_op.rResponse.rGetInfo.pszContentType);
// extract the content type header
FAIL_EXIT(hr = _GetRequestHeader(&m_op.rResponse.rGetInfo.pszContentType, HTTP_QUERY_CONTENT_TYPE));
// try to get the content length
m_op.rResponse.rGetInfo.fTotalKnown = _GetContentLength(&m_op.rResponse.rGetInfo.cbTotal);
do
{
// The buffer is owned by this object, but the client
// has the option of taking ownership of the buffer
// whenever a read completes. We reallocate the buffer
// here if necessary
FAIL_ABORT;
if (!m_op.rResponse.rGetInfo.pvBody && !MemAlloc((void**)&m_op.rResponse.rGetInfo.pvBody, HTTPMAIL_BUFSIZE + 1))
{
hr = E_OUTOFMEMORY;
break;
}
bRead = ReadBytes((char *)m_op.rResponse.rGetInfo.pvBody, HTTPMAIL_BUFSIZE, &cbReadBytes);
m_op.rResponse.rGetInfo.cbIncrement = cbReadBytes;
m_op.rResponse.rGetInfo.cbCurrent += cbReadBytes;
// we guarantee space for the terminating null by allocating
// a buffer one larger than bufsize
static_cast<char *>(m_op.rResponse.rGetInfo.pvBody)[cbReadBytes] = '\0';
// Send a message to the window that lives in the client's thread
_HrThunkResponse(0 == cbReadBytes);
} while (0 < cbReadBytes);
exit:
SafeMemFree(m_op.rResponse.rGetInfo.pvBody);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessPostResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessPostResponse(void)
{
HRESULT hr = S_OK;
// log the response
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
if (m_op.dwHttpStatus < 200 || m_op.dwHttpStatus > 299)
{
_HrThunkConnectionError();
hr = E_FAIL;
goto exit;
}
hr = _GetRequestHeader(&m_op.rResponse.rPostInfo.pszLocation, HTTP_QUERY_LOCATION);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessXMLResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessXMLResponse(void)
{
HRESULT hr = S_OK;
BOOL bRead;
LPSTR pszBody = NULL;
DWORD cbLength = 0;
CByteStream *pLogStream = NULL;
BOOL fFoundBytes = FALSE;
if (m_pLogFile && !m_op.fLoggedResponse)
pLogStream = new CByteStream();
// we only parse xml if the response is a 207 (multistatus)
if (m_op.dwHttpStatus != 207)
goto exit;
// create the xml parser
if (FAILED(hr = _CreateXMLParser()))
goto exit;
if (!MemAlloc((void **)&pszBody, HTTPMAIL_BUFSIZE))
{
hr = E_OUTOFMEMORY;
goto exit;
}
do
{
FAIL_ABORT;
bRead = ReadBytes(pszBody, HTTPMAIL_BUFSIZE, &cbLength);
if (0 == cbLength)
{
if (fFoundBytes)
{
// parse any remaining bytes in the parser's buffer
if (FAILED(hr = m_pParser->PushData(NULL, 0, TRUE)))
goto exit;
if (FAILED(hr = m_pParser->Run(-1)))
goto exit;
}
break;
}
fFoundBytes = TRUE;
// if logging, write the block into the log stream
if (pLogStream)
pLogStream->Write(pszBody, cbLength, NULL);
if (FAILED(hr = m_pParser->PushData(pszBody, cbLength, FALSE)))
goto exit;
if (FAILED(hr = m_pParser->Run(-1)))
{
if (hr == E_PENDING)
hr = S_OK;
else
goto exit;
}
} while (TRUE);
exit:
SafeMemFree(pszBody);
if (pLogStream)
{
LPSTR pszLog = NULL;
DWORD dwLog = 0;
pLogStream->HrAcquireStringA(&dwLog, &pszLog, ACQ_DISPLACE);
_LogResponse(pszLog, dwLog);
SafeMemFree(pszLog);
delete pLogStream;
}
if (m_pParser)
m_pParser->Reset();
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GeneratePropFindXML
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::GeneratePropFindXML(void)
{
HRESULT hr = S_OK;
LPSTR pszXML = NULL;
IxpAssert(NULL == m_op.pvData && 0 == m_op.cbDataLen);
IxpAssert(NULL != m_op.pPropFindRequest);
if (FAILED(hr = m_op.pPropFindRequest->GenerateXML(&pszXML)))
goto exit;
m_op.pvData = pszXML;
m_op.cbDataLen = lstrlen(pszXML);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AddDepthHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AddDepthHeader(void)
{
HRESULT hr = S_OK;
char szDepthHeader[64];
if (0 != m_op.dwDepth && !!(m_op.dwRHFlags & RH_NOROOT))
{
if (DEPTH_INFINITY == m_op.dwDepth)
StrCpyN(szDepthHeader, c_szDepthInfinityNoRootHeader, ARRAYSIZE(szDepthHeader));
else
wnsprintf(szDepthHeader, ARRAYSIZE(szDepthHeader), c_szDepthNoRootHeader, m_op.dwDepth);
}
else
{
if (DEPTH_INFINITY == m_op.dwDepth)
StrCpyN(szDepthHeader, c_szDepthInfinityHeader, ARRAYSIZE(szDepthHeader));
else
wnsprintf(szDepthHeader, ARRAYSIZE(szDepthHeader), c_szDepthHeader, m_op.dwDepth);
}
if (!HttpAddRequestHeaders(m_op.hRequest, szDepthHeader, lstrlen(szDepthHeader), HTTP_ADDREQ_FLAG_ADD))
{
_HrThunkConnectionError();
hr = E_FAIL;
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::GeneratePropPatchXML
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::GeneratePropPatchXML(void)
{
HRESULT hr = S_OK;
LPSTR pszXML = NULL;
IxpAssert(NULL == m_op.pvData && 0 == m_op.cbDataLen);
IxpAssert(NULL != m_op.pPropPatchRequest);
if (FAILED(hr = m_op.pPropPatchRequest->GenerateXML(&pszXML)))
goto exit;
m_op.pvData = pszXML;
m_op.cbDataLen = lstrlen(pszXML);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessCreatedResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessCreatedResponse(void)
{
HRESULT hr = S_OK;
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
if (HTTP_STATUS_CREATED != m_op.dwHttpStatus)
{
_HrThunkConnectionError();
hr = E_FAIL;
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AddCommonHeaders
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AddCommonHeaders(void)
{
HRESULT hr = S_OK;
CHAR szHeader[CCHMAX_RES];
if (!!(RH_ALLOWRENAME & m_op.dwRHFlags))
{
if (FAILED(hr = _AddRequestHeader(c_szAllowRenameHeader)))
goto exit;
}
if (!!(RH_TRANSLATEFALSE & m_op.dwRHFlags))
{
if (FAILED(hr = _AddRequestHeader(c_szTranslateFalseHeader)))
goto exit;
}
if (!!(RH_TRANSLATETRUE & m_op.dwRHFlags))
{
if (FAILED(hr = _AddRequestHeader(c_szTranslateTrueHeader)))
goto exit;
}
if (!!(RH_XMLCONTENTTYPE & m_op.dwRHFlags))
{
IxpAssert(NULL == m_op.pszContentType);
m_op.pszContentType = PszDupA(c_szXmlContentType);
if (NULL == m_op.pszContentType)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (FAILED(hr = AddContentTypeHeader()))
goto exit;
}
if (!!(RH_MESSAGECONTENTTYPE & m_op.dwRHFlags))
{
IxpAssert(NULL == m_op.pszContentType);
m_op.pszContentType = PszDupA(c_szMailContentType);
if (NULL == m_op.pszContentType)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (FAILED(hr = AddContentTypeHeader()))
goto exit;
}
if (!!(RH_SMTPMESSAGECONTENTTYPE & m_op.dwRHFlags))
{
IxpAssert(NULL == m_op.pszContentType);
m_op.pszContentType = PszDupA(c_szSmtpMessageContentType);
if (NULL == m_op.pszContentType)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
if (FAILED(hr = AddContentTypeHeader()))
goto exit;
}
if (!!(RH_BRIEF & m_op.dwRHFlags))
{
if (FAILED(hr = _AddRequestHeader(c_szBriefHeader)))
goto exit;
}
if (!!(RH_SAVEINSENTTRUE & m_op.dwRHFlags))
{
FAIL_EXIT(hr = _AddRequestHeader(c_szSaveInSentTrue));
}
if (!!(RH_SAVEINSENTFALSE & m_op.dwRHFlags))
{
FAIL_EXIT(hr = _AddRequestHeader(c_szSaveInSentFalse));
}
if (!!(RH_ROOTTIMESTAMP & m_op.dwRHFlags))
{
wnsprintf(szHeader, ARRAYSIZE(szHeader), c_szRootTimeStampHeader, m_op.pszRootTimeStamp, m_op.pszFolderTimeStamp);
FAIL_EXIT(hr = _AddRequestHeader(szHeader));
}
if (!!(RH_FOLDERTIMESTAMP & m_op.dwRHFlags))
{
wnsprintf(szHeader, ARRAYSIZE(szHeader), c_szFolderTimeStampHeader, m_op.pszFolderTimeStamp);
FAIL_EXIT(hr = _AddRequestHeader(szHeader));
}
// Fix for 88820
if (!!(RH_ADDCHARSET & m_op.dwRHFlags))
{
CODEPAGEINFO CodePageInfo;
MimeOleGetCodePageInfo(CP_ACP, &CodePageInfo);
*szHeader = 0;
wnsprintf(szHeader, ARRAYSIZE(szHeader), c_szAcceptCharset, CodePageInfo.szWebCset);
FAIL_EXIT(hr = _AddRequestHeader(szHeader));
}
// end of fix
exit:
return hr;
}
// CHTTPMailTransport::AddCharsetLine
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AddCharsetLine(void)
{
HRESULT hr = S_OK;
CHAR szHeader[CCHMAX_RES];
CODEPAGEINFO CodePageInfo;
MimeOleGetCodePageInfo(CP_ACP, &CodePageInfo);
*szHeader = 0;
wnsprintf(szHeader, ARRAYSIZE(szHeader), c_szAcceptCharset, CodePageInfo.szWebCset);
hr = _AddRequestHeader(szHeader);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AddDestinationHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AddDestinationHeader(void)
{
HRESULT hr = S_OK;
ULONG cchSize = (lstrlen(c_szDestinationHeader) + lstrlen(m_op.pszDestination) + 1);
LPSTR pszDestHeader = NULL;
if (!MemAlloc((void **)&pszDestHeader, cchSize * sizeof(pszDestHeader[0])))
{
hr = E_OUTOFMEMORY;
goto exit;
}
wnsprintf(pszDestHeader, cchSize, "%s%s", c_szDestinationHeader, m_op.pszDestination);
hr = _AddRequestHeader(pszDestHeader);
exit:
SafeMemFree(pszDestHeader);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::AddContentTypeHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::AddContentTypeHeader(void)
{
HRESULT hr = S_OK;
ULONG cchSize;
LPSTR pszContentTypeHeader = NULL;
if (NULL == m_op.pszContentType)
goto exit;
cchSize = lstrlen(c_szContentTypeHeader) + lstrlen(m_op.pszContentType) + 1;
if (!MemAlloc((void **)&pszContentTypeHeader, cchSize * sizeof(pszContentTypeHeader[0])))
{
hr = E_OUTOFMEMORY;
goto exit;
}
wnsprintf(pszContentTypeHeader, cchSize, "%s%s", c_szContentTypeHeader, m_op.pszContentType);
hr = _AddRequestHeader(pszContentTypeHeader);
exit:
SafeMemFree(pszContentTypeHeader);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessLocationResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessLocationResponse(void)
{
_GetRequestHeader(&m_op.rResponse.rCopyMoveInfo.pszLocation, HTTP_QUERY_LOCATION);
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitBCopyMove
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitBCopyMove(void)
{
HRESULT hr = S_OK;
// allocate a buffer to contain the response list
if (!MemAlloc((void **)&m_op.rResponse.rBCopyMoveList.prgBCopyMove,
BCOPYMOVE_MAXRESPONSES * sizeof(HTTPMAILBCOPYMOVE)))
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
ZeroMemory(m_op.rResponse.rBCopyMoveList.prgBCopyMove, BCOPYMOVE_MAXRESPONSES * sizeof(HTTPMAILBCOPYMOVE));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitRootProps
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitRootProps(void)
{
HRESULT hr = S_OK;
// it is possible to end up here, and have the root props
// if the caller either forced the request to go async,
// or queued up multiple requests for root props.
if (GetHasRootProps())
{
// finalize the root props, and return an error.
// this will generate the response to the caller,
// and fall out of the fsm.
FinalizeRootProps();
hr = E_FAIL;
}
else
{
IxpAssert(NULL == m_op.pPropFindRequest);
m_op.pPropFindRequest = new CPropFindRequest();
if (NULL == m_op.pPropFindRequest)
{
hr = E_OUTOFMEMORY;
goto exit;
}
hr = XP_CREATE_PROPFIND_REQUEST(ROOTPROPS, m_op.pPropFindRequest);
}
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FinalizeRootProps
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::FinalizeRootProps(void)
{
HRESULT hr = S_OK;
m_fHasRootProps = TRUE;
m_op.rResponse.rGetPropInfo.type = m_op.tyProp;
if (m_op.tyProp != HTTPMAIL_PROP_MAXPOLLINGINTERVAL)
{
m_op.rResponse.rIxpResult.hrResult = GetProperty(m_op.tyProp, &m_op.rResponse.rGetPropInfo.pszProp);
}
else
{
m_op.rResponse.rIxpResult.hrResult = GetPropertyDw(m_op.tyProp, &m_op.rResponse.rGetPropInfo.dwProp);
}
hr = _HrThunkResponse(TRUE);
SafeMemFree(m_op.rResponse.rGetPropInfo.pszProp);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitMemberInfo
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitMemberInfo(void)
{
HRESULT hr = S_OK;
IxpAssert(NULL == m_op.pPropFindRequest);
// create the propfind request
m_op.pPropFindRequest = new CPropFindRequest();
if (NULL == m_op.pPropFindRequest)
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
// always add the common properties
FAIL_EXIT(hr = XP_CREATE_PROPFIND_REQUEST(HTTPMEMBERINFO_COMMON, m_op.pPropFindRequest));
// if the client requested folder props, add that schema
if (!!(m_op.dwMIFlags & HTTP_MEMBERINFO_FOLDERPROPS))
FAIL_EXIT(hr = XP_CREATE_PROPFIND_REQUEST(HTTPMEMBERINFO_FOLDER, m_op.pPropFindRequest));
// if the client requested message props, add that schema
if (!!(m_op.dwMIFlags & HTTP_MEMBERINFO_MESSAGEPROPS))
FAIL_EXIT(hr = XP_CREATE_PROPFIND_REQUEST(HTTPMEMBERINFO_MESSAGE, m_op.pPropFindRequest));
// allocate a buffer to contain the response list
if (!MemAlloc((void **)&m_op.rResponse.rMemberInfoList.prgMemberInfo,
MEMBERINFO_MAXRESPONSES * sizeof(HTTPMEMBERINFO)))
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
ZeroMemory(m_op.rResponse.rMemberInfoList.prgMemberInfo, MEMBERINFO_MAXRESPONSES * sizeof(HTTPMEMBERINFO));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitMemberError
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitMemberError(void)
{
HRESULT hr = S_OK;
// allocate a buffer to contain the response list
if (!MemAlloc((void **)&m_op.rResponse.rMemberErrorList.prgMemberError,
MEMBERERROR_MAXRESPONSES * sizeof(HTTPMEMBERERROR)))
{
hr = TrapError(E_OUTOFMEMORY);
goto exit;
}
ZeroMemory(m_op.rResponse.rMemberErrorList.prgMemberError, MEMBERERROR_MAXRESPONSES * sizeof(HTTPMEMBERERROR));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// InitListContacts
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitListContacts(void)
{
HRESULT hr = S_OK;
IxpAssert(NULL == m_op.pPropFindRequest);
m_op.pPropFindRequest = new CPropFindRequest();
if (NULL == m_op.pPropFindRequest)
{
hr = E_OUTOFMEMORY;
goto exit;
}
hr = XP_CREATE_PROPFIND_REQUEST(HTTPCONTACTID, m_op.pPropFindRequest);
if (FAILED(hr))
goto exit;
// allocate a buffer to contain the response list
if (!MemAlloc((void **)&m_op.rResponse.rContactIdList.prgContactId,
LISTCONTACTS_MAXRESPONSES * sizeof(HTTPCONTACTID)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
ZeroMemory(m_op.rResponse.rContactIdList.prgContactId, LISTCONTACTS_MAXRESPONSES * sizeof(HTTPCONTACTID));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::InitContactInfo
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::InitContactInfo(void)
{
HRESULT hr = S_OK;
IxpAssert(NULL == m_op.pPropFindRequest);
m_op.pPropFindRequest = new CPropFindRequest();
if (NULL == m_op.pPropFindRequest)
{
hr = E_OUTOFMEMORY;
goto exit;
}
hr = XP_CREATE_PROPFIND_REQUEST(HTTPCONTACTINFO, m_op.pPropFindRequest);
if (FAILED(hr))
goto exit;
// allocate a buffer to contain the response list
if (!MemAlloc((void **)&m_op.rResponse.rContactInfoList.prgContactInfo,
CONTACTINFO_MAXRESPONSES * sizeof(HTTPCONTACTINFO)))
{
hr = E_OUTOFMEMORY;
goto exit;
}
ZeroMemory(m_op.rResponse.rContactInfoList.prgContactInfo, CONTACTINFO_MAXRESPONSES * sizeof(HTTPCONTACTINFO));
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessPostContactResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessPostContactResponse(void)
{
HRESULT hr = S_OK;
DWORD dwSize = MAX_PATH;
LPSTR pszLocation = NULL;
DWORD dwContext;
int iState;
if (m_pLogFile && !m_op.fLoggedResponse)
_LogResponse(NULL, 0);
if (HTTP_STATUS_CREATED != m_op.dwHttpStatus)
{
_HrThunkConnectionError();
hr = E_FAIL;
goto exit;
}
if (FAILED(hr = _GetRequestHeader(&pszLocation, HTTP_QUERY_LOCATION)))
goto exit;
// Prepare for the next phase
// save the context and the state
dwContext = m_op.dwContext;
iState = m_op.iState;
FreeOperation();
// restore context, state, parsing funcs, etc.
m_op.rResponse.command = HTTPMAIL_POSTCONTACT;
m_op.pszUrl = pszLocation;
pszLocation = NULL;
m_op.dwContext = dwContext;
m_op.pfnState = c_rgpfnPostContact;
m_op.cState = ARRAYSIZE(c_rgpfnPostContact);
m_op.iState = iState;
m_op.pParseFuncs = c_rgpfnPostOrPatchContactParse;
m_op.dwDepth = 0;
m_op.dwRHFlags = (RH_XMLCONTENTTYPE | RH_BRIEF);
m_op.rResponse.rPostContactInfo.pszHref = PszDupA(m_op.pszUrl);
if (NULL == m_op.rResponse.rPostContactInfo.pszHref)
hr = E_OUTOFMEMORY;
exit:
SafeMemFree(pszLocation);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ProcessPatchContactResponse
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ProcessPatchContactResponse(void)
{
HRESULT hr = S_OK;
LPSTR pszUrl = NULL;
DWORD dwContext;
int iState;
IHTTPMailCallback *pCallback = NULL;
// REVIEW: we should be handling multistatus responses
if (200 > m_op.dwHttpStatus || 300 < m_op.dwHttpStatus)
{
_HrThunkConnectionError();
hr = E_FAIL;
goto exit;
}
// prepare for the next phase
// save the context and the state
pszUrl = m_op.pszUrl;
m_op.pszUrl = NULL;
dwContext = m_op.dwContext;
iState = m_op.iState;
FreeOperation();
// restore context, etc.
m_op.rResponse.command = HTTPMAIL_PATCHCONTACT;
m_op.pszUrl = pszUrl;
m_op.dwContext = dwContext;
m_op.pfnState = c_rgpfnPatchContact;
m_op.cState = ARRAYSIZE(c_rgpfnPatchContact);
m_op.iState = iState;
m_op.pParseFuncs = c_rgpfnPostOrPatchContactParse; // share the post contact parse funcs
m_op.dwDepth = 0;
m_op.rResponse.rPatchContactInfo.pszHref = PszDupA(m_op.pszUrl);
m_op.dwRHFlags = (RH_BRIEF | RH_XMLCONTENTTYPE);
pszUrl = NULL;
exit:
return hr;
}
// --------------------------------------------------------------------------------
// XML Parsing Callbacks
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// CHTTPMailTransport::CreateElement
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::CreateElement(
CXMLNamespace *pBaseNamespace,
const WCHAR *pwcText,
ULONG ulLen,
ULONG ulNamespaceLen,
BOOL fTerminal)
{
// increment the stack pointer and, if there is room on the stack,
// push the element type
if (!fTerminal)
{
if (m_op.dwStackDepth < ELE_STACK_CAPACITY)
{
m_op.rgEleStack[m_op.dwStackDepth].ele = XMLElementToID(pwcText, ulLen, ulNamespaceLen, m_op.pTopNamespace);
m_op.rgEleStack[m_op.dwStackDepth].pBaseNamespace = pBaseNamespace;
m_op.rgEleStack[m_op.dwStackDepth].fBeganChildren = FALSE;
m_op.rgEleStack[m_op.dwStackDepth].pTextBuffer = NULL;
}
++m_op.dwStackDepth;
}
return S_OK;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::EndChildren(void)
{
HRESULT hr = S_OK;
// decrement the stack pointer
if (m_op.dwStackDepth <= ELE_STACK_CAPACITY)
{
LPPCDATABUFFER pTextBuffer = m_op.rgEleStack[m_op.dwStackDepth - 1].pTextBuffer;
if (pTextBuffer)
{
hr = (this->*(m_op.pParseFuncs->pfnHandleText))(pTextBuffer->pwcText, pTextBuffer->ulLen);
_ReleaseTextBuffer(pTextBuffer);
}
else
hr = (this->*(m_op.pParseFuncs->pfnHandleText))(NULL, 0);
// unroll the namespace
PopNamespaces(m_op.rgEleStack[m_op.dwStackDepth - 1].pBaseNamespace);
}
--m_op.dwStackDepth;
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::BCopyMove_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::BCopyMove_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPMAILBCOPYMOVE pInfo = &m_op.rResponse.rBCopyMoveList.prgBCopyMove[m_op.rResponse.rBCopyMoveList.cBCopyMove];
return XP_BIND_TO_STRUCT(HTTPMAILBCOPYMOVE, pwcText, ulLen, pInfo, NULL);
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::BCopyMove_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::BCopyMove_EndChildren(void)
{
HRESULT hr = S_OK;
if (StackTop(HMELE_DAV_RESPONSE) && VALIDSTACK(c_rgPropFindResponseStack))
{
// clear the prop flags, since we are about to increment the count
m_op.dwPropFlags = NOFLAGS;
// increment the list count and, if we've hit the max, send the notification
if (BCOPYMOVE_MAXRESPONSES == ++m_op.rResponse.rBCopyMoveList.cBCopyMove)
{
if (FAILED(hr = _HrThunkResponse(FALSE)))
goto exit;
FreeBCopyMoveList();
}
}
hr = EndChildren();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PropFind_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PropFind_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPSTR pszStatus = NULL;
// the only element that is handled here is <status>
if (StackTop(HMELE_DAV_STATUS) && VALIDSTACK(c_rgPropFindStatusStack))
{
m_op.fFoundStatus = TRUE;
m_op.dwStatus = 0;
if (SUCCEEDED(hr = AllocStrFromStrNW(pwcText, ulLen, &pszStatus)) && NULL != pszStatus)
{
// ignore errors parsing the status...we treat malformed status
// as status 0, which is an error
HrParseHTTPStatus(pszStatus, &m_op.dwStatus);
}
}
SafeMemFree(pszStatus);
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::RootProps_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::RootProps_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
BOOL fWasBound = FALSE;
hr = XP_BIND_TO_STRUCT(ROOTPROPS, pwcText, ulLen, &m_rootProps, &fWasBound);
if (FAILED(hr))
goto exit;
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::RootProps_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::RootProps_EndChildren(void)
{
// if we are popping a prop node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(ROOTPROPS, &m_rootProps, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
return EndChildren();
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MemberInfo_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::MemberInfo_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPMEMBERINFO pInfo = &m_op.rResponse.rMemberInfoList.prgMemberInfo[m_op.rResponse.rMemberInfoList.cMemberInfo];
BOOL fWasBound = FALSE;
FAIL_EXIT(hr = XP_BIND_TO_STRUCT(HTTPMEMBERINFO, pwcText, ulLen, pInfo, &fWasBound));
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MemberInfo_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::MemberInfo_EndChildren(void)
{
HRESULT hr = S_OK;
// if we are popping a propstat node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
// grab a pointer to the folder info we are accumulating
LPHTTPMEMBERINFO pInfo =
&m_op.rResponse.rMemberInfoList.prgMemberInfo[m_op.rResponse.rMemberInfoList.cMemberInfo];
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(HTTPMEMBERINFO, pInfo, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
else if (StackTop(HMELE_DAV_RESPONSE) && VALIDSTACK(c_rgPropFindResponseStack))
{
// increment the list count and, if we've hit the max, send the notification
if (MEMBERINFO_MAXRESPONSES == ++m_op.rResponse.rMemberInfoList.cMemberInfo)
{
if (FAILED(hr = _HrThunkResponse(FALSE)))
goto exit;
FreeMemberInfoList();
}
}
hr = EndChildren();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MemberError_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::MemberError_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPMEMBERERROR pInfo = &m_op.rResponse.rMemberErrorList.prgMemberError[m_op.rResponse.rMemberErrorList.cMemberError];
BOOL fWasBound = FALSE;
FAIL_EXIT(hr = XP_BIND_TO_STRUCT(HTTPMEMBERERROR, pwcText, ulLen, pInfo, &fWasBound));
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::MemberError_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::MemberError_EndChildren(void)
{
HRESULT hr = S_OK;
// if we are popping a propstat node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
// grab a pointer to the folder info we are accumulating
LPHTTPMEMBERERROR pInfo =
&m_op.rResponse.rMemberErrorList.prgMemberError[m_op.rResponse.rMemberErrorList.cMemberError];
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(HTTPMEMBERERROR, pInfo, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
else if (StackTop(HMELE_DAV_RESPONSE) && VALIDSTACK(c_rgPropFindResponseStack))
{
// increment the list count and, if we've hit the max, send the notification
if (MEMBERERROR_MAXRESPONSES == ++m_op.rResponse.rMemberErrorList.cMemberError)
{
if (FAILED(hr = _HrThunkResponse(FALSE)))
goto exit;
FreeMemberErrorList();
}
}
hr = EndChildren();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ListContacts_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ListContacts_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPCONTACTID pId = &m_op.rResponse.rContactIdList.prgContactId[m_op.rResponse.rContactIdList.cContactId];
BOOL fWasBound = FALSE;
hr = XP_BIND_TO_STRUCT(HTTPCONTACTID, pwcText, ulLen, pId, &fWasBound);
if (FAILED(hr))
goto exit;
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ListContacts_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ListContacts_EndChildren(void)
{
HRESULT hr = S_OK;
// if we are popping a propstat node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
// grab a pointer to the contact id we are accumulating
LPHTTPCONTACTID pId = &m_op.rResponse.rContactIdList.prgContactId[m_op.rResponse.rContactIdList.cContactId];
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(HTTPCONTACTID, pId, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
else if (StackTop(HMELE_DAV_RESPONSE) && VALIDSTACK(c_rgPropFindResponseStack))
{
// increment the list count and, if we've hit the max, send the notification
if (LISTCONTACTS_MAXRESPONSES == ++m_op.rResponse.rContactIdList.cContactId)
{
if (FAILED(hr = _HrThunkResponse(FALSE)))
goto exit;
FreeContactIdList();
}
}
hr = EndChildren();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ContactInfo_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ContactInfo_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPCONTACTINFO pInfo = &m_op.rResponse.rContactInfoList.prgContactInfo[m_op.rResponse.rContactInfoList.cContactInfo];
BOOL fWasBound = FALSE;
hr = XP_BIND_TO_STRUCT(HTTPCONTACTINFO, pwcText, ulLen, pInfo, &fWasBound);
if (FAILED(hr))
goto exit;
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::ContactInfo_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::ContactInfo_EndChildren()
{
HRESULT hr = S_OK;
// if we are popping a propstat node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
// grab a pointer to the contact id we are accumulating
LPHTTPCONTACTINFO pInfo = &m_op.rResponse.rContactInfoList.prgContactInfo[m_op.rResponse.rContactInfoList.cContactInfo];
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(HTTPCONTACTINFO, pInfo, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
else if (StackTop(HMELE_DAV_RESPONSE) && VALIDSTACK(c_rgPropFindResponseStack))
{
// increment the list count and, if we've hit the max, send the notification
if (CONTACTINFO_MAXRESPONSES == ++m_op.rResponse.rContactInfoList.cContactInfo)
{
if (FAILED(hr = _HrThunkResponse(FALSE)))
goto exit;
FreeContactInfoList();
}
}
hr = EndChildren();
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PostOrPatchContact_HandleText
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PostOrPatchContact_HandleText(const WCHAR *pwcText, ULONG ulLen)
{
HRESULT hr = S_OK;
LPHTTPCONTACTID pId = NULL;
BOOL fWasBound = FALSE;
if (HTTPMAIL_POSTCONTACT == m_op.rResponse.command)
pId = &m_op.rResponse.rPostContactInfo;
else if (HTTPMAIL_PATCHCONTACT == m_op.rResponse.command)
pId = &m_op.rResponse.rPatchContactInfo;
IxpAssert(pId);
hr = XP_BIND_TO_STRUCT(HTTPCONTACTID, pwcText, ulLen, pId, &fWasBound);
if (FAILED(hr))
goto exit;
if (!fWasBound)
hr = PropFind_HandleText(pwcText, ulLen);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::PostOrPatchContact_EndChildren
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::PostOrPatchContact_EndChildren(void)
{
HRESULT hr = S_OK;
// if we are popping a propstat node with a bad status code,
// free any data associated with the node
if (StackTop(HMELE_DAV_PROPSTAT) && VALIDSTACK(c_rgPropFindPropStatStack))
{
// grab a pointer to the contact id we are accumulating
LPHTTPCONTACTID pId = NULL;
if (HTTPMAIL_POSTCONTACT == m_op.rResponse.command)
pId = &m_op.rResponse.rPostContactInfo;
else if (HTTPMAIL_PATCHCONTACT == m_op.rResponse.command)
pId = &m_op.rResponse.rPatchContactInfo;
IxpAssert(pId);
if (!m_op.fFoundStatus || m_op.dwStatus != 200)
XP_FREE_STRUCT(HTTPCONTACTID, pId, &m_op.dwPropFlags);
m_op.fFoundStatus = FALSE;
m_op.dwPropFlags = NOFLAGS;
}
hr = EndChildren();
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_MemberInfo2
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_MemberInfo2(LPCSTR pszPath,
MEMBERINFOFLAGS flags,
DWORD dwDepth,
BOOL fIncludeRoot,
DWORD dwContext,
LPHTTPQUEUEDOP *ppOp)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp = NULL;
if (!ppOp)
{
IF_FAILEXIT(hr = E_INVALIDARG);
}
if (NULL == pszPath)
return TrapError(E_INVALIDARG);
FAIL_CREATEWND;
#pragma prefast(suppress:11, "noise")
*ppOp = NULL;
if (FAILED(hr = AllocQueuedOperation(pszPath, NULL, 0, &pOp)))
goto exit;
pOp->command = HTTPMAIL_MEMBERINFO;
pOp->dwMIFlags = flags;
pOp->dwDepth = dwDepth;
pOp->dwContext = dwContext;
pOp->pfnState = c_rgpfnMemberInfo;
pOp->cState = ARRAYSIZE(c_rgpfnMemberInfo);
pOp->pParseFuncs = c_rgpfnMemberInfoParse;
pOp->dwRHFlags = (RH_BRIEF | RH_XMLCONTENTTYPE);
if (!fIncludeRoot)
pOp->dwRHFlags |= RH_NOROOT;
exit:
if (SUCCEEDED(hr))
{
#pragma prefast(suppress:11, "noise")
*ppOp = pOp;
}
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::RootMemberInfo
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::RootMemberInfo(LPCSTR pszPath,
MEMBERINFOFLAGS flags,
DWORD dwDepth,
BOOL fIncludeRoot,
DWORD dwContext,
LPSTR pszRootTimeStamp,
LPSTR pszInboxTimeStamp)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp;
IF_FAILEXIT(hr = _MemberInfo2(pszPath, flags, dwDepth, fIncludeRoot, dwContext, &pOp));
pOp->dwRHFlags |= RH_ROOTTIMESTAMP | RH_ADDCHARSET;
pOp->pszRootTimeStamp = PszDupA(pszRootTimeStamp);
pOp->pszFolderTimeStamp = PszDupA(pszInboxTimeStamp);
QueueOperation(pOp);
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::FolderMemberInfo
// --------------------------------------------------------------------------------
STDMETHODIMP CHTTPMailTransport::FolderMemberInfo(LPCSTR pszPath,
MEMBERINFOFLAGS flags,
DWORD dwDepth,
BOOL fIncludeRoot,
DWORD dwContext,
LPSTR pszFolderTimeStamp,
LPSTR pszFolderName)
{
HRESULT hr = S_OK;
LPHTTPQUEUEDOP pOp;
IF_FAILEXIT(hr = _MemberInfo2(pszPath, flags, dwDepth, fIncludeRoot, dwContext, &pOp));
pOp->dwRHFlags |= RH_FOLDERTIMESTAMP | RH_ADDCHARSET;
pOp->pszFolderTimeStamp = PszDupA(pszFolderTimeStamp);
// To be used when we do timestamping on every folder. Right now the default is inbox
//pOp->pszFolderName = PszDupA(pszFolderName);
QueueOperation(pOp);
exit:
return hr;
}
HRESULT CHTTPMailTransport::_HrParseAndCopy(LPCSTR pszToken, LPSTR *ppszDest, LPSTR lpszSrc)
{
LPSTR lpszBeginning = lpszSrc;
LPSTR lpszEnd;
DWORD dwCount = 0;
HRESULT hr = E_FAIL;
int cchSize;
lpszBeginning = StrStr(lpszSrc, pszToken);
if (!lpszBeginning)
goto exit;
lpszBeginning = StrChr(lpszBeginning, '=');
if (!lpszBeginning)
goto exit;
// Skip the equal sign
++lpszBeginning;
SkipWhitespace(lpszBeginning, &dwCount);
lpszBeginning += dwCount;
lpszEnd = StrChr(lpszBeginning, ',');
if (!lpszEnd)
{
//Its possible that this token is at the end. So use the remaining string.
//Lets take a look at the length and make sure that it doesn't fall off the deep end.
lpszEnd = lpszBeginning + strlen(lpszBeginning);
}
AssertSz(((lpszEnd - lpszBeginning + 1) < 20), "This number looks awfully long, please make sure that this is correct")
cchSize = (int)(lpszEnd - lpszBeginning + 2);
if (!MemAlloc((void**)ppszDest, cchSize))
goto exit;
cchSize = (int)(lpszEnd - lpszBeginning + 1);
StrCpyN(*ppszDest, lpszBeginning, cchSize);
// Null terminate it
*(*ppszDest + (lpszEnd - lpszBeginning + 1)) = 0;
hr = S_OK;
exit:
return hr;
}
// --------------------------------------------------------------------------------
// CHTTPMailTransport::_GetTimestampHeader
// --------------------------------------------------------------------------------
HRESULT CHTTPMailTransport::_HrGetTimestampHeader(LPSTR *ppszHeader)
{
HRESULT hr = S_OK;
DWORD dwSize = MAX_PATH;
LPSTR pszHeader = NULL;
Assert(NULL != ppszHeader);
*ppszHeader = NULL;
retry:
if (!MemAlloc((void **)&pszHeader, dwSize))
{
hr = E_OUTOFMEMORY;
goto exit;
}
StrCpyN(pszHeader, c_szXTimestamp, dwSize);
if (!HttpQueryInfo(m_op.hRequest, HTTP_QUERY_RAW_HEADERS | HTTP_QUERY_CUSTOM, pszHeader, &dwSize, NULL))
{
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
hr = E_FAIL;
goto exit;
}
SafeMemFree(pszHeader);
goto retry;
}
*ppszHeader = pszHeader;
pszHeader = NULL;
exit:
SafeMemFree(pszHeader);
return hr;
}
| 32.115525 | 166 | 0.530405 | [
"object"
] |
e1ecdb6f74b79702467f6365eb0904c2065bd297 | 2,371 | cpp | C++ | problems/yosupo/lowest-common-ancestor/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/yosupo/lowest-common-ancestor/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/yosupo/lowest-common-ancestor/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);
struct lca_schieber_vishkin {
int N, timer = 0;
vector<int> preorder, up, I, A, head, depth;
static int lowest_one_bit(int n) { return n & -n; }
static int highest_one_bit(int n) { return n ? 1 << (31 - __builtin_clz(n)) : 0; }
explicit lca_schieber_vishkin(const vector<vector<int>>& tree, int root, int zero = 0)
: N(tree.size()), preorder(N), up(N), I(N), A(N), head(N), depth(N) {
init_dfs1(tree, root, zero);
init_dfs2(tree, root, zero, 0);
}
void init_dfs1(const vector<vector<int>>& tree, int u, int p) {
up[u] = p;
I[u] = preorder[u] = timer++;
for (int v : tree[u]) {
if (v != p) {
depth[v] = depth[u] + 1;
init_dfs1(tree, v, u);
if (lowest_one_bit(I[u]) < lowest_one_bit(I[v])) {
I[u] = I[v];
}
}
}
head[I[u]] = u;
}
void init_dfs2(const vector<vector<int>>& tree, int u, int p, int up) {
A[u] = up | lowest_one_bit(I[u]);
for (int v : tree[u]) {
if (v != p) {
init_dfs2(tree, v, u, A[u]);
}
}
}
int parent(int u) const { return up[u]; }
int enter_into_strip(int u, int hz) const {
if (lowest_one_bit(I[u]) == hz)
return u;
int hw = highest_one_bit(A[u] & (hz - 1));
return parent(head[(I[u] & -hw) | hw]);
}
int lca(int u, int v) const {
int hb = I[u] == I[v] ? lowest_one_bit(I[u]) : highest_one_bit(I[u] ^ I[v]);
int hz = lowest_one_bit(A[u] & A[v] & -hb);
int eu = enter_into_strip(u, hz);
int ev = enter_into_strip(v, hz);
return preorder[eu] < preorder[ev] ? eu : ev;
}
int dist(int u, int v) const { return depth[u] + depth[v] - 2 * depth[lca(u, v)]; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int N, Q;
cin >> N >> Q;
vector<vector<int>> tree(N);
for (int u = 1; u < N; u++) {
int p;
cin >> p;
tree[p].push_back(u);
}
lca_schieber_vishkin lca(tree, 0, -1);
for (int i = 0; i < Q; i++) {
int u, v;
cin >> u >> v;
cout << lca.lca(u, v) << '\n';
}
return 0;
}
| 29.6375 | 90 | 0.485027 | [
"vector"
] |
e1efb7f45eb75848b00819085f358299d2c79585 | 8,375 | cpp | C++ | PIPInterOpCUDA/CUDAVolumeTexture.cpp | lipilian/PlenopticImageProcessing | b732d8611404fa264459c82e7d844d3a5da6b6e5 | [
"MIT"
] | 8 | 2019-07-23T01:11:55.000Z | 2022-01-13T03:50:09.000Z | PIPInterOpCUDA/CUDAVolumeTexture.cpp | lipilian/PlenopticImageProcessing | b732d8611404fa264459c82e7d844d3a5da6b6e5 | [
"MIT"
] | null | null | null | PIPInterOpCUDA/CUDAVolumeTexture.cpp | lipilian/PlenopticImageProcessing | b732d8611404fa264459c82e7d844d3a5da6b6e5 | [
"MIT"
] | 2 | 2020-11-02T18:05:36.000Z | 2021-06-18T10:38:21.000Z | /**
* Copyright 2019 Arne Petersen, Kiel University
*
* 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 "CUDAVolumeTexture.hh"
using namespace PIP;
////////////////////////////////////////////////////////////////////////////////////////////////////////
CCUDAVolumeTexture::CCUDAVolumeTexture(const std::vector<CVImage_sptr>&vecZSlices, const bool flagReadNormalized)
{
if (vecZSlices.size() < 2)
{
throw CRuntimeException("CCUDAVolumeTexture : Volume needs at least 2 images!");
}
// Check validity of (first )image
if (((*vecZSlices.begin())->bytecount() <= 0) ||
(((*vecZSlices.begin())->CvMat().channels() != 1) && ((*vecZSlices.begin())->CvMat().channels() != 2) && ((*vecZSlices.begin())->CvMat().channels() != 4)))
{
throw CRuntimeException("CCUDAVolumeTexture : Invalid (empty or invalid type) CVImage given!");
}
// Try to allocate CUDA device memory and copy image if successfull. Else throw.
__AllocateCUDA(vecZSlices, flagReadNormalized);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
CCUDAVolumeTexture::~CCUDAVolumeTexture()
{
// DTor : all exception must be discarded
try
{
__FreeCUDA();
}
catch (...)
{
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void CCUDAVolumeTexture::__AllocateCUDA(const std::vector<CVImage_sptr>& spZSlices, const bool flagReadNormalized)
{
// Get iterator for first image (all others HAVE to be consistent)
auto itSlices = spZSlices.begin();
// Store input image properties
m_intSliceWidth = (*itSlices)->cols();
m_intSliceHeight = (*itSlices)->rows();
m_intChannelCount = (*itSlices)->CvMat().channels();
m_intDataType = (*itSlices)->type();
m_eImageType = (*itSlices)->descrMetaData.eImageType;
// increased while uploading slices
m_intSliceCount = 0;
// Determine byte count for each channel (channel count 1, 2 or 4)
// All of same size of 0
const int intBytesChannel1 = int((*itSlices)->CvMat().elemSize() / (*itSlices)->CvMat().channels());
const int intBytesChannel2 = int(((*itSlices)->CvMat().channels() > 1) ?
(*itSlices)->CvMat().elemSize() / (*itSlices)->CvMat().channels()
: 0);
const int intBytesChannel34 = int(((*itSlices)->CvMat().channels() == 4) ?
(*itSlices)->CvMat().elemSize() / (*itSlices)->CvMat().channels()
: 0);
// Determine type of data (signed integral, unsigned integral, float)
cudaChannelFormatKind cCFK;
switch ((*itSlices)->CvMat().depth())
{
case CV_32F:
m_dblInvNormalizationFac = 1.0;
cCFK = cudaChannelFormatKindFloat;
break;
case CV_16S:
m_dblInvNormalizationFac = double(std::numeric_limits<int16_t>::max());
cCFK = cudaChannelFormatKindSigned;
break;
case CV_8S:
m_dblInvNormalizationFac = double(std::numeric_limits<int8_t>::max());
cCFK = cudaChannelFormatKindSigned;
break;
case CV_16U:
m_dblInvNormalizationFac = double(std::numeric_limits<uint16_t>::max());
cCFK = cudaChannelFormatKindUnsigned;
break;
case CV_8U:
m_dblInvNormalizationFac = double(std::numeric_limits<uint8_t>::max());
cCFK = cudaChannelFormatKindUnsigned;
break;
default:
throw CRuntimeException("Illegal image storage type.");
}
// Generate channel description in cuda stile
m_descCudaFormat = cudaCreateChannelDesc(8 * intBytesChannel1, 8 * intBytesChannel2,
8 * intBytesChannel34, 8 * intBytesChannel34,
cCFK);
// Allocate cuda device array to bind to texture
cudaExtent dims;
dims.width = m_intSliceWidth;
dims.height = m_intSliceHeight;
dims.depth = spZSlices.size();
cudaMalloc3DArray(&m_dpVolumeArray, &m_descCudaFormat, dims);
if (m_dpVolumeArray == nullptr)
{
throw CRuntimeException(std::string("PIP::CCUDAVolumeTexture: CUDA 3D malloc returned nullptr."));
}
cudaError_t e;
if ((e = cudaGetLastError()) != 0)
{
m_dpVolumeArray = nullptr;
throw CRuntimeException(std::string("PIP::CCUDAVolumeTexture : CUDA 3D malloc error : \"") + std::string(cudaGetErrorString(e)) + std::string("\""));
}
// Copy all slices to cuda device array
cudaMemcpy3DParms copyParams = { 0 };
copyParams.dstArray = m_dpVolumeArray;
copyParams.extent = dims;
copyParams.kind = cudaMemcpyHostToDevice;
copyParams.extent = make_cudaExtent(m_intSliceWidth, m_intSliceHeight, 1);
for (itSlices = spZSlices.begin(); itSlices != spZSlices.end(); ++itSlices)
{
copyParams.dstPos = make_cudaPos(0, 0, itSlices - spZSlices.begin());
copyParams.srcPtr = make_cudaPitchedPtr((*itSlices)->data(), m_intSliceWidth * (intBytesChannel1 + intBytesChannel2 + intBytesChannel34),
m_intSliceWidth, m_intSliceHeight);
cudaMemcpy3D(©Params);
//cudaMemcpyToArray(m_dpVolumeArray, 0, 0, (void *) spImage->data(), spImage->bytecount(), cudaMemcpyHostToDevice);
if ((e = cudaGetLastError()) != 0)
{
m_dpVolumeArray = nullptr;
cudaFreeArray(m_dpVolumeArray);
throw CRuntimeException(std::string("PIP::CCUDAVolumeTexture : CUDA image copy error : \"")
+ std::string(cudaGetErrorString(e)) + std::string("\""));
}
// increase count for copied slices
++m_intSliceCount;
}
// Specify texture resource
struct cudaResourceDesc descResource;
// ../ sorry for that, NVIDIA code example
memset(&descResource, 0, sizeof(cudaResourceDesc));
descResource.resType = cudaResourceTypeArray;
descResource.res.array.array = m_dpVolumeArray;
// Specify texture object parameters
struct cudaTextureDesc descTexture;
// ../ sorry for that, NVIDIA code example
memset(&descTexture, 0, sizeof(descTexture));
descTexture.addressMode[0] = cudaAddressModeClamp;
descTexture.addressMode[1] = cudaAddressModeClamp;
descTexture.filterMode = cudaFilterModeLinear;
descTexture.normalizedCoords = 0;
if (flagReadNormalized)
{
descTexture.readMode = cudaReadModeNormalizedFloat;
}
else
{
descTexture.readMode = cudaReadModeElementType;
}
m_flagReadNormalized = flagReadNormalized;
// Create texture object and get handle
m_texTextureObj = 0;
cudaCreateTextureObject(&m_texTextureObj, &descResource, &descTexture, NULL);
if ((e = cudaGetLastError()) != 0)
{
cudaFreeArray(m_dpVolumeArray);
m_dpVolumeArray = nullptr;
throw CRuntimeException(std::string("PIP::CCUDAVolumeTexture : CUDA texture create error : \"")
+ std::string(cudaGetErrorString(e)) + std::string("\""));
}
}
void CCUDAVolumeTexture::__FreeCUDA()
{
cudaError_t e;
if ((e = cudaGetLastError()) != 0)
{
m_dpVolumeArray = nullptr;
throw CRuntimeException(std::string("PIP::CCUDAImageTexture : __FreeCUDA 1 error : \"")
+ std::string(cudaGetErrorString(e)) + std::string("\""));
}
// Result from error state, successfull CTor ensures !=nullptr
if (m_dpVolumeArray == nullptr) { return; }
// Destroy texture bound to handle
cudaDestroyTextureObject(m_texTextureObj);
if ((e = cudaGetLastError()) != 0)
{
m_dpVolumeArray = nullptr;
throw CRuntimeException(std::string("PIP::CCUDAImageTexture : __FreeCUDA 2 error : \"")
+ std::string(cudaGetErrorString(e)) + std::string("\""));
}
// Free device memory
cudaFreeArray(m_dpVolumeArray);
if ((e = cudaGetLastError()) != 0)
{
m_dpVolumeArray = nullptr;
throw CRuntimeException(std::string("PIP::CCUDAImageTexture : __FreeCUDA 3 error : \"")
+ std::string(cudaGetErrorString(e)) + std::string("\""));
}
m_dpVolumeArray = nullptr;
}
| 36.413043 | 157 | 0.699224 | [
"object",
"vector",
"3d"
] |
e1f414b6edcc765033cf8218573f882b1dcf543a | 4,661 | cpp | C++ | rosbag2_compression/src/rosbag2_compression/zstd_compressor.cpp | csli8192/rosbag2 | 61280b1303fc38956cdf4d1a5f9465c42ab97742 | [
"Apache-2.0"
] | null | null | null | rosbag2_compression/src/rosbag2_compression/zstd_compressor.cpp | csli8192/rosbag2 | 61280b1303fc38956cdf4d1a5f9465c42ab97742 | [
"Apache-2.0"
] | null | null | null | rosbag2_compression/src/rosbag2_compression/zstd_compressor.cpp | csli8192/rosbag2 | 61280b1303fc38956cdf4d1a5f9465c42ab97742 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Amazon.com, Inc. or its affiliates. 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 <algorithm>
#include <chrono>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include "rcpputils/filesystem_helper.hpp"
#include "compression_utils.hpp"
#include "rosbag2_compression/zstd_compressor.hpp"
namespace rosbag2_compression
{
ZstdCompressor::ZstdCompressor()
{
// From the zstd manual: https://facebook.github.io/zstd/zstd_manual.html#Chapter4
// When compressing many times,
// it is recommended to allocate a context just once,
// and re-use it for each successive compression operation.
// This will make workload friendlier for system's memory.
// Note : re-using context is just a speed / resource optimization.
// It doesn't change the compression ratio, which remains identical.
// Note 2 : In multi-threaded environments,
// use one different context per thread for parallel execution.
zstd_context_ = ZSTD_createCCtx();
}
ZstdCompressor::~ZstdCompressor()
{
ZSTD_freeCCtx(zstd_context_);
}
std::string ZstdCompressor::compress_uri(const std::string & uri)
{
const auto start = std::chrono::high_resolution_clock::now();
const auto compressed_uri = uri + "." + get_compression_identifier();
const auto decompressed_buffer = get_input_buffer(uri);
// Allocate based on compression bound and compress
const auto compressed_buffer_length = ZSTD_compressBound(decompressed_buffer.size());
std::vector<uint8_t> compressed_buffer(compressed_buffer_length);
// Perform compression and check.
// compression_result is either the actual compressed size or an error code.
const auto compression_result = ZSTD_compressCCtx(
zstd_context_,
compressed_buffer.data(), compressed_buffer.size(),
decompressed_buffer.data(), decompressed_buffer.size(), kDefaultZstdCompressionLevel);
throw_on_zstd_error(compression_result);
// Compression_buffer_length might be larger than the actual compression size
// Resize compressed_buffer so its size is the actual compression size.
compressed_buffer.resize(compression_result);
write_output_buffer(compressed_buffer, compressed_uri);
const auto end = std::chrono::high_resolution_clock::now();
print_compression_statistics(start, end, decompressed_buffer.size(), compression_result);
return compressed_uri;
}
void ZstdCompressor::compress_serialized_bag_message(
rosbag2_storage::SerializedBagMessage * message)
{
const auto start = std::chrono::high_resolution_clock::now();
// Allocate based on compression bound and compress
const auto maximum_compressed_length =
ZSTD_compressBound(message->serialized_data->buffer_length);
std::vector<uint8_t> compressed_buffer(maximum_compressed_length);
// Perform compression and check.
// compression_result is either the actual compressed size or an error code.
const auto compression_result = ZSTD_compressCCtx(
zstd_context_,
compressed_buffer.data(), maximum_compressed_length,
message->serialized_data->buffer, message->serialized_data->buffer_length,
kDefaultZstdCompressionLevel);
throw_on_zstd_error(compression_result);
// Compression_buffer_length might be larger than the actual compression size
// Resize compressed_buffer so its size is the actual compression size.
compressed_buffer.resize(compression_result);
const auto resize_result =
rcutils_uint8_array_resize(message->serialized_data.get(), compression_result);
throw_on_rcutils_resize_error(resize_result);
// Note that rcutils_uint8_array_resize changes buffer_capacity but not buffer_length, we
// have to do that manually.
message->serialized_data->buffer_length = compression_result;
std::copy(compressed_buffer.begin(), compressed_buffer.end(), message->serialized_data->buffer);
const auto end = std::chrono::high_resolution_clock::now();
print_compression_statistics(start, end, maximum_compressed_length, compression_result);
}
std::string ZstdCompressor::get_compression_identifier() const
{
return kCompressionIdentifier;
}
} // namespace rosbag2_compression
| 39.837607 | 98 | 0.780519 | [
"vector"
] |
e1f9dae3df3f4e454da51cadb871540bcad0d39e | 9,080 | cpp | C++ | DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp | Pcothren/DearPyGui | 0973b50e9de8d377907eec09f1307a2117f76a60 | [
"MIT"
] | 1 | 2020-10-09T01:38:18.000Z | 2020-10-09T01:38:18.000Z | DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp | Pcothren/DearPyGui | 0973b50e9de8d377907eec09f1307a2117f76a60 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/basic/mvColorPicker.cpp | Pcothren/DearPyGui | 0973b50e9de8d377907eec09f1307a2117f76a60 | [
"MIT"
] | null | null | null | #include "mvColorPicker.h"
#include "mvApp.h"
#include <array>
#include "mvItemRegistry.h"
namespace Marvel {
void mvColorPicker::InsertParser(std::map<std::string, mvPythonParser>* parsers)
{
mvPythonParser parser(mvPyDataType::UUID, "Adds an RGB color picker. Click and drag the color square to copy the color and drop on any other color widget to apply. Right Click allows the style of the color picker to be changed.", { "Widgets" });
mvAppItem::AddCommonArgs(parser, (CommonParserArgs)(
MV_PARSER_ARG_ID |
MV_PARSER_ARG_WIDTH |
MV_PARSER_ARG_HEIGHT |
MV_PARSER_ARG_INDENT |
MV_PARSER_ARG_PARENT |
MV_PARSER_ARG_BEFORE |
MV_PARSER_ARG_SOURCE |
MV_PARSER_ARG_CALLBACK |
MV_PARSER_ARG_USER_DATA |
MV_PARSER_ARG_SHOW |
MV_PARSER_ARG_ENABLED |
MV_PARSER_ARG_FILTER |
MV_PARSER_ARG_DROP_CALLBACK |
MV_PARSER_ARG_DRAG_CALLBACK |
MV_PARSER_ARG_PAYLOAD_TYPE |
MV_PARSER_ARG_TRACKED |
MV_PARSER_ARG_POS)
);
parser.addArg<mvPyDataType::IntList>("default_value", mvArgType::POSITIONAL_ARG, "(0, 0, 0, 255)");
parser.addArg<mvPyDataType::Bool>("no_alpha", mvArgType::KEYWORD_ARG, "False", "Ignore Alpha component.");
parser.addArg<mvPyDataType::Bool>("no_picker", mvArgType::KEYWORD_ARG, "False", "Disable picker popup when color square is clicked.");
parser.addArg<mvPyDataType::Bool>("no_side_preview", mvArgType::KEYWORD_ARG, "False", "Disable bigger color preview on right side of the picker, use small colored square preview instead , unless small preview is also hidden.");
parser.addArg<mvPyDataType::Bool>("no_small_preview", mvArgType::KEYWORD_ARG, "False", "Disable colored square preview next to the inputs. (e.g. to show only the inputs). This only displays if the side preview is not shown.");
parser.addArg<mvPyDataType::Bool>("no_inputs", mvArgType::KEYWORD_ARG, "False", "Disable inputs sliders/text widgets. (e.g. to show only the small preview colored square)");
parser.addArg<mvPyDataType::Bool>("no_tooltip", mvArgType::KEYWORD_ARG, "False", "Disable tooltip when hovering the preview.");
parser.addArg<mvPyDataType::Bool>("no_label", mvArgType::KEYWORD_ARG, "False", "Disable display of inline text label.");
parser.addArg<mvPyDataType::Bool>("alpha_bar", mvArgType::KEYWORD_ARG, "False", "Show vertical alpha bar/gradient in picker.");
parser.addArg<mvPyDataType::Bool>("alpha_preview", mvArgType::KEYWORD_ARG, "False", "Display preview as a transparent color over a checkerboard, instead of opaque.");
parser.addArg<mvPyDataType::Bool>("alpha_preview_half", mvArgType::KEYWORD_ARG, "False", "Display half opaque / half checkerboard, instead of opaque.");
parser.addArg<mvPyDataType::Bool>("display_rgb", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex.");
parser.addArg<mvPyDataType::Bool>("display_hsv", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex.");
parser.addArg<mvPyDataType::Bool>("display_hex", mvArgType::KEYWORD_ARG, "False", "Override _display_ type among RGB/HSV/Hex.");
parser.addArg<mvPyDataType::Bool>("uint8", mvArgType::KEYWORD_ARG, "False", "Display values formatted as 0..255.");
parser.addArg<mvPyDataType::Bool>("floats", mvArgType::KEYWORD_ARG, "False", "Display values formatted as 0.0..1.0 floats instead of 0..255 integers.");
parser.addArg<mvPyDataType::Bool>("input_rgb", mvArgType::KEYWORD_ARG, "False", "Input and output data in RGB format.");
parser.addArg<mvPyDataType::Bool>("input_hsv", mvArgType::KEYWORD_ARG, "False", "Input and output data in HSV format.");
parser.addArg<mvPyDataType::Bool>("picker_hue_bar", mvArgType::KEYWORD_ARG, "False", "Bar for Hue, rectangle for Sat/Value.");
parser.addArg<mvPyDataType::Bool>("picker_hue_wheel", mvArgType::KEYWORD_ARG, "False", "Wheel for Hue, triangle for Sat/Value.");
parser.finalize();
parsers->insert({ s_command, parser });
}
mvColorPicker::mvColorPicker(mvUUID uuid)
:
mvColorPtrBase(uuid)
{
}
void mvColorPicker::draw(ImDrawList* drawlist, float x, float y)
{
ScopedID id(m_uuid);
if (!m_enabled) std::copy(m_value->data(), m_value->data() + 4, m_disabled_value);
if (m_3component)
{
if (ImGui::ColorPicker3(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags))
mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_uuid, nullptr, m_user_data);
}
else
{
if (ImGui::ColorPicker4(m_label.c_str(), m_enabled ? m_value->data() : &m_disabled_value[0], m_flags))
mvApp::GetApp()->getCallbackRegistry().addCallback(getCallback(false), m_uuid, nullptr, m_user_data);
}
}
void mvColorPicker::handleSpecificPositionalArgs(PyObject* dict)
{
if (!mvApp::GetApp()->getParsers()[s_command].verifyPositionalArguments(dict))
return;
for (int i = 0; i < PyTuple_Size(dict); i++)
{
PyObject* item = PyTuple_GetItem(dict, i);
switch (i)
{
case 0:
setPyValue(item);
break;
default:
break;
}
}
}
void mvColorPicker::handleSpecificKeywordArgs(PyObject* dict)
{
if (dict == nullptr)
return;
// helpers for bit flipping
auto flagop = [dict](const char* keyword, int flag, int& flags)
{
if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag;
};
auto conflictingflagop = [dict](const std::vector<std::string>& keywords, std::vector<int> flags, int& mflags)
{
for (size_t i = 0; i < keywords.size(); i++)
{
if (PyObject* item = PyDict_GetItemString(dict, keywords[i].c_str()))
{
//turning all conflicting flags false
for (const auto& flag : flags) mflags &= ~flag;
//writing only the first conflicting flag
ToBool(item) ? mflags |= flags[i] : mflags &= ~flags[i];
break;
}
}
};
flagop("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags);
flagop("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags);
flagop("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags);
flagop("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags);
flagop("no_label", ImGuiColorEditFlags_NoLabel, m_flags);
flagop("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags);
flagop("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags);
flagop("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags);
flagop("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags);
flagop("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags);
static std::vector<std::string> AlphaPreviewKeywords{ "alpha_preview", "alpha_preview_half" };
static std::vector<int> AlphaPreviewFlags{ ImGuiColorEditFlags_AlphaPreview, ImGuiColorEditFlags_AlphaPreviewHalf };
static std::vector<std::string> DisplayValueTypeKeywords{ "uint8", "floats" };
static std::vector<int> DisplayValueTypeFlags{ ImGuiColorEditFlags_Uint8, ImGuiColorEditFlags_Float };
static std::vector<std::string> PickerTypeKeywords{ "picker_hue_bar", "picker_hue_wheel" };
static std::vector<int> PickerTypeFlags{ ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags_PickerHueWheel };
static std::vector<std::string> IOTypeKeywords{ "input_rgb", "input_hsv" };
static std::vector<int> IOTypeFlags{ ImGuiColorEditFlags_InputRGB, ImGuiColorEditFlags_InputHSV };
conflictingflagop(AlphaPreviewKeywords, AlphaPreviewFlags, m_flags);
conflictingflagop(DisplayValueTypeKeywords, DisplayValueTypeFlags, m_flags);
conflictingflagop(PickerTypeKeywords, PickerTypeFlags, m_flags);
conflictingflagop(IOTypeKeywords, IOTypeFlags, m_flags);
}
void mvColorPicker::getSpecificConfiguration(PyObject* dict)
{
if (dict == nullptr)
return;
// helper to check and set bit
auto checkbitset = [dict](const char* keyword, int flag, const int& flags)
{
PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag));
};
checkbitset("no_alpha", ImGuiColorEditFlags_NoAlpha, m_flags);
checkbitset("no_small_preview", ImGuiColorEditFlags_NoSmallPreview, m_flags);
checkbitset("no_inputs", ImGuiColorEditFlags_NoInputs, m_flags);
checkbitset("no_tooltip", ImGuiColorEditFlags_NoTooltip, m_flags);
checkbitset("no_label", ImGuiColorEditFlags_NoLabel, m_flags);
checkbitset("no_side_preview", ImGuiColorEditFlags_NoSidePreview, m_flags);
checkbitset("alpha_bar", ImGuiColorEditFlags_AlphaBar, m_flags);
checkbitset("alpha_preview", ImGuiColorEditFlags_AlphaPreview, m_flags);
checkbitset("alpha_preview_half", ImGuiColorEditFlags_AlphaPreviewHalf, m_flags);
checkbitset("display_rgb", ImGuiColorEditFlags_DisplayRGB, m_flags);
checkbitset("display_hsv", ImGuiColorEditFlags_DisplayHSV, m_flags);
checkbitset("display_hex", ImGuiColorEditFlags_DisplayHex, m_flags);
checkbitset("unit8", ImGuiColorEditFlags_Uint8, m_flags);
checkbitset("floats", ImGuiColorEditFlags_Float, m_flags);
checkbitset("picker_hue_bar", ImGuiColorEditFlags_PickerHueBar, m_flags);
checkbitset("picker_hue_wheel", ImGuiColorEditFlags_PickerHueWheel, m_flags);
checkbitset("input_rgb", ImGuiColorEditFlags_InputRGB, m_flags);
checkbitset("input_hsv", ImGuiColorEditFlags_InputHSV, m_flags);
}
} | 47.539267 | 247 | 0.753304 | [
"vector"
] |
e1fb9f848e1c4b83750b4abd940f6c307c48f0de | 6,862 | cc | C++ | content/renderer/media_recorder/h264_encoder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-05-24T13:52:28.000Z | 2021-05-24T13:53:10.000Z | content/renderer/media_recorder/h264_encoder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media_recorder/h264_encoder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-03-12T07:58:10.000Z | 2019-08-31T04:53:58.000Z | // Copyright 2017 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 "content/renderer/media_recorder/h264_encoder.h"
#include <string>
#include "base/bind.h"
#include "base/threading/thread.h"
#include "base/trace_event/trace_event.h"
#include "media/base/video_frame.h"
#include "third_party/openh264/src/codec/api/svc/codec_app_def.h"
#include "third_party/openh264/src/codec/api/svc/codec_def.h"
#include "ui/gfx/geometry/size.h"
using media::VideoFrame;
namespace content {
void H264Encoder::ISVCEncoderDeleter::operator()(ISVCEncoder* codec) {
if (!codec)
return;
const int uninit_ret = codec->Uninitialize();
CHECK_EQ(cmResultSuccess, uninit_ret);
WelsDestroySVCEncoder(codec);
}
// static
void H264Encoder::ShutdownEncoder(std::unique_ptr<base::Thread> encoding_thread,
ScopedISVCEncoderPtr encoder) {
DCHECK(encoding_thread->IsRunning());
encoding_thread->Stop();
// Both |encoding_thread| and |encoder| will be destroyed at end-of-scope.
}
H264Encoder::H264Encoder(
const VideoTrackRecorder::OnEncodedVideoCB& on_encoded_video_callback,
int32_t bits_per_second)
: Encoder(on_encoded_video_callback, bits_per_second) {
DCHECK(encoding_thread_->IsRunning());
}
H264Encoder::~H264Encoder() {
main_task_runner_->PostTask(
FROM_HERE,
base::Bind(&H264Encoder::ShutdownEncoder, base::Passed(&encoding_thread_),
base::Passed(&openh264_encoder_)));
}
void H264Encoder::EncodeOnEncodingTaskRunner(
scoped_refptr<VideoFrame> frame,
base::TimeTicks capture_timestamp) {
TRACE_EVENT0("video", "H264Encoder::EncodeOnEncodingTaskRunner");
DCHECK(encoding_task_runner_->BelongsToCurrentThread());
const gfx::Size frame_size = frame->visible_rect().size();
if (!openh264_encoder_ || configured_size_ != frame_size) {
ConfigureEncoderOnEncodingTaskRunner(frame_size);
first_frame_timestamp_ = capture_timestamp;
}
SSourcePicture picture = {};
picture.iPicWidth = frame_size.width();
picture.iPicHeight = frame_size.height();
picture.iColorFormat = EVideoFormatType::videoFormatI420;
picture.uiTimeStamp =
(capture_timestamp - first_frame_timestamp_).InMilliseconds();
picture.iStride[0] = frame->stride(VideoFrame::kYPlane);
picture.iStride[1] = frame->stride(VideoFrame::kUPlane);
picture.iStride[2] = frame->stride(VideoFrame::kVPlane);
picture.pData[0] = frame->visible_data(VideoFrame::kYPlane);
picture.pData[1] = frame->visible_data(VideoFrame::kUPlane);
picture.pData[2] = frame->visible_data(VideoFrame::kVPlane);
SFrameBSInfo info = {};
if (openh264_encoder_->EncodeFrame(&picture, &info) != cmResultSuccess) {
NOTREACHED() << "OpenH264 encoding failed";
return;
}
const media::WebmMuxer::VideoParameters video_params(frame);
frame = nullptr;
std::unique_ptr<std::string> data(new std::string);
const uint8_t kNALStartCode[4] = {0, 0, 0, 1};
for (int layer = 0; layer < info.iLayerNum; ++layer) {
const SLayerBSInfo& layerInfo = info.sLayerInfo[layer];
// Iterate NAL units making up this layer, noting fragments.
size_t layer_len = 0;
for (int nal = 0; nal < layerInfo.iNalCount; ++nal) {
// The following DCHECKs make sure that the header of each NAL unit is OK.
DCHECK_GE(layerInfo.pNalLengthInByte[nal], 4);
DCHECK_EQ(kNALStartCode[0], layerInfo.pBsBuf[layer_len + 0]);
DCHECK_EQ(kNALStartCode[1], layerInfo.pBsBuf[layer_len + 1]);
DCHECK_EQ(kNALStartCode[2], layerInfo.pBsBuf[layer_len + 2]);
DCHECK_EQ(kNALStartCode[3], layerInfo.pBsBuf[layer_len + 3]);
layer_len += layerInfo.pNalLengthInByte[nal];
}
// Copy the entire layer's data (including NAL start codes).
data->append(reinterpret_cast<char*>(layerInfo.pBsBuf), layer_len);
}
const bool is_key_frame = info.eFrameType == videoFrameTypeIDR;
origin_task_runner_->PostTask(
FROM_HERE, base::Bind(OnFrameEncodeCompleted, on_encoded_video_callback_,
video_params, base::Passed(&data), nullptr,
capture_timestamp, is_key_frame));
}
void H264Encoder::ConfigureEncoderOnEncodingTaskRunner(const gfx::Size& size) {
DCHECK(encoding_task_runner_->BelongsToCurrentThread());
ISVCEncoder* temp_encoder = nullptr;
if (WelsCreateSVCEncoder(&temp_encoder) != 0) {
NOTREACHED() << "Failed to create OpenH264 encoder";
return;
}
openh264_encoder_.reset(temp_encoder);
configured_size_ = size;
#if DCHECK_IS_ON()
int trace_level = WELS_LOG_INFO;
openh264_encoder_->SetOption(ENCODER_OPTION_TRACE_LEVEL, &trace_level);
#endif
SEncParamExt init_params;
openh264_encoder_->GetDefaultParams(&init_params);
init_params.iUsageType = CAMERA_VIDEO_REAL_TIME;
DCHECK_EQ(AUTO_REF_PIC_COUNT, init_params.iNumRefFrame);
DCHECK(!init_params.bSimulcastAVC);
init_params.uiIntraPeriod = 100; // Same as for VpxEncoder.
init_params.iPicWidth = size.width();
init_params.iPicHeight = size.height();
DCHECK_EQ(RC_QUALITY_MODE, init_params.iRCMode);
DCHECK_EQ(0, init_params.iPaddingFlag);
DCHECK_EQ(UNSPECIFIED_BIT_RATE, init_params.iTargetBitrate);
DCHECK_EQ(UNSPECIFIED_BIT_RATE, init_params.iMaxBitrate);
if (bits_per_second_ > 0) {
init_params.iRCMode = RC_BITRATE_MODE;
init_params.iTargetBitrate = bits_per_second_;
} else {
init_params.iRCMode = RC_OFF_MODE;
}
// Threading model: Set to 1 due to https://crbug.com/583348.
init_params.iMultipleThreadIdc = 1;
// TODO(mcasas): consider reducing complexity if there are few CPUs available.
init_params.iComplexityMode = MEDIUM_COMPLEXITY;
DCHECK(!init_params.bEnableDenoise);
DCHECK(init_params.bEnableFrameSkip);
// The base spatial layer 0 is the only one we use.
DCHECK_EQ(1, init_params.iSpatialLayerNum);
init_params.sSpatialLayers[0].iVideoWidth = init_params.iPicWidth;
init_params.sSpatialLayers[0].iVideoHeight = init_params.iPicHeight;
init_params.sSpatialLayers[0].iSpatialBitrate = init_params.iTargetBitrate;
// When uiSliceMode = SM_FIXEDSLCNUM_SLICE, uiSliceNum = 0 means auto design
// it with cpu core number.
// TODO(sprang): Set to 0 when we understand why the rate controller borks
// when uiSliceNum > 1. See https://github.com/cisco/openh264/issues/2591
init_params.sSpatialLayers[0].sSliceArgument.uiSliceNum = 1;
init_params.sSpatialLayers[0].sSliceArgument.uiSliceMode =
SM_FIXEDSLCNUM_SLICE;
if (openh264_encoder_->InitializeExt(&init_params) != cmResultSuccess) {
NOTREACHED() << "Failed to initialize OpenH264 encoder";
return;
}
int pixel_format = EVideoFormatType::videoFormatI420;
openh264_encoder_->SetOption(ENCODER_OPTION_DATAFORMAT, &pixel_format);
}
} // namespace content
| 38.122222 | 80 | 0.741766 | [
"geometry",
"model"
] |
c007d550e75a85aa38c8dd8b43c5fd11fe1d562a | 1,955 | cpp | C++ | libs/openFrameworks/types/ofParameter.cpp | Geistyp/openFrameworks | b7c67103aaf799d1d51fdf287eb17db3e8161920 | [
"MIT"
] | 18 | 2015-01-18T22:34:22.000Z | 2020-09-06T20:30:30.000Z | libs/openFrameworks/types/ofParameter.cpp | Geistyp/openFrameworks | b7c67103aaf799d1d51fdf287eb17db3e8161920 | [
"MIT"
] | 2 | 2015-08-04T00:07:46.000Z | 2017-05-10T15:53:51.000Z | libs/openFrameworks/types/ofParameter.cpp | Geistyp/openFrameworks | b7c67103aaf799d1d51fdf287eb17db3e8161920 | [
"MIT"
] | 10 | 2015-01-18T23:46:10.000Z | 2019-08-25T12:10:04.000Z | #include "ofParameter.h"
#include "ofParameterGroup.h"
ofAbstractParameter::ofAbstractParameter(){
parent = NULL;
}
ofAbstractParameter::~ofAbstractParameter(){
}
string ofAbstractParameter::getName() const {
return "";
}
void ofAbstractParameter::setName(string name) {
}
string ofAbstractParameter::getEscapedName() const{
return escape(getName());
}
string ofAbstractParameter::escape(string str) const{
ofStringReplace(str, " ", "_");
ofStringReplace(str, "<", "_");
ofStringReplace(str, ">", "_");
ofStringReplace(str, "{", "_");
ofStringReplace(str, "}", "_");
ofStringReplace(str, "[", "_");
ofStringReplace(str, "]", "_");
ofStringReplace(str, ",", "_");
ofStringReplace(str, "(", "_");
ofStringReplace(str, ")", "_");
ofStringReplace(str, "/", "_");
ofStringReplace(str, "\\", "_");
return str;
}
string ofAbstractParameter::toString() const {
return "";
}
void ofAbstractParameter::fromString(string str) {
}
string ofAbstractParameter::type() const{
return typeid(*this).name();
}
void ofAbstractParameter::setParent(ofParameterGroup * _parent){
parent = _parent;
}
const ofParameterGroup * ofAbstractParameter::getParent() const{
return parent;
}
ofParameterGroup * ofAbstractParameter::getParent(){
return parent;
}
vector<string> ofAbstractParameter::getGroupHierarchyNames() const{
vector<string> hierarchy;
if(getParent()){
hierarchy = getParent()->getGroupHierarchyNames();
}
hierarchy.push_back(getEscapedName());
return hierarchy;
}
void ofAbstractParameter::notifyParent(){
if(getParent()) getParent()->notifyParameterChanged(*this);
}
void ofAbstractParameter::setSerializable(bool serializable){
}
bool ofAbstractParameter::isSerializable() const{
return true;
}
ostream& operator<<(ostream& os, const ofAbstractParameter& p){
os << p.toString();
return os;
}
istream& operator>>(istream& is, ofAbstractParameter& p){
string str;
is >> str;
p.fromString(str);
return is;
}
| 19.94898 | 67 | 0.715601 | [
"vector"
] |
c00856550bd9b9c9d68c1820fbcf7355b84af115 | 6,087 | cpp | C++ | jsk_topic_tools/src/rosparam_utils.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | 5 | 2016-07-18T02:20:30.000Z | 2022-01-23T13:12:20.000Z | jsk_topic_tools/src/rosparam_utils.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | null | null | null | jsk_topic_tools/src/rosparam_utils.cpp | ShunjiroOsada/jsk_visualization_package | f5305ccb79b41a2efc994a535cb316e7467961de | [
"MIT"
] | 7 | 2015-11-01T13:40:30.000Z | 2020-02-21T12:59:18.000Z | // -*- mode: c++ -*-
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, JSK Lab
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/o2r other materials provided
* with the distribution.
* * Neither the name of the JSK Lab nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include "jsk_topic_tools/rosparam_utils.h"
#include "jsk_topic_tools/log_utils.h"
namespace jsk_topic_tools
{
double getXMLDoubleValue(XmlRpc::XmlRpcValue val)
{
switch(val.getType())
{
case XmlRpc::XmlRpcValue::TypeInt:
{
return (double)((int)val);
}
case XmlRpc::XmlRpcValue::TypeDouble:
{
return (double)val;
}
default:
{
ROS_ERROR_STREAM("the value cannot be converted into double: " << val);
throw std::runtime_error("the value cannot be converted into double");
}
}
}
bool readVectorParameter(ros::NodeHandle& nh,
const std::string& param_name,
std::vector<double>& result)
{
if (nh.hasParam(param_name)) {
XmlRpc::XmlRpcValue v;
nh.param(param_name, v, v);
if (v.getType() == XmlRpc::XmlRpcValue::TypeArray) {
result.resize(v.size());
for (size_t i = 0; i < v.size(); i++) {
result[i] = getXMLDoubleValue(v[i]);
}
return true;
}
else {
return false;
}
}
else {
return false;
}
}
bool readVectorParameter(ros::NodeHandle& nh,
const std::string& param_name,
std::vector<std::vector<double> >& result)
{
if (nh.hasParam(param_name)) {
XmlRpc::XmlRpcValue v_toplevel;
nh.param(param_name, v_toplevel, v_toplevel);
if (v_toplevel.getType() == XmlRpc::XmlRpcValue::TypeArray) {
result.resize(v_toplevel.size());
for (size_t i = 0; i < v_toplevel.size(); i++) {
// ensure v[i] is an array
XmlRpc::XmlRpcValue nested_v = v_toplevel[i];
if (nested_v.getType() == XmlRpc::XmlRpcValue::TypeArray) {
std::vector<double> nested_std_vector(nested_v.size());
for (size_t j = 0; j < nested_v.size(); j++) {
nested_std_vector[j] = getXMLDoubleValue(nested_v[j]);
}
result[i] = nested_std_vector;
}
else {
return false;
}
}
return true;
}
else {
return false;
}
}
else {
return false;
}
}
bool readVectorParameter(ros::NodeHandle& nh,
const std::string& param_name,
std::vector<std::vector<std::string> >& result)
{
if (nh.hasParam(param_name)) {
XmlRpc::XmlRpcValue v_toplevel;
nh.param(param_name, v_toplevel, v_toplevel);
if (v_toplevel.getType() == XmlRpc::XmlRpcValue::TypeArray) {
result.resize(v_toplevel.size());
for (size_t i = 0; i < v_toplevel.size(); i++) {
// ensure v[i] is an array
XmlRpc::XmlRpcValue nested_v = v_toplevel[i];
if (nested_v.getType() == XmlRpc::XmlRpcValue::TypeArray) {
std::vector<std::string> nested_std_vector(nested_v.size());
for (size_t j = 0; j < nested_v.size(); j++) {
if (nested_v[j].getType() == XmlRpc::XmlRpcValue::TypeString) {
nested_std_vector[j] = (std::string)nested_v[j];
}
else {
return false;
}
}
result[i] = nested_std_vector;
}
else {
return false;
}
}
return true;
}
else {
return false;
}
}
else {
return false;
}
}
bool readVectorParameter(ros::NodeHandle& nh,
const std::string& param_name,
std::vector<std::string>& result)
{
if (nh.hasParam(param_name)) {
XmlRpc::XmlRpcValue v;
nh.param(param_name, v, v);
if (v.getType() == XmlRpc::XmlRpcValue::TypeArray) {
result.resize(v.size());
for (size_t i = 0; i < result.size(); i++) {
if (v[i].getType() == XmlRpc::XmlRpcValue::TypeString) {
result[i] = (std::string)v[i];
}
else {
throw std::runtime_error(
"the value cannot be converted into std::string");
}
}
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
| 32.37766 | 77 | 0.565139 | [
"vector"
] |
c00efae33bf4fc48ce517c1325419a4e270a5065 | 1,931 | cpp | C++ | longestcommonsubsequence/longestcommonsubsequence/longestcommonsubsequence.cpp | jpvarbed/practiceproblems | 88770343139efcb478bd734346535df4f166e632 | [
"MIT"
] | null | null | null | longestcommonsubsequence/longestcommonsubsequence/longestcommonsubsequence.cpp | jpvarbed/practiceproblems | 88770343139efcb478bd734346535df4f166e632 | [
"MIT"
] | null | null | null | longestcommonsubsequence/longestcommonsubsequence/longestcommonsubsequence.cpp | jpvarbed/practiceproblems | 88770343139efcb478bd734346535df4f166e632 | [
"MIT"
] | null | null | null | // longestcommonsubsequence.cpp : Defines the entry point for the console application.
//
//Given a string(1 - d array), find if there is any sub - sequence that repeats itself.Here, sub - sequence can be a non - contiguous pattern, with the same relative order.
//[http://www.careercup.com/question?id=5931067269709824]
//Abab ab is repeated
//abba none.A and b follow different order
//Acbdaghfb yes there is a followed by b at two places
//Abcdacb yes a followed by b twice
//My answer :
//Subsequence can be found with dynamic programming.
//Find longest subsequence starting with each letter.
//For strings a, b if a[i] == b[j]
//Then m[i][j] = max(1 + M[i - 1][j - 1], M[i - 1][j], m[i][j - 1]
// Otherwise:
//M[i][j] = max(m[i - 1][j], m[i][j - 1])
//Max is then m[len(a) - 1, len(b) - 1]
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int findSub(const string& str)
{
size_t size = str.size();
vector<vector<int>> lookup(str.size(), vector<int>(str.size(), 0));
for (size_t i = 0; i < size; i++)
{
if (str[0] == str[i])
{
lookup[0][i] = 1;
}
}
for (size_t i = 0; i < size; i++)
{
if (str[0] == str[i])
{
lookup[i][0] = 1;
}
}
for (size_t i = 1; i < size; i++)
{
for (size_t j = 1; j < size; j++)
{
if (i != j && str[i] == str[j])
{
lookup[i][j] = max(max(1 + lookup[i - 1][j - 1],
lookup[i][j - 1]),
lookup[i - 1][j]);
}
else
{
lookup[i][j] = max(lookup[i - 1][j], lookup[i][j - 1]);
}
}
}
return lookup[size - 1][size - 1];
}
int main() {
struct TestRef {
string in;
int expected;
};
TestRef refs[] =
{
{ "abab", 2 },
{ "abba", 1 },
{ "acbdaghfb", 2 },
{ "abcdacb", 2 }
};
for (auto const& ref : refs)
{
if (ref.expected != findSub(ref.in))
{
cout << "wrong for " << ref.in << endl;
}
else
{
cout << "correct for " << ref.in << endl;
}
}
return 0;
} | 20.763441 | 172 | 0.567064 | [
"vector"
] |
c0116426baa5e2759b0dc3411dde1ba875999a8e | 3,747 | cpp | C++ | src/main/fst/fst/test/dotest.cpp | apollo008/orchid-fst | a4db8e3521aff2f221b47684b5fe7ff05d154055 | [
"Apache-2.0"
] | 9 | 2021-05-12T00:48:48.000Z | 2022-01-05T07:25:27.000Z | src/main/fst/fst/test/dotest.cpp | liuyujing89/orchid-fst-1 | 45fa506348b01848c9dc5bc95901790441aa9b13 | [
"Apache-2.0"
] | 2 | 2021-05-17T09:20:49.000Z | 2021-05-24T07:53:37.000Z | src/main/fst/fst/test/dotest.cpp | liuyujing89/orchid-fst-1 | 45fa506348b01848c9dc5bc95901790441aa9b13 | [
"Apache-2.0"
] | 2 | 2021-05-12T05:15:57.000Z | 2021-05-16T13:53:27.000Z | /*********************************************************************************
*Copyright(C),dingbinthu@163.com
*All rights reserved.
*
*FileName: dotest.cpp
*Author: dingbinthu@163.com
*Version: 1.0
*Date: 2/23/21
*Description:
**********************************************************************************/
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/CompilerOutputter.h>
#include <tulip/TLogDefine.h>
#include <string>
#include <cstring>
#include "fst/test/test.h"
#include "common/util/hash_util.h"
using namespace std;
using namespace CppUnit;
COMMON_USE_NAMESPACE;
class LogFlusherListener : public CppUnit::TestListener
{
virtual void addFailure (const TestFailure &failure)
{
tulip::TLogger::s_GetRootLogger()->s_FlushAll();
usleep(200000);
}
};
void recursivePrintTestName(Test *test, size_t indentLevel = 0)
{
if (test == NULL)
return;
for (size_t i = 0; i < indentLevel; i++) {
std::cout << " ";
}
std::cout << test->getName() << std::endl;
int testCount = test->getChildTestCount();
for (int i = 0; i < testCount; ++i) {
Test *childTest = test->getChildTestAt(i);
recursivePrintTestName(childTest, indentLevel+1);
}
}
static bool matchTestNameFilter(const std::string &testName, int argc, char **argv)
{
for (int iArg = 1; iArg < argc; ++iArg) {
const char *testNamePattern = argv[iArg];
if (testName.find(testNamePattern) != std::string::npos) {
return true;
}
}
return false;
}
void recursiveGetTests(Test *test, std::vector<Test *> &tests, int argc, char **argv)
{
if (test == NULL)
return;
bool matched = matchTestNameFilter(test->getName(), argc, argv);
if (matched) {
tests.push_back(test);
return;
}
int testCount = test->getChildTestCount();
for (int i = 0; i < testCount; ++i) {
Test *childTest = test->getChildTestAt(i);
recursiveGetTests(childTest, tests, argc, argv);
}
}
int main( int argc, char **argv)
{
Random<uint32_t>::seedDefault();
Random<uint64_t>::seedDefault();
TLOG_CONFIG(DOTEST_LOGGER_CONF);
LogFlusherListener logFlusherListener;
TextUi::TestRunner runner;
runner.setOutputter(new CompilerOutputter(&runner.result(), std::cerr));
runner.eventManager().addListener(&logFlusherListener);
TestFactoryRegistry ®istry = TestFactoryRegistry::getRegistry();
if (argc == 1) { // run all tests by default
runner.addTest( registry.makeTest() );
}
else if (argc == 2 && 0 == strcmp(argv[1], "-l")) { // list all tests and exit
Test *test = registry.makeTest();
recursivePrintTestName(test);
delete test;
TLOG_LOG_FLUSH();
TLOG_LOG_SHUTDOWN();
return 0;
}
else { // filter tests by names
Test *test = registry.makeTest();
runner.addTest(test);
std::vector<Test*> tests;
recursiveGetTests(test, tests, argc, argv);
bool ok = true;
for (std::vector<Test*>::const_iterator it = tests.begin(); it != tests.end(); ++it) {
Test *childTest = *it;;
std::cout << "Will run test " << childTest->getName() << std::endl;
ok = runner.run(childTest->getName(), false);
if (!ok) {
break;
}
}
TLOG_LOG_FLUSH();
TLOG_LOG_SHUTDOWN();
return ok ? 0 : 1;
}
bool ok = runner.run("", false);
TLOG_LOG_FLUSH();
TLOG_LOG_SHUTDOWN();
return ok ? 0 : 1;
}
| 29.738095 | 94 | 0.581265 | [
"vector"
] |
84fc7ba0d82e650cf4b21662f32f5fb919238d0b | 33,845 | cc | C++ | onnx/defs/sequence/defs.cc | justinchuby/onnx | 805ae1e634697e37b43701e585c9c253a29ce076 | [
"Apache-2.0"
] | null | null | null | onnx/defs/sequence/defs.cc | justinchuby/onnx | 805ae1e634697e37b43701e585c9c253a29ce076 | [
"Apache-2.0"
] | null | null | null | onnx/defs/sequence/defs.cc | justinchuby/onnx | 805ae1e634697e37b43701e585c9c253a29ce076 | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
#include "onnx/defs/function.h"
#include "onnx/defs/schema.h"
#include <algorithm>
#include <numeric>
namespace ONNX_NAMESPACE {
static const char* SequenceEmpty_ver11_doc = R"DOC(
Construct an empty tensor sequence, with given data type.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceEmpty,
11,
OpSchema()
.SetDoc(SequenceEmpty_ver11_doc)
.Attr(
"dtype",
"(Optional) The data type of the tensors in the output sequence. "
"The default type is 'float'.",
AttributeProto::INT,
OPTIONAL_VALUE)
.Output(0, "output", "Empty sequence.", "S")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain output types to any tensor type.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto* attr_proto = ctx.getAttribute("dtype");
auto elem_type = TensorProto::FLOAT;
if (nullptr != attr_proto) {
if (!attr_proto->has_i()) {
fail_type_inference("Attribute dtype should be of integer type and specify a type.");
}
auto attr_value = attr_proto->i();
elem_type = static_cast<TensorProto_DataType>(attr_value);
}
ctx.getOutputType(0)->mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type()->set_elem_type(
elem_type);
}));
static const char* SequenceConstruct_ver11_doc = R"DOC(
Construct a tensor sequence containing 'inputs' tensors.
All tensors in 'inputs' must have the same data type.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceConstruct,
11,
OpSchema()
.SetDoc(SequenceConstruct_ver11_doc)
.Input(0, "inputs", "Tensors.", "T", OpSchema::Variadic)
.Output(0, "output_sequence", "Sequence enclosing the input tensors.", "S")
.TypeConstraint("T", OpSchema::all_tensor_types(), "Constrain input types to any tensor type.")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain output types to any tensor type.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const size_t numInputs = ctx.getNumInputs();
if (numInputs < 1) {
fail_type_inference("SequenceConstruct is expected to have at least 1 input.");
}
std::vector<int> input_elem_types;
input_elem_types.reserve(numInputs);
for (size_t i = 0; i < numInputs; ++i) {
auto input_type = ctx.getInputType(i);
if (nullptr == input_type) {
fail_type_inference("Input type for input at index ", i, " is null. Type info is expected.");
}
input_elem_types.emplace_back(input_type->tensor_type().elem_type());
}
if (std::adjacent_find(input_elem_types.begin(), input_elem_types.end(), std::not_equal_to<int>()) !=
input_elem_types.end()) {
// not all input elem types are the same.
fail_type_inference("Element type of inputs are expected to be the same.");
}
auto* output_tensor_type =
ctx.getOutputType(0)->mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type();
output_tensor_type->set_elem_type(static_cast<TensorProto_DataType>(input_elem_types[0]));
if (!hasNInputShapes(ctx, static_cast<int>(numInputs))) {
return;
}
*(output_tensor_type->mutable_shape()) = ctx.getInputType(0)->tensor_type().shape();
for (size_t i = 1; i < numInputs; ++i) {
const auto& input_shape = ctx.getInputType(i)->tensor_type().shape();
UnionShapeInfo(input_shape, *output_tensor_type);
}
}));
static const char* SequenceInsert_ver11_doc = R"DOC(
Outputs a tensor sequence that inserts 'tensor' into 'input_sequence' at 'position'.
'tensor' must have the same data type as 'input_sequence'.
Accepted range for 'position' is in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'.
Negative value means counting positions from the back.
'position' is optional, by default it inserts 'tensor' to the back of 'input_sequence'.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceInsert,
11,
OpSchema()
.SetDoc(SequenceInsert_ver11_doc)
.Input(0, "input_sequence", "Input sequence.", "S")
.Input(1, "tensor", "Input tensor to be inserted into the input sequence.", "T")
.Input(
2,
"position",
"Position in the sequence where the new tensor is inserted. "
"It is optional and default is to insert to the back of the sequence. "
"Negative value means counting positions from the back. "
"Accepted range in `[-n, n]`, "
"where `n` is the number of tensors in 'input_sequence'. "
"It is an error if any of the index values are out of bounds. "
"It must be a scalar(tensor of empty shape).",
"I",
OpSchema::Optional)
.Output(0, "output_sequence", "Output sequence that contains the inserted tensor at given position.", "S")
.TypeConstraint("T", OpSchema::all_tensor_types(), "Constrain to any tensor type.")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.")
.TypeConstraint(
"I",
{"tensor(int32)", "tensor(int64)"},
"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto input0_type = ctx.getInputType(0);
const auto input1_type = ctx.getInputType(1);
if (nullptr == input0_type || nullptr == input1_type) {
fail_type_inference("Input Sequence and Tensor are expected to have type info. Current type is null.");
}
const auto seq_elem_type = input0_type->sequence_type().elem_type().tensor_type().elem_type();
const auto tensor_elem_type = input1_type->tensor_type().elem_type();
if (seq_elem_type != tensor_elem_type) {
fail_type_inference(
"Input Sequence and Tensor are expected to have the same elem type. Sequence=",
seq_elem_type,
" Tensor=",
tensor_elem_type);
}
auto* output_tensor_type =
ctx.getOutputType(0)->mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type();
output_tensor_type->set_elem_type(seq_elem_type);
if (!hasNInputShapes(ctx, 2)) {
return;
}
*(output_tensor_type->mutable_shape()) = input0_type->sequence_type().elem_type().tensor_type().shape();
UnionShapeInfo(input1_type->tensor_type().shape(), *output_tensor_type);
}));
static const char* SequenceAt_ver11_doc = R"DOC(
Outputs a tensor copy from the tensor at 'position' in 'input_sequence'.
Accepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.
Negative value means counting positions from the back.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceAt,
11,
OpSchema()
.SetDoc(SequenceAt_ver11_doc)
.Input(0, "input_sequence", "Input sequence.", "S")
.Input(
1,
"position",
"Position of the tensor in the sequence. "
"Negative value means counting positions from the back. "
"Accepted range in `[-n, n - 1]`, "
"where `n` is the number of tensors in 'input_sequence'. "
"It is an error if any of the index values are out of bounds. "
"It must be a scalar(tensor of empty shape).",
"I")
.Output(0, "tensor", "Output tensor at the specified position in the input sequence.", "T")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.")
.TypeConstraint("T", OpSchema::all_tensor_types(), "Constrain to any tensor type.")
.TypeConstraint(
"I",
{"tensor(int32)", "tensor(int64)"},
"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto input0_type = ctx.getInputType(0);
if (nullptr == input0_type) {
fail_type_inference("Input type for input at index 0 is null. Type info is expected.")
}
ctx.getOutputType(0)->CopyFrom(input0_type->sequence_type().elem_type());
}));
static const char* SequenceErase_ver11_doc = R"DOC(
Outputs a tensor sequence that removes the tensor at 'position' from 'input_sequence'.
Accepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.
Negative value means counting positions from the back.
'position' is optional, by default it erases the last tensor from 'input_sequence'.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceErase,
11,
OpSchema()
.SetDoc(SequenceErase_ver11_doc)
.Input(0, "input_sequence", "Input sequence.", "S")
.Input(
1,
"position",
"Position of the tensor in the sequence. "
"Negative value means counting positions from the back. "
"Accepted range in `[-n, n - 1]`, "
"where `n` is the number of tensors in 'input_sequence'. "
"It is an error if any of the index values are out of bounds. "
"It must be a scalar(tensor of empty shape).",
"I",
OpSchema::Optional)
.Output(0, "output_sequence", "Output sequence that has the tensor at the specified position removed.", "S")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.")
.TypeConstraint(
"I",
{"tensor(int32)", "tensor(int64)"},
"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto input0_type = ctx.getInputType(0);
if (nullptr == input0_type) {
fail_type_inference("Input type for input at index 0 is null. Type info is expected.")
}
ctx.getOutputType(0)->CopyFrom(*input0_type);
}));
static const char* SequenceLength_ver11_doc = R"DOC(
Produces a scalar(tensor of empty shape) containing the number of tensors in 'input_sequence'.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SequenceLength,
11,
OpSchema()
.SetDoc(SequenceLength_ver11_doc)
.Input(0, "input_sequence", "Input sequence.", "S")
.Output(0, "length", "Length of input sequence. It must be a scalar(tensor of empty shape).", "I")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.")
.TypeConstraint(
"I",
{"tensor(int64)"},
"Constrain output to integral tensor. It must be a scalar(tensor of empty shape).")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
auto* output_tensor_type = ctx.getOutputType(0)->mutable_tensor_type();
output_tensor_type->set_elem_type(TensorProto::INT64);
output_tensor_type->mutable_shape()->Clear();
}));
// Updated operators that consume/produce sequence of tensors.
static const char* SplitToSequence_ver11_doc =
R"DOC(Split a tensor into a sequence of tensors, along the specified
'axis'. Lengths of the parts can be specified using argument 'split'.
'split' must contain only positive numbers.
'split' is either a scalar (tensor of empty shape), or a 1-D tensor.
If 'split' is a scalar, then 'input' will be split into equally sized chunks(if possible).
Last chunk will be smaller if the 'input' size along the given axis 'axis' is not divisible
by 'split'.
Otherwise, the tensor is split into 'size(split)' chunks, with lengths of the parts on 'axis'
specified in 'split'. In this scenario, the sum of entries in 'split' must be equal to the
dimension size of input tensor on 'axis'.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
SplitToSequence,
11,
OpSchema()
.Input(0, "input", "The tensor to split", "T")
.Input(
1,
"split",
"Length of each output. "
"It can be either a scalar(tensor of empty shape), or a 1-D tensor. All values must be >= 0. ",
"I",
OpSchema::Optional)
.Output(0, "output_sequence", "One or more outputs forming a sequence of tensors after splitting", "S")
.TypeConstraint("T", OpSchema::all_tensor_types(), "Constrain input types to all tensor types.")
.TypeConstraint("I", {"tensor(int32)", "tensor(int64)"}, "Constrain split size to integral tensor.")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain output types to all tensor types.")
.Attr(
"axis",
"Which axis to split on. "
"A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1].",
AttributeProto::INT,
static_cast<int64_t>(0))
.Attr(
"keepdims",
"Keep the split dimension or not. Default 1, which means we keep split dimension. "
"If input 'split' is specified, this attribute is ignored.",
AttributeProto::INT,
static_cast<int64_t>(1))
.SetDoc(SplitToSequence_ver11_doc)
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto input0_type = ctx.getInputType(0);
if (nullptr == input0_type) {
fail_type_inference("Input type for input at index 0 is null. Type info is expected.")
}
ctx.getOutputType(0)->mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type()->set_elem_type(
input0_type->tensor_type().elem_type());
if (!hasInputShape(ctx, 0)) {
return;
}
const auto& inputShape = input0_type->tensor_type().shape();
int r = inputShape.dim_size();
int axis = static_cast<int>(getAttribute(ctx, "axis", 0));
if (axis < -r || axis > r - 1) {
fail_shape_inference("Invalid value of attribute 'axis'. Rank=", r, " Value=", axis);
}
if (axis < 0) {
axis += r;
}
size_t num_inputs = ctx.getNumInputs();
int64_t splitSize = 1;
int64_t keepdims = 1;
if (num_inputs == 1) {
// input split is omitted, default to split by 1.
auto attr_proto = ctx.getAttribute("keepdims");
if (attr_proto) {
keepdims = attr_proto->i();
}
} else {
splitSize = [&]() -> int64_t {
// Need input split shape info and initializer data to infer split sizes.
if (!hasInputShape(ctx, 1)) {
return -1;
}
const TensorProto* splitInitializer = ctx.getInputData(1);
if (nullptr == splitInitializer || !splitInitializer->has_data_type()) {
return -1;
}
std::vector<int64_t> splitSizes;
if (splitInitializer->data_type() == TensorProto::INT64) {
const auto& data = ParseData<int64_t>(splitInitializer);
splitSizes.insert(splitSizes.end(), data.begin(), data.end());
} else if (splitInitializer->data_type() == TensorProto::INT32) {
const auto& data = ParseData<int32_t>(splitInitializer);
splitSizes.insert(splitSizes.end(), data.begin(), data.end());
} else {
// unaccepted data type
fail_shape_inference("Only supports `int32_t` or `int64_t` inputs for split");
}
if (splitSizes.size() == 0) {
fail_shape_inference("Input 'split' can not be empty.");
}
const auto& splitDim = inputShape.dim(axis);
if (!splitDim.has_dim_value()) {
// Unable to verify nor infer exact split dimension size.
return -1;
}
int64_t splitDimValue = splitDim.dim_value();
const auto& splitShape = getInputShape(ctx, 1);
if (splitShape.dim_size() == 0) {
// split is scalar
if (splitDimValue % splitSizes[0] == 0) {
// all output chunks have the same shape, assign that to output sequence shape.
return splitSizes[0];
}
return -1;
} else {
// split is 1-D tensor
int64_t splitSizesSum = std::accumulate(splitSizes.begin(), splitSizes.end(), (int64_t)0);
if (splitDimValue != splitSizesSum) {
fail_shape_inference(
"Sum of split values not equal to 'input' dim size on 'axis'. 'axis' dim size=",
splitDimValue,
" sum of split values=",
splitSizesSum);
}
if (std::adjacent_find(splitSizes.begin(), splitSizes.end(), std::not_equal_to<int64_t>()) ==
splitSizes.end()) {
// all split sizes are the same.
return splitSizes[0];
}
return -1;
}
}();
}
if (keepdims) {
auto* outputShape = ctx.getOutputType(0)
->mutable_sequence_type()
->mutable_elem_type()
->mutable_tensor_type()
->mutable_shape();
*outputShape = inputShape;
auto* dim = outputShape->mutable_dim(axis);
// Tensors in sequence could not have different shapes explicitly.
// Only assign dim_value when all chunks have the same shape.
if (splitSize > 0) {
dim->set_dim_value(splitSize);
} else {
dim->clear_dim_value();
dim->clear_dim_param();
}
} else {
TensorShapeProto* outputShape = ctx.getOutputType(0)
->mutable_sequence_type()
->mutable_elem_type()
->mutable_tensor_type()
->mutable_shape();
for (int i = 0; i < inputShape.dim_size(); ++i) {
if (i != axis) {
auto* dim = outputShape->add_dim();
dim->CopyFrom(inputShape.dim(i));
}
}
}
}));
static const char* ConcatFromSequence_ver11_doc = R"DOC(
Concatenate a sequence of tensors into a single tensor.
All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.
By default 'new_axis' is 0, the behavior is similar to numpy.concatenate.
When 'new_axis' is 1, the behavior is similar to numpy.stack.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
ConcatFromSequence,
11,
OpSchema()
.Attr(
"axis",
"Which axis to concat on. Accepted range in `[-r, r - 1]`, "
"where `r` is the rank of input tensors. "
"When `new_axis` is 1, accepted range is `[-r - 1, r]`. ",
AttributeProto::INT)
.Attr(
"new_axis",
"Insert and concatenate on a new axis or not, "
"default 0 means do not insert new axis.",
AttributeProto::INT,
static_cast<int64_t>(0))
.SetDoc(ConcatFromSequence_ver11_doc)
.Input(0, "input_sequence", "Sequence of tensors for concatenation", "S")
.Output(0, "concat_result", "Concatenated tensor", "T")
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain input types to any tensor type.")
.TypeConstraint("T", OpSchema::all_tensor_types(), "Constrain output types to any tensor type.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
const auto input0_type = ctx.getInputType(0);
if (nullptr == input0_type) {
fail_type_inference("Input type for input at index 0 is null. Type info is expected.")
}
auto elem_type = input0_type->sequence_type().elem_type().tensor_type().elem_type();
ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(elem_type);
if (!hasInputShape(ctx, 0)) {
return;
}
auto axis_attr = ctx.getAttribute("axis");
if (!axis_attr) {
fail_shape_inference("Required attribute axis is missing");
}
int axis = static_cast<int>(axis_attr->i());
int new_axis = 0;
auto new_axis_attr = ctx.getAttribute("new_axis");
if (new_axis_attr) {
new_axis = static_cast<int>(new_axis_attr->i());
}
const auto& input_shape = ctx.getInputType(0)->sequence_type().elem_type().tensor_type().shape();
auto rank = input_shape.dim_size();
if (1 != new_axis && 0 != new_axis) {
fail_shape_inference("new_axis must be either 0 or 1");
}
auto upper_bound = 1 == new_axis ? rank : rank - 1;
auto lower_bound = 1 == new_axis ? -rank - 1 : -rank;
if (axis < lower_bound || axis > upper_bound) {
fail_shape_inference(
"Invalid value of attribute 'axis'. Accepted range=[",
lower_bound,
", ",
upper_bound,
"], Value=",
axis);
}
if (axis < 0) {
axis += (upper_bound + 1);
}
auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
for (int i = 0; i <= upper_bound; ++i) {
output_shape->add_dim();
if (i != axis) {
output_shape->mutable_dim(i)->CopyFrom(input_shape.dim((i > axis && new_axis) ? i - 1 : i));
}
}
}));
static const char* SequenceMap_ver17_doc = R"DOC(
Applies a sub-graph to each sample in the input sequence(s).
Inputs can be either tensors or sequences, with the exception of the first input which must
be a sequence. The length of the first input sequence will determine the number of samples in the
outputs. Any other sequence inputs should have the same number of samples. The number of inputs
and outputs, should match the one of the subgraph.
For each i-th element in the output, a sample will be extracted from the input sequence(s) at
the i-th position and the sub-graph will be applied to it.
The outputs will contain the outputs of the sub-graph for each sample, in the same order as in
the input.
This operator assumes that processing each sample is independent and could executed in parallel
or in any order. Users cannot expect any specific ordering in which each subgraph is computed.)DOC";
void SequenceMapInferenceFunction(InferenceContext& ctx) {
auto num_inputs = ctx.getNumInputs();
assert(num_inputs > 0);
auto num_outputs = ctx.getNumOutputs();
assert(num_outputs > 0);
std::vector<TypeProto> tmp_type_protos(num_inputs);
std::vector<const TypeProto*> subgraph_input_types;
subgraph_input_types.reserve(num_inputs);
for (size_t inputIndex = 0; inputIndex < num_inputs; inputIndex++) {
auto input_type = ctx.getInputType(inputIndex);
if (input_type == nullptr) {
fail_type_inference("Input ", inputIndex, " expected to have type info");
}
if (input_type->value_case() == TypeProto::kSequenceType) {
tmp_type_protos[inputIndex].CopyFrom(input_type->sequence_type().elem_type());
subgraph_input_types.push_back(&tmp_type_protos[inputIndex]);
} else {
if (inputIndex == 0)
fail_type_inference("Input ", inputIndex, " expected to be a sequence type");
subgraph_input_types.push_back(input_type);
}
}
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (!graphInferencer)
fail_type_inference("Graph attribute inferencer for \"body\" not available");
std::vector<const TensorProto*> input_data(num_inputs, nullptr);
std::vector<const TypeProto*> subgraph_output_types =
graphInferencer->doInferencing(subgraph_input_types, input_data);
// if empty(), assume inferencing was skipped
if (!subgraph_output_types.empty()) {
if (subgraph_output_types.size() != num_outputs) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
subgraph_output_types.size(),
" outputs. Expected ",
num_outputs);
}
for (size_t outputIndex = 0; outputIndex < num_outputs; outputIndex++) {
auto* subgraph_output_type = subgraph_output_types[outputIndex];
ctx.getOutputType(outputIndex)->mutable_sequence_type()->mutable_elem_type()->CopyFrom(*subgraph_output_type);
}
}
}
bool BuildSequenceMapBodyFunc(
const FunctionBodyBuildContext& ctx,
const OpSchema& schema,
FunctionProto& functionProto) {
schema.BuildFunction(functionProto);
// variadic input/outputs will be expanded
functionProto.clear_input();
functionProto.clear_output();
auto body_attr = ctx.getAttribute("body");
if (!body_attr || !body_attr->has_g())
ONNX_THROW_EX(std::invalid_argument("Invalid ``body`` argument. Expected a graph"));
const GraphProto& body = body_attr->g();
auto g_inputs = body.input();
int ninputs = g_inputs.size();
if (ninputs < 1)
ONNX_THROW_EX(std::invalid_argument("Expected 1 or more inputs."));
auto g_outputs = body.output();
int noutputs = g_outputs.size();
if (noutputs < 1)
ONNX_THROW_EX(std::invalid_argument("Expected 1 or more outputs."));
if (!ctx.hasInput(0))
ONNX_THROW_EX(std::invalid_argument(MakeString("Input 0 expected but not provided")));
const auto* first_input_type = ctx.getInputType(0);
assert(first_input_type);
if (!first_input_type->has_sequence_type())
ONNX_THROW_EX(std::invalid_argument("Expected a sequence type for input 0"));
auto schema_inputs = schema.inputs();
auto input_0_name = schema_inputs[0].GetName();
auto input_1_name = schema_inputs[1].GetName(); // variadic input
*functionProto.add_input() = input_0_name;
for (int i = 1; i < ninputs; i++) {
if (!ctx.hasInput(i))
ONNX_THROW_EX(std::invalid_argument(MakeString("Input ", i, " expected but not provided")));
*functionProto.add_input() = MakeString(input_1_name, "_", i);
}
auto schema_outputs = schema.outputs();
auto output_0_name = schema_outputs[0].GetName();
for (int i = 0; i < noutputs; i++) {
if (!ctx.hasOutput(i))
ONNX_THROW_EX(std::invalid_argument(MakeString("Output ", i, " expected but not provided")));
*functionProto.add_output() = MakeString(output_0_name, "_", i);
}
// Loop body subgraph
std::string loopbody_graph_name("SequenceMap_loop_body");
GraphProto loopbody_graph;
loopbody_graph.set_name(loopbody_graph_name);
{
TypeProto int64_type;
int64_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT64);
int64_type.mutable_tensor_type()->mutable_shape()->Clear();
TypeProto bool_type;
bool_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_BOOL);
bool_type.mutable_tensor_type()->mutable_shape()->Clear();
ValueInfoProto iter_count;
std::string iter_count_name = MakeString(loopbody_graph_name, "_itercount");
iter_count.set_name(iter_count_name);
*iter_count.mutable_type() = int64_type;
*loopbody_graph.add_input() = iter_count;
ValueInfoProto cond_in;
std::string cond_in_name = MakeString(loopbody_graph_name, "_cond_in");
cond_in.set_name(cond_in_name);
*cond_in.mutable_type() = bool_type;
*loopbody_graph.add_input() = cond_in;
ValueInfoProto cond_out;
std::string cond_out_name = MakeString(loopbody_graph_name, "_cond_out");
cond_out.set_name(cond_out_name);
*cond_out.mutable_type() = bool_type;
*loopbody_graph.add_output() = cond_out;
NodeProto cond_identity;
cond_identity.set_domain(ONNX_DOMAIN);
cond_identity.set_op_type("Identity");
cond_identity.add_input(cond_in_name);
cond_identity.add_output(cond_out_name);
*loopbody_graph.add_node() = cond_identity;
for (int inputIndex = 0; inputIndex < ninputs; inputIndex++) {
const auto* input_type = ctx.getInputType(inputIndex);
if (input_type && input_type->has_sequence_type()) {
// If it's a sequence input, extract ``iter_count`` element
NodeProto seq_at_node;
seq_at_node.set_domain(ONNX_DOMAIN);
seq_at_node.set_op_type("SequenceAt");
seq_at_node.add_input(functionProto.input(inputIndex));
seq_at_node.add_input(iter_count_name);
seq_at_node.add_output(g_inputs[inputIndex].name());
*loopbody_graph.add_node() = seq_at_node;
} else {
// If not a sequence, simply connect
NodeProto identity;
identity.set_domain(ONNX_DOMAIN);
identity.set_op_type("Identity");
identity.add_input(functionProto.input(inputIndex));
identity.add_output(g_inputs[inputIndex].name());
*loopbody_graph.add_node() = identity;
}
}
for (const auto& item : body.node())
*loopbody_graph.add_node() = item;
for (const auto& item : body.value_info())
*loopbody_graph.add_value_info() = item;
for (const auto& item : body.initializer())
*loopbody_graph.add_initializer() = item;
for (const auto& item : body.sparse_initializer())
*loopbody_graph.add_sparse_initializer() = item;
for (int outputIndex = 0; outputIndex < noutputs; outputIndex++) {
const auto& body_out_i = body.output(outputIndex);
assert(body_out_i.type().has_tensor_type());
std::string prefix = MakeString(loopbody_graph_name, "_", body_out_i.name());
std::string loopbody_in_name = MakeString(prefix, "_in");
ValueInfoProto tmp;
*tmp.mutable_type()->mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type() =
body_out_i.type().tensor_type();
tmp.set_name(loopbody_in_name);
*loopbody_graph.add_input() = tmp;
std::string loopbody_out_name = MakeString(prefix, "_out");
tmp.set_name(loopbody_out_name);
*loopbody_graph.add_output() = tmp;
NodeProto seq_insert_node;
seq_insert_node.set_domain(ONNX_DOMAIN);
seq_insert_node.set_op_type("SequenceInsert");
seq_insert_node.add_input(loopbody_in_name);
seq_insert_node.add_input(body_out_i.name());
seq_insert_node.add_output(loopbody_out_name);
*loopbody_graph.add_node() = seq_insert_node;
}
}
std::vector<FunctionBodyHelper::NodeDef> nodes;
// TODO: figure out a way to prevent name collisions?
auto first_input_name = functionProto.input(0);
std::string prefix = MakeString("SequenceMap_", first_input_name);
std::string seqlen = MakeString(prefix, "_seqlen");
nodes.push_back({{seqlen}, "SequenceLength", {first_input_name}});
std::string cond_bool = MakeString(prefix, "_cond");
nodes.push_back(FunctionBodyHelper::Const<bool>(cond_bool, true));
std::vector<std::string> loop_node_inputs = {seqlen, cond_bool};
std::vector<std::string> loop_node_outputs;
for (int outputIndex = 0; outputIndex < noutputs; outputIndex++) {
auto output_name = functionProto.output(outputIndex);
std::string out_prefix = MakeString("SequenceMap_", output_name);
std::string seqempty_name = MakeString(out_prefix, "_seqempty");
int64_t dtype = g_outputs[outputIndex].type().tensor_type().elem_type();
nodes.push_back({{seqempty_name}, "SequenceEmpty", {}, {MakeAttribute("dtype", dtype)}});
loop_node_inputs.push_back(seqempty_name);
loop_node_outputs.push_back(output_name);
}
nodes.push_back({loop_node_outputs, "Loop", loop_node_inputs, {MakeAttribute("body", loopbody_graph)}});
auto func_nodes = FunctionBodyHelper::BuildNodes(nodes);
for (const auto& node : func_nodes) {
auto new_node = functionProto.add_node();
new_node->CopyFrom(node);
}
return true;
}
ONNX_OPERATOR_SET_SCHEMA(
SequenceMap,
17,
OpSchema()
.SetDoc(SequenceMap_ver17_doc)
.Attr(
"body",
"The graph to be run for each sample in the sequence(s). "
"It should have as many inputs and outputs as inputs and "
"outputs to the SequenceMap function.",
AttributeProto::GRAPH)
.Input(0, "input_sequence", "Input sequence.", "S")
.Input(1, "additional_inputs", "Additional inputs to the graph", "V", OpSchema::Variadic, false, 0)
.Output(0, "out_sequence", "Output sequence(s)", "S", OpSchema::Variadic, false)
.TypeConstraint("S", OpSchema::all_tensor_sequence_types(), "Constrain input types to any sequence type.")
.TypeConstraint(
"V",
[]() {
auto t = OpSchema::all_tensor_types();
auto s = OpSchema::all_tensor_sequence_types();
t.insert(t.end(), s.begin(), s.end());
return t;
}(),
"Constrain to any tensor or sequence type.")
.SetContextDependentFunctionBodyBuilder(BuildSequenceMapBodyFunc)
.TypeAndShapeInferenceFunction(SequenceMapInferenceFunction));
} // namespace ONNX_NAMESPACE
| 43.059796 | 116 | 0.627065 | [
"shape",
"vector"
] |
84fd58d30ae6eeac610de536c09a2df1d36e81bc | 5,143 | cpp | C++ | be/src/exec/mysql_scanner.cpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 2 | 2021-08-23T12:20:39.000Z | 2021-09-09T10:20:11.000Z | be/src/exec/mysql_scanner.cpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 3 | 2021-05-07T09:51:56.000Z | 2021-05-22T13:04:03.000Z | be/src/exec/mysql_scanner.cpp | kaiker19/incubator-doris | f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be | [
"Apache-2.0"
] | 1 | 2022-01-12T08:34:49.000Z | 2022-01-12T08:34:49.000Z | // 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 <mysql/mysql.h>
#define __DorisMysql MYSQL
#define __DorisMysqlRes MYSQL_RES
#include "common/logging.h"
#include "mysql_scanner.h"
namespace doris {
MysqlScanner::MysqlScanner(const MysqlScannerParam& param)
: _my_param(param), _my_conn(NULL), _my_result(NULL), _is_open(false), _field_num(0) {}
MysqlScanner::~MysqlScanner() {
if (_my_result) {
mysql_free_result(_my_result);
_my_result = NULL;
}
if (_my_conn) {
mysql_close(_my_conn);
_my_conn = NULL;
}
}
Status MysqlScanner::open() {
if (_is_open) {
LOG(INFO) << "this scanner already opened";
return Status::OK();
}
_my_conn = mysql_init(NULL);
if (NULL == _my_conn) {
return Status::InternalError("mysql init failed.");
}
VLOG_CRITICAL << "MysqlScanner::Connect";
if (NULL == mysql_real_connect(_my_conn, _my_param.host.c_str(), _my_param.user.c_str(),
_my_param.passwd.c_str(), _my_param.db.c_str(),
atoi(_my_param.port.c_str()), NULL, _my_param.client_flag)) {
LOG(WARNING) << "connect Mysql: "
<< "Host: " << _my_param.host << " user: " << _my_param.user
<< " passwd: " << _my_param.passwd << " db: " << _my_param.db
<< " port: " << _my_param.port;
return _error_status("mysql real connect failed.");
}
if (mysql_set_character_set(_my_conn, "utf8")) {
return Status::InternalError("mysql set character set failed.");
}
_is_open = true;
return Status::OK();
}
Status MysqlScanner::query(const std::string& query) {
if (!_is_open) {
return Status::InternalError("Query before open.");
}
int sql_result = mysql_query(_my_conn, query.c_str());
if (0 != sql_result) {
LOG(WARNING) << "mysql query failed. query =" << query;
return _error_status("mysql query failed.");
} else {
LOG(INFO) << "mysql query success. query =" << query;
}
// clean the last query result
if (_my_result) {
mysql_free_result(_my_result);
}
// use store result because mysql table is small, can load in memory avoid of many RPC
_my_result = mysql_store_result(_my_conn);
if (NULL == _my_result) {
return _error_status("mysql store result failed.");
}
_field_num = mysql_num_fields(_my_result);
return Status::OK();
}
Status MysqlScanner::query(const std::string& table, const std::vector<std::string>& fields,
const std::vector<std::string>& filters, const uint64_t limit) {
if (!_is_open) {
return Status::InternalError("Query before open.");
}
_sql_str = "SELECT";
for (int i = 0; i < fields.size(); ++i) {
if (0 != i) {
_sql_str += ",";
}
_sql_str += " " + fields[i];
}
_sql_str += " FROM " + table;
if (!filters.empty()) {
_sql_str += " WHERE ";
for (int i = 0; i < filters.size(); ++i) {
if (0 != i) {
_sql_str += " AND";
}
_sql_str += " (" + filters[i] + ") ";
}
}
if (limit != -1) {
_sql_str += " LIMIT " + std::to_string(limit);
}
return query(_sql_str);
}
Status MysqlScanner::get_next_row(char*** buf, unsigned long** lengths, bool* eos) {
if (!_is_open) {
return Status::InternalError("GetNextRow before open.");
}
if (NULL == buf || NULL == lengths || NULL == eos) {
return Status::InternalError("input parameter invalid.");
}
if (NULL == _my_result) {
return Status::InternalError("get next row before query.");
}
*buf = mysql_fetch_row(_my_result);
if (NULL == *buf) {
*eos = true;
return Status::OK();
}
*lengths = mysql_fetch_lengths(_my_result);
if (NULL == *lengths) {
return _error_status("mysql fetch row failed.");
}
*eos = false;
return Status::OK();
}
Status MysqlScanner::_error_status(const std::string& prefix) {
std::stringstream msg;
msg << prefix << " Err: " << mysql_error(_my_conn);
LOG(INFO) << msg.str();
return Status::InternalError(msg.str());
}
} // namespace doris
/* vim: set ts=4 sw=4 sts=4 tw=100 noet: */
| 27.8 | 96 | 0.598483 | [
"vector"
] |
84fe3a91b461e587413dd525d8fbfe0a3298418f | 9,618 | cpp | C++ | src/main.cpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 185 | 2016-04-03T16:14:39.000Z | 2021-03-22T20:49:03.000Z | src/main.cpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 2 | 2016-04-04T05:50:12.000Z | 2017-01-17T18:12:09.000Z | src/main.cpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 10 | 2016-04-03T20:48:01.000Z | 2019-07-07T05:32:13.000Z | #include "CgStr.hpp"
#include "DoxytagResolver.hpp"
#include "MultiTuProcessor.hpp"
#include "SimpleTemplate.hpp"
#include "annotate.hpp"
#include "cgWrappers.hpp"
#include "cmdline.hpp"
#include <boost/filesystem.hpp>
#include <boost/io/ios_state.hpp>
#include <condition_variable>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
using namespace synth;
static char const kDefaultTemplateText[] =
R"EOT(<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>@@filename@@</title>
<link rel="stylesheet" href="@@rootpath@@/code.css">
</head>
<body>
<div class="highlight"><pre>@@code@@</pre></div>
<script src="@@rootpath@@/code.js"></script>
</body>
</html>)EOT";
namespace {
struct InitialPathResetter {
~InitialPathResetter() {
boost::system::error_code ec;
fs::current_path(fs::initial_path(), ec);
if (ec) {
std::cerr << "Failed resetting working directory: " << ec;
}
}
};
struct ThreadSharedState {
CXIndex cidx;
MultiTuProcessor& multiTuProcessor;
std::mutex workingDirMut;
std::mutex outputMut;
std::condition_variable workingDirChangedOrFree;
unsigned nWorkingDirUsers;
std::atomic_bool cancel;
};
class UIntRef {
public:
UIntRef(
unsigned& refd, std::condition_variable& zeroSignal, std::mutex& mut)
: m_refd(refd)
, m_zeroSignal(zeroSignal)
, m_mut(mut)
, m_acquired(false)
{ }
// Note: The referenced unsigned must be syncronized by the caller.
void acquire()
{
assert(!m_acquired);
++m_refd;
m_acquired = true;
}
~UIntRef()
{
if (m_acquired) {
bool zeroReached;
{
std::lock_guard<std::mutex> lock(m_mut);
zeroReached = --m_refd == 0;
}
if (zeroReached)
m_zeroSignal.notify_all();
}
}
private:
unsigned& m_refd;
std::condition_variable& m_zeroSignal;
std::mutex& m_mut;
bool m_acquired;
};
} // anonyomous namespace
static std::vector<CgStr> getClArgs(CXCompileCommand cmd)
{
std::vector<CgStr> result;
unsigned nArgs = clang_CompileCommand_getNumArgs(cmd);
result.reserve(nArgs);
for (unsigned i = 0; i < nArgs; ++i)
result.push_back(clang_CompileCommand_getArg(cmd, i));
return result;
}
static bool processCompileCommand(
CXCompileCommand cmd,
std::vector<char const*> extraArgs,
float pct,
ThreadSharedState& state)
{
CgStr file(clang_CompileCommand_getFilename(cmd));
if (!file.empty() && !state.multiTuProcessor.isFileIncluded(file.get()))
return false;
std::vector<CgStr> clArgsHandles = getClArgs(cmd);
std::vector<char const*> clArgs;
clArgs.reserve(clArgsHandles.size() + extraArgs.size());
for (CgStr const& s : clArgsHandles)
clArgs.push_back(s.get());
clArgs.insert(clArgs.end(), extraArgs.begin(), extraArgs.end());
CgStr dirStr = clang_CompileCommand_getDirectory(cmd);
UIntRef dirRef(
state.nWorkingDirUsers,
state.workingDirChangedOrFree,
state.workingDirMut);
bool dirChanged = false;
if (!dirStr.empty()) {
fs::path dir = std::move(dirStr).gets();
bool dirOk;
std::unique_lock<std::mutex> lock(state.workingDirMut);
state.workingDirChangedOrFree.wait(lock, [&]() {
if (state.cancel)
return true;
dirOk = fs::current_path() == dir;
return dirOk || state.nWorkingDirUsers == 0;
});
if (state.cancel)
return false;
dirRef.acquire();
if (!dirOk) {
fs::current_path(dir);
dirChanged = true;
}
} else {
std::lock_guard<std::mutex> lock(state.workingDirMut);
dirRef.acquire();
}
{
std::lock_guard<std::mutex> lock(state.outputMut);
if (dirChanged)
std::clog << "Entered directory " << dirStr.get() << '\n';
boost::io::ios_all_saver saver(std::clog);
std::clog.flags(std::clog.flags() | std::ios::fixed);
std::clog.precision(2);
std::clog << '[' << std::setw(6) << pct << "%]: " << file << "...\n";
}
return processTu(
state.cidx,
state.multiTuProcessor,
clArgs.data(),
static_cast<int>(clArgs.size())) == EXIT_SUCCESS;
}
// Adapted from
// http://insanecoding.blogspot.co.at/2011/11/how-to-read-in-file-in-c.html
static std::string getFileContents(char const* fname)
{
std::ifstream in(fname, std::ios::in | std::ios::binary);
in.exceptions(std::ios::badbit);
std::ostringstream contents;
contents << in.rdbuf();
return std::move(contents).str();
}
static int executeCmdLine(CmdLineArgs const& args)
{
SimpleTemplate tpl("");
if (args.templateFile) {
try {
tpl = SimpleTemplate(getFileContents(args.templateFile));
} catch (std::ios::failure const& e) {
std::cerr << "Error reading output template: " << e.what() << '\n';
return EXIT_FAILURE;
}
} else {
tpl = SimpleTemplate(kDefaultTemplateText);
}
std::vector<ExternalRefLinker> refLinkers;
for (auto const& doxyMapping : args.doxyTagFiles) {
refLinkers.push_back(std::bind(&DoxytagResolver::link,
DoxytagResolver::fromTagFilename(
doxyMapping.first,
doxyMapping.second),
std::placeholders::_1, std::placeholders::_2));
}
CgIdxHandle hcidx(clang_createIndex(
/*excludeDeclarationsFromPCH:*/ true,
/*displayDiagnostics:*/ true));
MultiTuProcessor state(
PathMap(args.inOutDirs.begin(), args.inOutDirs.end()),
[&refLinkers](Markup& m, CXCursor c) {
assert(!m.isRef());
for (auto const& refLinker : refLinkers) {
refLinker(m, c);
if (m.isRef())
break;
}
});
state.setMaxIdSz(args.maxIdSz);
if (args.compilationDbDir) {
CXCompilationDatabase_Error err;
CgDbHandle db(clang_CompilationDatabase_fromDirectory(
args.compilationDbDir, &err));
if (err != CXCompilationDatabase_NoError) {
std::cerr << "Failed loading compilation database (code "
<< static_cast<int>(err)
<< ")\n";
return err + 20;
}
CgCmdsHandle cmds(
clang_CompilationDatabase_getAllCompileCommands(db.get()));
unsigned nCmds = clang_CompileCommands_getSize(cmds.get());
if (nCmds == 0) {
std::cerr << "No compilation commands in DB.\n";
return EXIT_SUCCESS;
}
InitialPathResetter pathResetter;
ThreadSharedState tstate {
/*cidx=*/ hcidx.get(),
/*multiTuProcessor=*/ state,
/*workingDirMut=*/ {},
/*outputMut=*/ {},
/*workingDirChangedOrFree=*/ {},
/*nWorkingDirUsers=*/ 0u,
/*cancel=*/ {false}};
// It seems [1] that during creation of the first translation,
// no others may be created or data races occur inside libclang.
// [1]: Detected by clang's TSan.
unsigned idx = 0;
while (!processCompileCommand(
clang_CompileCommands_getCommand(cmds.get(), idx++),
args.clangArgs,
0,
tstate)
) {
assert(tstate.nWorkingDirUsers == 0);
}
std::atomic_uint sharedCmdIdx(idx);
std::vector<std::thread> threads;
threads.reserve(args.nThreads - 1);
std::clog << "Using " << args.nThreads << " threads.\n";
auto const worker = [&]() {
while (!tstate.cancel) {
unsigned cmdIdx = sharedCmdIdx++;
if (cmdIdx >= nCmds)
return;
processCompileCommand(
clang_CompileCommands_getCommand(cmds.get(), cmdIdx),
args.clangArgs,
static_cast<float>(cmdIdx) / nCmds * 100,
tstate);
}
};
try {
for (unsigned i = 0; i < args.nThreads - 1; ++i)
threads.emplace_back(worker);
worker();
} catch (...) {
tstate.cancel = true; // Do before locking to reduce wait time.
{
std::lock_guard<std::mutex> lock(tstate.workingDirMut);
tstate.cancel = true; // Repeat for condition variable.
}
tstate.workingDirChangedOrFree.notify_all();
for (auto& th : threads)
th.join();
assert(tstate.nWorkingDirUsers == 0);
throw;
}
for (auto& th : threads)
th.join();
assert(tstate.nWorkingDirUsers == 0);
} else {
int r = synth::processTu(
hcidx.get(),
state,
args.clangArgs.data(),
args.nClangArgs);
if (r)
return r;
}
state.writeOutput(tpl);
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
try {
fs::initial_path(); // Save initial path.
return executeCmdLine(CmdLineArgs::parse(argc, argv));
} catch (std::exception const& e) {
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
}
| 29.685185 | 79 | 0.565918 | [
"vector"
] |
1701594f854b50708cb89fafe8ca1ddff46f2f1e | 17,614 | cc | C++ | chrome/browser/metrics/metrics_service_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/metrics/metrics_service_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/metrics/metrics_service_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests the MetricsService stat recording to make sure that the numbers are
// what we expect.
#include "components/metrics/metrics_service.h"
#include <string>
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/process/memory.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/metrics/chrome_metrics_service_client.h"
#include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/metrics/metrics_reporting_default_state.h"
#include "components/metrics/metrics_switches.h"
#include "components/metrics/persistent_histograms.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/filename_util.h"
#include "services/service_manager/embedder/switches.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/base/window_open_disposition.h"
#include "url/gurl.h"
#if defined(OS_POSIX)
#include <sys/wait.h>
#endif
#if defined(OS_WIN)
#include "sandbox/win/src/sandbox_types.h"
#endif
#if defined(OS_MAC) || defined(OS_LINUX)
namespace {
// Check CrashExitCodes.Renderer histogram for a single bucket entry and then
// verify that the bucket entry contains a signal and the signal is |signal|.
void VerifyRendererExitCodeIsSignal(
const base::HistogramTester& histogram_tester,
int signal) {
const auto buckets =
histogram_tester.GetAllSamples("CrashExitCodes.Renderer");
ASSERT_EQ(1UL, buckets.size());
EXPECT_EQ(1, buckets[0].count);
int32_t exit_code = buckets[0].min;
EXPECT_TRUE(WIFSIGNALED(exit_code));
EXPECT_EQ(signal, WTERMSIG(exit_code));
}
} // namespace
#endif // OS_MAC || OS_LINUX
// This test class verifies that metrics reporting works correctly for various
// renderer behaviors such as page loads, recording crashed tabs, and browser
// starts. It also verifies that if a renderer process crashes, the correct exit
// code is recorded.
//
// TODO(isherman): We should also verify that
// metrics::prefs::kStabilityExitedCleanly is set correctly after each of these
// tests, but this preference isn't set until the browser exits... it's not
// clear to me how to test that.
class MetricsServiceBrowserTest : public InProcessBrowserTest {
public:
MetricsServiceBrowserTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Enable the metrics service for testing (in recording-only mode).
command_line->AppendSwitch(metrics::switches::kMetricsRecordingOnly);
}
void SetUp() override {
ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
&metrics_consent_);
InProcessBrowserTest::SetUp();
}
// Open three tabs then navigate to |crashy_url| and wait for the renderer to
// crash.
void OpenTabsAndNavigateToCrashyUrl(const std::string& crashy_url) {
// Opens three tabs.
OpenThreeTabs();
// Kill the process for one of the tabs by navigating to |crashy_url|.
content::RenderProcessHostWatcher observer(
browser()->tab_strip_model()->GetActiveWebContents(),
content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
// Opens one tab.
ui_test_utils::NavigateToURL(browser(), GURL(crashy_url));
observer.Wait();
// The MetricsService listens for the same notification, so the |observer|
// might finish waiting before the MetricsService has a chance to process
// the notification. To avoid racing here, we repeatedly run the message
// loop until the MetricsService catches up. This should happen "real soon
// now", since the notification is posted to all observers essentially
// simultaneously... so busy waiting here shouldn't be too bad.
const PrefService* prefs = g_browser_process->local_state();
while (!prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount)) {
content::RunAllPendingInMessageLoop();
}
}
// Open a couple of tabs of random content.
//
// Calling this method causes three page load events:
// 1. title2.html
// 2. iframe.html
// 3. title1.html (iframed by iframe.html)
void OpenThreeTabs() {
const int kBrowserTestFlags =
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP;
base::FilePath test_directory;
ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_directory));
base::FilePath page1_path = test_directory.AppendASCII("title2.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(page1_path),
WindowOpenDisposition::NEW_FOREGROUND_TAB, kBrowserTestFlags);
base::FilePath page2_path = test_directory.AppendASCII("iframe.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(page2_path),
WindowOpenDisposition::NEW_FOREGROUND_TAB, kBrowserTestFlags);
}
private:
bool metrics_consent_ = true;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceBrowserTest);
};
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserTest, CloseRenderersNormally) {
OpenThreeTabs();
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityLaunchCount));
EXPECT_EQ(3, prefs->GetInteger(metrics::prefs::kStabilityPageLoadCount));
EXPECT_EQ(0, prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount));
}
// Flaky on Linux. See http://crbug.com/131094
// Child crashes fail the process on ASan (see crbug.com/411251,
// crbug.com/368525).
// Flaky timeouts on Win7 Tests (dbg)(1); see https://crbug.com/985255.
#if defined(OS_LINUX) || defined(ADDRESS_SANITIZER) || \
(defined(OS_WIN) && !defined(NDEBUG))
#define MAYBE_CrashRenderers DISABLED_CrashRenderers
#define MAYBE_CheckCrashRenderers DISABLED_CheckCrashRenderers
#else
#define MAYBE_CrashRenderers CrashRenderers
#define MAYBE_CheckCrashRenderers CheckCrashRenderers
#endif
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserTest, MAYBE_CrashRenderers) {
base::HistogramTester histogram_tester;
OpenTabsAndNavigateToCrashyUrl(content::kChromeUICrashURL);
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityLaunchCount));
// The three tabs from OpenTabs() and the one tab to open chrome://crash/.
EXPECT_EQ(4, prefs->GetInteger(metrics::prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount));
#if defined(OS_WIN)
// Consult Stability Team before changing this test as it's recorded to
// histograms and used for stability measurement.
histogram_tester.ExpectUniqueSample(
"CrashExitCodes.Renderer",
std::abs(static_cast<int32_t>(STATUS_ACCESS_VIOLATION)), 1);
#elif defined(OS_MAC) || defined(OS_LINUX)
VerifyRendererExitCodeIsSignal(histogram_tester, SIGSEGV);
#endif
histogram_tester.ExpectUniqueSample("Tabs.SadTab.CrashCreated", 1, 1);
}
// Test is disabled on Windows AMR64 because
// TerminateWithHeapCorruption() isn't expected to work there.
// See: https://crbug.com/1054423
#if defined(OS_WIN)
#if defined(ARCH_CPU_ARM64)
#define MAYBE_HeapCorruptionInRenderer DISABLED_HeapCorruptionInRenderer
#else
#define MAYBE_HeapCorruptionInRenderer HeapCorruptionInRenderer
#endif
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserTest,
MAYBE_HeapCorruptionInRenderer) {
base::HistogramTester histogram_tester;
OpenTabsAndNavigateToCrashyUrl(content::kChromeUIHeapCorruptionCrashURL);
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityLaunchCount));
// The three tabs from OpenTabs() and the one tab to open chrome://crash/.
EXPECT_EQ(4, prefs->GetInteger(metrics::prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount));
histogram_tester.ExpectUniqueSample(
"CrashExitCodes.Renderer",
std::abs(static_cast<int32_t>(STATUS_HEAP_CORRUPTION)), 1);
histogram_tester.ExpectUniqueSample("Tabs.SadTab.CrashCreated", 1, 1);
LOG(INFO) << histogram_tester.GetAllHistogramsRecorded();
}
#endif // OS_WIN
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserTest, MAYBE_CheckCrashRenderers) {
base::HistogramTester histogram_tester;
OpenTabsAndNavigateToCrashyUrl(content::kChromeUICheckCrashURL);
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityLaunchCount));
// The three tabs from OpenTabs() and the one tab to open
// chrome://checkcrash/.
EXPECT_EQ(4, prefs->GetInteger(metrics::prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount));
#if defined(OS_WIN)
// Consult Stability Team before changing this test as it's recorded to
// histograms and used for stability measurement.
histogram_tester.ExpectUniqueSample(
"CrashExitCodes.Renderer",
std::abs(static_cast<int32_t>(STATUS_BREAKPOINT)), 1);
#elif defined(OS_MAC) || defined(OS_LINUX)
VerifyRendererExitCodeIsSignal(histogram_tester, SIGTRAP);
#endif
histogram_tester.ExpectUniqueSample("Tabs.SadTab.CrashCreated", 1, 1);
}
// OOM code only works on Windows.
#if defined(OS_WIN) && !defined(ADDRESS_SANITIZER)
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserTest, OOMRenderers) {
// Disable stack traces during this test since DbgHelp is unreliable in
// low-memory conditions (see crbug.com/692564).
base::CommandLine::ForCurrentProcess()->AppendSwitch(
service_manager::switches::kDisableInProcessStackTraces);
base::HistogramTester histogram_tester;
OpenTabsAndNavigateToCrashyUrl(content::kChromeUIMemoryExhaustURL);
// Verify that the expected stability metrics were recorded.
const PrefService* prefs = g_browser_process->local_state();
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityLaunchCount));
// The three tabs from OpenTabs() and the one tab to open
// chrome://memory-exhaust/.
EXPECT_EQ(4, prefs->GetInteger(metrics::prefs::kStabilityPageLoadCount));
EXPECT_EQ(1, prefs->GetInteger(metrics::prefs::kStabilityRendererCrashCount));
// On 64-bit, the Job object should terminate the renderer on an OOM. However,
// if the system is low on memory already, then the allocator might just return
// a normal OOM before hitting the Job limit.
// Note: Exit codes are recorded after being passed through std::abs see
// MapCrashExitCodeForHistogram.
#if defined(ARCH_CPU_64_BITS)
const base::Bucket expected_possible_exit_codes[] = {
base::Bucket(
std::abs(static_cast<int32_t>(sandbox::SBOX_FATAL_MEMORY_EXCEEDED)),
1),
base::Bucket(std::abs(static_cast<int32_t>(base::win::kOomExceptionCode)),
1)};
#else
const base::Bucket expected_possible_exit_codes[] = {base::Bucket(
std::abs(static_cast<int32_t>(base::win::kOomExceptionCode)), 1)};
#endif
EXPECT_THAT(histogram_tester.GetAllSamples("CrashExitCodes.Renderer"),
::testing::IsSubsetOf(expected_possible_exit_codes));
histogram_tester.ExpectUniqueSample("Tabs.SadTab.OomCreated", 1, 1);
}
#endif // OS_WIN && !ADDRESS_SANITIZER
// Base class for testing if browser-metrics files get removed or not.
// The code under tests is run before any actual test methods so the test
// conditions must be created during SetUp in order to affect said code.
class MetricsServiceBrowserFilesTest : public InProcessBrowserTest {
using super = InProcessBrowserTest;
public:
MetricsServiceBrowserFilesTest() {}
bool SetUpUserDataDirectory() override {
if (!super::SetUpUserDataDirectory())
return false;
base::ScopedAllowBlockingForTesting allow_blocking;
base::FilePath user_dir;
CHECK(base::PathService::Get(chrome::DIR_USER_DATA, &user_dir));
// Create a local-state file with what we want the browser to use. This
// has to be done here because there is no hook between when the browser
// is initialized and the metrics-client acts on the pref values. The
// "Local State" directory is hard-coded because the FILE_LOCAL_STATE
// path is not yet defined at this point.
{
base::test::TaskEnvironment task_env;
auto state = base::MakeRefCounted<JsonPrefStore>(
user_dir.Append(FILE_PATH_LITERAL("Local State")));
state->SetValue(
metrics::prefs::kMetricsDefaultOptIn,
std::make_unique<base::Value>(metrics::EnableMetricsDefault::OPT_OUT),
0);
}
// Create the upload dir. Note that ASSERT macros won't fail in SetUp,
// hence the use of CHECK.
upload_dir_ = user_dir.AppendASCII(kBrowserMetricsName);
CHECK(!base::PathExists(upload_dir_));
CHECK(base::CreateDirectory(upload_dir_));
// Create a file inside the upload dir that can be watched to see if an
// attempt was made to delete everything.
base::File upload_file(
upload_dir().AppendASCII("foo.bar"),
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
CHECK_EQ(6, upload_file.WriteAtCurrentPos("foobar", 6));
return true;
}
void SetUp() override {
ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
&metrics_consent_);
super::SetUp();
}
// Check for the existence of any non-pma files that were created as part
// of the test. PMA files may be created as part of the browser setup and
// cannot be deleted while open on all operating systems.
bool HasNonPMAFiles() {
base::ScopedAllowBlockingForTesting allow_blocking;
if (!base::PathExists(upload_dir_))
return false;
base::FileEnumerator file_iter(upload_dir_, true,
base::FileEnumerator::FILES);
while (!file_iter.Next().empty()) {
if (file_iter.GetInfo().GetName().Extension() !=
FILE_PATH_LITERAL(".pma")) {
return true;
}
}
return false;
}
base::FilePath& upload_dir() { return upload_dir_; }
void set_metrics_consent(bool enabled) { metrics_consent_ = enabled; }
private:
bool metrics_consent_ = true;
base::FilePath upload_dir_;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceBrowserFilesTest);
};
// Specific class for testing when metrics upload is fully enabled.
class MetricsServiceBrowserDoUploadTest
: public MetricsServiceBrowserFilesTest {
public:
MetricsServiceBrowserDoUploadTest() {}
void SetUp() override {
set_metrics_consent(true);
feature_list_.InitAndEnableFeature(
metrics::internal::kMetricsReportingFeature);
MetricsServiceBrowserFilesTest::SetUp();
}
private:
base::test::ScopedFeatureList feature_list_;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceBrowserDoUploadTest);
};
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserDoUploadTest, FilesRemain) {
// SetUp() has provided consent and made metrics "sampled-in" (enabled).
EXPECT_TRUE(HasNonPMAFiles());
}
// Specific class for testing when metrics upload is explicitly disabled.
class MetricsServiceBrowserNoUploadTest
: public MetricsServiceBrowserFilesTest {
public:
MetricsServiceBrowserNoUploadTest() {}
void SetUp() override {
set_metrics_consent(false);
feature_list_.InitAndEnableFeature(
metrics::internal::kMetricsReportingFeature);
MetricsServiceBrowserFilesTest::SetUp();
}
private:
base::test::ScopedFeatureList feature_list_;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceBrowserNoUploadTest);
};
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserNoUploadTest, FilesRemoved) {
// SetUp() has removed consent and made metrics "sampled-in" (enabled).
EXPECT_FALSE(HasNonPMAFiles());
}
// Specific class for testing when metrics upload is disabled by sampling.
class MetricsServiceBrowserSampledOutTest
: public MetricsServiceBrowserFilesTest {
public:
MetricsServiceBrowserSampledOutTest() {}
void SetUp() override {
set_metrics_consent(true);
feature_list_.InitAndDisableFeature(
metrics::internal::kMetricsReportingFeature);
MetricsServiceBrowserFilesTest::SetUp();
}
private:
base::test::ScopedFeatureList feature_list_;
DISALLOW_COPY_AND_ASSIGN(MetricsServiceBrowserSampledOutTest);
};
IN_PROC_BROWSER_TEST_F(MetricsServiceBrowserSampledOutTest, FilesRemoved) {
// SetUp() has provided consent and made metrics "sampled-out" (disabled).
EXPECT_FALSE(HasNonPMAFiles());
}
| 38.54267 | 80 | 0.758601 | [
"object"
] |
1702532474d7087be75b7ad295f9566434628518 | 52,558 | cpp | C++ | system/GLESv2_enc/GLESv2Validation.cpp | android-risc-v/device_generic_goldfish-opengl | fcc7f13afd7b6ee061da2bd2db980e9a0733689b | [
"Apache-2.0"
] | 1 | 2022-01-08T17:41:53.000Z | 2022-01-08T17:41:53.000Z | system/GLESv2_enc/GLESv2Validation.cpp | android-risc-v/device_generic_goldfish-opengl | fcc7f13afd7b6ee061da2bd2db980e9a0733689b | [
"Apache-2.0"
] | 2 | 2021-07-28T11:11:39.000Z | 2021-11-23T03:00:17.000Z | system/GLESv2_enc/GLESv2Validation.cpp | android-risc-v/device_generic_goldfish-opengl | fcc7f13afd7b6ee061da2bd2db980e9a0733689b | [
"Apache-2.0"
] | 2 | 2021-07-24T08:14:11.000Z | 2021-11-04T12:46:22.000Z | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "GLESv2Validation.h"
#include <sstream>
#define LIST_VALID_TEX_INTERNALFORMATS(f) \
f(GL_BGRA8_EXT) \
f(GL_R8) \
f(GL_R8_SNORM) \
f(GL_R16F) \
f(GL_R32F) \
f(GL_R8UI) \
f(GL_R8I) \
f(GL_R16UI) \
f(GL_R16I) \
f(GL_R32UI) \
f(GL_R32I) \
f(GL_RG8) \
f(GL_RG8_SNORM) \
f(GL_RG16F) \
f(GL_RG32F) \
f(GL_RG8UI) \
f(GL_RG8I) \
f(GL_RG16UI) \
f(GL_RG16I) \
f(GL_RG32UI) \
f(GL_RG32I) \
f(GL_RGB8) \
f(GL_SRGB8) \
f(GL_RGB565) \
f(GL_RGB8_SNORM) \
f(GL_R11F_G11F_B10F) \
f(GL_RGB9_E5) \
f(GL_RGB16F) \
f(GL_RGB32F) \
f(GL_RGB8UI) \
f(GL_RGB8I) \
f(GL_RGB16UI) \
f(GL_RGB16I) \
f(GL_RGB32UI) \
f(GL_RGB32I) \
f(GL_RGBA8) \
f(GL_SRGB8_ALPHA8) \
f(GL_RGBA8_SNORM) \
f(GL_RGB5_A1) \
f(GL_RGBA4) \
f(GL_RGB10_A2) \
f(GL_RGBA16F) \
f(GL_RGBA32F) \
f(GL_RGBA8UI) \
f(GL_RGBA8I) \
f(GL_RGB10_A2UI) \
f(GL_RGBA16UI) \
f(GL_RGBA16I) \
f(GL_RGBA32I) \
f(GL_RGBA32UI) \
f(GL_DEPTH_COMPONENT16) \
f(GL_DEPTH_COMPONENT24) \
f(GL_DEPTH_COMPONENT32F) \
f(GL_DEPTH24_STENCIL8) \
f(GL_DEPTH32F_STENCIL8) \
f(GL_ETC1_RGB8_OES) \
f(GL_COMPRESSED_R11_EAC) \
f(GL_COMPRESSED_SIGNED_R11_EAC) \
f(GL_COMPRESSED_RG11_EAC) \
f(GL_COMPRESSED_SIGNED_RG11_EAC) \
f(GL_COMPRESSED_RGB8_ETC2) \
f(GL_COMPRESSED_SRGB8_ETC2) \
f(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2) \
f(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2) \
f(GL_COMPRESSED_RGBA8_ETC2_EAC) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC) \
f(GL_COMPRESSED_RGBA_ASTC_4x4_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_5x4_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_5x5_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_6x5_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_6x6_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_8x5_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_8x6_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_8x8_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_10x5_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_10x6_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_10x8_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_10x10_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_12x10_KHR) \
f(GL_COMPRESSED_RGBA_ASTC_12x12_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR) \
f(GL_COMPRESSED_RGBA_BPTC_UNORM_EXT) \
f(GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT) \
f(GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT) \
f(GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT) \
f(GL_COMPRESSED_RGB_S3TC_DXT1_EXT) \
f(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) \
f(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT) \
f(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT) \
f(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT)
#define LIST_INTEGER_TEX_FORMATS(f) \
f(GL_RED_INTEGER) \
f(GL_RG_INTEGER) \
f(GL_RGB_INTEGER) \
f(GL_RGBA_INTEGER) \
f(GL_R8UI) \
f(GL_R8I) \
f(GL_R16UI) \
f(GL_R16I) \
f(GL_R32UI) \
f(GL_R32I) \
f(GL_RG8UI) \
f(GL_RG8I) \
f(GL_RG16UI) \
f(GL_RG16I) \
f(GL_RG32UI) \
f(GL_RG32I) \
f(GL_RGB8UI) \
f(GL_RGB8I) \
f(GL_RGB16UI) \
f(GL_RGB16I) \
f(GL_RGB32UI) \
f(GL_RGB32I) \
f(GL_RGBA8UI) \
f(GL_RGBA8I) \
f(GL_RGB10_A2UI) \
f(GL_RGBA16UI) \
f(GL_RGBA16I) \
f(GL_RGBA32I) \
f(GL_RGBA32UI) \
#define LIST_VALID_TEXFORMAT_COMBINATIONS(f) \
f(GL_BGRA8_EXT, GL_BGRA_EXT, GL_UNSIGNED_BYTE) \
f(GL_R8, GL_RED, GL_UNSIGNED_BYTE) \
f(GL_R8_SNORM, GL_RED, GL_BYTE) \
f(GL_R16F, GL_RED, GL_FLOAT) \
f(GL_R16F, GL_RED, GL_HALF_FLOAT) \
f(GL_R32F, GL_RED, GL_FLOAT) \
f(GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE) \
f(GL_R8I, GL_RED_INTEGER, GL_BYTE) \
f(GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT) \
f(GL_R16I, GL_RED_INTEGER, GL_SHORT) \
f(GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT) \
f(GL_R32I, GL_RED_INTEGER, GL_INT) \
f(GL_RG8, GL_RG, GL_UNSIGNED_BYTE) \
f(GL_RG8_SNORM, GL_RG, GL_BYTE) \
f(GL_RG16F, GL_RG, GL_HALF_FLOAT) \
f(GL_RG16F, GL_RG, GL_FLOAT) \
f(GL_RG32F, GL_RG, GL_FLOAT) \
f(GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE) \
f(GL_RG8I, GL_RG_INTEGER, GL_BYTE) \
f(GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT) \
f(GL_RG16I, GL_RG_INTEGER, GL_SHORT) \
f(GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT) \
f(GL_RG32I, GL_RG_INTEGER, GL_INT) \
f(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_RGB565, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5) \
f(GL_RGB8_SNORM, GL_RGB, GL_BYTE) \
f(GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV) \
f(GL_R11F_G11F_B10F, GL_RGB, GL_HALF_FLOAT) \
f(GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT) \
f(GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV) \
f(GL_RGB9_E5, GL_RGB, GL_HALF_FLOAT) \
f(GL_RGB9_E5, GL_RGB, GL_FLOAT) \
f(GL_RGB16F, GL_RGB, GL_HALF_FLOAT) \
f(GL_RGB16F, GL_RGB, GL_FLOAT) \
f(GL_RGB32F, GL_RGB, GL_FLOAT) \
f(GL_RGB8UI, GL_RGB_INTEGER, GL_UNSIGNED_BYTE) \
f(GL_RGB8I, GL_RGB_INTEGER, GL_BYTE) \
f(GL_RGB16UI, GL_RGB_INTEGER, GL_UNSIGNED_SHORT) \
f(GL_RGB16I, GL_RGB_INTEGER, GL_SHORT) \
f(GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT) \
f(GL_RGB32I, GL_RGB_INTEGER, GL_INT) \
f(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_RGBA8_SNORM, GL_RGBA, GL_BYTE) \
f(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1) \
f(GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV) \
f(GL_RGBA4, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4) \
f(GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV) \
f(GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT) \
f(GL_RGBA16F, GL_RGBA, GL_FLOAT) \
f(GL_RGBA32F, GL_RGBA, GL_FLOAT) \
f(GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE) \
f(GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE) \
f(GL_RGB10_A2UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV) \
f(GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT) \
f(GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT) \
f(GL_RGBA32I, GL_RGBA_INTEGER, GL_INT) \
f(GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT) \
f(GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT) \
f(GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT) \
f(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT) \
f(GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT) \
f(GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8) \
f(GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV) \
f(GL_COMPRESSED_R11_EAC, GL_RED, GL_FLOAT) \
f(GL_COMPRESSED_SIGNED_R11_EAC, GL_RED, GL_FLOAT) \
f(GL_COMPRESSED_RG11_EAC, GL_RG, GL_FLOAT) \
f(GL_COMPRESSED_SIGNED_RG11_EAC, GL_RG, GL_FLOAT) \
f(GL_COMPRESSED_RGB8_ETC2, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ETC2, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA8_ETC2_EAC, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_5x4_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_6x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_8x8_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_10x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_10x8_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_10x10_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_12x10_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_ASTC_12x12_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_BPTC_UNORM_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE) \
f(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE)
namespace GLESv2Validation {
GLbitfield allBufferMapAccessFlags =
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |
GL_MAP_INVALIDATE_RANGE_BIT |
GL_MAP_INVALIDATE_BUFFER_BIT |
GL_MAP_FLUSH_EXPLICIT_BIT |
GL_MAP_UNSYNCHRONIZED_BIT;
bool bufferTarget(GL2Encoder* ctx, GLenum target) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
switch (target) {
case GL_ARRAY_BUFFER: // Vertex attributes
case GL_ELEMENT_ARRAY_BUFFER: // Vertex array indices
return true;
// GLES 3.0 buffers
case GL_COPY_READ_BUFFER: // Buffer copy source
case GL_COPY_WRITE_BUFFER: // Buffer copy destination
case GL_PIXEL_PACK_BUFFER: // Pixel read target
case GL_PIXEL_UNPACK_BUFFER: // Texture data source
case GL_TRANSFORM_FEEDBACK_BUFFER: // Transform feedback buffer
case GL_UNIFORM_BUFFER: // Uniform block storage
return glesMajorVersion >= 3;
// GLES 3.1 buffers
case GL_ATOMIC_COUNTER_BUFFER: // Atomic counter storage
case GL_DISPATCH_INDIRECT_BUFFER: // Indirect compute dispatch commands
case GL_DRAW_INDIRECT_BUFFER: // Indirect command arguments
case GL_SHADER_STORAGE_BUFFER: // Read-write storage for shaders
return glesMajorVersion >= 3 && glesMinorVersion >= 1;
default:
return false;
}
}
bool bufferParam(GL2Encoder* ctx, GLenum pname) {
int glesMajorVersion = ctx->majorVersion();
switch (pname) {
case GL_BUFFER_SIZE:
case GL_BUFFER_USAGE:
return true;
case GL_BUFFER_ACCESS_FLAGS:
case GL_BUFFER_MAPPED:
case GL_BUFFER_MAP_LENGTH:
case GL_BUFFER_MAP_OFFSET:
return glesMajorVersion >= 3;
default:
return false;
}
}
bool bufferUsage(GL2Encoder* ctx, GLenum usage) {
int glesMajorVersion = ctx->majorVersion();
switch(usage) {
case GL_STREAM_DRAW:
case GL_STATIC_DRAW:
case GL_DYNAMIC_DRAW:
return true;
case GL_STREAM_READ:
case GL_STATIC_READ:
case GL_DYNAMIC_READ:
case GL_STREAM_COPY:
case GL_STATIC_COPY:
case GL_DYNAMIC_COPY:
return glesMajorVersion >= 3;
}
return false;
}
bool pixelStoreParam(GL2Encoder* ctx, GLenum param) {
int glesMajorVersion = ctx->majorVersion();
switch(param) {
case GL_UNPACK_ALIGNMENT:
case GL_PACK_ALIGNMENT:
return true;
case GL_UNPACK_ROW_LENGTH:
case GL_UNPACK_IMAGE_HEIGHT:
case GL_UNPACK_SKIP_PIXELS:
case GL_UNPACK_SKIP_ROWS:
case GL_UNPACK_SKIP_IMAGES:
case GL_PACK_ROW_LENGTH:
case GL_PACK_SKIP_PIXELS:
case GL_PACK_SKIP_ROWS:
return glesMajorVersion >= 3;
default:
return false;
}
}
bool pixelStoreValue(GLenum param, GLint value) {
switch(param) {
case GL_UNPACK_ALIGNMENT:
case GL_PACK_ALIGNMENT:
return (value == 1) || (value == 2) || (value == 4) || (value == 8);
case GL_UNPACK_ROW_LENGTH:
case GL_UNPACK_IMAGE_HEIGHT:
case GL_UNPACK_SKIP_PIXELS:
case GL_UNPACK_SKIP_ROWS:
case GL_UNPACK_SKIP_IMAGES:
case GL_PACK_ROW_LENGTH:
case GL_PACK_SKIP_PIXELS:
case GL_PACK_SKIP_ROWS:
return value >= 0;
default:
return false;
}
}
bool rboFormat(GL2Encoder* ctx, GLenum internalformat) {
int glesMajorVersion = ctx->majorVersion();
switch (internalformat) {
// Funny internal formats
// that will cause an incomplete framebuffer
// attachment error pre-gles3. For dEQP,
// we can also just abort early here in
// RenderbufferStorage with a GL_INVALID_ENUM.
case GL_DEPTH_COMPONENT32F:
case GL_R8:
case GL_R8UI:
case GL_R8I:
case GL_R16UI:
case GL_R16I:
case GL_R32UI:
case GL_R32I:
case GL_RG8:
case GL_RG8UI:
case GL_RG8I:
case GL_RG16UI:
case GL_RG16I:
case GL_RG32UI:
case GL_RG32I:
case GL_SRGB8_ALPHA8:
case GL_RGBA8UI:
case GL_RGBA8I:
case GL_RGB10_A2:
case GL_RGB10_A2UI:
case GL_RGBA16UI:
case GL_RGBA16I:
case GL_RGBA32I:
case GL_RGBA32UI:
case GL_RGB32F:
return glesMajorVersion >= 3;
// These 4 formats are still not OK,
// but dEQP expects GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT or
// GL_FRAMEBUFFER_UNSUPPORTED if the extension is not present,
// not a GL_INVALID_ENUM from earlier on.
// So let's forward these to the rest of
// FBO initialization
// In GLES 3, these are rejected immediately if not
// supported.
case GL_R16F:
case GL_RG16F:
case GL_RGBA16F:
case GL_R32F:
case GL_RG32F:
case GL_RGBA32F:
case GL_R11F_G11F_B10F:
return glesMajorVersion >= 3 && ctx->hasExtension("GL_EXT_color_buffer_float");
case GL_RGB16F:
return glesMajorVersion >= 3 && ctx->hasExtension("GL_EXT_color_buffer_half_float");
// dEQP expects GL_FRAMEBUFFER_UNSUPPORTED or GL_FRAMEBUFFER_COMPLETE
// for this format
// These formats are OK
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_STENCIL_INDEX8:
case GL_DEPTH32F_STENCIL8:
case GL_DEPTH24_STENCIL8_OES:
return true;
break;
// Everything else: still not OK,
// and they need the GL_INVALID_ENUM
}
return false;
}
bool framebufferTarget(GL2Encoder* ctx, GLenum target) {
int glesMajorVersion = ctx->majorVersion();
switch (target) {
case GL_FRAMEBUFFER:
return true;
case GL_DRAW_FRAMEBUFFER:
case GL_READ_FRAMEBUFFER:
return glesMajorVersion >= 3;
}
return false;
}
bool framebufferAttachment(GL2Encoder* ctx, GLenum attachment) {
int glesMajorVersion = ctx->majorVersion();
switch (attachment) {
case GL_COLOR_ATTACHMENT0:
case GL_DEPTH_ATTACHMENT:
case GL_STENCIL_ATTACHMENT:
return true;
case GL_COLOR_ATTACHMENT1:
case GL_COLOR_ATTACHMENT2:
case GL_COLOR_ATTACHMENT3:
case GL_COLOR_ATTACHMENT4:
case GL_COLOR_ATTACHMENT5:
case GL_COLOR_ATTACHMENT6:
case GL_COLOR_ATTACHMENT7:
case GL_COLOR_ATTACHMENT8:
case GL_COLOR_ATTACHMENT9:
case GL_COLOR_ATTACHMENT10:
case GL_COLOR_ATTACHMENT11:
case GL_COLOR_ATTACHMENT12:
case GL_COLOR_ATTACHMENT13:
case GL_COLOR_ATTACHMENT14:
case GL_COLOR_ATTACHMENT15:
case GL_DEPTH_STENCIL_ATTACHMENT:
return glesMajorVersion >= 3;
}
return false;
}
bool readPixelsFormat(GLenum format) {
switch (format) {
case GL_RED:
case GL_RED_INTEGER:
case GL_RG:
case GL_RG_INTEGER:
case GL_RGB:
case GL_RGB_INTEGER:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE:
case GL_ALPHA:
return true;
}
return false;
}
bool readPixelsType(GLenum format) {
switch (format) {
case GL_UNSIGNED_BYTE:
case GL_BYTE:
case GL_HALF_FLOAT:
case GL_FLOAT:
case GL_INT:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_2_10_10_10_REV:
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_5_9_9_9_REV:
return true;
}
return false;
}
bool pixelOp(GLenum format,GLenum type) {
switch(type) {
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
return format == GL_RGBA;
case GL_UNSIGNED_SHORT_5_6_5:
return format == GL_RGB;
}
return true;
}
bool vertexAttribType(GL2Encoder* ctx, GLenum type)
{
int glesMajorVersion = ctx->majorVersion();
bool retval = false;
switch (type) {
case GL_BYTE:
case GL_UNSIGNED_BYTE:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_FIXED:
case GL_FLOAT:
// The following are technically only available if certain GLES2 extensions are.
// However, they are supported by desktop GL3, which is a reasonable requirement
// for the desktop GL version. Therefore, consider them valid.
case GL_INT:
case GL_UNSIGNED_INT:
case GL_HALF_FLOAT_OES:
retval = true;
break;
case GL_HALF_FLOAT:
case GL_INT_2_10_10_10_REV:
case GL_UNSIGNED_INT_2_10_10_10_REV:
retval = glesMajorVersion >= 3;
break;
}
return retval;
}
bool readPixelsFboFormatMatch(GLenum, GLenum type, GLenum fboTexType) {
#define INVALID_TYPE_MATCH(x, y) \
if (type == x && fboTexType == y) return false; \
if (type == y && fboTexType == x) return false; \
// These are meant to reject additional format/type mismatches
// not caught by underlying system.
INVALID_TYPE_MATCH(GL_FLOAT, GL_BYTE)
INVALID_TYPE_MATCH(GL_FLOAT, GL_UNSIGNED_BYTE)
INVALID_TYPE_MATCH(GL_FLOAT, GL_UNSIGNED_INT)
INVALID_TYPE_MATCH(GL_FLOAT, GL_INT)
return true;
}
bool blitFramebufferFormat(GLenum readFormat, GLenum drawFormat) {
#define INVALID_MATCH(x, y) \
if (readFormat == x && drawFormat == y) return false; \
if (readFormat == y && drawFormat == x) return false; \
INVALID_MATCH(GL_FLOAT, GL_BYTE)
INVALID_MATCH(GL_FLOAT, GL_UNSIGNED_BYTE)
INVALID_MATCH(GL_FLOAT, GL_UNSIGNED_INT)
INVALID_MATCH(GL_FLOAT, GL_INT)
INVALID_MATCH(GL_INT, GL_UNSIGNED_BYTE);
INVALID_MATCH(GL_UNSIGNED_INT, GL_UNSIGNED_BYTE);
INVALID_MATCH(GL_INT, GL_BYTE);
INVALID_MATCH(GL_UNSIGNED_INT, GL_BYTE);
INVALID_MATCH(GL_DEPTH32F_STENCIL8, GL_DEPTH24_STENCIL8);
return true;
}
bool textureTarget(GL2Encoder* ctx, GLenum target) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
switch (target) {
case GL_TEXTURE_EXTERNAL_OES:
case GL_TEXTURE_2D:
case GL_TEXTURE_CUBE_MAP:
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
return true;
case GL_TEXTURE_2D_ARRAY:
case GL_TEXTURE_3D:
return glesMajorVersion >= 3;
case GL_TEXTURE_2D_MULTISAMPLE:
return glesMajorVersion >= 3 &&
glesMinorVersion >= 1;
default:
break;
}
return false;
}
bool textureParams(GL2Encoder* ctx, GLenum param) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
switch(param) {
case GL_TEXTURE_MIN_FILTER:
case GL_TEXTURE_MAG_FILTER:
case GL_TEXTURE_WRAP_S:
case GL_TEXTURE_WRAP_T:
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
return true;
case GL_TEXTURE_SWIZZLE_R:
case GL_TEXTURE_SWIZZLE_G:
case GL_TEXTURE_SWIZZLE_B:
case GL_TEXTURE_SWIZZLE_A:
case GL_TEXTURE_MIN_LOD:
case GL_TEXTURE_MAX_LOD:
case GL_TEXTURE_BASE_LEVEL:
case GL_TEXTURE_MAX_LEVEL:
case GL_TEXTURE_COMPARE_MODE:
case GL_TEXTURE_COMPARE_FUNC:
case GL_TEXTURE_WRAP_R:
case GL_TEXTURE_IMMUTABLE_FORMAT:
case GL_TEXTURE_IMMUTABLE_LEVELS:
return glesMajorVersion >= 3;
case GL_DEPTH_STENCIL_TEXTURE_MODE:
return glesMajorVersion >= 3 && glesMinorVersion >= 1;
default:
return false;
}
}
bool samplerParams(GL2Encoder* ctx, GLenum param) {
(void)ctx;
switch(param) {
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
case GL_TEXTURE_MIN_FILTER:
case GL_TEXTURE_MAG_FILTER:
case GL_TEXTURE_WRAP_S:
case GL_TEXTURE_WRAP_T:
case GL_TEXTURE_WRAP_R:
case GL_TEXTURE_MIN_LOD:
case GL_TEXTURE_MAX_LOD:
case GL_TEXTURE_COMPARE_MODE:
case GL_TEXTURE_COMPARE_FUNC:
return true;
default:
return false;
}
}
bool textureParamValue(GL2Encoder* ctx, GLenum pname, GLint intval, GLfloat floatval, GLenum enumval) {
(void)ctx;
(void)floatval;
switch (pname) {
case GL_TEXTURE_BASE_LEVEL:
return intval >= 0;
case GL_TEXTURE_COMPARE_MODE:
return
(enumval == GL_NONE) ||
(enumval == GL_COMPARE_REF_TO_TEXTURE);
case GL_TEXTURE_COMPARE_FUNC:
return
(enumval == GL_LEQUAL) ||
(enumval == GL_GEQUAL) ||
(enumval == GL_LESS) ||
(enumval == GL_GREATER) ||
(enumval == GL_EQUAL) ||
(enumval == GL_NOTEQUAL) ||
(enumval == GL_ALWAYS) ||
(enumval == GL_NEVER);
case GL_TEXTURE_MAG_FILTER:
return
(enumval == GL_NEAREST) ||
(enumval == GL_LINEAR);
case GL_TEXTURE_MAX_LEVEL:
return intval >= 0;
case GL_TEXTURE_MAX_LOD:
return true;
case GL_TEXTURE_MIN_FILTER:
return
(enumval == GL_NEAREST) ||
(enumval == GL_LINEAR) ||
(enumval == GL_NEAREST_MIPMAP_NEAREST) ||
(enumval == GL_NEAREST_MIPMAP_LINEAR) ||
(enumval == GL_LINEAR_MIPMAP_NEAREST) ||
(enumval == GL_LINEAR_MIPMAP_LINEAR);
case GL_TEXTURE_MIN_LOD:
return true;
case GL_TEXTURE_SWIZZLE_R:
case GL_TEXTURE_SWIZZLE_G:
case GL_TEXTURE_SWIZZLE_B:
case GL_TEXTURE_SWIZZLE_A:
return
(enumval == GL_RED) ||
(enumval == GL_GREEN) ||
(enumval == GL_BLUE) ||
(enumval == GL_ALPHA) ||
(enumval == GL_ZERO) ||
(enumval == GL_ONE);
case GL_TEXTURE_WRAP_S:
case GL_TEXTURE_WRAP_T:
case GL_TEXTURE_WRAP_R:
return
(enumval == GL_CLAMP_TO_EDGE) ||
(enumval == GL_REPEAT) ||
(enumval == GL_MIRRORED_REPEAT);
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
return true;
case GL_TEXTURE_IMMUTABLE_FORMAT:
case GL_TEXTURE_IMMUTABLE_LEVELS:
case GL_DEPTH_STENCIL_TEXTURE_MODE:
return true;
default:
return true;
}
}
bool isIntegerFormat(GLenum format) {
#define CHECK_EQUAL(x) case x: return true;
switch (format) {
LIST_INTEGER_TEX_FORMATS(CHECK_EQUAL)
default:
return false;
}
}
bool isCompressedFormat(GLenum internalformat) {
#define COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(internal) \
case internal: \
return true; \
switch (internalformat) {
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_R11_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SIGNED_R11_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RG11_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SIGNED_RG11_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGB8_ETC2)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ETC2)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA8_ETC2_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_4x4_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_5x4_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_5x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_6x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_6x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_8x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_8x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_8x8_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_10x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_10x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_10x8_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_10x10_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_12x10_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_RGBA_ASTC_12x12_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR)
COMPRESSED_TEX_IMAGE_IS_COMPRESSED_FORMAT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR)
default:
break;
}
return false;
}
bool supportedCompressedFormat(GL2Encoder* ctx, GLenum internalformat) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
#define COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(internal) \
case internal: \
return glesMajorVersion > 1 && ctx->hasExtension("GL_KHR_texture_compression_astc_ldr"); \
#define COMPRESSED_TEX_IMAGE_SUPPORT_CASE_BPTC(internal) \
case internal: \
return glesMajorVersion > 1 && ctx->hasExtension("GL_EXT_texture_compression_bptc"); \
#define COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(internal) \
case internal: \
return glesMajorVersion > 1 && ctx->hasExtension("GL_EXT_texture_compression_s3tc"); \
#define COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC_SRGB(internal) \
case internal: \
return glesMajorVersion > 1 && ctx->hasExtension("GL_EXT_texture_compression_s3tc") && ctx->hasExtension("GL_EXT_texture_sRGB"); \
#define COMPRESSED_TEX_IMAGE_SUPPORT_CASE(internal, maj, min) \
case internal: \
if (maj < 3) return true; \
if (glesMajorVersion < maj) return false; \
if (glesMinorVersion < min) return false; \
break; \
#define COMPRESSED_TEX_IMAGE_NOTSUPPORTED(internal) \
case internal: \
return false ; \
switch (internalformat) {
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_ETC1_RGB8_OES, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_R11_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_SIGNED_R11_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_RG11_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_SIGNED_RG11_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_RGB8_ETC2, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_SRGB8_ETC2, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_RGBA8_ETC2_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, 2, 0)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_4x4_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_5x4_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_5x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_6x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_6x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_8x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_8x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_8x8_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_10x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_10x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_10x8_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_10x10_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_12x10_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_RGBA_ASTC_12x12_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_ASTC(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_BPTC(GL_COMPRESSED_RGBA_BPTC_UNORM_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_BPTC(GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_BPTC(GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_BPTC(GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(GL_COMPRESSED_RGB_S3TC_DXT1_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC_SRGB(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC_SRGB(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT)
COMPRESSED_TEX_IMAGE_SUPPORT_CASE_S3TC_SRGB(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT)
default:
break;
}
return false;
}
bool unsizedFormat(GLenum format) {
switch (format) {
case GL_RED:
case GL_RED_INTEGER:
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL:
case GL_RG:
case GL_RG_INTEGER:
case GL_RGB:
case GL_RGB_INTEGER:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
}
return false;
}
// TODO: fix this
bool filterableTexFormat(GL2Encoder* ctx, GLenum internalformat) {
switch (internalformat) {
case GL_R32F:
case GL_RG32F:
case GL_RGB32F:
case GL_RGBA32F:
return ctx->hasExtension("GL_OES_texture_float");
case GL_R8UI:
case GL_R8I:
case GL_R16UI:
case GL_R16I:
case GL_R32UI:
case GL_R32I:
case GL_RG8UI:
case GL_RG8I:
case GL_RG16UI:
case GL_RG16I:
case GL_RG32UI:
case GL_RG32I:
case GL_RGBA8UI:
case GL_RGBA8I:
case GL_RGB10_A2UI:
case GL_RGBA16UI:
case GL_RGBA16I:
case GL_RGBA32I:
case GL_RGBA32UI:
return false;
}
return true;
}
bool colorRenderableFormat(GL2Encoder* ctx, GLenum internalformat) {
int glesMajorVersion = ctx->majorVersion();
switch (internalformat) {
case GL_R8:
case GL_RG8:
case GL_RGB8:
case GL_RGB565:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGBA8:
case GL_RGB10_A2:
case GL_RGB10_A2UI:
case GL_SRGB8_ALPHA8:
case GL_R8I:
case GL_R8UI:
case GL_R16I:
case GL_R16UI:
case GL_R32I:
case GL_R32UI:
case GL_RG8I:
case GL_RG8UI:
case GL_RG16I:
case GL_RG16UI:
case GL_RG32I:
case GL_RG32UI:
case GL_RGBA8I:
case GL_RGBA8UI:
case GL_RGBA16I:
case GL_RGBA16UI:
case GL_RGBA32I:
case GL_RGBA32UI:
return true;
case GL_R16F:
case GL_RG16F:
case GL_RGBA16F:
case GL_R32F:
case GL_RG32F:
case GL_RGBA32F:
case GL_R11F_G11F_B10F:
return glesMajorVersion >= 3 && ctx->hasExtension("GL_EXT_color_buffer_float");
break;
case GL_RGB16F:
return glesMajorVersion >= 3 && ctx->hasExtension("GL_EXT_color_buffer_half_float");
break;
}
return false;
}
bool depthRenderableFormat(GL2Encoder* ctx, GLenum internalformat) {
switch (internalformat) {
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32F:
case GL_DEPTH24_STENCIL8:
case GL_DEPTH32F_STENCIL8:
return true;
case GL_DEPTH_COMPONENT32_OES:
return ctx->hasExtension("GL_OES_depth32");
}
return false;
}
bool stencilRenderableFormat(GL2Encoder*, GLenum internalformat) {
switch (internalformat) {
case GL_DEPTH_STENCIL:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8:
case GL_DEPTH32F_STENCIL8:
return true;
}
return false;
}
bool isCubeMapTarget(GLenum target) {
switch (target) {
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
return true;
default:
break;
}
return false;
}
#define LIST_VALID_TEXFORMATS(f) \
f(GL_DEPTH_COMPONENT) \
f(GL_DEPTH_STENCIL) \
f(GL_RED) \
f(GL_RED_INTEGER) \
f(GL_RG) \
f(GL_RGB) \
f(GL_RGBA) \
f(GL_RGBA_INTEGER) \
f(GL_RGB_INTEGER) \
f(GL_RG_INTEGER) \
f(GL_BGRA_EXT) \
f(GL_ALPHA) \
f(GL_LUMINANCE) \
f(GL_LUMINANCE_ALPHA) \
#define LIST_VALID_TEXTYPES(f) \
f(GL_BYTE) \
f(GL_FLOAT) \
f(GL_FLOAT_32_UNSIGNED_INT_24_8_REV) \
f(GL_HALF_FLOAT) \
f(GL_HALF_FLOAT_OES) \
f(GL_INT) \
f(GL_SHORT) \
f(GL_UNSIGNED_BYTE) \
f(GL_UNSIGNED_INT) \
f(GL_UNSIGNED_INT_10F_11F_11F_REV) \
f(GL_UNSIGNED_INT_2_10_10_10_REV) \
f(GL_UNSIGNED_INT_24_8) \
f(GL_UNSIGNED_INT_5_9_9_9_REV) \
f(GL_UNSIGNED_SHORT) \
f(GL_UNSIGNED_SHORT_4_4_4_4) \
f(GL_UNSIGNED_SHORT_5_5_5_1) \
f(GL_UNSIGNED_SHORT_5_6_5) \
bool pixelType(GL2Encoder* ctx, GLenum type) {
int glesMajorVersion = ctx->majorVersion();
if (glesMajorVersion < 3) {
switch (type) {
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_24_8:
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
case GL_FLOAT:
return true;
}
return false;
}
#define GLES3_TYPE_CASE(type) \
case type: \
switch (type) {
LIST_VALID_TEXTYPES(GLES3_TYPE_CASE)
return glesMajorVersion >= 3;
default:
break;
}
return false;
}
bool pixelFormat(GL2Encoder* ctx, GLenum format) {
int glesMajorVersion = ctx->majorVersion();
if (glesMajorVersion < 3) {
switch (format) {
case GL_DEPTH_COMPONENT:
// GLES3 compatible
// Required in dEQP
case GL_RED:
case GL_RG:
case GL_DEPTH_STENCIL_OES:
case GL_ALPHA:
case GL_RGB:
case GL_RGBA:
case GL_BGRA_EXT:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
}
return false;
}
#define GLES3_FORMAT_CASE(format) \
case format:
switch (format) {
LIST_VALID_TEXFORMATS(GLES3_FORMAT_CASE)
return glesMajorVersion >= 3;
default:
break;
}
return false;
}
bool pixelInternalFormat(GLenum internalformat) {
#define VALID_INTERNAL_FORMAT(format) \
case format: \
return true; \
switch (internalformat) {
LIST_VALID_TEX_INTERNALFORMATS(VALID_INTERNAL_FORMAT)
default:
break;
}
ALOGW("error internal format: 0x%x is invalid\n", internalformat);
return false;
}
bool pixelSizedFormat(GL2Encoder* ctx, GLenum internalformat, GLenum format, GLenum type) {
int glesMajorVersion = ctx->majorVersion();
if (internalformat == format) {
return true;
}
if (glesMajorVersion < 3) {
switch (format) {
case GL_RED:
switch (type) {
case GL_UNSIGNED_BYTE:
return internalformat == GL_R8;
case GL_HALF_FLOAT:
case GL_FLOAT:
return internalformat == GL_R16F;
case GL_BYTE:
return internalformat == GL_R8_SNORM;
default:
return false;
}
break;
case GL_RG:
switch (type) {
case GL_UNSIGNED_BYTE:
return internalformat == GL_RG8;
case GL_HALF_FLOAT:
case GL_FLOAT:
return internalformat == GL_RG16F;
default:
return false;
}
break;
case GL_RGB:
switch (type) {
case GL_HALF_FLOAT:
case GL_FLOAT:
return internalformat == GL_RGB16F
|| internalformat == GL_R11F_G11F_B10F;
case GL_UNSIGNED_INT_10F_11F_11F_REV:
return internalformat == GL_R11F_G11F_B10F;
default:
return internalformat == GL_RGB8 ||
internalformat == GL_RGB;
}
break;
case GL_RGBA:
switch (type) {
case GL_HALF_FLOAT:
case GL_FLOAT:
return internalformat == GL_RGBA16F;
default:
return internalformat == GL_RGBA8 ||
internalformat == GL_RGBA;
}
break;
}
}
#define VALIDATE_FORMAT_COMBINATION(x, y, z) \
if (internalformat == x && format == y && type == z) return true; \
LIST_VALID_TEXFORMAT_COMBINATIONS(VALIDATE_FORMAT_COMBINATION)
return false;
}
void getCompatibleFormatTypeForInternalFormat(GLenum internalformat, GLenum* format_out, GLenum* type_out) {
#define RETURN_COMPATIBLE_FORMAT(x, y, z) \
if (internalformat == x) { \
*format_out = y; \
*type_out = z; \
return; \
} \
LIST_VALID_TEXFORMAT_COMBINATIONS(RETURN_COMPATIBLE_FORMAT)
}
bool shaderType(GL2Encoder* ctx, GLenum type) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
switch (type) {
case GL_VERTEX_SHADER:
case GL_FRAGMENT_SHADER:
return true;
case GL_COMPUTE_SHADER:
return glesMajorVersion >= 3 && glesMinorVersion >= 1;
}
return false;
}
bool internalFormatTarget(GL2Encoder* ctx, GLenum target) {
int glesMajorVersion = ctx->majorVersion();
int glesMinorVersion = ctx->minorVersion();
switch (target) {
case GL_RENDERBUFFER:
return true;
case GL_TEXTURE_2D_MULTISAMPLE:
return glesMajorVersion >= 3 && glesMinorVersion >= 1;
}
return false;
}
std::string vertexAttribIndexRangeErrorMsg(GL2Encoder* ctx, GLuint index) {
std::stringstream ss;
GLint maxIndex;
ctx->glGetIntegerv(ctx, GL_MAX_VERTEX_ATTRIBS, &maxIndex);
ss << "Invalid vertex attribute index. Wanted index: " << index << ". Max index: " << maxIndex;
return ss.str();
}
bool allowedFace(GLenum face) {
switch (face) {
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
return true;
default:
return false;
}
}
bool allowedFunc(GLenum func) {
switch (func) {
case GL_NEVER:
case GL_ALWAYS:
case GL_LESS:
case GL_LEQUAL:
case GL_EQUAL:
case GL_GREATER:
case GL_GEQUAL:
case GL_NOTEQUAL:
return true;
default:
return false;
}
}
bool allowedStencilOp(GLenum op) {
switch (op) {
case GL_KEEP:
case GL_ZERO:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
return true;
default:
return false;
}
}
bool allowedBlendEquation(GLenum eq) {
switch (eq) {
case GL_FUNC_ADD:
case GL_FUNC_SUBTRACT:
case GL_FUNC_REVERSE_SUBTRACT:
case GL_MIN:
case GL_MAX:
return true;
default:
return false;
}
}
bool allowedBlendFunc(GLenum func) {
switch (func) {
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
case GL_SRC_ALPHA_SATURATE:
return true;
default:
return false;
}
}
bool allowedCullFace(GLenum mode) {
switch (mode) {
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
return true;
default:
return false;
}
}
bool allowedFrontFace(GLenum mode) {
switch (mode) {
case GL_CCW:
case GL_CW:
return true;
default:
return false;
}
}
bool allowedEnable(int majorVersion, int minorVersion, GLenum cap) {
switch (cap) {
case GL_CULL_FACE:
case GL_POLYGON_OFFSET_FILL:
case GL_SAMPLE_ALPHA_TO_COVERAGE:
case GL_SAMPLE_COVERAGE:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST:
case GL_DEPTH_TEST:
case GL_BLEND:
case GL_DITHER:
return true;
case GL_PRIMITIVE_RESTART_FIXED_INDEX:
case GL_RASTERIZER_DISCARD:
return majorVersion >= 3;
case GL_SAMPLE_MASK:
return majorVersion >= 3 && minorVersion >= 1;
default:
return false;
}
}
bool allowedGetShader(GLenum pname) {
switch (pname) {
case GL_SHADER_TYPE:
case GL_DELETE_STATUS:
case GL_COMPILE_STATUS:
case GL_INFO_LOG_LENGTH:
case GL_SHADER_SOURCE_LENGTH:
return true;
default:
return false;
}
}
bool allowedShaderType(GLenum shadertype) {
switch (shadertype) {
case GL_VERTEX_SHADER:
case GL_FRAGMENT_SHADER:
return true;
default:
return false;
}
}
bool allowedPrecisionType(GLenum precisiontype) {
switch (precisiontype) {
case GL_LOW_FLOAT:
case GL_MEDIUM_FLOAT:
case GL_HIGH_FLOAT:
case GL_LOW_INT:
case GL_MEDIUM_INT:
case GL_HIGH_INT:
return true;
default:
return false;
}
}
bool allowedGetProgram(int majorVersion, int minorVersion, GLenum pname) {
switch (pname) {
case GL_DELETE_STATUS:
case GL_LINK_STATUS:
case GL_VALIDATE_STATUS:
case GL_INFO_LOG_LENGTH:
case GL_ATTACHED_SHADERS:
case GL_ACTIVE_ATTRIBUTES:
case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
case GL_ACTIVE_UNIFORMS:
case GL_ACTIVE_UNIFORM_MAX_LENGTH:
return true;
case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
case GL_PROGRAM_BINARY_LENGTH:
case GL_TRANSFORM_FEEDBACK_VARYINGS:
case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH:
case GL_ACTIVE_UNIFORM_BLOCKS:
case GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH:
return majorVersion > 2;
case GL_COMPUTE_WORK_GROUP_SIZE:
case GL_PROGRAM_SEPARABLE:
case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
return majorVersion > 2 && minorVersion > 0;
default:
return false;
}
}
bool allowedGetActiveUniforms(GLenum pname) {
switch (pname) {
case GL_UNIFORM_TYPE:
case GL_UNIFORM_SIZE:
case GL_UNIFORM_NAME_LENGTH:
case GL_UNIFORM_BLOCK_INDEX:
case GL_UNIFORM_OFFSET:
case GL_UNIFORM_ARRAY_STRIDE:
case GL_UNIFORM_MATRIX_STRIDE:
case GL_UNIFORM_IS_ROW_MAJOR:
return true;
default:
return false;
}
}
bool allowedGetActiveUniformBlock(GLenum pname) {
switch (pname) {
case GL_UNIFORM_BLOCK_BINDING:
case GL_UNIFORM_BLOCK_DATA_SIZE:
case GL_UNIFORM_BLOCK_NAME_LENGTH:
case GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS:
case GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES:
case GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER:
case GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER:
return true;
default:
return false;
}
}
bool allowedGetVertexAttrib(GLenum pname) {
switch (pname) {
case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
case GL_VERTEX_ATTRIB_ARRAY_SIZE:
case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
case GL_VERTEX_ATTRIB_ARRAY_TYPE:
case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
case GL_VERTEX_ATTRIB_ARRAY_INTEGER:
case GL_VERTEX_ATTRIB_ARRAY_DIVISOR:
case GL_VERTEX_ATTRIB_BINDING:
case GL_VERTEX_ATTRIB_RELATIVE_OFFSET:
case GL_CURRENT_VERTEX_ATTRIB:
return true;
default:
return false;
}
}
bool allowedGetRenderbufferParameter(GLenum pname) {
switch (pname) {
case GL_RENDERBUFFER_WIDTH:
case GL_RENDERBUFFER_HEIGHT:
case GL_RENDERBUFFER_INTERNAL_FORMAT:
case GL_RENDERBUFFER_RED_SIZE:
case GL_RENDERBUFFER_GREEN_SIZE:
case GL_RENDERBUFFER_BLUE_SIZE:
case GL_RENDERBUFFER_ALPHA_SIZE:
case GL_RENDERBUFFER_DEPTH_SIZE:
case GL_RENDERBUFFER_STENCIL_SIZE:
case GL_RENDERBUFFER_SAMPLES:
return true;
default:
return false;
}
}
bool allowedQueryTarget(GLenum target) {
switch (target) {
case GL_ANY_SAMPLES_PASSED:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
return true;
default:
return false;
}
}
bool allowedQueryParam(GLenum pname) {
switch (pname) {
case GL_CURRENT_QUERY:
return true;
default:
return false;
}
}
bool allowedQueryObjectParam(GLenum pname) {
switch (pname) {
case GL_QUERY_RESULT:
case GL_QUERY_RESULT_AVAILABLE:
return true;
default:
return false;
}
}
bool allowedGetSyncParam(GLenum pname) {
switch (pname) {
case GL_OBJECT_TYPE:
case GL_SYNC_STATUS:
case GL_SYNC_CONDITION:
case GL_SYNC_FLAGS:
return true;
default:
return false;
}
}
bool allowedHintTarget(GLenum target) {
switch (target) {
case GL_GENERATE_MIPMAP_HINT:
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
return true;
default:
return false;
}
}
bool allowedHintMode(GLenum mode) {
switch (mode) {
case GL_DONT_CARE:
case GL_NICEST:
case GL_FASTEST:
return true;
default:
return false;
}
}
} // namespace GLESv2Validation
| 32.931078 | 136 | 0.705335 | [
"transform"
] |
170fd016a12d83b259580fd0e9a174de7ae41f58 | 5,652 | cpp | C++ | test/stlperf_test.cpp | kohei101/multidimalgorithm | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | 3 | 2018-10-08T16:30:06.000Z | 2018-10-24T05:05:11.000Z | test/stlperf_test.cpp | kohei101/mdds | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | null | null | null | test/stlperf_test.cpp | kohei101/mdds | c479747d204b8953933fdbec9a88650a75b822b7 | [
"MIT"
] | null | null | null | /*************************************************************************
*
* Copyright (c) 2010 Kohei Yoshida
*
* 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 <vector>
#include <unordered_set>
#include <set>
#include <list>
#include <algorithm>
#include <cassert>
#include <stdio.h>
#include <string>
#include <sys/time.h>
using namespace std;
namespace {
class StackPrinter
{
public:
explicit StackPrinter(const char* msg) : msMsg(msg)
{
fprintf(stdout, "%s: --begin\n", msMsg.c_str());
mfStartTime = getTime();
}
~StackPrinter()
{
double fEndTime = getTime();
fprintf(stdout, "%s: --end (duration: %g sec)\n", msMsg.c_str(), (fEndTime - mfStartTime));
}
void printTime(int line) const
{
double fEndTime = getTime();
fprintf(stdout, "%s: --(%d) (duration: %g sec)\n", msMsg.c_str(), line, (fEndTime - mfStartTime));
}
private:
double getTime() const
{
timeval tv;
gettimeofday(&tv, nullptr);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
::std::string msMsg;
double mfStartTime;
};
} // namespace
int main()
{
size_t store_size = 100000;
{
StackPrinter __stack_printer__("vector non-reserved");
vector<void*> store;
{
StackPrinter __stack_printer2__(" push_back");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
{
// coverity[dereference] - this is intentional
store.push_back(ptr++);
}
}
{
StackPrinter __stack_printer2__(" find and pop_back");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
{
vector<void*>::iterator itr = find(store.begin(), store.end(), ptr);
if (itr != store.end())
{
*itr = store.back();
store.pop_back();
}
// coverity[dereference] - this is intentional
++ptr;
}
}
assert(store.empty());
}
{
StackPrinter __stack_printer__("vector reserved");
vector<void*> store;
{
StackPrinter __stack_printer2__(" push_back");
string* ptr = 0x00000000;
store.reserve(store_size);
for (size_t i = 0; i < store_size; ++i)
store.push_back(ptr++);
}
{
StackPrinter __stack_printer2__(" find and pop_back");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
{
vector<void*>::iterator itr = find(store.begin(), store.end(), ptr);
if (itr != store.end())
{
*itr = store.back();
store.pop_back();
}
++ptr;
}
}
assert(store.empty());
}
{
StackPrinter __stack_printer__("list");
list<void*> store;
{
StackPrinter __stack_printer2__(" push_back");
string* ptr = 0x00000000;
++ptr;
for (size_t i = 0; i < store_size; ++i)
store.push_back(ptr++);
}
{
StackPrinter __stack_printer2__(" remove");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
store.remove(ptr++);
}
}
{
StackPrinter __stack_printer__("set");
set<void*> store;
{
StackPrinter __stack_printer2__(" insert");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
store.insert(ptr++);
}
{
StackPrinter __stack_printer2__(" erase");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
store.erase(ptr++);
}
}
{
StackPrinter __stack_printer__("unordered set");
unordered_set<void*> store;
{
StackPrinter __stack_printer2__(" insert");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
store.insert(ptr++);
}
{
StackPrinter __stack_printer2__(" erase");
string* ptr = 0x00000000;
for (size_t i = 0; i < store_size; ++i)
store.erase(ptr++);
}
}
}
| 29.747368 | 106 | 0.524947 | [
"vector"
] |
1712e315f96c5334ae9f4f4f69f7182772015528 | 322 | cpp | C++ | v_0_1/Passengers_file/Mastercode.cpp | TimoLoomets/TeamSuccessRobotex2018Taxify | 702da19a93761892174f3950924e0da07ea0c568 | [
"MIT"
] | 1 | 2018-07-03T21:17:29.000Z | 2018-07-03T21:17:29.000Z | v_0_1/Passengers_file/Mastercode.cpp | TimoLoomets/TeamSuccessRobotex2018Taxify | 702da19a93761892174f3950924e0da07ea0c568 | [
"MIT"
] | null | null | null | v_0_1/Passengers_file/Mastercode.cpp | TimoLoomets/TeamSuccessRobotex2018Taxify | 702da19a93761892174f3950924e0da07ea0c568 | [
"MIT"
] | 2 | 2018-07-03T21:17:31.000Z | 2018-07-06T15:55:21.000Z | #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <locale>
#include <iomanip>
#include <time.h>
#include <stdio.h>
using namespace std;
void main() {
}; | 15.333333 | 21 | 0.65528 | [
"vector"
] |
1717f27176c7b27d64005a1f3918dcd86390a3c3 | 10,920 | cpp | C++ | FortniteCheatSRCUpdateEveryUpdate/Source Files/util/Util.cpp | Visual9999/FortniteCheatSRCUpdateEveryUpdate | 830e25b0ddcdb3e8540eadb72fdf4014161d9d42 | [
"Apache-2.0"
] | 112 | 2020-08-25T19:26:11.000Z | 2022-02-24T16:03:39.000Z | FortniteCheatSRCUpdateEveryUpdate/Source Files/util/Util.cpp | masterpaster-ritz/FortniteCheatSRCUpdateEveryUpdate | 830e25b0ddcdb3e8540eadb72fdf4014161d9d42 | [
"Apache-2.0"
] | 50 | 2020-09-05T06:26:22.000Z | 2022-03-30T13:34:11.000Z | FortniteCheatSRCUpdateEveryUpdate/Source Files/util/Util.cpp | masterpaster-ritz/FortniteCheatSRCUpdateEveryUpdate | 830e25b0ddcdb3e8540eadb72fdf4014161d9d42 | [
"Apache-2.0"
] | 63 | 2020-08-28T08:28:53.000Z | 2022-02-24T16:03:04.000Z | /*
Visual#9999, Updated by bunyip24#9999, sigs fixed by homeless1337-
*/
#include "../../Header Files/includes.h"
#include "../../DiscordHook/Discord.h"
#include "../../Header Files/xorstr.h"
#include "../../imgui/imgui_xorstr.h"
#include <corecrt_math.h>
namespace Util {
GObjects* objects = nullptr;
FString(*GetObjectNameInternal)(PVOID) = nullptr;
VOID(*FreeInternal)(PVOID) = nullptr;
BOOL(*LineOfSightToInternal)(PVOID PlayerController, PVOID Actor, FVector* ViewPoint) = nullptr;
VOID(*CalculateProjectionMatrixGivenView)(FMinimalViewInfo* viewInfo, BYTE aspectRatioAxisConstraint, PBYTE viewport, FSceneViewProjectionData* inOutProjectionData) = nullptr;
struct {
FMinimalViewInfo Info;
float ProjectionMatrix[4][4];
} view = { 0 };
VOID CreateConsole() {
AllocConsole();
static_cast<VOID>(freopen("CONIN$", xorstr("r"), stdin));
static_cast<VOID>(freopen("CONOUT$", xorstr("w"), stdout));
static_cast<VOID>(freopen("CONOUT$", xorstr("w"), stderr));
}
BOOLEAN MaskCompare(PVOID buffer, LPCSTR pattern, LPCSTR mask) {
for (auto b = reinterpret_cast<PBYTE>(buffer); *mask; ++pattern, ++mask, ++b) {
if (*mask == ('x') && *reinterpret_cast<LPCBYTE>(pattern) != *b) {
return FALSE;
}
}
return TRUE;
}
PBYTE FindPattern(PVOID base, DWORD size, LPCSTR pattern, LPCSTR mask) {
size -= static_cast<DWORD>(strlen(mask));
for (auto i = 0UL; i < size; ++i) {
auto addr = reinterpret_cast<PBYTE>(base) + i;
if (MaskCompare(addr, pattern, mask)) {
return addr;
}
}
return NULL;
}
PBYTE FindPattern(LPCSTR pattern, LPCSTR mask) {
MODULEINFO info = { 0 };
GetModuleInformation(GetCurrentProcess(), GetModuleHandle(0), &info, sizeof(info));
return FindPattern(info.lpBaseOfDll, info.SizeOfImage, pattern, mask);
}
VOID Free(PVOID buffer) {
FreeInternal(buffer);
}
std::wstring GetObjectFirstName(UObject* object) {
auto internalName = GetObjectNameInternal(object);
if (!internalName.c_str()) {
return L"";
}
std::wstring name(internalName.c_str());
Free(internalName.c_str());
return name;
}
std::wstring GetObjectName(UObject* object) {
std::wstring name(L"");
for (auto i = 0; object; object = object->Outer, ++i) {
auto internalName = GetObjectNameInternal(object);
if (!internalName.c_str()) {
break;
}
name = internalName.c_str() + std::wstring(i > 0 ? (xorstr(L".")) : xorstr(L"")) + name;
Free(internalName.c_str());
}
return name;
}
BOOLEAN GetOffsets(std::vector<Offsets::OFFSET>& offsets) {
auto current = 0ULL;
auto size = offsets.size();
for (auto array : objects->ObjectArray->Objects) {
auto fuObject = array;
for (auto i = 0; i < 0x10000 && fuObject->Object; ++i, ++fuObject) {
auto object = fuObject->Object;
if (object->ObjectFlags != 0x41) {
continue;
}
auto name = GetObjectName(object);
for (auto& o : offsets) {
if (!o.Offset && name == o.Name) {
o.Offset = *reinterpret_cast<PDWORD>(reinterpret_cast<PBYTE>(object) + 0x44);
if (++current == size) {
return TRUE;
}
break;
}
}
}
}
for (auto& o : offsets) {
if (!o.Offset) {
WCHAR buffer[0xFF] = { 0 };
wsprintf(buffer, xorstr(L"Offset %ws not found"), o.Name);
MessageBox(0, buffer, xorstr(L"Failure"), 0);
}
}
return FALSE;
}
PVOID FindObject(LPCWSTR name) {
for (auto array : objects->ObjectArray->Objects) {
auto fuObject = array;
for (auto i = 0; i < 0x10000 && fuObject->Object; ++i, ++fuObject) {
auto object = fuObject->Object;
if (object->ObjectFlags != 0x41) {
continue;
}
if (GetObjectName(object) == name) {
return object;
}
}
}
return 0;
}
VOID ToMatrixWithScale(float* in, float out[4][4])
{
auto* rotation = &in[0];
auto* translation = &in[4];
auto* scale = &in[8];
out[3][0] = translation[0];
out[3][1] = translation[1];
out[3][2] = translation[2];
auto x2 = rotation[0] + rotation[0];
auto y2 = rotation[1] + rotation[1];
auto z2 = rotation[2] + rotation[2];
auto xx2 = rotation[0] * x2;
auto yy2 = rotation[1] * y2;
auto zz2 = rotation[2] * z2;
out[0][0] = (1.0f - (yy2 + zz2)) * scale[0];
out[1][1] = (1.0f - (xx2 + zz2)) * scale[1];
out[2][2] = (1.0f - (xx2 + yy2)) * scale[2];
auto yz2 = rotation[1] * z2;
auto wx2 = rotation[3] * x2;
out[2][1] = (yz2 - wx2) * scale[2];
out[1][2] = (yz2 + wx2) * scale[1];
auto xy2 = rotation[0] * y2;
auto wz2 = rotation[3] * z2;
out[1][0] = (xy2 - wz2) * scale[1];
out[0][1] = (xy2 + wz2) * scale[0];
auto xz2 = rotation[0] * z2;
auto wy2 = rotation[3] * y2;
out[2][0] = (xz2 + wy2) * scale[2];
out[0][2] = (xz2 - wy2) * scale[0];
out[0][3] = 0.0f;
out[1][3] = 0.0f;
out[2][3] = 0.0f;
out[3][3] = 1.0f;
}
VOID MultiplyMatrices(float a[4][4], float b[4][4], float out[4][4]) {
for (auto r = 0; r < 4; ++r) {
for (auto c = 0; c < 4; ++c) {
auto sum = 0.0f;
for (auto i = 0; i < 4; ++i) {
sum += a[r][i] * b[i][c];
}
out[r][c] = sum;
}
}
}
VOID GetBoneLocation(float compMatrix[4][4], PVOID bones, DWORD index, float out[3]) {
float boneMatrix[4][4];
ToMatrixWithScale((float*)((PBYTE)bones + (index * 0x30)), boneMatrix);
float result[4][4];
MultiplyMatrices(boneMatrix, compMatrix, result);
out[0] = result[3][0];
out[1] = result[3][1];
out[2] = result[3][2];
}
VOID GetViewProjectionMatrix(FSceneViewProjectionData* projectionData, float out[4][4]) {
auto loc = &projectionData->ViewOrigin;
float translation[4][4] = {
{ 1.0f, 0.0f, 0.0f, 0.0f, },
{ 0.0f, 1.0f, 0.0f, 0.0f, },
{ 0.0f, 0.0f, 1.0f, 0.0f, },
{ -loc->X, -loc->Y, -loc->Z, 0.0f, },
};
float temp[4][4];
MultiplyMatrices(translation, projectionData->ViewRotationMatrix.M, temp);
MultiplyMatrices(temp, projectionData->ProjectionMatrix.M, out);
}
BOOLEAN ProjectWorldToScreen(float viewProjection[4][4], float width, float height, float inOutPosition[3]) {
float res[4] = {
viewProjection[0][0] * inOutPosition[0] + viewProjection[1][0] * inOutPosition[1] + viewProjection[2][0] * inOutPosition[2] + viewProjection[3][0],
viewProjection[0][1] * inOutPosition[0] + viewProjection[1][1] * inOutPosition[1] + viewProjection[2][1] * inOutPosition[2] + viewProjection[3][1],
viewProjection[0][2] * inOutPosition[0] + viewProjection[1][2] * inOutPosition[1] + viewProjection[2][2] * inOutPosition[2] + viewProjection[3][2],
viewProjection[0][3] * inOutPosition[0] + viewProjection[1][3] * inOutPosition[1] + viewProjection[2][3] * inOutPosition[2] + viewProjection[3][3],
};
auto r = res[3];
if (r > 0) {
auto rhw = 1.0f / r;
inOutPosition[0] = (((res[0] * rhw) / 2.0f) + 0.5f) * width;
inOutPosition[1] = (0.5f - ((res[1] * rhw) / 2.0f)) * height;
inOutPosition[2] = r;
return TRUE;
}
return FALSE;
}
VOID CalculateProjectionMatrixGivenViewHook(FMinimalViewInfo* viewInfo, BYTE aspectRatioAxisConstraint, PBYTE viewport, FSceneViewProjectionData* inOutProjectionData) {
CalculateProjectionMatrixGivenView(viewInfo, aspectRatioAxisConstraint, viewport, inOutProjectionData);
view.Info = *viewInfo;
GetViewProjectionMatrix(inOutProjectionData, view.ProjectionMatrix);
}
BOOLEAN WorldToScreen(float width, float height, float inOutPosition[3]) {
return ProjectWorldToScreen(view.ProjectionMatrix, width, height, inOutPosition);
}
BOOLEAN LineOfSightTo(PVOID PlayerController, PVOID Actor, FVector* ViewPoint) {
return SpoofCall(LineOfSightToInternal, PlayerController, Actor, ViewPoint);
}
FMinimalViewInfo& GetViewInfo() {
return view.Info;
}
FVector* GetPawnRootLocation(PVOID pawn) {
auto root = ReadPointer(pawn, Offsets::Engine::Actor::RootComponent);
if (!root) {
return nullptr;
}
return reinterpret_cast<FVector*>(reinterpret_cast<PBYTE>(root) + Offsets::Engine::SceneComponent::RelativeLocation);
}
float Normalize(float angle) {
float a = (float)fmod(fmod(angle, 360.0) + 360.0, 360.0);
if (a > 180.0f) {
a -= 360.0f;
}
return a;
}
VOID CalcAngle(float* src, float* dst, float* angles) {
float rel[3] = {
dst[0] - src[0],
dst[1] - src[1],
dst[2] - src[2],
};
auto dist = sqrtf(rel[0] * rel[0] + rel[1] * rel[1] + rel[2] * rel[2]);
auto yaw = atan2f(rel[1], rel[0]) * (180.0f / PI);
auto pitch = (-((acosf((rel[2] / dist)) * 180.0f / PI) - 90.0f));
angles[0] = Normalize(pitch);
angles[1] = Normalize(yaw);
}
BOOLEAN Initialize() {
// x48\x00\x00\x00\x00\x00\x00\x48\x98\x4C\x8B\x04\xD1\x48\x8D\x0C\x40\x49\x8D\x04\xC8\xEB\x02
// xx??????xxxxxxxxxxxxxxxx
auto addr = FindPattern(xorstr("\x48\x8B\x05\x00\x00\x00\x00\x48\x8B\x0C\xC8\x48\x8B\x04\xD1"), xorstr("xxx????xxxxxxxx"));
if (!addr) {
MessageBox(0, xorstr(L"Failed to find GOjects."), xorstr(L"github.com/visual9999"), 0);
return FALSE;
}
objects = reinterpret_cast<decltype(objects)>(RELATIVE_ADDR(addr, 7));
addr = FindPattern(xorstr("\x48\x89\x5C\x24\x00\x48\x89\x74\x24\x00\x55\x57\x41\x56\x48\x8D\xAC\x24\x00\x00\x00\x00\x48\x81\xEC\x00\x00\x00\x00\x48\x8B\x05\x00\x00\x00\x00\x48\x33\xC4\x48\x89\x85\x00\x00\x00\x00\x45\x33\xF6\x48\x8B\xF2\x44\x39\x71\x04\x0F\x85\x00\x00\x00\x00\x8B\x19\x0F\xB7\xFB\xE8\x00\x00\x00\x00\x8B\xCB\x48\x8D\x54\x24"), xorstr("xxxxx????xxxxxxxxxxxxxxxx????xxxxx????xxxxxxxxxxxxx????xxx"));
if (!addr) {
MessageBox(0, xorstr(L"Failed to find GetObjectNameInternal."), xorstr(L"github.com/visual9999"), 0);
return FALSE;
}
GetObjectNameInternal = reinterpret_cast<decltype(GetObjectNameInternal)>(addr);
addr = FindPattern(xorstr("\x48\x85\xC9\x0F\x84\x00\x00\x00\x00\x53\x48\x83\xEC\x20\x48\x89\x7C\x24\x30\x48\x8B\xD9\x48\x8B\x3D\x00\x00\x00\x00\x48\x85\xFF\x0F\x84\x00\x00\x00\x00\x48\x8B\x07\x4C\x8B\x40\x30\x48\x8D\x05\x00\x00\x00\x00\x4C\x3B\xC0"), xorstr("xxxxx????xxxxxxxxxxxxxxxx????xxxxx????xxxxxxxxxxxxx????xxx"));
if (!addr) {
MessageBox(0, xorstr(L"Failed to find FreeInternal."), xorstr(L"github.com/visual9999"), 0);
return FALSE;
}
FreeInternal = reinterpret_cast<decltype(FreeInternal)>(addr);
addr = FindPattern(xorstr("\xE8\x00\x00\x00\x00\x41\x88\x07\x48\x83\xC4\x30"), xorstr("x????xxxxxxx"));
if (!addr) {
MessageBox(0, xorstr(L"Failed to find ProjectionMatrixGivenView."), xorstr(L"github.com/visual9999"), 0);
return FALSE;
}
addr -= 0x280;
DISCORD.HookFunction((uintptr_t)addr, (uintptr_t)CalculateProjectionMatrixGivenViewHook, (uintptr_t)&CalculateProjectionMatrixGivenView);
addr = FindPattern(xorstr("\xE8\x00\x00\x00\x00\x48\x8B\x0D\x00\x00\x00\x00\x33\xD2\x40\x8A\xF8"), xorstr("x????xxx????xxxxx"));
if (!addr) {
MessageBox(0, xorstr(L"Failed to find LineOfSightTo."), xorstr(L"github.com/visual9999"), 0);
return FALSE;
}
LineOfSightToInternal = reinterpret_cast<decltype(LineOfSightToInternal)>(addr);
return TRUE;
}
}
| 30.934844 | 415 | 0.650092 | [
"object",
"vector"
] |
171bc65fadb2592a58fbc99ea8fa0513f779c8dc | 2,409 | hpp | C++ | include/SSVOpenHexagon/Core/HexagonDialogBox.hpp | InfoTeddy/SSVOpenHexagon | e81861cd46898542e652aa3fe5b1faa68d2e7d01 | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Core/HexagonDialogBox.hpp | InfoTeddy/SSVOpenHexagon | e81861cd46898542e652aa3fe5b1faa68d2e7d01 | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Core/HexagonDialogBox.hpp | InfoTeddy/SSVOpenHexagon | e81861cd46898542e652aa3fe5b1faa68d2e7d01 | [
"AFL-3.0"
] | null | null | null | // Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0
#pragma once
#include "SSVOpenHexagon/Global/Common.hpp"
#include "SSVOpenHexagon/Utils/FastVertexVector.hpp"
#include <SSVStart/GameSystem/GameSystem.hpp>
#include <string>
namespace hg
{
class HGAssets;
class StyleData;
enum class DBoxDraw
{
topLeft = 0,
center,
centerUpperHalf
};
class HexagonDialogBox
{
private:
using KKey = sf::Keyboard::Key;
using Color = sf::Color;
using DrawFunc = std::function<void(const Color&, const Color&)>;
HGAssets& assets;
ssvs::GameWindow& window;
StyleData& styleData;
DrawFunc drawFunc;
Utils::FastVertexVector<sf::PrimitiveType::Quads> dialogFrame;
std::vector<std::string> dialogText;
sf::Font& imagine;
sf::Text txtDialog;
float dialogWidth{0.f};
float frameSize{0.f};
float doubleFrameSize{0.f};
float lineHeight{0.f};
float totalHeight{0.f};
float xPos{0.f};
float yPos{0.f};
KKey keyToClose{KKey::Unknown};
[[nodiscard]] DrawFunc drawModeToDrawFunc(DBoxDraw drawMode);
void drawText(
const Color& txtColor, const float xOffset, const float yOffset);
void drawBox(const Color& frameColor, const float x1, const float x2,
const float y1, const float y2);
void drawCenter(const Color& txtColor, const Color& backdropColor);
void drawCenterUpperHalf(const Color& txtColor, const Color& backdropColor);
void drawTopLeft(const Color& txtColor, const Color& backdropColor);
public:
HexagonDialogBox(
HGAssets& mAssets, ssvs::GameWindow& window, StyleData& styleData);
void create(const std::string& output, const int charSize,
const float mFrameSize, const DBoxDraw mDrawMode,
const float xPos = 0.f, const float yPos = 0.f);
void create(const std::string& output, const int charSize,
const float mFrameSize, const DBoxDraw mDrawMode,
const KKey mKeyToClose, const float mXPos = 0.f,
const float mYPos = 0.f);
void draw(const Color& txtColor, const Color& backdropColor);
void clearDialogBox();
[[nodiscard]] KKey getKeyToClose() const noexcept
{
return keyToClose;
}
[[nodiscard]] bool empty() const noexcept
{
return dialogText.empty();
}
};
} // namespace hg
| 26.184783 | 80 | 0.686592 | [
"vector"
] |
171e5e6ea6a93ba54c0e6fa64f9782c31f746165 | 724 | cpp | C++ | leetcode/Generate Parentheses.cpp | BeautifulBeer/algorithms | 88b845dd1853ef11a839a7acb36999cf25a46fef | [
"MIT"
] | null | null | null | leetcode/Generate Parentheses.cpp | BeautifulBeer/algorithms | 88b845dd1853ef11a839a7acb36999cf25a46fef | [
"MIT"
] | null | null | null | leetcode/Generate Parentheses.cpp | BeautifulBeer/algorithms | 88b845dd1853ef11a839a7acb36999cf25a46fef | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string> result;
int length;
char* s;
void go(int one, int zero, int depth){
if(one == 0){
for(int i=depth; i<this->length; i++){
s[i] = ')';
}
this->result.emplace_back(string(s, this->length));
return;
}
if(one > 0){
s[depth] = '(';
go(one-1, zero+1, depth+1);
}
if(zero > 0){
s[depth] = ')';
go(one, zero-1, depth+1);
}
}
vector<string> generateParenthesis(int n) {
this->length = n * 2;
this->s = new char[this->length];
go(n, 0, 0);
return this->result;
}
}; | 24.133333 | 63 | 0.418508 | [
"vector"
] |
171fc6f3e622d012f32661d0f5a676bc47315d35 | 420 | cpp | C++ | Dataset/Leetcode/test/66/468.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/66/468.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/66/468.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> XXX(vector<int>& digits) {
for (int i = digits.size() - 1; i >= 0; i--) {
if (digits[i] == 9) digits[i] = 0;
else {
++digits[i];
break;
}
}
if (digits[0] == 0) {
digits.push_back(1);
swap(digits.front(), digits.back());
}
return digits;
}
};
| 22.105263 | 54 | 0.390476 | [
"vector"
] |
17208cb37aa14b178d94230c27229fb14b0d8936 | 5,015 | hpp | C++ | Engine/Include/FishEngine/Quaternion.hpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Include/FishEngine/Quaternion.hpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Include/FishEngine/Quaternion.hpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #pragma once
#include "Vector3.hpp"
namespace FishEngine
{
enum class RotationOrder
{
ZXY, // default
XYZ,
YZX,
XZY,
YXZ,
ZYX,
};
class FE_EXPORT Quaternion
{
public:
union
{
struct { float x, y, z, w; };
float m[4];
};
static constexpr float kEpsilon = 1E-06f;
static const Quaternion identity;
Quaternion(float x, float y, float z, float w)
: x(x), y(y), z(z), w(w)
{
NormalizeSelf();
}
Quaternion() : Quaternion(0, 0, 0, 1) {}
// Returns the euler angle representation of the rotation.
Vector3 eulerAngles() const;
// Set the euler angle representation of the rotation.
void setEulerAngles(const Vector3& angles);
float operator[](int index) const { return m[index]; }
float & operator[](int index) { return m[index]; }
void Set(float new_x, float new_y, float new_z, float new_w);
// Creates a rotation which rotates angle degrees around axis.
static Quaternion AngleAxis(const float angle, const Vector3& axis);
// Converts a rotation to angle-axis representation (angles in degrees).
void ToAngleAxis(float* angle, Vector3* axis);
// Creates a rotation which rotates from fromDirection to toDirection.
// Usually you use this to rotate a transform so that one of its axes eg. the y-axis - follows a target direction toDirection in world space.
static Quaternion FromToRotation(const Vector3& fromDirection, const Vector3& toDirection);
// Creates a rotation which rotates from fromDirection to toDirection.
void SetFromToRotation(const Vector3& fromDirection, const Vector3& toDirection);
/**
* Creates a rotation with the specified forward and upwards directions.
*
* @param const Vector3 & forward The direction to look in.
* @param const Vector3 & upwards The vector that defines in which direction up is.
* @return FishEngine::Quaternion
*/
static Quaternion LookRotation(const Vector3& forward, const Vector3& upwards = Vector3::up);
/**
* Creates a rotation with the specified forward and upwards directions.
*
* @param const Vector3 & view The direction to look in.
* @param const Vector3 & up The vector that defines in which direction up is.
* @return void
*/
void SetLookRotation(const Vector3& view, const Vector3& up = Vector3::up);
// Spherically interpolates between a and b by t. The parameter t is clamped to the range [0, 1].
static Quaternion Slerp(const Quaternion& a, const Quaternion& b, float t);
// >Spherically interpolates between a and b by t. The parameter t is not clamped.
static Quaternion SlerpUnclamped(const Quaternion& a, const Quaternion& b, float t);
// Interpolates between a and b by t and normalizes the result afterwards. The parameter t is clamped to the range [0, 1].
static Quaternion Lerp(const Quaternion& a, const Quaternion& b, float t);
// Interpolates between a and b by t and normalizes the result afterwards.The parameter t is not clamped.
static Quaternion LerpUnclamped(const Quaternion& a, const Quaternion& b, float t);
// Rotates a rotation from towards to.
static Quaternion RotateTowards(const Quaternion& from, const Quaternion& to, float maxDegreesDelta);
// Returns the Inverse of rotation.
static Quaternion Inverse(const Quaternion& rotation);
// Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis(in that order).
static Quaternion Euler(float x, float y, float z);
// Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis (in that order).
static Quaternion Euler(const Vector3& euler);
static Quaternion Euler(RotationOrder order, float x, float y, float z);
static Quaternion Euler(RotationOrder order, const Vector3& euler);
Quaternion operator -() const;
Quaternion operator* (const Quaternion & rhs) const;
Quaternion operator*=(const Quaternion & rhs);
Vector3 operator* (const Vector3 & point) const;
friend bool operator==(const Quaternion & lhs, const Quaternion& rhs);
friend bool operator!=(const Quaternion & lhs, const Quaternion& rhs);
friend Quaternion operator* (Quaternion const & q, float scale);
friend Quaternion operator* (float scale, Quaternion const & q);
Quaternion & operator+=(const Quaternion& rhs);
Quaternion & operator-=(const Quaternion& rhs);
friend Quaternion operator + (const Quaternion& lhs, const Quaternion& rhs);
friend Quaternion operator - (const Quaternion& lhs, const Quaternion& rhs);
// The dot product between two rotations.
static float Dot(const Quaternion& a, const Quaternion& b);
// Returns the angle in degrees between two rotations a and b.
static float Angle(const Quaternion& a, const Quaternion& b);
void NormalizeSelf();
// Returns the Inverse of this rotation.
Quaternion inverse() const;
private:
static Vector3 Internal_MakePositive(Vector3 euler);
};
}
#include "Quaternion.inl"
| 34.586207 | 143 | 0.724427 | [
"vector",
"transform"
] |
17299d02d8d15f0c22b727bf65a89c3ba45eb10e | 781 | cpp | C++ | Fusion/src/Platform/OpenGL/OpenGLIndexBuffer.cpp | WhoseTheNerd/Fusion | 35ab536388392b3ba2e14f288eecbc292abd7dea | [
"Apache-2.0"
] | 4 | 2018-11-12T18:43:02.000Z | 2020-02-02T10:18:56.000Z | Fusion/src/Platform/OpenGL/OpenGLIndexBuffer.cpp | WhoseTheNerd/Fusion | 35ab536388392b3ba2e14f288eecbc292abd7dea | [
"Apache-2.0"
] | 2 | 2018-12-22T13:18:05.000Z | 2019-07-24T20:15:45.000Z | Fusion/src/Platform/OpenGL/OpenGLIndexBuffer.cpp | WhoseTheNerd/Fusion | 35ab536388392b3ba2e14f288eecbc292abd7dea | [
"Apache-2.0"
] | null | null | null | #include "fpch.h"
#include "OpenGLIndexBuffer.h"
#include <glad/glad.h>
namespace Fusion { namespace Graphics {
Ref<IndexBuffer> IndexBuffer::Create(const std::vector<uint32_t>& indices)
{
return CreateRef<OpenGLIndexBuffer>(indices);
}
OpenGLIndexBuffer::OpenGLIndexBuffer(const std::vector<uint32_t>& indices)
: m_Count(static_cast<uint32_t>(indices.size()))
{
glCreateBuffers(1, &m_BufferID);
glNamedBufferData(m_BufferID, indices.size() * sizeof(uint32_t), indices.data(), GL_STATIC_DRAW);
}
OpenGLIndexBuffer::~OpenGLIndexBuffer()
{
glDeleteBuffers(1, &m_BufferID);
}
void OpenGLIndexBuffer::Bind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_BufferID);
}
void OpenGLIndexBuffer::Unbind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
}
} }
| 22.314286 | 99 | 0.746479 | [
"vector"
] |
173264e4340045f1cfe39ee165a00b3f3d84b5ef | 1,643 | hpp | C++ | cudaaligner/src/ukkonen_cpu.hpp | pb-cdunn/GenomeWorks | 84f22f7e72c0fe8e5554d7ddfebf22c93ffb4610 | [
"Apache-2.0"
] | 160 | 2019-07-02T03:35:10.000Z | 2020-05-05T09:08:26.000Z | cudaaligner/src/ukkonen_cpu.hpp | pb-cdunn/GenomeWorks | 84f22f7e72c0fe8e5554d7ddfebf22c93ffb4610 | [
"Apache-2.0"
] | 253 | 2019-07-02T13:08:28.000Z | 2020-05-07T18:47:08.000Z | cudaaligner/src/ukkonen_cpu.hpp | pb-cdunn/GenomeWorks | 84f22f7e72c0fe8e5554d7ddfebf22c93ffb4610 | [
"Apache-2.0"
] | 54 | 2019-07-02T14:33:48.000Z | 2020-05-01T16:04:21.000Z | /*
* Copyright 2019-2020 NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "matrix_cpu.hpp"
#include <claraparabricks/genomeworks/cudaaligner/cudaaligner.hpp>
#include <vector>
#include <tuple>
namespace claraparabricks
{
namespace genomeworks
{
namespace cudaaligner
{
inline std::tuple<int, int> to_band_indices(int i, int j, int p)
{
int const kd = (j - i + p) / 2;
int const l = (j + i);
return std::make_tuple(kd, l);
}
inline std::tuple<int, int> to_matrix_indices(int kd, int l, int p)
{
int const j = kd - (p + l) / 2 + l;
int const i = l - j;
return std::make_tuple(i, j);
}
std::vector<int8_t> ukkonen_backtrace(matrix<int> const& scores, int n, int m, int p);
matrix<int> ukkonen_build_score_matrix(std::string const& target, std::string const& query, int p);
matrix<int> ukkonen_build_score_matrix_naive(std::string const& target, std::string const& query, int t);
std::vector<int8_t> ukkonen_cpu(std::string const& target, std::string const& query, int const p);
} // namespace cudaaligner
} // namespace genomeworks
} // namespace claraparabricks
| 26.5 | 105 | 0.719416 | [
"vector"
] |
173320db6571b0ca76dd14799f85cdc9708ee750 | 6,796 | cc | C++ | src/cpp/basic/cocompiled_models_benchmark.cc | SanggunLee/edgetpu | d3cf166783265f475c1ddba5883e150ee84f7bfe | [
"Apache-2.0"
] | 320 | 2019-09-19T07:10:48.000Z | 2022-03-12T01:48:56.000Z | src/cpp/basic/cocompiled_models_benchmark.cc | Machine-Learning-Practice/edgetpu | 6d699665efdc5d84944b5233223c55fe5d3bd1a6 | [
"Apache-2.0"
] | 563 | 2019-09-27T06:40:40.000Z | 2022-03-31T23:12:15.000Z | src/cpp/basic/cocompiled_models_benchmark.cc | Machine-Learning-Practice/edgetpu | 6d699665efdc5d84944b5233223c55fe5d3bd1a6 | [
"Apache-2.0"
] | 119 | 2019-09-25T02:51:10.000Z | 2022-03-03T08:11:12.000Z | #include "absl/flags/parse.h"
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "src/cpp/test_utils.h"
namespace coral {
template <CompilationType Compilation>
static void BM_Compilation_TwoSmall(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/mobilenet_v1_0.25_128_quant_cocompiled_with_"
"mobilenet_v1_0.5_160_quant_edgetpu.tflite"
: "mobilenet_v1_0.25_128_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/mobilenet_v1_0.5_160_quant_cocompiled_with_"
"mobilenet_v1_0.25_128_quant_edgetpu.tflite"
: "mobilenet_v1_0.5_160_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_TwoSmall, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_TwoSmall, kSingleCompilation);
template <CompilationType Compilation>
static void BM_Compilation_TwoLarge(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/inception_v4_299_quant_cocompiled_with_inception_v3_"
"299_quant_edgetpu.tflite"
: "inception_v4_299_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/inception_v3_299_quant_cocompiled_with_inception_v4_"
"299_quant_edgetpu.tflite"
: "inception_v3_299_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_TwoLarge, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_TwoLarge, kSingleCompilation);
template <CompilationType Compilation>
static void BM_Compilation_Small_Large(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/mobilenet_v1_0.25_128_quant_cocompiled_with_"
"inception_v4_299_quant_edgetpu.tflite"
: "mobilenet_v1_0.25_128_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/inception_v4_299_quant_cocompiled_with_mobilenet_v1_"
"0.25_128_quant_edgetpu.tflite"
: "inception_v4_299_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_Small_Large, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_Small_Large, kSingleCompilation);
template <CompilationType Compilation>
static void BM_Compilation_Large_Small(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/inception_v4_299_quant_cocompiled_with_mobilenet_v1_"
"0.25_128_quant_edgetpu.tflite"
: "inception_v4_299_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/mobilenet_v1_0.25_128_quant_cocompiled_with_"
"inception_v4_299_quant_edgetpu.tflite"
: "mobilenet_v1_0.25_128_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_Large_Small, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_Large_Small, kSingleCompilation);
template <CompilationType Compilation>
static void BM_Compilation_Four_Small(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"mobilenet_v1_1.0_224_quant_cocompiled_with_3quant_edgetpu.tflite"
: "mobilenet_v1_1.0_224_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"mobilenet_v1_0.25_128_quant_cocompiled_with_3quant_edgetpu.tflite"
: "mobilenet_v1_0.25_128_quant_edgetpu.tflite");
const std::string model_path2 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"mobilenet_v1_0.5_160_quant_cocompiled_with_3quant_edgetpu.tflite"
: "mobilenet_v1_0.5_160_quant_edgetpu.tflite");
const std::string model_path3 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"mobilenet_v1_0.75_192_quant_cocompiled_with_3quant_edgetpu.tflite"
: "mobilenet_v1_0.75_192_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1,
model_path2, model_path3};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_Four_Small, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_Four_Small, kSingleCompilation);
template <CompilationType Compilation>
static void BM_Compilation_Four_Large(benchmark::State& state) {
const std::string model_path0 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"inception_v1_224_quant_cocompiled_with_3quant_edgetpu.tflite"
: "inception_v1_224_quant_edgetpu.tflite");
const std::string model_path1 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"inception_v2_224_quant_cocompiled_with_3quant_edgetpu.tflite"
: "inception_v2_224_quant_edgetpu.tflite");
const std::string model_path2 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"inception_v3_299_quant_cocompiled_with_3quant_edgetpu.tflite"
: "inception_v3_299_quant_edgetpu.tflite");
const std::string model_path3 = TestDataPath(
(Compilation == kCoCompilation)
? "cocompilation/"
"inception_v4_299_quant_cocompiled_with_3quant_edgetpu.tflite"
: "inception_v4_299_quant_edgetpu.tflite");
const std::vector<std::string> model_paths = {model_path0, model_path1,
model_path2, model_path3};
coral::BenchmarkModelsOnEdgeTpu(model_paths, state);
}
BENCHMARK_TEMPLATE(BM_Compilation_Four_Large, kCoCompilation);
BENCHMARK_TEMPLATE(BM_Compilation_Four_Large, kSingleCompilation);
} // namespace coral
int main(int argc, char** argv) {
benchmark::Initialize(&argc, argv);
absl::ParseCommandLine(argc, argv);
benchmark::RunSpecifiedBenchmarks();
return 0;
}
| 46.547945 | 80 | 0.740877 | [
"vector"
] |
1736bfc363ab1a1722b5f213612b402abb274b2f | 23,837 | cpp | C++ | src/core/RStorage.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/core/RStorage.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/core/RStorage.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QCAD 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 QCAD.
*/
#include "RDocument.h"
#include "RSettings.h"
#include "RStorage.h"
#include "RMainWindow.h"
RStorage::RStorage() :
document(NULL),
modified(false),
maxDrawOrder(0),
idCounter(0),
handleCounter(0),
currentColor(RColor::ByLayer),
currentLineweight(RLineweight::WeightByLayer),
currentLinetypeId(RLinetype::INVALID_ID),
//currentLayerId(RLayer::INVALID_ID),
currentViewId(RView::INVALID_ID),
currentBlockId(RBlock::INVALID_ID),
lastTransactionId(-1),
lastTransactionGroup(1) {
}
void RStorage::clear() {
modified = false;
maxDrawOrder = 0;
idCounter = 0;
handleCounter = 0;
currentColor = RColor::ByLayer;
currentLineweight = RLineweight::WeightByLayer,
currentLinetypeId = RLinetype::INVALID_ID;
currentViewId = RView::INVALID_ID;
currentBlockId = RBlock::INVALID_ID;
lastTransactionId = -1;
lastTransactionGroup = 1;
}
void RStorage::setObjectId(RObject& object, RObject::Id objectId) const {
object.setId(objectId);
}
void RStorage::setObjectHandle(RObject& object, RObject::Handle objectHandle) {
object.setHandle(objectHandle);
if (objectHandle>handleCounter) {
handleCounter = objectHandle+1;
}
}
void RStorage::setUndoStatus(RObject& object, bool status) {
object.setUndone(status);
}
RObject::Id RStorage::getNewObjectId() {
return idCounter++;
}
RObject::Id RStorage::getMaxObjectId() {
return idCounter;
}
RObject::Handle RStorage::getNewObjectHandle() {
return handleCounter++;
}
RObject::Handle RStorage::getMaxObjectHandle() {
return handleCounter;
}
//RTransaction RStorage::setCurrentLayer(RLayer::Id layerId) {
// RTransaction transaction(*this, "Setting current layer", true);
// setCurrentLayer(transaction, layerId);
// transaction.end();
// return transaction;
//}
//RTransaction RStorage::setCurrentLayer(const QString& layerName) {
// RLayer::Id id = getLayerId(layerName);
// if (id == RLayer::INVALID_ID) {
// return RTransaction();
// }
// return setCurrentLayer(id);
//}
//void RStorage::setCurrentLayer(RTransaction& transaction, RLayer::Id layerId) {
// QSharedPointer<RDocumentVariables> v = queryDocumentVariables();
// v->setCurrentLayerId(layerId);
// transaction.addObject(v);
//}
//void RStorage::setCurrentLayer(RTransaction& transaction, const QString& layerName) {
// RLayer::Id id = getLayerId(layerName);
// if (id == RLayer::INVALID_ID) {
// return;
// }
// setCurrentLayer(transaction, id);
//}
void RStorage::setCurrentLayer(RLayer::Id layerId, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
Q_ASSERT(!docVars.isNull());
docVars->setCurrentLayerId(layerId);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
void RStorage::setCurrentLayer(const QString& layerName, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
Q_ASSERT(!docVars.isNull());
RLayer::Id layerId = getLayerId(layerName);
if (layerId == RLayer::INVALID_ID) {
return;
}
docVars->setCurrentLayerId(layerId);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
RLayer::Id RStorage::getCurrentLayerId() const {
QSharedPointer<RDocumentVariables> v = queryDocumentVariablesDirect();
if (v.isNull()) {
return RLayer::INVALID_ID;
}
return v->getCurrentLayerId();
}
void RStorage::setCurrentColor(const RColor& color) {
currentColor = color;
}
RColor RStorage::getCurrentColor() const {
return currentColor;
}
void RStorage::setCurrentLineweight(RLineweight::Lineweight lw) {
currentLineweight = lw;
}
RLineweight::Lineweight RStorage::getCurrentLineweight() const {
return currentLineweight;
}
void RStorage::setCurrentLinetype(RLinetype::Id ltId) {
currentLinetypeId = ltId;
}
void RStorage::setCurrentLinetype(const QString& name) {
QSet<RLinetype::Id> ltIds = queryAllLinetypes();
QSet<RLinetype::Id>::iterator it;
for (it = ltIds.begin(); it != ltIds.end(); ++it) {
QSharedPointer<RLinetype> lt = queryLinetypeDirect(*it);
if (lt->getName().toUpper()==name.toUpper()) {
setCurrentLinetype(lt->getId());
return;
}
}
}
void RStorage::setCurrentLinetypePattern(const RLinetypePattern& p) {
setCurrentLinetype(p.getName());
}
RLinetype::Id RStorage::getCurrentLinetypeId() const {
return currentLinetypeId;
}
RLinetypePattern RStorage::getCurrentLinetypePattern() const {
QSharedPointer<RLinetype> lt = queryCurrentLinetype();
if (lt.isNull()) {
return RLinetypePattern();
}
return lt->getPattern();
}
bool RStorage::hasView(const QString& viewName) const {
QStringList sl = getViewNames().toList();
return sl.contains(viewName, Qt::CaseInsensitive);
}
bool RStorage::hasLayer(const QString& layerName) const {
QStringList sl = getLayerNames().toList();
return sl.contains(layerName, Qt::CaseInsensitive);
}
bool RStorage::hasLayout(const QString& layoutName) const {
QStringList sl = getLayoutNames().toList();
return sl.contains(layoutName, Qt::CaseInsensitive);
}
bool RStorage::hasBlock(const QString& blockName) const {
QStringList sl = getBlockNames().toList();
return sl.contains(blockName, Qt::CaseInsensitive);
}
bool RStorage::hasLinetype(const QString& linetypeName) const {
QStringList sl = getLinetypeNames().toList();
return sl.contains(linetypeName, Qt::CaseInsensitive);
}
QList<REntity::Id> RStorage::orderBackToFront(const QSet<REntity::Id>& entityIds) const {
QMap<int, REntity::Id> res;
QSet<REntity::Id>::const_iterator it;
//maxDrawOrder = 0;
for (it = entityIds.begin(); it != entityIds.end(); ++it) {
QSharedPointer<REntity> e = queryEntityDirect(*it);
if (!e.isNull()) {
res.insertMulti(e->getDrawOrder(), *it);
//maxDrawOrder = qMax(e->getDrawOrder()+1, maxDrawOrder);
}
}
return res.values();
}
int RStorage::getMinDrawOrder() {
QSet<REntity::Id> entityIds = queryAllEntities(false, false);
QSet<REntity::Id>::const_iterator it;
int minDrawOrder = maxDrawOrder;
for (it = entityIds.begin(); it != entityIds.end(); ++it) {
QSharedPointer<REntity> e = queryEntityDirect(*it);
if (!e.isNull()) {
if (e->getDrawOrder()<minDrawOrder) {
minDrawOrder = e->getDrawOrder();
}
}
}
return minDrawOrder - 1;
}
QSharedPointer<RDocumentVariables> RStorage::startDocumentVariablesTransaction(RTransaction*& transaction, bool& useLocalTransaction) {
useLocalTransaction = (transaction==NULL);
if (useLocalTransaction) {
transaction = new RTransaction(*this, "Change document setting", true);
}
return queryDocumentVariables();
}
void RStorage::endDocumentVariablesTransaction(RTransaction* transaction, bool useLocalTransaction, QSharedPointer<RDocumentVariables> docVars) {
transaction->addObject(docVars);
if (RMainWindow::hasMainWindow()) {
RMainWindow::getMainWindow()->postTransactionEvent(*transaction,
transaction->hasOnlyChanges());
}
if (useLocalTransaction) {
transaction->end();
delete transaction;
}
}
void RStorage::setUnit(RS::Unit unit, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
Q_ASSERT(!docVars.isNull());
docVars->setUnit(unit);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
RS::Unit RStorage::getUnit() const {
QSharedPointer<RDocumentVariables> v = queryDocumentVariablesDirect();
if (v.isNull()) {
return RS::None;
}
return v->getUnit();
}
void RStorage::setMeasurement(RS::Measurement m, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
Q_ASSERT(!docVars.isNull());
docVars->setMeasurement(m);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
RS::Measurement RStorage::getMeasurement() const {
QSharedPointer<RDocumentVariables> v = queryDocumentVariablesDirect();
if (v.isNull()) {
return RS::UnknownMeasurement;
}
return v->getMeasurement();
}
void RStorage::setDimensionFont(const QString& f, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
Q_ASSERT(!docVars.isNull());
docVars->setDimensionFont(f);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
QString RStorage::getDimensionFont() const {
QSharedPointer<RDocumentVariables> v = queryDocumentVariablesDirect();
if (v.isNull()) {
return "Standard";
}
return v->getDimensionFont();
}
void RStorage::setLinetypeScale(double v, RTransaction* transaction) {
bool useLocalTransaction;
QSharedPointer<RDocumentVariables> docVars = startDocumentVariablesTransaction(transaction, useLocalTransaction);
docVars->setLinetypeScale(v);
endDocumentVariablesTransaction(transaction, useLocalTransaction, docVars);
}
double RStorage::getLinetypeScale() const {
QSharedPointer<RDocumentVariables> v = queryDocumentVariablesDirect();
if (v.isNull()) {
return 1.0;
}
return v->getLinetypeScale();
}
/**
* Stream operator for QDebug
*/
QDebug operator<<(QDebug dbg, RStorage& s) {
dbg.nospace() << "RStorage(" << QString("%1").arg((long int)&s, 0, 16) << ", ";
dbg.nospace() << "\n";
//dbg.nospace() << "current block ID: " << s.getCurrentBlockId() << "\n";
dbg.nospace() << "modified: " << s.isModified() << "\n";
QSharedPointer<RBlock> block = s.queryCurrentBlock();
if (block.isNull()) {
dbg.nospace() << "current block: INVALID\n";
}
else {
dbg.nospace() << "current block: " << block->getName() << "\n";
}
//dbg.nospace() << "current layer ID: " << s.getCurrentLayerId() << "\n";
QSharedPointer<RLayer> layer = s.queryCurrentLayer();
if (layer.isNull()) {
dbg.nospace() << "current layer: INVALID\n";
}
else {
dbg.nospace() << "current layer: " << layer->getName() << "\n";
}
dbg.nospace() << "current view ID: " << s.getCurrentViewId() << "\n";
QSharedPointer<RLinetype> linetype = s.queryCurrentLinetype();
if (linetype.isNull()) {
dbg.nospace() << "current linetype: INVALID\n";
}
else {
dbg.nospace() << "current linetype: " << linetype->getName() << "\n";
}
dbg.nospace() << "drawing unit: " << s.getUnit() << "\n";
dbg.nospace() << "dimension font: " << s.getDimensionFont() << "\n";
dbg.nospace() << "bounding box: " << s.getBoundingBox() << "\n";
dbg.nospace() << "document variables: " << *s.queryDocumentVariables() << "\n";
{
QSet<RLayer::Id> layers = s.queryAllLayers(true);
QSetIterator<RLayer::Id> i(layers);
while (i.hasNext()) {
RLayer::Id id = i.next();
QSharedPointer<RLayer> l = s.queryObjectDirect(id).dynamicCast<RLayer>();
if (l.isNull()) {
dbg.nospace() << "layer not found: " << id;
continue;
}
dbg.nospace() << *l.data() << "\n";
}
}
{
QSet<RView::Id> views = s.queryAllViews(true);
QSetIterator<RView::Id> i(views);
while (i.hasNext()) {
RView::Id id = i.next();
QSharedPointer<RView> v = s.queryObjectDirect(id).dynamicCast<RView>();
if (v.isNull()) {
dbg.nospace() << "view not found: " << id;
continue;
}
dbg.nospace() << *v.data() << "\n";
}
}
{
QSet<RBlock::Id> blocks = s.queryAllBlocks(true);
QSetIterator<RBlock::Id> i(blocks);
while (i.hasNext()) {
RBlock::Id id = i.next();
QSharedPointer<RBlock> b = s.queryObjectDirect(id).dynamicCast<RBlock>();
if (b.isNull()) {
dbg.nospace() << "block not found: " << id;
continue;
}
dbg.nospace() << *b.data() << "\n";
dbg.nospace() << "block entities: " << s.queryBlockEntities(id) << "\n";
}
}
{
QSet<RLinetype::Id> linetypes = s.queryAllLinetypes();
QSetIterator<RLinetype::Id> i(linetypes);
while (i.hasNext()) {
RLinetype::Id id = i.next();
QSharedPointer<RLinetype> l = s.queryObjectDirect(id).dynamicCast<RLinetype>();
if (l.isNull()) {
dbg.nospace() << "linetype not found: " << id;
continue;
}
dbg.nospace() << *l.data() << "\n";
}
}
{
QSet<REntity::Id> entities = s.querySelectedEntities();
if (entities.size()==0) {
entities = s.queryAllEntities(true, true);
}
QSetIterator<REntity::Id> i(entities);
while (i.hasNext()) {
REntity::Id id = i.next();
QSharedPointer<REntity> e = s.queryObjectDirect(id).dynamicCast<REntity>();
if (e.isNull()) {
dbg.nospace() << "entity not found: " << id;
continue;
}
dbg.nospace() << "Bounding Box: " << e->getBoundingBox() << "\n";
dbg.nospace() << *e.data() << "\n\n";
}
}
dbg.nospace() << "lastTransactionId: " << s.getLastTransactionId() << "\n";
for (int a = 0; a <= s.getMaxTransactionId(); ++a) {
RTransaction t = s.getTransaction(a);
dbg.nospace() << t << "\n";
}
dbg.nospace() << "variables: \n";
{
QStringList vars = s.getVariables();
vars.sort();
QListIterator<QString> i(vars);
while (i.hasNext()) {
QString key = i.next();
dbg.nospace() << "\t" << key << ": " << s.getVariable(key) << "\n";
}
}
dbg.nospace() << "Known variables (DXF): \n";
{
for (int i=0; i<=RS::MaxKnownVariable; i++) {
QVariant v = s.getKnownVariable((RS::KnownVariable)i);
if (v.isValid()) {
dbg.nospace() << "\t"
<< RStorage::getKnownVariableName((RS::KnownVariable)i)
<< ": " << v << "\n";
}
}
}
dbg.nospace() << ")";
return dbg.space();
}
/**
* \return Name of the given known variable enum. Used for debugging.
*/
QString RStorage::getKnownVariableName(RS::KnownVariable n) {
switch(n) {
case RS::ANGBASE:
return "ANGBASE";
case RS::ANGDIR:
return "ANGDIR";
case RS::ATTMODE:
return "ATTMODE";
case RS::AUNITS:
return "AUNITS";
case RS::AUPREC:
return "AUPREC";
case RS::CECOLOR:
return "CECOLOR";
case RS::CELTSCALE:
return "CELTSCALE";
case RS::CHAMFERA:
return "CHAMFERA";
case RS::CHAMFERB:
return "CHAMFERB";
case RS::CHAMFERC:
return "CHAMFERC";
case RS::CHAMFERD:
return "CHAMFERD";
case RS::CMLJUST:
return "CMLJUST";
case RS::CMLSCALE:
return "CMLSCALE";
case RS::DIMADEC:
return "DIMADEC";
case RS::DIMALT:
return "DIMALT";
case RS::DIMALTD:
return "DIMALTD";
case RS::DIMALTF:
return "DIMALTF";
case RS::DIMALTRND:
return "DIMALTRND";
case RS::DIMALTTD:
return "DIMALTTD";
case RS::DIMALTTZ:
return "DIMALTTZ";
case RS::DIMALTU:
return "DIMALTU";
case RS::DIMALTZ:
return "DIMALTZ";
case RS::DIMAPOST:
return "DIMAPOST";
case RS::DIMASZ:
return "DIMASZ";
case RS::DIMATFIT:
return "DIMATFIT";
case RS::DIMAUNIT:
return "DIMAUNIT";
case RS::DIMAZIN:
return "DIMAZIN";
case RS::DIMBLK:
return "DIMBLK";
case RS::DIMBLK1:
return "DIMBLK1";
case RS::DIMBLK2:
return "DIMBLK2";
case RS::DIMCEN:
return "DIMCEN";
case RS::DIMCLRD:
return "DIMCLRD";
case RS::DIMCLRE:
return "DIMCLRE";
case RS::DIMCLRT:
return "DIMCLRT";
case RS::DIMDEC:
return "DIMDEC";
case RS::DIMDLE:
return "DIMDLE";
case RS::DIMDLI:
return "DIMDLI";
case RS::DIMDSEP:
return "DIMDSEP";
case RS::DIMEXE:
return "DIMEXE";
case RS::DIMEXO:
return "DIMEXO";
case RS::DIMFRAC:
return "DIMFRAC";
case RS::DIMGAP:
return "DIMGAP";
case RS::DIMJUST:
return "DIMJUST";
case RS::DIMLDRBLK:
return "DIMLDRBLK";
case RS::DIMLFAC:
return "DIMLFAC";
case RS::DIMLIM:
return "DIMLIM";
case RS::DIMLUNIT:
return "DIMLUNIT";
case RS::DIMLWD:
return "DIMLWD";
case RS::DIMLWE:
return "DIMLWE";
case RS::DIMPOST:
return "DIMPOST";
case RS::DIMRND:
return "DIMRND";
case RS::DIMSAH:
return "DIMSAH";
case RS::DIMSCALE:
return "DIMSCALE";
case RS::DIMSD1:
return "DIMSD1";
case RS::DIMSD2:
return "DIMSD2";
case RS::DIMSE1:
return "DIMSE1";
case RS::DIMSE2:
return "DIMSE2";
case RS::DIMSOXD:
return "DIMSOXD";
case RS::DIMTAD:
return "DIMTAD";
case RS::DIMTDEC:
return "DIMTDEC";
case RS::DIMTFAC:
return "DIMTFAC";
case RS::DIMTIH:
return "DIMTIH";
case RS::DIMTIX:
return "DIMTIX";
case RS::DIMTM:
return "DIMTM";
case RS::DIMTOFL:
return "DIMTOFL";
case RS::DIMTOH:
return "DIMTOH";
case RS::DIMTOL:
return "DIMTOL";
case RS::DIMTOLJ:
return "DIMTOLJ";
case RS::DIMTP:
return "DIMTP";
case RS::DIMTSZ:
return "DIMTSZ";
case RS::DIMTVP:
return "DIMTVP";
case RS::DIMTXSTY:
return "DIMTXSTY";
case RS::DIMTXT:
return "DIMTXT";
case RS::DIMTZIN:
return "DIMTZIN";
case RS::DIMUPT:
return "DIMUPT";
case RS::DIMZIN:
return "DIMZIN";
case RS::DISPSILH:
return "DISPSILH";
case RS::DRAWORDERCTL:
return "DRAWORDERCTL";
case RS::ELEVATION:
return "ELEVATION";
case RS::EXTMAX:
return "EXTMAX";
case RS::EXTMIN:
return "EXTMIN";
case RS::FACETRES:
return "FACETRES";
case RS::FILLETRAD:
return "FILLETRAD";
case RS::FILLMODE:
return "FILLMODE";
case RS::INSBASE:
return "INSBASE";
case RS::INSUNITS:
return "INSUNITS";
case RS::ISOLINES:
return "ISOLINES";
case RS::LIMCHECK:
return "LIMCHECK";
case RS::LIMMAX:
return "LIMMAX";
case RS::LIMMIN:
return "LIMMIN";
case RS::LTSCALE:
return "LTSCALE";
case RS::LUNITS:
return "LUNITS";
case RS::LUPREC:
return "LUPREC";
case RS::MAXACTVP:
return "MAXACTVP";
case RS::MEASUREMENT:
return "MEASUREMENT";
case RS::MIRRTEXT:
return "MIRRTEXT";
case RS::ORTHOMODE:
return "ORTHOMODE";
case RS::PDMODE:
return "PDMODE";
case RS::PDSIZE:
return "PDSIZE";
case RS::PELEVATION:
return "PELEVATION";
case RS::PELLIPSE:
return "PELLIPSE";
case RS::PEXTMAX:
return "PEXTMAX";
case RS::PEXTMIN:
return "PEXTMIN";
case RS::PINSBASE:
return "PINSBASE";
case RS::PLIMCHECK:
return "PLIMCHECK";
case RS::PLIMMAX:
return "PLIMMAX";
case RS::PLIMMIN:
return "PLIMMIN";
case RS::PLINEGEN:
return "PLINEGEN";
case RS::PLINEWID:
return "PLINEWID";
case RS::PROXYGRAPHICS:
return "PROXYGRAPHICS";
case RS::PSLTSCALE:
return "PSLTSCALE";
case RS::PUCSNAME:
return "PUCSNAME";
case RS::PUCSORG:
return "PUCSORG";
case RS::PUCSXDIR:
return "PUCSXDIR";
case RS::PUCSYDIR:
return "PUCSYDIR";
case RS::QTEXTMODE:
return "QTEXTMODE";
case RS::REGENMODE:
return "REGENMODE";
case RS::SHADEDGE:
return "SHADEDGE";
case RS::SHADEDIF:
return "SHADEDIF";
case RS::SKETCHINC:
return "SKETCHINC";
case RS::SKPOLY:
return "SKPOLY";
case RS::SPLFRAME:
return "SPLFRAME";
case RS::SPLINESEGS:
return "SPLINESEGS";
case RS::SPLINETYPE:
return "SPLINETYPE";
case RS::SURFTAB1:
return "SURFTAB1";
case RS::SURFTAB2:
return "SURFTAB2";
case RS::SURFTYPE:
return "SURFTYPE";
case RS::SURFU:
return "SURFU";
case RS::SURFV:
return "SURFV";
case RS::TEXTQLTY:
return "TEXTQLTY";
case RS::TEXTSIZE:
return "TEXTSIZE";
case RS::THICKNESS:
return "THICKNESS";
case RS::TILEMODE:
return "TILEMODE";
case RS::TRACEWID:
return "TRACEWID";
case RS::TREEDEPTH:
return "TREEDEPTH";
case RS::UCSNAME:
return "UCSNAME";
case RS::UCSORG:
return "UCSORG";
case RS::UCSXDIR:
return "UCSXDIR";
case RS::UCSYDIR:
return "UCSYDIR";
case RS::UNITMODE:
return "UNITMODE";
case RS::USERI1:
return "USERI1";
case RS::USERI2:
return "USERI2";
case RS::USERI3:
return "USERI3";
case RS::USERI4:
return "USERI4";
case RS::USERI5:
return "USERI5";
case RS::USERR1:
return "USERR1";
case RS::USERR2:
return "USERR2";
case RS::USERR3:
return "USERR3";
case RS::USERR4:
return "USERR4";
case RS::USERR5:
return "USERR5";
case RS::USRTIMER:
return "USRTIMER";
case RS::VISRETAIN:
return "VISRETAIN";
case RS::WORLDVIEW:
return "WORLDVIEW";
default:
return "Unknown";
}
}
/**
* Adds a listener for modified status changed events.
* This can for example be a modification indication widget.
*/
void RStorage::addModifiedListener(RModifiedListener* l) {
if (l!=NULL) {
modifiedListeners.push_back(l);
} else {
qWarning("RStorage::addModifiedListener(): Listener is NULL.");
}
}
void RStorage::setModified(bool m) {
if (m!=modified) {
modified = m;
QList<RModifiedListener*>::iterator it;
for (it = modifiedListeners.begin(); it != modifiedListeners.end(); ++it) {
(*it)->updateModifiedListener(this);
}
}
}
| 29.247853 | 145 | 0.609011 | [
"object"
] |
173832d11785ca14347d234049d2d7753bc281b8 | 2,655 | cpp | C++ | library/tree/treePathVertexWeightVectorDot.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/tree/treePathVertexWeightVectorDot.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/tree/treePathVertexWeightVectorDot.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <tuple>
#include <vector>
#include <algorithm>
using namespace std;
#include "treePathVertexWeightVectorDot.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <tuple>
#include <iostream>
#include "../common/iostreamhelper.h"
#include "../common/profile.h"
#include "../common/rand.h"
static vector<int> makeTree(int N) {
vector<int> res(N);
for (int i = 1; i < N; i++)
res[i] = RandInt32::get() % i;
return res;
}
static vector<int> makePath(TreePathVertexWeightVectorDot& tree, int u) {
vector<int> res;
while (u >= 0) {
res.push_back(u);
u = tree.P[0][u];
}
return res;
}
static vector<long long> makeGT(TreePathVertexWeightVectorDot& tree, const vector<pair<int,int>>& qry) {
vector<long long> res;
for (auto& it : qry) {
auto path1 = makePath(tree, it.first);
auto path2 = makePath(tree, it.second);
long long dot = 0;
for (int i = 0; i < int(path1.size()); i++)
dot += 1ll * tree.W[path1[i]] * tree.W[path2[i]];
res.push_back(dot);
}
return res;
}
void testTreePathVertexWeightVectorDot() {
//return; //TODO: if you want to test, make this line a comment.
cout << "--- Tree Path - Vertex Weight Vector Dot -----------------------" << endl;
{
const int T = 10;
const int N = 1'000;
const int MAXW = 1'000;
for (int tt = 0; tt < T; tt++) {
vector<int> W(N);
for (int i = 0; i < N; i++)
W[i] = RandInt32::get() % MAXW + 1;
auto treeP = makeTree(N);
TreePathVertexWeightVectorDot tree(W);
for (int i = 1; i < N; i++)
tree.add(treeP[i], i);
tree.build();
vector<vector<int>> depthGroup(*max_element(tree.level.begin(), tree.level.end()) + 1);
for (int u = 0; u < N; u++)
depthGroup[tree.level[u]].push_back(u);
vector<pair<int, int>> qry;
for (int i = 0; i < N; i++) {
int j = i % depthGroup.size();
int u = depthGroup[j][RandInt32::get() % depthGroup[j].size()];
int v = depthGroup[j][RandInt32::get() % depthGroup[j].size()];
qry.emplace_back(u, v);
}
auto gt = makeGT(tree, qry);
auto ans = tree.solve(qry);
if (ans != gt) {
cout << "Mismatched : " << ans << ", " << gt << endl;
}
assert(ans == gt);
}
}
cout << "OK!" << endl;
}
| 27.947368 | 104 | 0.497928 | [
"vector"
] |
173a4b1e9b9438044c535cd5ab686ad233ed429c | 9,842 | cpp | C++ | RisLib/risNetUdpMsgSocket.cpp | chrishoen/Dev_RisLibLx | ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff | [
"MIT"
] | null | null | null | RisLib/risNetUdpMsgSocket.cpp | chrishoen/Dev_RisLibLx | ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff | [
"MIT"
] | null | null | null | RisLib/risNetUdpMsgSocket.cpp | chrishoen/Dev_RisLibLx | ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff | [
"MIT"
] | null | null | null | //******************************************************************************
//******************************************************************************
//******************************************************************************
#include "stdafx.h"
#include "risNetUdpMsgSocket.h"
namespace Ris
{
namespace Net
{
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Constructor.
UdpRxMsgSocket::UdpRxMsgSocket()
{
mRxMemory = 0;
mMemorySize = 0;
mRxLength = 0;
mRxCount = 0;
mValidFlag = false;
mMonkey = 0;
}
UdpRxMsgSocket::~UdpRxMsgSocket()
{
if (mRxMemory) free(mRxMemory);
if (mMonkey) delete mMonkey;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Initialize variables.
void UdpRxMsgSocket::initialize(Settings& aSettings)
{
// Store the settings pointer.
mSettings = aSettings;
// Create a message monkey.
mMonkey = mSettings.mMonkeyCreator->createMonkey();
// Allocate memory for byte buffers.
mMemorySize = mMonkey->getMaxBufferSize();
mRxMemory = (char*)malloc(mMemorySize);
// Metrics.
mRxCount = 0;
mRxLength = 0;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Configure the socket.
void UdpRxMsgSocket::configure()
{
// Configure the socket.
BaseClass::mLocal.set(mSettings.mLocalIpAddr, mSettings.mLocalIpPort);
BaseClass::doSocket();
BaseClass::doBind();
// Set valid flag from base class results.
mValidFlag = BaseClass::mStatus == 0;
// Show.
if (mValidFlag)
{
TS::print(1, "UdpRxMsgSocket PASS %16s : %5d",
BaseClass::mLocal.mIpAddr.mString,
BaseClass::mLocal.mPort);
}
else
{
TS::print(1, "UdpRxMsgSocket FAIL %16s : %5d $ %d %d",
BaseClass::mLocal.mIpAddr.mString,
BaseClass::mLocal.mPort,
BaseClass::mStatus,
BaseClass::mError);
}
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Receive a message from the socket with a blocking recv call into a
// byte buffer and extract a message from the byte buffer. Return the
// message and true if successful. As part of the termination process,
// returning false means that the socket was closed or that there was
// an error.
bool UdpRxMsgSocket::doReceiveMsg(ByteContent*& aMsg)
{
//***************************************************************************
//***************************************************************************
//***************************************************************************
// Initialize.
// Do this first.
aMsg = 0;
// Guard.
if (!mValidFlag)
{
TS::print(0, "ERROR UdpRxMsgSocket INVALID SOCKET");
return false;
}
// Create a byte buffer from preallocated memory.
ByteBuffer tByteBuffer(mRxMemory, mMemorySize);
//***************************************************************************
//***************************************************************************
//***************************************************************************
// Read the message into the receive buffer.
tByteBuffer.setCopyFrom();
BaseClass::doRecvFrom(mFromAddress, tByteBuffer.getBaseAddress(), mRxLength, mMemorySize);
// Guard.
// If bad status then return false.
// Returning true means socket was not closed.
// Returning false means socket was closed.
if (mRxLength <= 0)
{
if (BaseClass::mError == 0)
{
TS::print(1, "UdpRxMsgSocket CLOSED");
}
else
{
TS::print(0, "ERROR UdpRxMsgSocket %d %d", BaseClass::mStatus, BaseClass::mError);
}
return false;
}
TS::print(3, "UdpRxMsgSocket rx message %d", mRxLength);
// Set the buffer length.
tByteBuffer.setLength(mRxLength);
//***************************************************************************
//***************************************************************************
//***************************************************************************
// Copy from the receive buffer into the message monkey and validate
// the header.
// Extract the header.
mMonkey->extractMessageHeaderParms(&tByteBuffer);
TS::print(3, "UdpRxMsgSocket rx header %d %d",
mMonkey->mHeaderValidFlag,
mMonkey->mHeaderLength);
// If the header is not valid then error.
if (!mMonkey->mHeaderValidFlag)
{
TS::print(0, "ERROR UdpRxMsgSocket INVALID HEADER", mStatus, mError);
return false;
}
//***************************************************************************
//***************************************************************************
//***************************************************************************
// At this point the buffer contains the complete message. Extract the
// message from the byte buffer into a new message object and return it.
// Extract the message.
tByteBuffer.rewind();
aMsg = mMonkey->getMsgFromBuffer(&tByteBuffer);
// Test for errors.
if (aMsg == 0)
{
TS::print(0, "ERROR UdpRxMsgSocket INVALID MESSAGE", mStatus, mError);
mStatus = tByteBuffer.getError();
return false;
}
// Done.
mRxCount++;
return true;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
UdpTxMsgSocket::UdpTxMsgSocket()
{
mTxMemory = 0;
mMemorySize = 0;
mTxCount = 0;
mTxLength = 0;
mValidFlag = false;
mMonkey = 0;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
UdpTxMsgSocket::~UdpTxMsgSocket()
{
if (mTxMemory) free(mTxMemory);
if (mMonkey) delete mMonkey;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Initialize variables.
void UdpTxMsgSocket::initialize(Settings& aSettings)
{
// Store the settings.
mSettings = aSettings;
// Create a message monkey.
mMonkey = mSettings.mMonkeyCreator->createMonkey();
// Allocate memory for byte buffers.
mMemorySize = mMonkey->getMaxBufferSize();
mTxMemory = (char*)malloc(mMemorySize);
// Metrics.
mTxCount = 0;
mTxLength = 0;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Configure the socket.
void UdpTxMsgSocket::configure()
{
// Configure the socket.
BaseClass::mRemote.set(mSettings.mRemoteIpAddr, mSettings.mRemoteIpPort);
BaseClass::doSocket();
// Set valid flag from base class results.
mValidFlag = BaseClass::mStatus == 0;
// Show.
if (mValidFlag)
{
TS::print(1, "UdpTxMsgSocket PASS %16s : %5d",
BaseClass::mRemote.mIpAddr.mString,
BaseClass::mRemote.mPort);
}
else
{
TS::print(1, "UdpTxMsgSocket FAIL %16s : %5d $ %d %d",
BaseClass::mRemote.mIpAddr.mString,
BaseClass::mRemote.mPort,
BaseClass::mStatus,
BaseClass::mError);
}
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
// Copy a message into a byte buffer and then send the byte buffer to the
// socket with a blocking send call. Return true if successful.
// It is protected by the transmit mutex.
bool UdpTxMsgSocket::doSendMsg(ByteContent* aMsg)
{
// Guard.
if (!mValidFlag)
{
TS::print(0, "ERROR UdpTxMsgSocket INVALID SOCKET");
delete aMsg;
return false;
}
// Mutex.
mTxMutex.lock();
// Create a byte buffer from preallocated memory.
ByteBuffer tByteBuffer(mTxMemory, mMemorySize);
// Copy the message to the buffer.
mMonkey->putMsgToBuffer(&tByteBuffer, aMsg);
// Delete the message.
delete aMsg;
// Transmit the buffer.
mTxLength = tByteBuffer.getLength();
bool tRet = doSendTo(mRemote, tByteBuffer.getBaseAddress(), mTxLength);
mTxCount++;
// Mutex.
mTxMutex.unlock();
if (tRet)
{
TS::print(3, "UdpTxMsgSocket tx message %d", mTxLength);
}
else
{
TS::print(0, "ERROR UdpTxMsgSocket INVALID SEND");
}
// Done.
return tRet;
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
}//namespace
}//namespace
| 30.376543 | 93 | 0.410384 | [
"object"
] |
173c22308e0c6c3c1d84fac8eec6afcbb7d3e56a | 5,685 | cpp | C++ | tests/test-session-json.cpp | isndev/qbm-json | 0f7b999ff3e232d0f0ffb633eaaf744519b69d04 | [
"Apache-2.0"
] | null | null | null | tests/test-session-json.cpp | isndev/qbm-json | 0f7b999ff3e232d0f0ffb633eaaf744519b69d04 | [
"Apache-2.0"
] | null | null | null | tests/test-session-json.cpp | isndev/qbm-json | 0f7b999ff3e232d0f0ffb633eaaf744519b69d04 | [
"Apache-2.0"
] | null | null | null | /*
* qb - C++ Actor Framework
* Copyright (C) 2011-2020 isndev (www.qbaf.io). 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 "../json.h"
#include <atomic>
#include <chrono>
#include <gtest/gtest.h>
#include <qb/io/async.h>
#include <thread>
using namespace qb::io;
constexpr const std::size_t NB_ITERATION = 4096;
constexpr const char STRING_MESSAGE[] = "Here is my content test";
std::atomic<std::size_t> msg_count_server_side = 0;
std::atomic<std::size_t> msg_count_client_side = 0;
bool
all_done() {
return msg_count_server_side == (NB_ITERATION) &&
msg_count_client_side == NB_ITERATION;
}
// OVER TCP
class TestServer;
class TestServerClient : public use<TestServerClient>::tcp::client<TestServer> {
public:
using Protocol = qb::json::protocol<TestServerClient>;
explicit TestServerClient(IOServer &server)
: client(server) {}
~TestServerClient() {
EXPECT_EQ(msg_count_server_side, NB_ITERATION);
}
void
on(Protocol::message &&msg) {
EXPECT_EQ(msg.json["message"].get<std::string>().size(),
sizeof(STRING_MESSAGE) - 1);
*this << msg.json << '\0';
++msg_count_server_side;
}
};
class TestServer : public use<TestServer>::tcp::server<TestServerClient> {
std::size_t connection_count = 0u;
public:
~TestServer() {
EXPECT_EQ(connection_count, 1u);
}
void
on(IOSession &) {
++connection_count;
}
};
class TestClient : public use<TestClient>::tcp::client<> {
public:
using Protocol = qb::json::protocol<TestClient>;
~TestClient() {
EXPECT_EQ(msg_count_client_side, NB_ITERATION);
}
void
on(Protocol::message &&msg) {
EXPECT_EQ(msg.json["message"].get<std::string>().size(),
sizeof(STRING_MESSAGE) - 1);
++msg_count_client_side;
}
};
TEST(Session, JSON_OVER_TCP) {
async::init();
msg_count_server_side = 0;
msg_count_client_side = 0;
TestServer server;
server.transport().listen(60123);
server.start();
std::thread t([]() {
async::init();
TestClient client;
if (SocketStatus::Done != client.transport().connect("127.0.0.1", 60123)) {
throw std::runtime_error("could not connect");
}
client.start();
for (auto i = 0u; i < NB_ITERATION; ++i) {
client << nlohmann::json{{"message", STRING_MESSAGE}} << '\0';
}
for (auto i = 0; i < (NB_ITERATION * 5) && !all_done(); ++i)
async::run(EVRUN_ONCE);
});
for (auto i = 0; i < (NB_ITERATION * 5) && !all_done(); ++i)
async::run(EVRUN_ONCE);
t.join();
}
// OVER SECURE TCP
#ifdef QB_IO_WITH_SSL
class TestSecureServer;
class TestSecureServerClient
: public use<TestSecureServerClient>::tcp::ssl::client<TestSecureServer> {
public:
using Protocol = qb::json::protocol_packed<TestSecureServerClient>;
explicit TestSecureServerClient(IOServer &server)
: client(server) {}
~TestSecureServerClient() {
EXPECT_EQ(msg_count_server_side, NB_ITERATION);
}
void
on(Protocol::message &&msg) {
EXPECT_EQ(msg.json["message"].get<std::string>().size(),
sizeof(STRING_MESSAGE) - 1);
*this << qb::json::object::to_msgpack(msg.json) << '\0';
++msg_count_server_side;
}
};
class TestSecureServer
: public use<TestSecureServer>::tcp::ssl::server<TestSecureServerClient> {
std::size_t connection_count = 0u;
public:
~TestSecureServer() {
EXPECT_EQ(connection_count, 1u);
}
void
on(IOSession &) {
++connection_count;
}
};
class TestSecureClient : public use<TestSecureClient>::tcp::ssl::client<> {
public:
using Protocol = qb::json::protocol_packed<TestSecureClient>;
~TestSecureClient() {
EXPECT_EQ(msg_count_client_side, NB_ITERATION);
}
void
on(Protocol::message &&msg) {
EXPECT_EQ(msg.json["message"].get<std::string>().size(),
sizeof(STRING_MESSAGE) - 1);
++msg_count_client_side;
}
};
TEST(Session, JSON_OVER_SECURE_TCP) {
async::init();
msg_count_server_side = 0;
msg_count_client_side = 0;
TestSecureServer server;
server.transport().init(
ssl::create_server_context(SSLv23_server_method(), "cert.pem", "key.pem"));
server.transport().listen(60123);
server.start();
std::thread t([]() {
async::init();
TestSecureClient client;
if (SocketStatus::Done != client.transport().connect("127.0.0.1", 60123)) {
throw std::runtime_error("could not connect");
}
client.start();
for (auto i = 0u; i < NB_ITERATION; ++i) {
client << qb::json::object::to_msgpack(
nlohmann::json{{"message", STRING_MESSAGE}})
<< '\0';
}
for (auto i = 0; i < (NB_ITERATION * 5) && !all_done(); ++i)
async::run(EVRUN_ONCE);
});
for (auto i = 0; i < (NB_ITERATION * 5) && !all_done(); ++i)
async::run(EVRUN_ONCE);
t.join();
}
#endif | 26.44186 | 83 | 0.618294 | [
"object"
] |
173e85a94446783e0698ace3a00b900e5d112f61 | 44,047 | cc | C++ | src/fluid/fluidmsg/fluid/of13/of13common.cc | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 19 | 2020-04-25T15:51:52.000Z | 2021-11-24T04:51:02.000Z | src/fluid/fluidmsg/fluid/of13/of13common.cc | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 10 | 2020-09-09T09:54:20.000Z | 2021-04-27T20:47:52.000Z | src/fluid/fluidmsg/fluid/of13/of13common.cc | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 24 | 2020-05-31T01:41:12.000Z | 2022-01-16T17:06:35.000Z | #include "of13common.hh"
namespace fluid_msg {
namespace of13 {
HelloElem::HelloElem(uint16_t type, uint16_t length) {
this->type_ = type;
this->length_ = length;
}
bool HelloElem::operator==(const HelloElem &other) const {
return ((this->type_ == other.type_) && (this->length_ == other.length_));
}
bool HelloElem::operator!=(const HelloElem &other) const {
return !(*this == other);
}
HelloElemVersionBitmap::HelloElemVersionBitmap(std::list<uint32_t> bitmaps)
: HelloElem(of13::OFPHET_VERSIONBITMAP,
sizeof(struct of13::ofp_hello_elem_versionbitmap)) {
this->bitmaps_ = bitmaps;
this->length_ += bitmaps.size() * sizeof(uint32_t);
}
bool HelloElemVersionBitmap::operator==(
const HelloElemVersionBitmap &other) const {
return ((HelloElem::operator==(other)) && (this->bitmaps_ == other.bitmaps_));
}
bool HelloElemVersionBitmap::operator!=(
const HelloElemVersionBitmap &other) const {
return !(*this == other);
}
void HelloElemVersionBitmap::add_bitmap(uint32_t bitmap) {
this->bitmaps_.push_back(bitmap);
this->length_ += sizeof(uint32_t);
}
size_t HelloElemVersionBitmap::pack(uint8_t *buffer) {
struct of13::ofp_hello_elem_versionbitmap *elem =
(struct of13::ofp_hello_elem_versionbitmap *)buffer;
elem->type = hton16(this->type_);
elem->length = hton16(this->length_);
uint8_t *p = buffer + sizeof(struct of13::ofp_hello_elem_versionbitmap);
for (std::list<uint32_t>::iterator it = this->bitmaps_.begin();
it != this->bitmaps_.end(); it++) {
uint32_t bitmap = hton32(*it);
memcpy(p, &bitmap, sizeof(uint32_t));
p += sizeof(uint32_t);
}
return 0;
}
of_error HelloElemVersionBitmap::unpack(uint8_t *buffer) {
struct of13::ofp_hello_elem_versionbitmap *elem =
(struct of13::ofp_hello_elem_versionbitmap *)buffer;
this->type_ = ntoh16(elem->type);
this->length_ = ntoh16(elem->length);
uint32_t bitmaps;
memcpy(&bitmaps, elem->bitmaps, sizeof(uint32_t));
uint8_t *p = buffer + sizeof(struct of13::ofp_hello_elem_versionbitmap);
size_t len =
this->length_ - sizeof(struct of13::ofp_hello_elem_versionbitmap);
while (len) {
uint32_t bitmap = ntoh32((*(uint32_t *)p));
this->bitmaps_.push_back(bitmap);
p += sizeof(uint32_t);
len -= sizeof(uint32_t);
}
return 0;
}
Port::Port() : PortCommon(), port_no_(0), curr_speed_(0), max_speed_(0) {}
Port::Port(uint32_t port_no, EthAddress hw_addr, std::string name,
uint32_t config, uint32_t state, uint32_t curr, uint32_t advertised,
uint32_t supported, uint32_t peer, uint32_t curr_speed,
uint32_t max_speed)
: PortCommon(hw_addr, name, config, state, curr, advertised, supported,
peer),
port_no_(port_no),
curr_speed_(curr_speed),
max_speed_(max_speed) {}
bool Port::operator==(const Port &other) const {
return ((PortCommon::operator==(other)) &&
(this->port_no_ == other.port_no_) &&
(this->curr_speed_ == other.curr_speed_) &&
(this->max_speed_ == other.max_speed_));
}
bool Port::operator!=(const Port &other) const { return !(*this == other); }
size_t Port::pack(uint8_t *buffer) {
struct of13::ofp_port *port = (struct of13::ofp_port *)buffer;
port->port_no = hton32(this->port_no_);
memset(port->pad, 0x0, 4);
memcpy(port->hw_addr, this->hw_addr_.get_data(), OFP_ETH_ALEN);
memset(port->pad2, 0x0, 2);
memset(port->name, 0x0, OFP_MAX_PORT_NAME_LEN);
memcpy(port->name, this->name_.c_str(),
this->name_.size() < OFP_MAX_PORT_NAME_LEN ? this->name_.size()
: OFP_MAX_PORT_NAME_LEN);
port->config = hton32(this->config_);
port->state = hton32(this->state_);
port->curr = hton32(this->curr_);
port->advertised = hton32(this->advertised_);
port->supported = hton32(this->supported_);
port->peer = hton32(this->peer_);
port->curr_speed = hton32(this->curr_speed_);
port->max_speed = hton32(this->max_speed_);
return 0;
}
of_error Port::unpack(uint8_t *buffer) {
struct of13::ofp_port *port = (struct of13::ofp_port *)buffer;
this->port_no_ = ntoh32(port->port_no);
this->hw_addr_ = EthAddress(port->hw_addr);
this->name_ = std::string(port->name);
this->config_ = ntoh32(port->config);
this->state_ = ntoh32(port->state);
this->curr_ = ntoh32(port->curr);
this->advertised_ = ntoh32(port->advertised);
this->supported_ = ntoh32(port->supported);
this->peer_ = ntoh32(port->peer);
this->curr_speed_ = ntoh32(port->curr_speed);
this->max_speed_ = ntoh32(port->max_speed);
return 0;
}
QueuePropMinRate::QueuePropMinRate(uint16_t rate)
: QueuePropRate(of13::OFPQT_MIN_RATE, rate) {
this->len_ = sizeof(struct of13::ofp_queue_prop_min_rate);
}
bool QueuePropMinRate::equals(const QueueProperty &other) {
if (const QueuePropMinRate *prop =
dynamic_cast<const QueuePropMinRate *>(&other)) {
return ((QueuePropRate::equals(other)));
} else {
return false;
}
}
size_t QueuePropMinRate::pack(uint8_t *buffer) {
struct of13::ofp_queue_prop_min_rate *qp =
(struct of13::ofp_queue_prop_min_rate *)buffer;
QueueProperty::pack(buffer);
qp->rate = hton16(this->rate_);
memset(qp->pad, 0x0, 6);
return this->len_;
}
of_error QueuePropMinRate::unpack(uint8_t *buffer) {
struct of13::ofp_queue_prop_min_rate *qp =
(struct of13::ofp_queue_prop_min_rate *)buffer;
QueueProperty::unpack(buffer);
this->rate_ = ntoh16(qp->rate);
return 0;
}
QueuePropMaxRate::QueuePropMaxRate(uint16_t rate)
: QueuePropRate(of13::OFPQT_MAX_RATE, rate) {
this->len_ = sizeof(struct of13::ofp_queue_prop_min_rate);
}
bool QueuePropMaxRate::equals(const QueueProperty &other) {
if (const QueuePropMaxRate *prop =
dynamic_cast<const QueuePropMaxRate *>(&other)) {
return ((QueuePropRate::equals(other)));
} else {
return false;
}
}
size_t QueuePropMaxRate::pack(uint8_t *buffer) {
struct of13::ofp_queue_prop_min_rate *qp =
(struct of13::ofp_queue_prop_min_rate *)buffer;
QueueProperty::pack(buffer);
qp->rate = hton16(this->rate_);
memset(qp->pad, 0x0, 6);
return this->len_;
}
of_error QueuePropMaxRate::unpack(uint8_t *buffer) {
struct of13::ofp_queue_prop_min_rate *qp =
(struct of13::ofp_queue_prop_min_rate *)buffer;
QueueProperty::unpack(buffer);
this->rate_ = ntoh16(qp->rate);
return 0;
}
QueueExperimenter::QueueExperimenter(uint32_t experimenter)
: QueueProperty(of13::OFPQT_EXPERIMENTER) {
this->experimenter_ = experimenter;
this->len_ = sizeof(struct of13::ofp_queue_prop_min_rate);
}
size_t QueueExperimenter::pack(uint8_t *buffer) {
struct of13::ofp_queue_prop_experimenter *qp =
(struct of13::ofp_queue_prop_experimenter *)buffer;
QueueProperty::pack(buffer);
qp->experimenter = hton32(this->experimenter_);
memset(qp->pad, 0x0, 4);
return this->len_;
}
of_error QueueExperimenter::unpack(uint8_t *buffer) {
struct of13::ofp_queue_prop_experimenter *qp =
(struct of13::ofp_queue_prop_experimenter *)buffer;
QueueProperty::unpack(buffer);
this->experimenter_ = ntoh32(qp->experimenter);
return 0;
}
PacketQueue::PacketQueue() : PacketQueueCommon(), port_(0) {
this->len_ = sizeof(struct of13::ofp_packet_queue);
}
PacketQueue::PacketQueue(uint32_t queue_id, uint32_t port)
: PacketQueueCommon(queue_id) {
this->port_ = port;
this->len_ = sizeof(struct of13::ofp_packet_queue);
}
PacketQueue::PacketQueue(uint32_t queue_id, uint32_t port,
QueuePropertyList properties)
: PacketQueueCommon(queue_id) {
this->port_ = port;
this->properties_ = properties;
this->len_ = sizeof(struct of13::ofp_packet_queue) + properties.length();
}
bool PacketQueue::operator==(const PacketQueue &other) const {
return ((PacketQueueCommon::operator==(other)) &&
(this->port_ == other.port_));
}
bool PacketQueue::operator!=(const PacketQueue &other) const {
return !(*this == other);
}
size_t PacketQueue::pack(uint8_t *buffer) {
struct of13::ofp_packet_queue *pq = (struct of13::ofp_packet_queue *)buffer;
pq->queue_id = hton32(this->queue_id_);
pq->port = hton32(this->port_);
pq->len = hton16(this->len_);
memset(pq->pad, 0x0, 6);
uint8_t *p = buffer + sizeof(struct of13::ofp_packet_queue);
this->properties_.pack(p);
return this->len_;
}
of_error PacketQueue::unpack(uint8_t *buffer) {
struct of13::ofp_packet_queue *pq = (struct of13::ofp_packet_queue *)buffer;
this->queue_id_ = ntoh32(pq->queue_id);
this->port_ = ntoh32(pq->port);
this->len_ = ntoh16(pq->len);
uint8_t *p = buffer + sizeof(struct of13::ofp_packet_queue);
this->properties_.length(this->len_ - sizeof(struct of13::ofp_packet_queue));
this->properties_.unpack13(p);
return 0;
}
Bucket::Bucket()
: length_(sizeof(struct of13::ofp_bucket)),
weight_(0),
watch_port_(0),
watch_group_(0) {}
Bucket::Bucket(uint16_t weight, uint32_t watch_port, uint32_t watch_group) {
this->weight_ = weight;
this->watch_port_ = watch_port;
this->watch_group_ = watch_group;
this->length_ = sizeof(struct of13::ofp_bucket);
}
Bucket::Bucket(uint16_t weight, uint32_t watch_port, uint32_t watch_group,
ActionSet actions) {
this->weight_ = weight;
this->watch_port_ = watch_port;
this->watch_group_ = watch_group;
this->actions_ = actions;
this->length_ = sizeof(struct of13::ofp_bucket) + actions.length();
}
bool Bucket::operator==(const Bucket &other) const {
return ((this->length_ == other.length_) &&
(this->weight_ == other.weight_) &&
(this->watch_port_ == other.watch_port_) &&
(this->watch_group_ == other.watch_group_) &&
(this->actions_ == other.actions_));
}
bool Bucket::operator!=(const Bucket &other) const { return !(*this == other); }
void Bucket::actions(ActionSet actions) {
this->actions_ = actions;
this->length_ += actions.length();
}
void Bucket::add_action(Action &action) {
this->actions_.add_action(action);
this->length_ += action.length();
}
void Bucket::add_action(Action *action) {
this->actions_.add_action(action);
this->length_ += action->length();
}
size_t Bucket::pack(uint8_t *buffer) {
struct of13::ofp_bucket *b = (struct of13::ofp_bucket *)buffer;
b->len = hton16(this->length_);
b->weight = hton16(this->weight_);
b->watch_port = hton32(this->watch_port_);
b->watch_group = hton32(this->watch_group_);
memset(b->pad, 0x0, 4);
this->actions_.pack(buffer + sizeof(struct of13::ofp_bucket));
return 0;
}
of_error Bucket::unpack(uint8_t *buffer) {
struct of13::ofp_bucket *b = (struct of13::ofp_bucket *)buffer;
this->length_ = ntoh16(b->len);
this->weight_ = ntoh16(b->weight);
this->watch_port_ = ntoh32(b->watch_port);
this->watch_group_ = ntoh32(b->watch_group);
this->actions_.length(this->length_ - sizeof(struct of13::ofp_bucket));
this->actions_.unpack(buffer + sizeof(struct of13::ofp_bucket));
return 0;
}
FlowStats::FlowStats() : FlowStatsCommon(), flags_(0) {
this->length_ =
sizeof(struct of13::ofp_flow_stats) - sizeof(struct of13::ofp_match);
}
FlowStats::FlowStats(uint8_t table_id, uint32_t duration_sec,
uint32_t duration_nsec, uint16_t priority,
uint16_t idle_timeout, uint16_t hard_timeout,
uint16_t flags, uint64_t cookie, uint64_t packet_count,
uint64_t byte_count)
: FlowStatsCommon(table_id, duration_sec, duration_nsec, priority,
idle_timeout, hard_timeout, cookie, packet_count,
byte_count) {
this->flags_ = flags;
this->length_ =
sizeof(struct of13::ofp_flow_stats) - sizeof(struct of13::ofp_match);
}
bool FlowStats::operator==(const FlowStats &other) const {
return ((FlowStatsCommon::operator==(other)) &&
(this->flags_ == other.flags_) &&
(this->instructions_ == other.instructions_) &&
(this->match_ == other.match_));
}
bool FlowStats::operator!=(const FlowStats &other) const {
return !(*this == other);
}
size_t FlowStats::pack(uint8_t *buffer) {
size_t padding =
ROUND_UP(sizeof(struct of13::ofp_flow_stats) -
sizeof(struct of13::ofp_match) + this->match_.length(),
8) -
(sizeof(struct of13::ofp_flow_stats) - sizeof(struct of13::ofp_match) +
this->match_.length());
struct of13::ofp_flow_stats *fs = (struct of13::ofp_flow_stats *)buffer;
fs->length = hton16(this->length_);
fs->table_id = this->table_id_;
memset(&fs->pad, 0x0, 1);
fs->duration_sec = hton32(this->duration_sec_);
fs->duration_nsec = hton32(this->duration_nsec_);
fs->priority = hton16(this->priority_);
fs->idle_timeout = hton16(this->idle_timeout_);
fs->hard_timeout = hton16(this->hard_timeout_);
fs->flags = hton16(this->flags_);
memset(fs->pad2, 0x0, 4);
fs->cookie = hton64(this->cookie_);
fs->packet_count = hton64(this->packet_count_);
fs->byte_count = hton64(this->byte_count_);
uint8_t *p = buffer + (sizeof(struct of13::ofp_flow_stats) -
sizeof(struct of13::ofp_match));
this->match_.pack(p);
p += this->match_.length();
memset(p, 0x0, padding);
p += padding;
this->instructions_.pack(p);
return this->length_;
}
of_error FlowStats::unpack(uint8_t *buffer) {
struct of13::ofp_flow_stats *fs = (struct of13::ofp_flow_stats *)buffer;
this->length_ = ntoh16(fs->length);
this->table_id_ = fs->table_id;
this->duration_sec_ = ntoh32(fs->duration_sec);
this->duration_nsec_ = ntoh32(fs->duration_nsec);
this->priority_ = ntoh16(fs->priority);
this->idle_timeout_ = ntoh16(fs->idle_timeout);
this->hard_timeout_ = ntoh16(fs->hard_timeout);
this->flags_ = ntoh16(fs->flags);
this->cookie_ = ntoh64(fs->cookie);
this->packet_count_ = ntoh64(fs->packet_count);
this->byte_count_ = ntoh64(fs->byte_count);
uint8_t *p = buffer + (sizeof(struct of13::ofp_flow_stats) -
sizeof(struct of13::ofp_match));
this->match_.unpack(p);
this->instructions_.length(
this->length_ -
((sizeof(struct of13::ofp_flow_stats) - sizeof(struct of13::ofp_match)) +
ROUND_UP(this->match_.length(), 8)));
p += ROUND_UP(this->match_.length(), 8);
this->instructions_.unpack(p);
return 0;
}
void FlowStats::match(of13::Match match) {
this->match_ = match;
this->length_ += match.length();
// Padding bytes
this->length_ = ROUND_UP(this->length_, 8);
}
OXMTLV *FlowStats::get_oxm_field(uint8_t field) {
return this->match_.oxm_field(field);
}
void FlowStats::instructions(InstructionSet instructions) {
this->instructions_ = instructions;
this->length_ += instructions.length();
}
void FlowStats::add_instruction(Instruction *inst) {
this->instructions_.add_instruction(inst);
this->length_ += inst->length();
}
TableStats::TableStats() : TableStatsCommon() {}
TableStats::TableStats(uint8_t table_id, uint32_t active_count,
uint64_t lookup_count, uint64_t matched_count)
: TableStatsCommon(table_id, active_count, lookup_count, matched_count) {}
size_t TableStats::pack(uint8_t *buffer) {
struct of13::ofp_table_stats *ts = (struct of13::ofp_table_stats *)buffer;
ts->table_id = this->table_id_;
memset(ts->pad, 0x0, 3);
ts->active_count = hton32(this->active_count_);
ts->lookup_count = hton64(this->lookup_count_);
ts->matched_count = hton64(this->matched_count_);
return 0;
}
of_error TableStats::unpack(uint8_t *buffer) {
struct of13::ofp_table_stats *ts = (struct of13::ofp_table_stats *)buffer;
this->table_id_ = ts->table_id;
this->active_count_ = ntoh32(ts->active_count);
this->lookup_count_ = ntoh64(ts->lookup_count);
this->matched_count_ = ntoh64(ts->matched_count);
return 0;
}
PortStats::PortStats()
: PortStatsCommon(), port_no_(0), duration_sec_(0), duration_nsec_(0) {}
PortStats::PortStats(uint32_t port_no, struct port_rx_tx_stats rx_tx_stats,
struct port_err_stats err_stats, uint64_t collisions,
uint32_t duration_sec, uint32_t duration_nsec)
: PortStatsCommon(rx_tx_stats, err_stats, collisions) {
this->port_no_ = port_no;
this->duration_sec_ = duration_sec;
this->duration_nsec_ = duration_nsec;
}
bool PortStats::operator==(const PortStats &other) const {
return ((PortStatsCommon::operator==(other)) &&
(this->port_no_ == other.port_no_) &&
(this->duration_sec_ == other.duration_sec_) &&
(this->duration_nsec_ == other.duration_nsec_));
}
bool PortStats::operator!=(const PortStats &other) const {
return !(*this == other);
}
size_t PortStats::pack(uint8_t *buffer) {
struct of13::ofp_port_stats *ps = (struct of13::ofp_port_stats *)buffer;
ps->port_no = hton32(this->port_no_);
memset(ps->pad, 0x0, 6);
PortStatsCommon::pack(buffer + 8);
ps->collisions = hton64(this->collisions_);
ps->duration_sec = hton32(this->duration_sec_);
ps->duration_nsec = hton32(this->duration_nsec_);
return 0;
}
of_error PortStats::unpack(uint8_t *buffer) {
struct of13::ofp_port_stats *ps = (struct of13::ofp_port_stats *)buffer;
this->port_no_ = ntoh32(ps->port_no);
PortStatsCommon::unpack(buffer + 8);
this->collisions_ = ntoh64(ps->collisions);
this->duration_sec_ = hton32(ps->duration_sec);
this->duration_nsec_ = hton32(ps->duration_nsec);
return 0;
}
QueueStats::QueueStats()
: QueueStatsCommon(), port_no_(0), duration_sec_(0), duration_nsec_(0) {}
QueueStats::QueueStats(uint32_t port_no, uint32_t queue_id, uint64_t tx_bytes,
uint64_t tx_packets, uint64_t tx_errors,
uint32_t duration_sec, uint32_t duration_nsec)
: QueueStatsCommon(queue_id, tx_bytes, tx_packets, tx_errors) {
this->port_no_ = port_no;
this->duration_sec_ = duration_sec;
this->duration_nsec_ = duration_nsec;
}
bool QueueStats::operator==(const QueueStats &other) const {
return ((QueueStatsCommon::operator==(other)) &&
(this->port_no_ == other.port_no_) &&
(this->duration_sec_ == other.duration_sec_) &&
(this->duration_nsec_ == other.duration_nsec_));
}
bool QueueStats::operator!=(const QueueStats &other) const {
return !(*this == other);
}
size_t QueueStats::pack(uint8_t *buffer) {
struct of13::ofp_queue_stats *qs = (struct of13::ofp_queue_stats *)buffer;
qs->port_no = hton32(this->port_no_);
qs->queue_id = hton32(this->queue_id_);
qs->tx_bytes = hton64(this->tx_bytes_);
qs->tx_packets = hton64(this->tx_packets_);
qs->tx_errors = hton64(this->tx_errors_);
qs->duration_sec = hton32(this->duration_sec_);
qs->duration_nsec = hton32(this->duration_nsec_);
return 0;
}
of_error QueueStats::unpack(uint8_t *buffer) {
struct of13::ofp_queue_stats *qs = (struct of13::ofp_queue_stats *)buffer;
this->port_no_ = ntoh32(qs->port_no);
this->queue_id_ = ntoh32(qs->queue_id);
this->tx_bytes_ = ntoh64(qs->tx_bytes);
this->tx_packets_ = ntoh64(qs->tx_packets);
this->tx_errors_ = ntoh64(qs->tx_errors);
this->duration_sec_ = ntoh32(qs->duration_sec);
this->duration_nsec_ = ntoh32(qs->duration_nsec);
return 0;
}
BucketStats::BucketStats() : packet_count_(0), byte_count_(0) {}
BucketStats::BucketStats(uint64_t packet_count, uint64_t byte_count) {
this->packet_count_ = packet_count;
this->byte_count_ = byte_count;
}
bool BucketStats::operator==(const BucketStats &other) const {
return ((this->packet_count_ == other.packet_count_) &&
(this->byte_count_ == other.byte_count_));
}
bool BucketStats::operator!=(const BucketStats &other) const {
return !(*this == other);
}
size_t BucketStats::pack(uint8_t *buffer) {
struct of13::ofp_bucket_counter *bc =
(struct of13::ofp_bucket_counter *)buffer;
bc->packet_count = hton64(this->packet_count_);
bc->byte_count = hton64(this->byte_count_);
return 0;
}
of_error BucketStats::unpack(uint8_t *buffer) {
struct of13::ofp_bucket_counter *bc =
(struct of13::ofp_bucket_counter *)buffer;
this->packet_count_ = ntoh64(bc->packet_count);
this->byte_count_ = ntoh64(bc->byte_count);
return 0;
}
GroupStats::GroupStats(uint32_t group_id, uint32_t ref_count,
uint64_t packet_count, uint64_t byte_count,
uint32_t duration_sec, uint32_t duration_nsec) {
this->group_id_ = group_id;
this->ref_count_ = ref_count;
this->packet_count_ = packet_count;
this->byte_count_ = byte_count;
this->duration_sec_ = duration_sec;
this->duration_nsec_ = duration_nsec;
this->length_ = sizeof(struct of13::ofp_group_stats);
}
GroupStats::GroupStats(uint32_t group_id, uint32_t ref_count,
uint64_t packet_count, uint64_t byte_count,
uint32_t duration_sec, uint32_t duration_nsec,
std::vector<BucketStats> bucket_stats) {
this->group_id_ = group_id;
this->ref_count_ = ref_count;
this->packet_count_ = packet_count;
this->byte_count_ = byte_count;
this->duration_sec_ = duration_sec;
this->duration_nsec_ = duration_nsec;
this->bucket_stats_ = bucket_stats;
this->length_ = sizeof(struct of13::ofp_group_stats) +
bucket_stats.size() * sizeof(struct of13::ofp_bucket_counter);
}
bool GroupStats::operator==(const GroupStats &other) const {
return ((this->group_id_ == other.group_id_) &&
(this->ref_count_ == other.ref_count_) &&
(this->packet_count_ == other.packet_count_) &&
(this->byte_count_ == other.byte_count_) &&
(this->duration_sec_ == other.duration_sec_) &&
(this->duration_nsec_ == other.duration_nsec_) &&
(this->bucket_stats_ == other.bucket_stats_) &&
(this->length_ == other.length_));
}
bool GroupStats::operator!=(const GroupStats &other) const {
return !(*this == other);
}
size_t GroupStats::pack(uint8_t *buffer) {
struct of13::ofp_group_stats *gs = (struct of13::ofp_group_stats *)buffer;
gs->length = hton16(this->length_);
gs->group_id = hton32(this->group_id_);
gs->ref_count = hton32(this->ref_count_);
gs->packet_count = hton64(this->packet_count_);
gs->byte_count = hton64(this->byte_count_);
gs->duration_sec = hton32(this->duration_sec_);
gs->duration_nsec = hton32(this->duration_nsec_);
uint8_t *p = buffer + sizeof(of13::ofp_group_stats);
for (std::vector<BucketStats>::iterator it = this->bucket_stats_.begin();
it != this->bucket_stats_.end(); ++it) {
it->pack(p);
p += sizeof(struct of13::ofp_bucket_counter);
}
return 0;
}
of_error GroupStats::unpack(uint8_t *buffer) {
struct of13::ofp_group_stats *gs = (struct of13::ofp_group_stats *)buffer;
this->length_ = ntoh16(gs->length);
this->group_id_ = ntoh32(gs->group_id);
this->ref_count_ = ntoh32(gs->ref_count);
this->packet_count_ = ntoh64(gs->packet_count);
this->byte_count_ = ntoh64(gs->byte_count);
this->duration_sec_ = ntoh32(gs->duration_sec);
this->duration_nsec_ = ntoh32(gs->duration_nsec);
uint8_t *p = buffer + sizeof(of13::ofp_group_stats);
size_t len = this->length_ - sizeof(of13::ofp_group_stats);
while (len) {
BucketStats stats;
stats.unpack(p);
this->bucket_stats_.push_back(stats);
p += sizeof(struct of13::ofp_bucket_counter);
len -= sizeof(struct of13::ofp_bucket_counter);
}
return 0;
}
void GroupStats::bucket_stats(std::vector<BucketStats> bucket_stats) {
this->bucket_stats_ = bucket_stats;
this->length_ +=
bucket_stats.size() * sizeof(struct of13::ofp_bucket_counter);
}
void GroupStats::add_bucket_stat(BucketStats stat) {
this->bucket_stats_.push_back(stat);
this->length_ += sizeof(struct of13::ofp_bucket_counter);
}
GroupDesc::GroupDesc(uint8_t type, uint32_t group_id) {
this->type_ = type;
this->group_id_ = group_id;
this->length_ = sizeof(struct of13::ofp_group_desc_stats);
}
GroupDesc::GroupDesc(uint8_t type, uint32_t group_id,
std::vector<of13::Bucket> buckets) {
this->type_ = type;
this->group_id_ = group_id;
this->buckets_ = buckets;
this->length_ = sizeof(struct of13::ofp_group_desc_stats) + buckets_len();
}
bool GroupDesc::operator==(const GroupDesc &other) const {
return (
(this->type_ == other.type_) && (this->group_id_ == other.group_id_) &&
(this->length_ == other.length_) && (this->buckets_ == other.buckets_));
}
bool GroupDesc::operator!=(const GroupDesc &other) const {
return !(*this == other);
}
size_t GroupDesc::pack(uint8_t *buffer) {
struct of13::ofp_group_desc_stats *gd =
(struct of13::ofp_group_desc_stats *)buffer;
gd->length = hton16(this->length_);
gd->type = this->type_;
memset(&gd->pad, 0x0, 1);
gd->group_id = hton32(this->group_id_);
uint8_t *p = buffer + sizeof(struct of13::ofp_group_desc_stats);
for (std::vector<Bucket>::iterator it = this->buckets_.begin();
it != this->buckets_.end(); ++it) {
it->pack(p);
p += it->len();
}
return this->length_;
}
of_error GroupDesc::unpack(uint8_t *buffer) {
struct of13::ofp_group_desc_stats *gd =
(struct of13::ofp_group_desc_stats *)buffer;
this->length_ = ntoh16(gd->length);
this->type_ = gd->type;
this->group_id_ = ntoh32(gd->group_id);
size_t len = this->length_ - sizeof(struct of13::ofp_group_desc_stats);
uint8_t *p = buffer + sizeof(struct of13::ofp_group_desc_stats);
while (len) {
Bucket bucket;
bucket.unpack(p);
this->buckets_.push_back(bucket);
p += bucket.len();
len -= bucket.len();
}
return 0;
}
void GroupDesc::buckets(std::vector<Bucket> buckets) {
this->buckets_ = buckets;
this->length_ += buckets_len();
}
void GroupDesc::add_bucket(Bucket bucket) {
this->buckets_.push_back(bucket);
this->length_ += bucket.len();
}
size_t GroupDesc::buckets_len() {
size_t len = 0;
for (std::vector<Bucket>::iterator it = this->buckets_.begin();
it != this->buckets_.end(); ++it) {
len += it->len();
}
return len;
};
GroupFeatures::GroupFeatures(uint32_t types, uint32_t capabilities,
uint32_t max_groups[4], uint32_t actions[4]) {
this->types_ = types;
this->capabilities_ = capabilities;
memcpy(this->max_groups_, max_groups, 16);
memcpy(this->actions_, actions, 16);
}
bool GroupFeatures::operator==(const GroupFeatures &other) const {
for (int i = 0; i < 4; i++) {
if (this->max_groups_[i] != other.max_groups_[i]) {
return false;
}
if (this->actions_[i] != other.actions_[i]) {
return false;
}
}
return ((this->types_ == other.types_) &&
(this->capabilities_ == other.capabilities_));
}
bool GroupFeatures::operator!=(const GroupFeatures &other) const {
return !(*this == other);
}
size_t GroupFeatures::pack(uint8_t *buffer) {
struct of13::ofp_group_features *gf =
(struct of13::ofp_group_features *)buffer;
gf->types = hton32(this->types_);
gf->capabilities = hton32(this->capabilities_);
for (int i = 0; i < 4; i++) {
gf->max_groups[i] = hton32(this->max_groups_[i]);
gf->actions[i] = hton32(this->actions_[i]);
}
return 0;
}
of_error GroupFeatures::unpack(uint8_t *buffer) {
struct of13::ofp_group_features *gf =
(struct of13::ofp_group_features *)buffer;
this->types_ = ntoh32(gf->types);
this->capabilities_ = ntoh32(gf->capabilities);
for (int i = 0; i < 4; i++) {
this->max_groups_[i] = ntoh32(gf->max_groups[i]);
this->actions_[i] = ntoh32(gf->actions[i]);
}
return 0;
}
TableFeatureProp::TableFeatureProp(uint16_t type) {
this->type_ = type;
this->length_ = sizeof(struct of13::ofp_table_feature_prop_header);
this->padding_ =
ROUND_UP(sizeof(struct of13::ofp_table_feature_prop_header), 8) -
sizeof(struct of13::ofp_table_feature_prop_header);
}
bool TableFeatureProp::equals(const TableFeatureProp &other) {
return ((*this == other));
}
bool TableFeatureProp::operator==(const TableFeatureProp &other) const {
return ((this->type_ == other.type_) && (this->length_ == other.length_));
}
bool TableFeatureProp::operator!=(const TableFeatureProp &other) const {
return !(*this == other);
}
size_t TableFeatureProp::pack(uint8_t *buffer) {
struct of13::ofp_table_feature_prop_header *fp =
(struct of13::ofp_table_feature_prop_header *)buffer;
fp->type = hton16(this->type_);
fp->length = hton16(this->length_);
return 0;
}
of_error TableFeatureProp::unpack(uint8_t *buffer) {
struct of13::ofp_table_feature_prop_header *fp =
(struct of13::ofp_table_feature_prop_header *)buffer;
this->type_ = ntoh16(fp->type);
this->length_ = ntoh16(fp->length);
return 0;
}
TableFeaturePropInstruction::TableFeaturePropInstruction(
uint16_t type, std::vector<Instruction> instruction_ids)
: TableFeatureProp(type) {
this->instruction_ids_ = instruction_ids;
this->length_ +=
instruction_ids.size() * sizeof(struct of13::ofp_instruction);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
bool TableFeaturePropInstruction::equals(const TableFeatureProp &other) {
if (const TableFeaturePropInstruction *prop =
dynamic_cast<const TableFeaturePropInstruction *>(&other)) {
return ((TableFeatureProp::equals(other)) &&
(this->instruction_ids_ == prop->instruction_ids_));
} else {
return false;
}
}
size_t TableFeaturePropInstruction::pack(uint8_t *buffer) {
TableFeatureProp::pack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
for (std::vector<Instruction>::iterator it = this->instruction_ids_.begin();
it != this->instruction_ids_.end(); ++it) {
it->pack(p);
p += sizeof(struct of13::ofp_instruction);
}
memset(p, 0x0, this->padding_);
return 0;
}
of_error TableFeaturePropInstruction::unpack(uint8_t *buffer) {
TableFeatureProp::unpack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
size_t len =
this->length_ - sizeof(struct of13::ofp_table_feature_prop_header);
Instruction inst;
while (len) {
inst.unpack(p);
this->instruction_ids_.push_back(inst);
p += sizeof(struct of13::ofp_instruction);
len -= sizeof(struct of13::ofp_instruction);
}
return 0;
}
void TableFeaturePropInstruction::instruction_ids(
std::vector<Instruction> instruction_ids) {
this->instruction_ids_ = instruction_ids;
// Total length with padding
this->length_ +=
instruction_ids.size() * sizeof(struct of13::ofp_instruction);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
TableFeaturePropNextTables::TableFeaturePropNextTables(
uint16_t type, std::vector<uint8_t> next_table_ids)
: TableFeatureProp(type) {
this->next_table_ids_ = next_table_ids_;
this->length_ += next_table_ids_.size();
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
bool TableFeaturePropNextTables::equals(const TableFeatureProp &other) {
if (const TableFeaturePropNextTables *prop =
dynamic_cast<const TableFeaturePropNextTables *>(&other)) {
return ((TableFeatureProp::equals(other)) &&
(this->next_table_ids_ == prop->next_table_ids_));
} else {
return false;
}
}
size_t TableFeaturePropNextTables::pack(uint8_t *buffer) {
TableFeatureProp::pack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
for (std::vector<uint8_t>::iterator it = this->next_table_ids_.begin();
it != this->next_table_ids_.end(); ++it) {
memcpy(p, &(*it), sizeof(uint8_t));
p += sizeof(uint8_t);
}
memset(p, 0x0, this->padding_);
return 0;
}
of_error TableFeaturePropNextTables::unpack(uint8_t *buffer) {
TableFeatureProp::unpack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
size_t len =
this->length_ - sizeof(struct of13::ofp_table_feature_prop_header);
while (len) {
this->next_table_ids_.push_back(*p);
p += sizeof(uint8_t);
len -= sizeof(uint8_t);
}
return 0;
}
void TableFeaturePropNextTables::table_ids(
std::vector<uint8_t> next_table_ids) {
this->next_table_ids_ = next_table_ids;
this->length_ += next_table_ids_.size() * sizeof(uint8_t);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
TableFeaturePropActions::TableFeaturePropActions(uint16_t type,
std::vector<Action> action_ids)
: TableFeatureProp(type) {
this->action_ids_ = action_ids;
this->length_ += action_ids.size() * sizeof(struct ofp_action_header);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
bool TableFeaturePropActions::equals(const TableFeatureProp &other) {
if (const TableFeaturePropActions *prop =
dynamic_cast<const TableFeaturePropActions *>(&other)) {
return ((TableFeatureProp::equals(other)) &&
(this->action_ids_ == prop->action_ids_));
} else {
return false;
}
}
size_t TableFeaturePropActions::pack(uint8_t *buffer) {
TableFeatureProp::pack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
for (std::vector<Action>::iterator it = this->action_ids_.begin();
it != this->action_ids_.end(); ++it) {
it->pack(p);
p += sizeof(struct ofp_action_header);
}
memset(p, 0x0, this->padding_);
return 0;
}
of_error TableFeaturePropActions::unpack(uint8_t *buffer) {
TableFeatureProp::unpack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
size_t len =
this->length_ - sizeof(struct of13::ofp_table_feature_prop_header);
Action act;
while (len) {
act.unpack(p);
this->action_ids_.push_back(act);
p += sizeof(struct ofp_action_header);
len -= sizeof(struct ofp_action_header);
}
return 0;
}
void TableFeaturePropActions::action_ids(std::vector<Action> action_ids) {
this->action_ids_ = action_ids;
this->length_ += action_ids.size() * sizeof(struct ofp_action_header);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
TableFeaturePropOXM::TableFeaturePropOXM(uint16_t type,
std::vector<uint32_t> oxm_ids)
: TableFeatureProp(type) {
this->oxm_ids_ = oxm_ids;
this->length_ += oxm_ids_.size() * sizeof(uint32_t);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
bool TableFeaturePropOXM::equals(const TableFeatureProp &other) {
if (const TableFeaturePropOXM *prop =
dynamic_cast<const TableFeaturePropOXM *>(&other)) {
return ((TableFeatureProp::equals(other)) &&
(this->oxm_ids_ == prop->oxm_ids_));
} else {
return false;
}
}
size_t TableFeaturePropOXM::pack(uint8_t *buffer) {
TableFeatureProp::pack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
for (std::vector<uint32_t>::iterator it = this->oxm_ids_.begin();
it != this->oxm_ids_.end(); ++it) {
memcpy(p, &(*it), sizeof(uint32_t));
p += sizeof(uint32_t);
}
memset(p, 0x0, this->padding_);
return 0;
}
of_error TableFeaturePropOXM::unpack(uint8_t *buffer) {
TableFeatureProp::unpack(buffer);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_feature_prop_header);
size_t len =
this->length_ - sizeof(struct of13::ofp_table_feature_prop_header);
while (len) {
uint32_t *oxm_id = (uint32_t *)p;
this->oxm_ids_.push_back(*oxm_id);
p += sizeof(uint32_t);
len -= sizeof(uint32_t);
}
return 0;
}
void TableFeaturePropOXM::oxm_ids(std::vector<uint32_t> oxm_ids) {
this->oxm_ids_ = oxm_ids;
this->length_ += oxm_ids_.size() * sizeof(uint32_t);
this->padding_ = ROUND_UP(this->length_, 8) - this->length_;
}
TableFeaturePropExperimenter::TableFeaturePropExperimenter(
uint16_t type, uint32_t experimenter, uint32_t exp_type)
: TableFeatureProp(type) {
this->experimenter_ = experimenter;
this->exp_type_ = exp_type;
this->length_ += sizeof(struct of13::ofp_table_feature_prop_experimenter);
}
bool TableFeaturePropExperimenter::equals(const TableFeatureProp &other) {
if (const TableFeaturePropExperimenter *prop =
dynamic_cast<const TableFeaturePropExperimenter *>(&other)) {
return ((TableFeatureProp::equals(other)) &&
(this->experimenter_ == prop->experimenter_) &&
(this->exp_type_ == prop->exp_type_));
} else {
return false;
}
}
size_t TableFeaturePropExperimenter::pack(uint8_t *buffer) {
struct of13::ofp_table_feature_prop_experimenter *pe =
(struct of13::ofp_table_feature_prop_experimenter *)buffer;
TableFeatureProp::pack(buffer);
pe->experimenter = hton32(this->experimenter_);
pe->exp_type = hton32(this->exp_type_);
return 0;
}
of_error TableFeaturePropExperimenter::unpack(uint8_t *buffer) {
struct of13::ofp_table_feature_prop_experimenter *pe =
(struct of13::ofp_table_feature_prop_experimenter *)buffer;
TableFeatureProp::unpack(buffer);
this->experimenter_ = ntoh32(pe->experimenter);
this->exp_type_ = ntoh32(pe->exp_type);
return 0;
}
TablePropertiesList::TablePropertiesList(
std::list<TableFeatureProp *> property_list) {
this->property_list_ = property_list_;
for (std::list<TableFeatureProp *>::const_iterator it = property_list.begin();
it != property_list.end(); ++it) {
this->length_ += (*it)->length();
}
}
TablePropertiesList::TablePropertiesList(const TablePropertiesList &other) {
this->length_ = other.length_;
for (std::list<TableFeatureProp *>::const_iterator it =
other.property_list_.begin();
it != other.property_list_.end(); ++it) {
this->property_list_.push_back((*it)->clone());
}
}
TablePropertiesList::~TablePropertiesList() {
this->property_list_.remove_if(TableFeatureProp::delete_all);
}
bool TablePropertiesList::operator==(const TablePropertiesList &other) const {
std::list<TableFeatureProp *>::const_iterator ot =
other.property_list_.begin();
for (std::list<TableFeatureProp *>::const_iterator it =
this->property_list_.begin();
it != this->property_list_.end(); ++it, ++ot) {
if (!((*it)->equals(**ot))) {
return false;
}
}
return true;
}
bool TablePropertiesList::operator!=(const TablePropertiesList &other) const {
return !(*this == other);
}
size_t TablePropertiesList::pack(uint8_t *buffer) {
uint8_t *p = buffer;
for (std::list<TableFeatureProp *>::iterator
it = this->property_list_.begin(),
end = this->property_list_.end();
it != end; it++) {
(*it)->pack(p);
p += (*it)->length() + (*it)->padding();
}
return 0;
}
of_error TablePropertiesList::unpack(uint8_t *buffer) {
uint8_t *p = buffer;
size_t len = this->length_;
TableFeatureProp *prop;
while (len) {
uint16_t type = ntoh16(*((uint16_t *)p));
prop = TableFeatures::make_table_feature_prop(type);
prop->unpack(p);
this->property_list_.push_back(prop);
len -= prop->length() + prop->padding();
p += prop->length() + prop->padding();
}
return 0;
}
TablePropertiesList &TablePropertiesList::operator=(TablePropertiesList other) {
swap(*this, other);
return *this;
}
void swap(TablePropertiesList &first, TablePropertiesList &second) {
std::swap(first.length_, second.length_);
std::swap(first.property_list_, second.property_list_);
}
void TablePropertiesList::property_list(
std::list<TableFeatureProp *> property_list) {
this->property_list_ = property_list;
for (std::list<TableFeatureProp *>::const_iterator it = property_list.begin();
it != property_list.end(); ++it) {
this->length_ += (*it)->length() + (*it)->padding();
}
}
void TablePropertiesList::add_property(TableFeatureProp *prop) {
this->property_list_.push_back(prop);
this->length_ = prop->length() + prop->padding();
}
TableFeatures::TableFeatures(uint8_t table_id, std::string name,
uint64_t metadata_match, uint64_t metadata_write,
uint32_t config, uint32_t max_entries)
: table_id_(table_id),
name_(name),
metadata_match_(metadata_match),
metadata_write_(metadata_write),
config_(config),
max_entries_(max_entries) {
this->length_ = sizeof(struct of13::ofp_table_features);
}
bool TableFeatures::operator==(const TableFeatures &other) const {
return ((this->length_ == other.length_) &&
(this->table_id_ == other.table_id_) &&
(this->name_ == other.name_) &&
(this->metadata_match_ == other.metadata_match_) &&
(this->metadata_write_ == other.metadata_write_) &&
(this->config_ == other.config_) &&
(this->max_entries_ == other.max_entries_) &&
(this->properties_ == other.properties_));
}
bool TableFeatures::operator!=(const TableFeatures &other) const {
return !(*this == other);
}
uint16_t TableFeatures::length() {
// Return padded len
return ROUND_UP(this->length_, 8);
}
size_t TableFeatures::pack(uint8_t *buffer) {
struct of13::ofp_table_features *tf =
(struct of13::ofp_table_features *)buffer;
tf->length = hton16(length());
tf->table_id = this->table_id_;
memset(tf->pad, 0x0, 5);
memset(tf->name, 0x0, OFP_MAX_TABLE_NAME_LEN);
memcpy(tf->name, this->name_.c_str(),
this->name_.size() < OFP_MAX_TABLE_NAME_LEN ? this->name_.size()
: OFP_MAX_TABLE_NAME_LEN);
tf->metadata_match = hton64(this->metadata_match_);
tf->metadata_write = hton64(this->metadata_write_);
tf->config = hton32(this->config_);
tf->max_entries = hton32(this->max_entries_);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_features);
this->properties_.pack(p);
return length();
}
of_error TableFeatures::unpack(uint8_t *buffer) {
struct of13::ofp_table_features *tf =
(struct of13::ofp_table_features *)buffer;
this->length_ = ntoh16(tf->length);
this->table_id_ = tf->table_id;
this->name_ = std::string(tf->name);
this->metadata_match_ = ntoh64(tf->metadata_match);
this->metadata_write_ = ntoh64(tf->metadata_write);
this->config_ = ntoh32(tf->config);
this->max_entries_ = ntoh32(tf->max_entries);
uint8_t *p = buffer + sizeof(struct of13::ofp_table_features);
this->properties_.length(this->length_ -
sizeof(struct of13::ofp_table_features));
this->properties_.unpack(p);
return 0;
}
void TableFeatures::properties(TablePropertiesList properties) {
this->properties_ = properties;
this->length_ += properties.length();
}
void TableFeatures::add_table_prop(TableFeatureProp *prop) {
this->properties_.add_property(prop);
this->length_ += prop->length() + prop->padding();
}
TableFeatureProp *TableFeatures::make_table_feature_prop(uint16_t type) {
if (type == OFPTFPT_INSTRUCTIONS || type == OFPTFPT_INSTRUCTIONS_MISS) {
return new TableFeaturePropInstruction(type);
}
if (type == OFPTFPT_NEXT_TABLES || type == OFPTFPT_NEXT_TABLES_MISS) {
return new TableFeaturePropNextTables(type);
}
if (type == OFPTFPT_WRITE_ACTIONS || type == OFPTFPT_WRITE_ACTIONS_MISS ||
type == OFPTFPT_APPLY_ACTIONS || type == OFPTFPT_APPLY_ACTIONS_MISS) {
return new TableFeaturePropActions(type);
}
if (type == OFPTFPT_MATCH || type == OFPTFPT_WILDCARDS ||
type == OFPTFPT_WRITE_SETFIELD || type == OFPTFPT_WRITE_SETFIELD_MISS ||
type == OFPTFPT_APPLY_SETFIELD || type == OFPTFPT_APPLY_SETFIELD_MISS) {
return new TableFeaturePropOXM(type);
}
if (type == OFPTFPT_EXPERIMENTER || type == OFPTFPT_EXPERIMENTER_MISS) {
return new TableFeaturePropExperimenter(type);
}
return NULL;
}
} // namespace of13
QueueProperty *QueueProperty::make_queue_of13_property(uint16_t property) {
switch (property) {
case (of13::OFPQT_MAX_RATE): {
return new of13::QueuePropMaxRate();
}
case (of13::OFPQT_MIN_RATE): {
return new of13::QueuePropMinRate();
}
case (of13::OFPQT_EXPERIMENTER): {
return new of13::QueueExperimenter();
}
}
return NULL;
}
} // namespace fluid_msg
| 34.039413 | 80 | 0.688333 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.