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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4b508b4616dd10fa91825d125d5db6632cfa6cee | 520 | cpp | C++ | code/container-with-most-water.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | 4 | 2018-04-09T12:57:46.000Z | 2019-07-30T00:25:40.000Z | java/code/container-with-most-water.cpp | sunchenglong/algorithm-essentials | 1b6d360e4993b14db221b0d97b238df49c792446 | [
"CC0-1.0"
] | null | null | null | java/code/container-with-most-water.cpp | sunchenglong/algorithm-essentials | 1b6d360e4993b14db221b0d97b238df49c792446 | [
"CC0-1.0"
] | 3 | 2018-11-19T03:11:15.000Z | 2021-07-28T11:48:30.000Z | // Container With Most Water
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int maxArea(vector<int> &height) {
int start = 0;
int end = height.size() - 1;
int result = INT_MIN;
while (start < end) {
int area = min(height[end], height[start]) * (end - start);
result = max(result, area);
if (height[start] <= height[end]) {
start++;
} else {
end--;
}
}
return result;
}
}; | 26 | 71 | 0.457692 | [
"vector"
] |
4b50f5302a342a33dc6b3425089b16b68b40b560 | 10,073 | cpp | C++ | core/fpdfapi/page/cpdf_textobject.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | null | null | null | core/fpdfapi/page/cpdf_textobject.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | null | null | null | core/fpdfapi/page/cpdf_textobject.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/page/cpdf_textobject.h"
#include <algorithm>
#include <utility>
#include "core/fpdfapi/font/cpdf_cidfont.h"
#include "core/fpdfapi/font/cpdf_font.h"
#include "third_party/base/check.h"
#define ISLATINWORD(u) (u != 0x20 && u <= 0x28FF)
CPDF_TextObject::Item::Item() = default;
CPDF_TextObject::Item::Item(const Item& that) = default;
CPDF_TextObject::Item::~Item() = default;
CPDF_TextObject::CPDF_TextObject(int32_t content_stream)
: CPDF_PageObject(content_stream) {}
CPDF_TextObject::CPDF_TextObject() : CPDF_TextObject(kNoContentStream) {}
CPDF_TextObject::~CPDF_TextObject() {
// Move m_CharCodes to a local variable so it will be captured in crash dumps,
// to help with investigating crbug.com/782215.
auto char_codes_copy = std::move(m_CharCodes);
}
size_t CPDF_TextObject::CountItems() const {
return m_CharCodes.size();
}
CPDF_TextObject::Item CPDF_TextObject::GetItemInfo(size_t index) const {
DCHECK(index < m_CharCodes.size());
Item info;
info.m_CharCode = m_CharCodes[index];
info.m_Origin = CFX_PointF(index > 0 ? m_CharPos[index - 1] : 0, 0);
if (info.m_CharCode == CPDF_Font::kInvalidCharCode)
return info;
RetainPtr<CPDF_Font> pFont = GetFont();
if (!pFont->IsCIDFont() || !pFont->AsCIDFont()->IsVertWriting())
return info;
uint16_t cid = pFont->AsCIDFont()->CIDFromCharCode(info.m_CharCode);
info.m_Origin = CFX_PointF(0, info.m_Origin.x);
CFX_Point16 vertical_origin = pFont->AsCIDFont()->GetVertOrigin(cid);
float fontsize = GetFontSize();
info.m_Origin.x -= fontsize * vertical_origin.x / 1000;
info.m_Origin.y -= fontsize * vertical_origin.y / 1000;
return info;
}
size_t CPDF_TextObject::CountChars() const {
size_t count = 0;
for (uint32_t charcode : m_CharCodes) {
if (charcode != CPDF_Font::kInvalidCharCode)
++count;
}
return count;
}
uint32_t CPDF_TextObject::GetCharCode(size_t index) const {
size_t count = 0;
for (uint32_t code : m_CharCodes) {
if (code == CPDF_Font::kInvalidCharCode)
continue;
if (count++ != index)
continue;
return code;
}
return CPDF_Font::kInvalidCharCode;
}
CPDF_TextObject::Item CPDF_TextObject::GetCharInfo(size_t index) const {
size_t count = 0;
for (size_t i = 0; i < m_CharCodes.size(); ++i) {
uint32_t charcode = m_CharCodes[i];
if (charcode == CPDF_Font::kInvalidCharCode)
continue;
if (count++ == index)
return GetItemInfo(i);
}
return Item();
}
int CPDF_TextObject::CountWords() const {
RetainPtr<CPDF_Font> pFont = GetFont();
bool bInLatinWord = false;
int nWords = 0;
for (size_t i = 0, sz = CountChars(); i < sz; ++i) {
uint32_t charcode = GetCharCode(i);
WideString swUnicode = pFont->UnicodeFromCharCode(charcode);
uint16_t unicode = 0;
if (swUnicode.GetLength() > 0)
unicode = swUnicode[0];
bool bIsLatin = ISLATINWORD(unicode);
if (bIsLatin && bInLatinWord)
continue;
bInLatinWord = bIsLatin;
if (unicode != 0x20)
nWords++;
}
return nWords;
}
WideString CPDF_TextObject::GetWordString(int nWordIndex) const {
RetainPtr<CPDF_Font> pFont = GetFont();
WideString swRet;
int nWords = 0;
bool bInLatinWord = false;
for (size_t i = 0, sz = CountChars(); i < sz; ++i) {
uint32_t charcode = GetCharCode(i);
WideString swUnicode = pFont->UnicodeFromCharCode(charcode);
uint16_t unicode = 0;
if (swUnicode.GetLength() > 0)
unicode = swUnicode[0];
bool bIsLatin = ISLATINWORD(unicode);
if (!bIsLatin || !bInLatinWord) {
bInLatinWord = bIsLatin;
if (unicode != 0x20)
nWords++;
}
if (nWords - 1 == nWordIndex)
swRet += unicode;
}
return swRet;
}
std::unique_ptr<CPDF_TextObject> CPDF_TextObject::Clone() const {
auto obj = std::make_unique<CPDF_TextObject>();
obj->CopyData(this);
obj->m_CharCodes = m_CharCodes;
obj->m_CharPos = m_CharPos;
obj->m_Pos = m_Pos;
return obj;
}
CPDF_PageObject::Type CPDF_TextObject::GetType() const {
return TEXT;
}
void CPDF_TextObject::Transform(const CFX_Matrix& matrix) {
SetTextMatrix(GetTextMatrix() * matrix);
SetDirty(true);
}
bool CPDF_TextObject::IsText() const {
return true;
}
CPDF_TextObject* CPDF_TextObject::AsText() {
return this;
}
const CPDF_TextObject* CPDF_TextObject::AsText() const {
return this;
}
CFX_Matrix CPDF_TextObject::GetTextMatrix() const {
const float* pTextMatrix = m_TextState.GetMatrix();
return CFX_Matrix(pTextMatrix[0], pTextMatrix[2], pTextMatrix[1],
pTextMatrix[3], m_Pos.x, m_Pos.y);
}
void CPDF_TextObject::SetTextMatrix(const CFX_Matrix& matrix) {
float* pTextMatrix = m_TextState.GetMutableMatrix();
pTextMatrix[0] = matrix.a;
pTextMatrix[1] = matrix.c;
pTextMatrix[2] = matrix.b;
pTextMatrix[3] = matrix.d;
m_Pos = CFX_PointF(matrix.e, matrix.f);
CalcPositionData(0);
}
void CPDF_TextObject::SetSegments(const ByteString* pStrs,
const std::vector<float>& kernings,
size_t nSegs) {
m_CharCodes.clear();
m_CharPos.clear();
RetainPtr<CPDF_Font> pFont = GetFont();
int nChars = 0;
for (size_t i = 0; i < nSegs; ++i)
nChars += pFont->CountChar(pStrs[i].AsStringView());
nChars += nSegs - 1;
m_CharCodes.resize(nChars);
m_CharPos.resize(nChars - 1);
size_t index = 0;
for (size_t i = 0; i < nSegs; ++i) {
ByteStringView segment = pStrs[i].AsStringView();
size_t offset = 0;
while (offset < segment.GetLength()) {
DCHECK(index < m_CharCodes.size());
m_CharCodes[index++] = pFont->GetNextChar(segment, &offset);
}
if (i != nSegs - 1) {
m_CharPos[index - 1] = kernings[i];
m_CharCodes[index++] = CPDF_Font::kInvalidCharCode;
}
}
}
void CPDF_TextObject::SetText(const ByteString& str) {
SetSegments(&str, std::vector<float>(), 1);
CalcPositionData(/*horz_scale=*/1.0f);
SetDirty(true);
}
float CPDF_TextObject::GetCharWidth(uint32_t charcode) const {
float fontsize = GetFontSize() / 1000;
RetainPtr<CPDF_Font> pFont = GetFont();
bool bVertWriting = false;
CPDF_CIDFont* pCIDFont = pFont->AsCIDFont();
if (pCIDFont)
bVertWriting = pCIDFont->IsVertWriting();
if (!bVertWriting)
return pFont->GetCharWidthF(charcode) * fontsize;
uint16_t cid = pCIDFont->CIDFromCharCode(charcode);
return pCIDFont->GetVertWidth(cid) * fontsize;
}
RetainPtr<CPDF_Font> CPDF_TextObject::GetFont() const {
return m_TextState.GetFont();
}
float CPDF_TextObject::GetFontSize() const {
return m_TextState.GetFontSize();
}
TextRenderingMode CPDF_TextObject::GetTextRenderMode() const {
return m_TextState.GetTextMode();
}
void CPDF_TextObject::SetTextRenderMode(TextRenderingMode mode) {
m_TextState.SetTextMode(mode);
SetDirty(true);
}
CFX_PointF CPDF_TextObject::CalcPositionData(float horz_scale) {
float curpos = 0;
float min_x = 10000 * 1.0f;
float max_x = -10000 * 1.0f;
float min_y = 10000 * 1.0f;
float max_y = -10000 * 1.0f;
RetainPtr<CPDF_Font> pFont = GetFont();
bool bVertWriting = false;
CPDF_CIDFont* pCIDFont = pFont->AsCIDFont();
if (pCIDFont)
bVertWriting = pCIDFont->IsVertWriting();
float fontsize = GetFontSize();
for (size_t i = 0; i < m_CharCodes.size(); ++i) {
uint32_t charcode = m_CharCodes[i];
if (i > 0) {
if (charcode == CPDF_Font::kInvalidCharCode) {
curpos -= (m_CharPos[i - 1] * fontsize) / 1000;
continue;
}
m_CharPos[i - 1] = curpos;
}
FX_RECT char_rect = pFont->GetCharBBox(charcode);
float charwidth;
if (!bVertWriting) {
min_y = std::min(
min_y, static_cast<float>(std::min(char_rect.top, char_rect.bottom)));
max_y = std::max(
max_y, static_cast<float>(std::max(char_rect.top, char_rect.bottom)));
float char_left = curpos + char_rect.left * fontsize / 1000;
float char_right = curpos + char_rect.right * fontsize / 1000;
min_x = std::min(min_x, std::min(char_left, char_right));
max_x = std::max(max_x, std::max(char_left, char_right));
charwidth = pFont->GetCharWidthF(charcode) * fontsize / 1000;
} else {
uint16_t cid = pCIDFont->CIDFromCharCode(charcode);
CFX_Point16 vertical_origin = pCIDFont->GetVertOrigin(cid);
char_rect.left -= vertical_origin.x;
char_rect.right -= vertical_origin.x;
char_rect.top -= vertical_origin.y;
char_rect.bottom -= vertical_origin.y;
min_x = std::min(
min_x, static_cast<float>(std::min(char_rect.left, char_rect.right)));
max_x = std::max(
max_x, static_cast<float>(std::max(char_rect.left, char_rect.right)));
float char_top = curpos + char_rect.top * fontsize / 1000;
float char_bottom = curpos + char_rect.bottom * fontsize / 1000;
min_y = std::min(min_y, std::min(char_top, char_bottom));
max_y = std::max(max_y, std::max(char_top, char_bottom));
charwidth = pCIDFont->GetVertWidth(cid) * fontsize / 1000;
}
curpos += charwidth;
if (charcode == ' ' && (!pCIDFont || pCIDFont->GetCharSize(' ') == 1))
curpos += m_TextState.GetWordSpace();
curpos += m_TextState.GetCharSpace();
}
CFX_PointF ret;
if (bVertWriting) {
ret.y = curpos;
min_x = min_x * fontsize / 1000;
max_x = max_x * fontsize / 1000;
} else {
ret.x = curpos * horz_scale;
min_y = min_y * fontsize / 1000;
max_y = max_y * fontsize / 1000;
}
SetRect(
GetTextMatrix().TransformRect(CFX_FloatRect(min_x, min_y, max_x, max_y)));
if (!TextRenderingModeIsStrokeMode(m_TextState.GetTextMode()))
return ret;
float half_width = m_GraphState.GetLineWidth() / 2;
m_Rect.left -= half_width;
m_Rect.right += half_width;
m_Rect.top += half_width;
m_Rect.bottom -= half_width;
return ret;
}
| 29.890208 | 80 | 0.675171 | [
"vector",
"transform"
] |
4b517079e2b08ca82aa57ff0e26787593ef13653 | 27,585 | cc | C++ | tensorflow/core/data/hash_utils.cc | ashutom/tensorflow-upstream | c16069c19de9e286dd664abb78d0ea421e9f32d4 | [
"Apache-2.0"
] | 10 | 2021-05-25T17:43:04.000Z | 2022-03-08T10:46:09.000Z | tensorflow/core/data/hash_utils.cc | CaptainGizzy21/tensorflow | 3457a2b122e50b4d44ceaaed5a663d635e5c22df | [
"Apache-2.0"
] | 1,056 | 2019-12-15T01:20:31.000Z | 2022-02-10T02:06:28.000Z | tensorflow/core/data/hash_utils.cc | CaptainGizzy21/tensorflow | 3457a2b122e50b4d44ceaaed5a663d635e5c22df | [
"Apache-2.0"
] | 6 | 2016-09-07T04:00:15.000Z | 2022-01-12T01:47:38.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/data/hash_utils.h"
#include <queue>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_def_builder.h"
#include "tensorflow/core/framework/op_def_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/lib/strings/proto_serialization.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/regexp.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/util/work_sharder.h"
namespace tensorflow {
namespace data {
namespace {
// clang-format off
constexpr std::array<const char*, 3> kOpsWithSeed = {
"AnonymousRandomSeedGenerator",
"ShuffleDataset",
"ShuffleAndRepeatDataset"
};
// clang-format on
constexpr char kSeedInputName[] = "seed";
constexpr char kSeed2InputName[] = "seed2";
constexpr char kSeedGeneratorInputName[] = "seed_generator";
template <std::size_t SIZE>
bool IsNodeOfType(const NodeDef& node,
const std::array<const char*, SIZE>& op_types) {
for (const auto& type : op_types) {
if (MatchesAnyVersion(type, node.op())) {
return true;
}
}
return false;
}
Status FindNode(const GraphDef& graph, const string& name,
const NodeDef** result) {
for (const auto& node : graph.node()) {
if (node.name() == name) {
*result = &node;
return Status::OK();
}
}
return errors::NotFound("Could not find node ", name, ".");
}
Status GetSink(const GraphDef& graph_def, const NodeDef** sink) {
for (auto& node : graph_def.node()) {
if (node.op() == "_Retval") {
*sink = &node;
break;
}
}
if (sink == nullptr) {
return errors::Internal("Cannot find sink node for dataset graph.");
}
return Status::OK();
}
Status ShouldIgnoreInput(const NodeDef& node, int i, bool* result) {
*result = false;
if (IsNodeOfType(node, kOpsWithSeed)) {
const OpRegistrationData* reg;
auto status = OpRegistry::Global()->LookUp(node.op(), ®);
if (status.ok()) {
if (reg->op_def.input_arg_size() > i) {
const std::string input_arg_name = reg->op_def.input_arg(i).name();
if (input_arg_name == kSeedInputName ||
input_arg_name == kSeed2InputName ||
input_arg_name == kSeedGeneratorInputName) {
VLOG(2) << "Ignoring arg: " << input_arg_name
<< " from node: " << node.name();
*result = true;
return Status::OK();
}
}
} else if (errors::IsNotFound(status)) {
LOG(WARNING) << "Cannot find " << node.op()
<< " in global op registry, so cannot determine which "
"inputs are seeds.";
} else {
return status;
}
}
return Status::OK();
}
Status ParseInputNodeName(const std::string& input_name, std::string* node_name,
std::string* suffix, bool* is_control_input) {
if (input_name[0] == '^') {
*node_name = input_name.substr(1);
*is_control_input = true;
return Status::OK();
}
std::pair<std::string, std::string> node_spec =
absl::StrSplit(input_name, absl::MaxSplits(':', 1));
*node_name = node_spec.first;
*suffix = node_spec.second;
*is_control_input = false;
return Status::OK();
}
// Given a graph_def and a root_node, this class computes a fingerprint that
// tries to capture the structure of the graph rooted at the provided node.
// It does not at any point rely on the names of the nodes in the graph and
// just relies on the connections between different nodes. In the presence of
// multiple cycles in the graph, there is a non-zero possibility that two
// graphs with different structure might end up with the same fingerprint
// as in order to break cycles we prune away some edges (in a deterministic
// fashion though). Idea for this algorithm was borrowed from:
// https://stackoverflow.com/questions/11338746/directed-graphs-with-a-given-root-node-match-another-directed-graph-for-equali
class GraphHasher {
public:
// `GraphHasher` does not take ownership of `graph_def`, `root_node`, or
// `flib_def`.
explicit GraphHasher(const GraphDef* graph, const NodeDef* root,
const FunctionLibraryDefinition* flib)
: graph_(graph), root_(root), flib_(flib) {}
Status Init() {
// Pre-process the graph to do a BFS and prune away cycles that might cause
// problems.
absl::flat_hash_set<std::string> visited;
std::queue<const NodeDef*> bfs_queue;
bfs_queue.push(root_);
while (!bfs_queue.empty()) {
const NodeDef* node = bfs_queue.front();
bfs_queue.pop();
if (visited.contains(node->name())) {
continue;
}
visited.insert(node->name());
NodeRep node_rep;
for (int i = 0; i < node->input_size(); ++i) {
DCHECK_GT(node->input(i).length(), 0);
// We skip trying to take the hash of the seeds of any ops, as they
// are irrelevant to the hash of the graph and may vary from run to run.
bool should_ignore_input = false;
TF_RETURN_IF_ERROR(ShouldIgnoreInput(*node, i, &should_ignore_input));
if (should_ignore_input) continue;
std::string node_name, suffix;
bool is_control_input;
TF_RETURN_IF_ERROR(ParseInputNodeName(node->input(i), &node_name,
&suffix, &is_control_input));
const NodeDef* input_node;
TF_RETURN_IF_ERROR(FindNode(*graph_, node_name, &input_node));
// If we've already seen this node before, skip it and don't add it to
// the queue.
if (visited.find(node_name) != visited.end()) {
EdgeRep cycle_edge(node, input_node);
cycle_forming_edges_.insert(cycle_edge.GetHash());
continue;
}
if (is_control_input) {
node_rep.node_control_inputs.push_back(input_node);
} else {
node_rep.node_inputs.push_back(std::make_pair(input_node, suffix));
bfs_queue.push(input_node);
}
}
nodes_[node] = node_rep;
}
return Status::OK();
}
Status HashRoot(uint64* hash) { return HashNode(root_, hash); }
Status CheckEqual(GraphHasher* that) {
return CheckNodesEqual(root_, that, that->root_);
}
private:
Status HashNode(const NodeDef* node, uint64* hash) {
auto it = cache_.find(node);
if (it != cache_.end()) {
*hash = it->second;
return Status::OK();
}
NodeRep* node_rep = gtl::FindOrNull(nodes_, node);
if (node_rep == nullptr) {
return errors::InvalidArgument("Could not find node: ", node->name());
}
uint64 non_input_hash;
TF_RETURN_IF_ERROR(
HashNodeNonInput(node, /*hash_functions=*/true, &non_input_hash));
uint64 control_inputs_hash;
TF_RETURN_IF_ERROR(
HashControlInputs(node_rep->node_control_inputs, &control_inputs_hash));
// Hash regular inputs. We combine them in an ordered fashion.
uint64 inputs_hash = 0;
for (const auto& input : node_rep->node_inputs) {
uint64 node_hash = 0;
EdgeRep edge(node, input.first);
// If the edge was pruned we get the non input node hash to avoid cycles.
if (cycle_forming_edges_.find(edge.GetHash()) !=
cycle_forming_edges_.end()) {
TF_RETURN_IF_ERROR(
HashNodeNonInput(input.first, /*hash_functions=*/true, &node_hash));
} else {
TF_RETURN_IF_ERROR(HashNode(input.first, &node_hash));
}
inputs_hash = Hash64Combine(
inputs_hash, Hash64Combine(node_hash, Hash64(input.second)));
}
*hash = Hash64Combine(non_input_hash,
Hash64Combine(control_inputs_hash, inputs_hash));
cache_[node] = *hash;
return Status::OK();
}
Status CheckNodesEqual(const NodeDef* this_node, GraphHasher* that,
const NodeDef* that_node) {
Status s = CheckNodesEqualHelper(this_node, that, that_node);
if (!s.ok()) {
return errors::FailedPrecondition("Nodes ", this_node->name(), " and ",
that_node->name(),
" are not the same:\n", s);
}
return s;
}
Status CheckNodesEqualHelper(const NodeDef* this_node, GraphHasher* that,
const NodeDef* that_node) {
TF_RETURN_IF_ERROR(CheckNodesEqualNonInput(this_node, that, that_node,
/*compare_functions=*/true));
TF_RETURN_IF_ERROR(
CheckControlInputsEqual(nodes_[this_node].node_control_inputs, that,
that->nodes_[that_node].node_control_inputs));
auto& this_node_inputs = nodes_[this_node].node_inputs;
auto& that_node_inputs = that->nodes_[that_node].node_inputs;
if (this_node_inputs.size() != that_node_inputs.size()) {
return errors::FailedPrecondition(
"Nodes have different numbers of node inputs: ",
this_node_inputs.size(), " vs ", that_node_inputs.size());
}
for (int i = 0; i < this_node_inputs.size(); ++i) {
const NodeDef* this_input = this_node_inputs[i].first;
const NodeDef* that_input = that_node_inputs[i].first;
if (is_cycle_forming_edge(this_node, this_input)) {
TF_RETURN_IF_ERROR(CheckNodesEqualNonInput(this_input, that, that_input,
/*compare_functions=*/true));
} else {
TF_RETURN_IF_ERROR(CheckNodesEqual(this_input, that, that_input));
}
std::string this_input_suffix = this_node_inputs[i].second;
std::string that_input_suffix = that_node_inputs[i].second;
if (this_input_suffix != that_input_suffix) {
return errors::FailedPrecondition(
"Node inputs ", this_input->name(), " and ", that_input->name(),
" have different suffixes: ", this_input_suffix, " vs ",
that_input_suffix);
}
}
return Status::OK();
}
Status HashNodeNonInput(const NodeDef* node, bool hash_functions,
uint64* hash) {
// Hash Attrs. We get the list of attrs from the op registry and then look
// up their values in the NodeDef attr map. This avoids looping over
// a map which is non-deterministic.
uint64 attrs_hash = 0;
const OpRegistrationData* reg;
TF_RETURN_IF_ERROR(flib_->LookUp(node->op(), ®));
uint64 op_hash = 0;
if (reg->is_function_op) {
if (hash_functions) {
TF_RETURN_IF_ERROR(HashFunction(node->op(), node->attr(), &op_hash));
}
} else {
op_hash = Hash64(node->op());
}
for (const auto& attr : reg->op_def.attr()) {
const auto& attr_key = attr.name();
if (!node->attr().contains(attr_key)) continue;
auto attr_value = node->attr().at(attr_key);
if (attr_key == kColocationAttrName ||
attr_key == kColocationGroupPrefix) {
continue;
}
uint64 attr_hash = 0;
TF_RETURN_IF_ERROR(
HashAttr(attr_key, attr_value, hash_functions, &attr_hash));
attrs_hash = Hash64Combine(attrs_hash, attr_hash);
}
// Hash Device.
uint64 device_hash = Hash64(node->device());
*hash = Hash64Combine(op_hash, Hash64Combine(attrs_hash, device_hash));
return Status::OK();
}
Status CheckNodesEqualNonInput(const NodeDef* this_node, GraphHasher* that,
const NodeDef* that_node,
bool compare_functions) {
// We get the list of attrs from the op registry and then look
// up their values in the NodeDef attr map. This avoids looping over
// a map which is non-deterministic.
const OpRegistrationData* reg;
TF_RETURN_IF_ERROR(flib_->LookUp(this_node->op(), ®));
if (reg->is_function_op) {
if (compare_functions) {
TF_RETURN_IF_ERROR(
CheckFunctionsEqual(this_node->op(), this_node->attr(), that,
that_node->op(), that_node->attr()));
}
} else {
if (this_node->op() != that_node->op()) {
return errors::FailedPrecondition(
"ops for nodes ", this_node->name(), " and ", that_node->name(),
" are different: ", this_node->op(), " != ", that_node->op());
}
}
for (const auto& attr : reg->op_def.attr()) {
const auto& attr_key = attr.name();
if (this_node->attr().contains(attr_key) !=
that_node->attr().contains(attr_key)) {
return errors::FailedPrecondition(
"attr with key ", attr_key, " is different for nodes ",
this_node->name(), " and ", that_node->name(),
". Present in former: ", this_node->attr().contains(attr_key),
". Present in latter: ", that_node->attr().contains(attr_key));
}
if (!this_node->attr().contains(attr_key)) continue;
if (attr_key == kColocationAttrName ||
attr_key == kColocationGroupPrefix) {
continue;
}
auto this_attr = this_node->attr().at(attr_key);
auto that_attr = that_node->attr().at(attr_key);
TF_RETURN_IF_ERROR(CheckAttrsEqual(attr_key, this_attr, that, that_attr,
compare_functions));
}
if (this_node->device() != that_node->device()) {
return errors::FailedPrecondition(
"Devices are different for nodes ", this_node->name(), " and ",
that_node->name(), ": ", this_node->device(), " vs ",
that_node->device());
}
return Status::OK();
}
Status HashAttr(const std::string& attr_name, const AttrValue& attr_value,
bool hash_functions, uint64* hash) {
uint64 value_hash = 0;
if (attr_value.has_func()) {
if (hash_functions) {
TF_RETURN_IF_ERROR(HashFunction(attr_value.func(), &value_hash));
}
} else if (attr_value.has_list() && attr_value.list().func_size() > 0) {
if (hash_functions) {
for (auto& func : attr_value.list().func()) {
uint64 func_hash;
TF_RETURN_IF_ERROR(HashFunction(func, &func_hash));
value_hash = Hash64Combine(value_hash, func_hash);
}
}
} else {
value_hash = DeterministicProtoHash64(attr_value);
}
*hash = Hash64(absl::StrCat(attr_name, "=", value_hash));
return Status::OK();
}
Status CheckAttrsEqual(const std::string& attr_name,
const AttrValue& this_attr, GraphHasher* that,
const AttrValue& that_attr, bool compare_functions) {
if (this_attr.has_func() != that_attr.has_func()) {
return errors::FailedPrecondition(
"AttrValues are of different types: ", this_attr.DebugString(),
" vs ", that_attr.DebugString());
}
if (this_attr.has_func()) {
if (compare_functions) {
TF_RETURN_IF_ERROR(
CheckFunctionsEqual(this_attr.func(), that, that_attr.func()));
}
return Status::OK();
}
if (this_attr.has_list() != that_attr.has_list()) {
return errors::FailedPrecondition(
"AttrValues are of different types: ", this_attr.DebugString(),
" vs ", that_attr.DebugString());
}
if (this_attr.has_list()) {
if (this_attr.list().func_size() != that_attr.list().func_size()) {
return errors::FailedPrecondition(
"AttrValues have func lists of different sizes: ",
this_attr.DebugString(), " vs ", that_attr.DebugString());
}
if (compare_functions) {
for (int i = 0; i < this_attr.list().func_size(); ++i) {
TF_RETURN_IF_ERROR(CheckFunctionsEqual(this_attr.list().func(i), that,
that_attr.list().func(i)));
}
}
return Status::OK();
}
uint64 this_hash, that_hash;
TF_RETURN_IF_ERROR(
HashAttr(attr_name, this_attr, /*hash_functions=*/true, &this_hash));
TF_RETURN_IF_ERROR(that->HashAttr(attr_name, that_attr,
/*hash_functions=*/true, &that_hash));
if (this_hash != that_hash) {
return errors::FailedPrecondition(
"AttrValues are different: ", this_attr.DebugString(), " vs ",
that_attr.DebugString());
}
return Status::OK();
}
Status HashFunction(const NameAttrList& func, uint64* hash) {
return HashFunction(func.name(), func.attr(), hash);
}
Status HashFunction(const std::string& name, const AttrValueMap& attrs,
uint64* hash) {
const FunctionDef* fdef = flib_->Find(name);
// Convert to a GraphDef.
std::unique_ptr<FunctionBody> fbody;
TF_RETURN_IF_ERROR(
FunctionDefToBodyHelper(*fdef, AttrSlice(&attrs), flib_, &fbody));
GraphDef graph_def = fbody->graph->ToGraphDefDebug();
// For each return node, we create a new GraphHasher to compute a hash.
// We then combine these hashes to produce the hash ordered.
uint64 ret_nodes_hash = 0;
for (const auto& ret_node : fbody->ret_nodes) {
uint64 ret_node_hash = 0;
GraphHasher hasher(&graph_def, &ret_node->def(), flib_);
TF_RETURN_IF_ERROR(hasher.Init());
TF_RETURN_IF_ERROR(hasher.HashRoot(&ret_node_hash));
ret_nodes_hash = Hash64Combine(ret_nodes_hash, ret_node_hash);
}
std::vector<const NodeDef*> control_rets;
for (const auto& control_ret_node : fbody->control_ret_nodes) {
control_rets.push_back(&control_ret_node->def());
}
uint64 control_ret_nodes_hash = 0;
TF_RETURN_IF_ERROR(
HashControlInputs(control_rets, &control_ret_nodes_hash));
*hash = Hash64Combine(ret_nodes_hash, control_ret_nodes_hash);
return Status::OK();
}
Status CheckFunctionsEqual(const NameAttrList& this_func, GraphHasher* that,
const NameAttrList& that_func) {
return CheckFunctionsEqual(this_func.name(), this_func.attr(), that,
that_func.name(), that_func.attr());
}
Status CheckFunctionsEqual(const std::string& this_name,
const AttrValueMap& this_attrs, GraphHasher* that,
const std::string& that_name,
const AttrValueMap& that_attrs) {
Status s = CheckFunctionsEqualHelper(this_name, this_attrs, that, that_name,
that_attrs);
if (!s.ok()) {
return errors::FailedPrecondition("Functions ", this_name, " and ",
that_name, " are not the same:\n", s);
}
return s;
}
Status CheckFunctionsEqualHelper(const std::string& this_name,
const AttrValueMap& this_attrs,
GraphHasher* that,
const std::string& that_name,
const AttrValueMap& that_attrs) {
const FunctionDef* this_fdef = flib_->Find(this_name);
const FunctionDef* that_fdef = that->flib_->Find(that_name);
// Convert to GraphDefs.
std::unique_ptr<FunctionBody> this_fbody;
TF_RETURN_IF_ERROR(FunctionDefToBodyHelper(
*this_fdef, AttrSlice(&this_attrs), flib_, &this_fbody));
GraphDef this_graph_def = this_fbody->graph->ToGraphDefDebug();
std::unique_ptr<FunctionBody> that_fbody;
TF_RETURN_IF_ERROR(FunctionDefToBodyHelper(
*that_fdef, AttrSlice(&that_attrs), that->flib_, &that_fbody));
GraphDef that_graph_def = that_fbody->graph->ToGraphDefDebug();
if (this_fbody->ret_nodes.size() != that_fbody->ret_nodes.size()) {
return errors::FailedPrecondition(
"Different numbers of ret nodes for functions ", this_name, " and ",
that_name, ": ", this_fbody->ret_nodes.size(), " vs ",
that_fbody->ret_nodes.size());
}
for (int i = 0; i < this_fbody->ret_nodes.size(); ++i) {
const NodeDef* this_root = &this_fbody->ret_nodes[i]->def();
const NodeDef* that_root = &that_fbody->ret_nodes[i]->def();
GraphHasher this_hasher(&this_graph_def, this_root, flib_);
TF_RETURN_IF_ERROR(this_hasher.Init());
GraphHasher that_hasher(&that_graph_def, that_root, that->flib_);
TF_RETURN_IF_ERROR(that_hasher.Init());
TF_RETURN_IF_ERROR(this_hasher.CheckEqual(&that_hasher));
}
std::vector<const NodeDef*> this_control_rets;
for (const auto& control_ret_node : this_fbody->control_ret_nodes) {
this_control_rets.push_back(&control_ret_node->def());
}
std::vector<const NodeDef*> that_control_rets;
for (const auto& control_ret_node : that_fbody->control_ret_nodes) {
that_control_rets.push_back(&control_ret_node->def());
}
TF_RETURN_IF_ERROR(
CheckControlInputsEqual(this_control_rets, that, that_control_rets));
return Status::OK();
}
Status HashControlInputs(const std::vector<const NodeDef*>& inputs,
uint64* hash) {
*hash = 0;
for (const NodeDef* input : inputs) {
uint64 node_hash = 0;
TF_RETURN_IF_ERROR(
HashNodeNonInput(input, /*hash_functions=*/false, &node_hash));
*hash = Hash64CombineUnordered(*hash, node_hash);
}
return Status::OK();
}
Status CheckControlInputsEqual(
const std::vector<const NodeDef*>& this_inputs, GraphHasher* that,
const std::vector<const NodeDef*>& that_inputs) {
absl::flat_hash_map<uint64, const NodeDef*> this_hashes;
for (const NodeDef* input : this_inputs) {
uint64 node_hash = 0;
TF_RETURN_IF_ERROR(
HashNodeNonInput(input, /*hash_functions=*/false, &node_hash));
this_hashes[node_hash] = input;
}
absl::flat_hash_map<uint64, const NodeDef*> that_hashes;
for (const NodeDef* input : that_inputs) {
uint64 node_hash = 0;
TF_RETURN_IF_ERROR(
HashNodeNonInput(input, /*hash_functions=*/false, &node_hash));
if (this_hashes.contains(node_hash)) {
this_hashes.erase(node_hash);
} else {
that_hashes[node_hash] = input;
}
}
if (!this_hashes.empty()) {
std::vector<std::string> this_unmatched;
for (const auto& it : this_hashes) {
this_unmatched.push_back(it.second->name());
}
std::vector<std::string> that_unmatched;
for (const auto& it : that_hashes) {
that_unmatched.push_back(it.second->name());
}
return errors::FailedPrecondition(
"Control dependencies are different. One node has dependencies [",
absl::StrJoin(this_unmatched, ", "),
"], which don't match any of the other node's dependencies [",
absl::StrJoin(that_unmatched, ", "), "]");
}
return Status::OK();
}
private:
bool is_cycle_forming_edge(const NodeDef* start, const NodeDef* end) {
EdgeRep edge(start, end);
return cycle_forming_edges_.contains(edge.GetHash());
}
struct NodeRep {
std::vector<const NodeDef*> node_control_inputs;
std::vector<std::pair<const NodeDef*, std::string>> node_inputs;
};
struct EdgeRep {
const NodeDef* start_node;
const NodeDef* end_node;
EdgeRep(const NodeDef* start, const NodeDef* end)
: start_node(start), end_node(end) {}
uint64 GetHash() {
return Hash64Combine(absl::Hash<const NodeDef*>()(start_node),
absl::Hash<const NodeDef*>()(end_node));
}
};
const GraphDef* const graph_; // Not owned.
const NodeDef* const root_; // Not owned.
const FunctionLibraryDefinition* const flib_; // Not owned.
// Edges that need to be pruned as their presence will cause cycles.
absl::flat_hash_set<uint64> cycle_forming_edges_;
absl::flat_hash_map<const NodeDef*, NodeRep> nodes_;
absl::flat_hash_map<const NodeDef*, uint64> cache_;
};
} // anonymous namespace
Status HashTensor(const Tensor& tensor, uint64* hash) {
const tstring* s = nullptr;
// Hash tensor type.
*hash = Hash64Combine(0, tensor.dtype());
// Hash tensor shape.
for (int i = 0; i < tensor.shape().dims(); ++i) {
*hash = Hash64Combine(*hash, tensor.shape().dim_size(i));
}
// Hash tensor data.
switch (tensor.dtype()) {
case DT_RESOURCE:
case DT_VARIANT:
return errors::Unimplemented("Hashing ", DataTypeString(tensor.dtype()),
" is not supported.");
case DT_STRING:
s = tensor.flat<tstring>().data();
for (int i = 0; i < tensor.NumElements(); ++i, ++s) {
*hash = Hash64Combine(*hash, Hash64(s->data(), s->size()));
}
break;
default:
*hash = Hash64(tensor.tensor_data().data(), tensor.tensor_data().size());
}
return Status::OK();
}
Status HashNode(const GraphDef& graph, const NodeDef& node, uint64* hash) {
const FunctionLibraryDefinition flib_def(OpRegistry::Global(),
graph.library());
return HashNode(graph, node, flib_def, hash);
}
Status HashNode(const GraphDef& graph, const NodeDef& node,
const FunctionLibraryDefinition& flib_def, uint64* hash) {
GraphHasher hasher(&graph, &node, &flib_def);
TF_RETURN_IF_ERROR(hasher.Init());
return hasher.HashRoot(hash);
}
Status HashGraph(const GraphDef& graph_def, uint64* hash) {
const NodeDef* sink = nullptr;
TF_RETURN_IF_ERROR(GetSink(graph_def, &sink));
return HashNode(graph_def, *sink, hash);
}
Status CheckGraphsEqual(const GraphDef& a, const GraphDef& b) {
const NodeDef* sink_a;
TF_RETURN_IF_ERROR(GetSink(a, &sink_a));
const NodeDef* sink_b;
TF_RETURN_IF_ERROR(GetSink(b, &sink_b));
return CheckSubgraphsEqual(a, sink_a, b, sink_b);
}
Status CheckSubgraphsEqual(const GraphDef& a, const NodeDef* node_a,
const GraphDef& b, const NodeDef* node_b) {
const FunctionLibraryDefinition flib_def_a(OpRegistry::Global(), a.library());
GraphHasher hasher_a(&a, node_a, &flib_def_a);
TF_RETURN_IF_ERROR(hasher_a.Init());
const FunctionLibraryDefinition flib_def_b(OpRegistry::Global(), b.library());
GraphHasher hasher_b(&b, node_b, &flib_def_b);
TF_RETURN_IF_ERROR(hasher_b.Init());
return hasher_a.CheckEqual(&hasher_b);
}
} // namespace data
} // namespace tensorflow
| 38.526536 | 126 | 0.636179 | [
"shape",
"vector"
] |
4b52dc15f594d48c4679c7c1f4794aa2f75535ef | 28,937 | cpp | C++ | native_addon/wj_image/bitmap.cpp | SafeOnlineWorld/web_jsx | 7ce26957e40c4e6658042d4f2e6f3d93a77b709f | [
"CC-BY-4.0"
] | 2 | 2019-11-27T07:24:54.000Z | 2020-01-03T10:12:36.000Z | native_addon/wj_image/bitmap.cpp | SafeOnlineWorld/web_jsx | 7ce26957e40c4e6658042d4f2e6f3d93a77b709f | [
"CC-BY-4.0"
] | 2 | 2020-02-17T08:12:52.000Z | 2020-09-21T14:33:29.000Z | native_addon/wj_image/bitmap.cpp | SafeOnlineWorld/web_jsx | 7ce26957e40c4e6658042d4f2e6f3d93a77b709f | [
"CC-BY-4.0"
] | 2 | 2019-11-26T11:38:39.000Z | 2019-12-17T17:12:01.000Z | /**
* Copyright (c) 2018, SOW (https://www.safeonline.world). (https://github.com/RKTUXYN) All rights reserved.
* @author {SOW}
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
# include "bitmap.h"
# include <web_jsx/web_jsx.h>
# include <web_jsx/v8_util.h>
# include <web_jsx/base64.h>
# include <web_jsx/wjsx_env.h>
//#pragma warning (disable : 4231)
//#pragma warning(disable : 4996)
# include <iostream>
# include <fstream>
# include <sstream>
# include <string>
# include <vector>
#if !defined(READ_CHUNK)
# define READ_CHUNK 16384
#endif//!READ_CHUNK
typedef struct {
uint8_t r, g, b, a;
} rgb32;
#pragma pack(2)
typedef struct {
uint16_t bfType;
uint32_t bfSize;
uint16_t bfReserved1;
uint16_t bfReserved2;
uint32_t bfOffBits;
} bitmap_file_header;
#pragma pack()
#pragma pack(2)
typedef struct {
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
uint16_t biPlanes;
uint16_t biBitCount;
uint32_t biCompression;
uint32_t biSizeImage;
int16_t biXPelsPerMeter;
int16_t biYPelsPerMeter;
uint32_t biClrUsed;
uint32_t biClrImportant;
} bitmap_info_header;
#pragma pack()
#pragma pack(2)
typedef struct {
bitmap_file_header fHeader;
bitmap_info_header iHeader;
} bitmap_header;
#pragma pack()
//Read more about convert image_format
//https://www.codeproject.com/Articles/1300/CxImage
enum image_format {
BMP = 0,
PNG = 1,
JPEG = 2,
JPG = 3,
GIF = 4,
TIFF = 5,
TIF = 5
};
class bitmap {
private:
bitmap_header* _header;
uint8_t* _pixels;
int _is_error;
char* _internal_error;
int _is_loaded;
std::string* _input_file_path;
image_format _format;
int panic(const char* error, int error_code);
template<class _source_stream>
int load_from_stream(_source_stream& stream);
template<class _source_stream>
int save_to_stream(_source_stream& stream, int is_memory, image_format format);
int save_to_vector(std::vector<char>& dest, image_format format);
//int set_pixel(uint8_t* _pixels, rgb32* pixel, uint32_t x, uint32_t y);
public:
explicit bitmap(image_format format);
explicit bitmap(const char* path, image_format format);
//creates a deep copy of the source image.
bitmap(const bitmap& other);
~bitmap();
int load(const char* path);
int from_base64(const char* data);
int to_base64(std::string& out);
int save(const char* path, image_format format);
rgb32* get_pixel(uint32_t x, uint32_t y) const;
int set_pixel(rgb32* pixel, uint32_t x, uint32_t y);
int resize(bitmap& dest);
int resize(const uint32_t new_width, const uint32_t new_height);
int create_canvas(const uint32_t width, const uint32_t heigh);
uint32_t get_width() const;
uint32_t get_height() const;
image_format get_format() const;
int has_error();
int is_loaded() const;
const char* get_last_error();
void free_memory();
void reset_rgb();
void clear();
void dump_data();
uint8_t* data()const;
bitmap_header* header()const;
// Assignment operator creates a deep copy of the source image.
//bitmap& operator = (const bitmap& other);
};
template<class _source_stream>
inline int bitmap::load_from_stream(_source_stream& stream) {
if (_header == NULL) {
_header = new bitmap_header;
}
stream.read(reinterpret_cast<char*>(&_header->fHeader), sizeof(_header->fHeader));
if (_header->fHeader.bfType != 0x4d42) {
return this->panic("Invalid format. Only bitmaps are supported.", TRUE);
}
stream.read(reinterpret_cast<char*>(&_header->iHeader), sizeof(_header->iHeader));
if (_header->iHeader.biCompression != 0) {
return this->panic("Invalid bitmap. Only uncompressed bitmaps are supported.", TRUE);
}
if (_header->iHeader.biBitCount != 24) {
return this->panic("Invalid bitmap. Only 24bit bitmaps are supported.", TRUE);
}
stream.seekg(_header->fHeader.bfOffBits, std::ios::beg);
_pixels = new uint8_t[_header->fHeader.bfSize - _header->fHeader.bfOffBits];
stream.read(reinterpret_cast<char*>(&_pixels[0]), _header->fHeader.bfSize - _header->fHeader.bfOffBits);
size_t buff_len = (_header->iHeader.biWidth * _header->iHeader.biHeight * sizeof(rgb32));
uint8_t* temp = new uint8_t[buff_len];
uint8_t* in = _pixels;
rgb32* out = reinterpret_cast<rgb32*>(temp);
int padding = (_header->iHeader.biSizeImage - _header->iHeader.biWidth * _header->iHeader.biHeight * 3) / _header->iHeader.biHeight;
for (int i = 0; i < _header->iHeader.biHeight; ++i, in += padding) {
for (int j = 0; j < _header->iHeader.biWidth; ++j) {
out->b = *(in++);
out->g = *(in++);
out->r = *(in++);
out->a = 0xFF;
++out;
}
}
delete[] _pixels;
_pixels = temp;
_is_loaded = TRUE;
return _is_loaded;
}
template<class _source_stream>
inline int bitmap::save_to_stream(_source_stream& stream, int is_memory, image_format format) {
stream.write(reinterpret_cast<char*>(&_header->fHeader), sizeof(_header->fHeader));
stream.write(reinterpret_cast<char*>(&_header->iHeader), sizeof(_header->iHeader));
stream.seekp(_header->fHeader.bfOffBits, std::ios::beg);
uint8_t* temp = new uint8_t[_header->fHeader.bfSize - _header->fHeader.bfOffBits];
uint8_t* out = temp;
rgb32* in = reinterpret_cast<rgb32*>(_pixels);
//int nPadding = ((_header->iHeader.biWidth / 4) + 1) * 4;
int padding = (_header->iHeader.biSizeImage - _header->iHeader.biWidth * _header->iHeader.biHeight * 3) / _header->iHeader.biHeight;
for (int i = 0; i < _header->iHeader.biHeight; ++i, out += padding) {
for (int j = 0; j < _header->iHeader.biWidth; ++j) {
*(out++) = in->b;
*(out++) = in->g;
*(out++) = in->r;
++in;
}
}
stream.write(reinterpret_cast<char*>(&temp[0]), _header->fHeader.bfSize - _header->fHeader.bfOffBits);
delete[] temp;
return TRUE;
}
//12:43 AM 1/11/2020
void insert_vct(std::vector<char>& dest, char* data, size_t len) {
dest.insert(dest.end(), data, len + data);
}
bitmap::bitmap(image_format format) {
_internal_error = NULL; _is_error = FALSE; _is_loaded = FALSE;
_header = new bitmap_header; _pixels = NULL; _input_file_path = NULL;
_format = format;
if (_format != BMP) {
this->panic("Unsupported Image format.", TRUE);
}
}
bitmap::bitmap(const char* path, image_format format){
_internal_error = NULL; _is_error = FALSE; _is_loaded = FALSE;
_header = new bitmap_header; _pixels = NULL;
_input_file_path = new std::string(path);
_format = format;
if (_format != BMP) {
this->panic("Unsupported Image format.", TRUE);
}
return;
}
//creates a deep copy of the source image.
bitmap::bitmap(const bitmap& other){
if (other.is_loaded() == FALSE)return;
this->free_memory();
_header = new bitmap_header;
memcpy(_header, other.header(), sizeof(bitmap_header));
size_t len = _header->iHeader.biWidth * _header->iHeader.biHeight * sizeof(rgb32);
_pixels = new uint8_t[len];
memcpy(_pixels, other.data(), len);
_is_loaded = TRUE;
_format = BMP;
return;
}
int bitmap::load(const char* path) {
this->free_memory();
if (path == NULL && _input_file_path == NULL) {
return this->panic("No input file path found...", TRUE);
}
if (_format != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
std::ifstream* file;
if (path != NULL) {
file = new std::ifstream(path, std::ios::in | std::ios::binary);
}
else {
file = new std::ifstream(_input_file_path->c_str(), std::ios::in | std::ios::binary);
}
file->setf(std::ios_base::binary);
if (!file->is_open()) {
delete file;
return this->panic("Unable to open file", TRUE);
}
int ret = this->load_from_stream(*file);
file->close(); delete file;
if (path != NULL) {
_free_obj(_input_file_path);
_input_file_path = new std::string(path);
}
return ret;
}
int bitmap::from_base64(const char* data){
this->free_memory();
_NEW_STR(docoded_data);
int ret = sow_web_jsx::base64::to_decode_str(data, *docoded_data) == true ? TRUE : FALSE;
if (is_error_code(ret) == TRUE) {
docoded_data->clear(); delete docoded_data;
return ret;
}
std::stringstream* stream = new std::stringstream(std::stringstream::in | std::ios::out | std::stringstream::binary);
stream->write(docoded_data->c_str(), docoded_data->size());
_free_obj(docoded_data);
ret = this->load_from_stream(*stream);
stream->clear(); delete stream;
return ret;
}
int bitmap::save_to_vector(std::vector<char>& dest, image_format format) {
dest.reserve(_header->fHeader.bfSize);
insert_vct(dest, reinterpret_cast<char*>(&_header->fHeader), sizeof(_header->fHeader));
insert_vct(dest, reinterpret_cast<char*>(&_header->iHeader), sizeof(_header->iHeader));
uint8_t* temp = new uint8_t[_header->fHeader.bfSize - _header->fHeader.bfOffBits];
uint8_t* out = temp;
rgb32* in = reinterpret_cast<rgb32*>(_pixels);
//int nPadding = ((_header->iHeader.biWidth / 4) + 1) * 4;
int padding = (_header->iHeader.biSizeImage - _header->iHeader.biWidth * _header->iHeader.biHeight * 3) / _header->iHeader.biHeight;
for (int i = 0; i < _header->iHeader.biHeight; ++i, out += padding) {
for (int j = 0; j < _header->iHeader.biWidth; ++j) {
*(out++) = in->b;
*(out++) = in->g;
*(out++) = in->r;
++in;
}
}
insert_vct(dest, reinterpret_cast<char*>(&temp[0]), _header->fHeader.bfSize - _header->fHeader.bfOffBits);
delete[] temp;
return TRUE;
}
int bitmap::to_base64(std::string& out) {
std::vector<char>* dest = new std::vector<char>();
int ret = FALSE;
if (_input_file_path != NULL) {
std::ifstream* file = new std::ifstream(_input_file_path->c_str(), std::ios::in | std::ios::binary);
if (!file->is_open()) {
delete file; _free_obj(dest);
return this->panic("Unable to open file", TRUE);
}
ret = load_file_to_vct(*file, *dest);
file->close();
}
else {
if (_pixels == NULL) {
_free_obj(dest);
return FALSE;
}
ret = save_to_vector(*dest, image_format::BMP);
}
if (is_error_code(ret) == FALSE) {
std::string* data = new std::string(dest->data(), dest->size());
ret = sow_web_jsx::base64::to_encode_str(*data, out) == true ? TRUE : FALSE;
_free_obj(data);
}
_free_obj(dest);
return ret;
}
bitmap::~bitmap() {
this->free_memory();
}
int bitmap::save(const char* path, image_format format) {
if (_format != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
if (_is_loaded == FALSE) {
return this->panic("Please Load an Image than try again.", TRUE);
}
std::ofstream* file = new std::ofstream(path, std::ios::out | std::ios::binary);
if (!file->is_open()) {
return this->panic("Unable to open file", TRUE);
}
save_to_stream(*file, FALSE, BMP);
file->close(); delete file;
return TRUE;
}
rgb32* bitmap::get_pixel(uint32_t x, uint32_t y) const {
if (_format != BMP) {
return NULL;
}
rgb32* temp = reinterpret_cast<rgb32*>(_pixels);
return &temp[(_header->iHeader.biHeight - 1 - y) * _header->iHeader.biWidth + x];
}
int bitmap::set_pixel(rgb32* pixel, uint32_t x, uint32_t y) {
if (_format != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
rgb32* temp = reinterpret_cast<rgb32*>(_pixels);
memcpy(&temp[(_header->iHeader.biHeight - 1 - y) * _header->iHeader.biWidth + x], pixel, sizeof(rgb32));
return TRUE;
}
void bitmap::dump_data() {
if (_format != BMP)return;
std::cout << "Bitmap data:" << std::endl;
std::cout << "============" << std::endl;
std::cout << "Width: " << _header->iHeader.biWidth << std::endl;
std::cout << "Height: " << _header->iHeader.biHeight << std::endl;
std::cout << "Data:" << std::endl;
for (int cy = 0; cy < _header->iHeader.biHeight; cy++) {
for (int cx = 0; cx < _header->iHeader.biWidth; cx++) {
int pixel = (cy * (_header->iHeader.biWidth * 3)) + (cx * 3);
std::cout << "rgb(" << (int)_pixels[pixel] << "," << (int)_pixels[pixel + 1] << "," << (int)_pixels[pixel + 2] << ") ";
}
std::cout << std::endl;
}
std::cout << "_________________________________________________________" << std::endl;
}
int bitmap::resize(bitmap& dest) {
if (_format != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
if (dest.get_format() != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
if (_is_loaded == FALSE)return FALSE;
if (_pixels == NULL) return FALSE;
uint32_t new_width = dest.get_width(), new_height = dest.get_height();
double scale_width = static_cast<double>(new_width) / static_cast<double>(_header->iHeader.biWidth);
double scale_height = static_cast<double>(new_height) / static_cast<double>(_header->iHeader.biHeight);
for (uint32_t y = 0; y < new_height; ++y) {
for (uint32_t x = 0; x < new_width; ++x) {
rgb32* tmp_pixel = get_pixel(static_cast<uint32_t>(x / scale_width), static_cast<uint32_t>(y / scale_height));
dest.set_pixel(tmp_pixel, x, y);
}
}
return TRUE;
}
uint8_t* bitmap::data()const {
return _pixels;
}
bitmap_header* bitmap::header()const {
return _header;
}
int bitmap::resize(const uint32_t new_width, const uint32_t new_height){
if (_format != BMP) {
return this->panic("Unsupported Image format.", TRUE);
}
bitmap* bmp = new bitmap(BMP);
int ret = bmp->create_canvas(new_width, new_height);
if (is_error_code(ret) == TRUE)return ret;
ret = this->resize(*bmp);
if (is_error_code(ret) == TRUE)return ret;
*this = *bmp;
return ret;
}
int bitmap::create_canvas(const uint32_t width, const uint32_t height){
this->free_memory();
if (width % 4 != 0) {
return panic("There is a windows-imposed requirement on BMP that the width be a multiple of 4", TRUE);
}
_header = new bitmap_header;
_header->fHeader.bfType = 0x4d42;
_header->iHeader.biSize = 40;//
_header->fHeader.bfOffBits = 14 + _header->iHeader.biSize;
_header->fHeader.bfSize = _header->fHeader.bfOffBits + (width * height * 3);
_header->fHeader.bfReserved1 = 0;
_header->fHeader.bfReserved2 = 0;
_header->iHeader.biWidth = width;
_header->iHeader.biHeight = height;
_header->iHeader.biPlanes = 1;
_header->iHeader.biBitCount = 24;
_header->iHeader.biCompression = 0;
_header->iHeader.biSizeImage = width * height * (uint32_t)(_header->iHeader.biBitCount / 8);
_is_loaded = TRUE; _is_error = FALSE;
this->reset_rgb();
return TRUE;
}
//Draw white background
void bitmap::reset_rgb() {
if (_is_loaded == FALSE)return;
if (_format != BMP)return;
rgb32* in = new rgb32();
in->r = (uint8_t)(0xff);
in->g = (uint8_t)(0xff);
in->b = (uint8_t)(0xff);
in->a = (uint8_t)(0xff);
if (_pixels != NULL) {
delete[]_pixels; _pixels = NULL;
}
_pixels = new uint8_t[_header->iHeader.biWidth * _header->iHeader.biHeight * sizeof(rgb32)];
rgb32* out = reinterpret_cast<rgb32*>(_pixels);
for (int32_t i = 0; i < _header->iHeader.biHeight; ++i) {
for (int32_t j = 0; j < _header->iHeader.biWidth; ++j) {
out->b = in->b;
out->g = in->g;
out->r = in->r;
out->a = in->a;
++out;
}
}
delete in;
}
uint32_t bitmap::get_width() const {
return _header->iHeader.biWidth;
}
uint32_t bitmap::get_height() const {
return _header->iHeader.biHeight;
}
image_format bitmap::get_format() const{
return _format;
}
int bitmap::has_error(){
return _is_error == TRUE || _is_error < 0 ? TRUE : FALSE;
}
int bitmap::is_loaded() const {
return _is_loaded;
}
const char* bitmap::get_last_error() {
if (has_error() == TRUE) {
return const_cast<const char*>(_internal_error);
}
return "No reason found from context!!!";
}
void bitmap::free_memory(){
_free_char(_internal_error);
_free_obj(_input_file_path);
if (_pixels != NULL) {
delete[] _pixels; _pixels = NULL;
}
if (_header != NULL) {
delete _header; _header = NULL;
}
_is_error = FALSE; _is_loaded = FALSE;
return;
}
void bitmap::clear(){
this->free_memory();
}
int bitmap::panic(const char* error, int error_code) {
_free_char(_internal_error);
size_t len = strlen(error);
_internal_error = new char[len + 1];
strcpy_s(_internal_error, len, error);
if (error_code >= 0)error_code = error_code * -1;
_is_error = error_code;
return _is_error;
}
using namespace sow_web_jsx;
void bitmap_export(v8::Isolate* isolate, v8::Handle<v8::Object> target) {
v8::Local<v8::FunctionTemplate> bit_map_tpl = v8::FunctionTemplate::New(isolate, [](const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (!args.IsConstructCall()) {
throw_js_error(isolate, "Cannot call constructor as function!!!");
return;
}
wjsx_env* wj_env = ::unwrap_wjsx_env(isolate);
bitmap* bmp = NULL;
if (args[0]->IsString()) {
native_string utf_str(isolate, args[0]);
std::string* abs_path = new std::string(wj_env->get_root_dir());
sow_web_jsx::get_server_map_path(utf_str.c_str(), *abs_path);
bmp = new bitmap(abs_path->c_str(), image_format::BMP);
utf_str.clear(); _free_obj(abs_path);
}
else {
bmp = new bitmap(image_format::BMP);
}
v8::Local<v8::Object> obj = args.This();
obj->SetInternalField(0, v8::External::New(isolate, bmp));
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>> pobj(isolate, obj);
pobj.SetWeak<bitmap*>(&bmp, [](const v8::WeakCallbackInfo<bitmap*>& data) {
delete[] data.GetParameter();
}, v8::WeakCallbackType::kParameter);
});
bit_map_tpl->SetClassName(v8_str(isolate, "BitMap"));
bit_map_tpl->InstanceTemplate()->SetInternalFieldCount(1);
v8::Local<v8::ObjectTemplate> prototype = bit_map_tpl->PrototypeTemplate();
set_prototype(isolate, prototype, "release", [](js_method_args) {
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL)return;
bmp->free_memory();
delete bmp; bmp = NULL;
args.Holder()->SetAlignedPointerInInternalField(0, nullptr);
});
set_prototype(isolate, prototype, "lock_bits", [](js_method_args) {
args.GetReturnValue().Set(args.Holder());
});
set_prototype(isolate, prototype, "unlock_bits", [](js_method_args) {
args.GetReturnValue().Set(args.Holder());
});
set_prototype(isolate, prototype, "reset", [](js_method_args) {
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
bmp->reset_rgb();
args.GetReturnValue().Set(args.Holder());
});
set_prototype(isolate, prototype, "release_mem", [](js_method_args) {
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL)return;
bmp->clear();
args.GetReturnValue().Set(args.Holder());
});
set_prototype(isolate, prototype, "dump_data", [](js_method_args) {
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
bmp->dump_data();
args.GetReturnValue().Set(args.Holder());
});
set_prototype(isolate, prototype, "load", [](js_method_args) {
v8::Isolate* isolate = args.GetIsolate();
if (!args[0]->IsString()) {
throw_js_error(isolate, "File Path Required required....");
return;
}
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(isolate, "bitmap object disposed...");
return;
}
native_string utf_abs_path_str(isolate, args[0]);
wjsx_env* wj_env = ::unwrap_wjsx_env(isolate);
std::string* abs_path = new std::string(wj_env->get_root_dir());
::get_server_map_path(utf_abs_path_str.c_str(), *abs_path);
int ret = bmp->load(abs_path->c_str());
_free_obj(abs_path); utf_abs_path_str.clear();
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
return;
}
args.GetReturnValue().Set(v8::Integer::New(isolate, ret));
});
set_prototype(isolate, prototype, "to_base64", [](js_method_args) {
bitmap* bmp = ::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
std::string* out = new std::string();
int ret = bmp->to_base64(*out);
if (is_error_code(ret) == TRUE) {
throw_js_error(args.GetIsolate(), "Unable to convert base64 image...");
}
else {
args.GetReturnValue().Set(v8_str(args.GetIsolate(), out->c_str()));
}
_free_obj(out);
});
set_prototype(isolate, prototype, "load_from_base64", [](js_method_args) {
if (!args[0]->IsString()) {
throw_js_type_error(args.GetIsolate(), "base64 Data required....");
return;
}
v8::Isolate* isolate = args.GetIsolate();
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(isolate, "bitmap object disposed...");
return;
}
native_string utf_base64(isolate, args[0]);
int ret = bmp->from_base64(utf_base64.c_str());
utf_base64.clear();
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
return;
}
args.GetReturnValue().Set(v8::Integer::New(isolate, ret));
});
set_prototype(isolate, prototype, "save", [](js_method_args) {
if (!args[0]->IsString()) {
throw_js_type_error(args.GetIsolate(), "File Path required....");
return;
}
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
v8::Isolate* isolate = args.GetIsolate();
native_string utf_abs_path_str(isolate, args[0]);
wjsx_env* wj_env = ::unwrap_wjsx_env(isolate);
std::string* abs_path = new std::string(wj_env->get_root_dir());
sow_web_jsx::get_server_map_path(utf_abs_path_str.c_str(), *abs_path);
int ret = bmp->save(abs_path->c_str(), image_format::BMP);
_free_obj(abs_path); utf_abs_path_str.clear();
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
return;
}
args.GetReturnValue().Set(v8::Integer::New(isolate, ret));
});
set_prototype(isolate, prototype, "get_width", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
uint32_t width = bmp->get_width();
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), static_cast<int>(width)));
});
set_prototype(isolate, prototype, "get_height", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), "Image does not loaded yet...");
return;
}
uint32_t height = bmp->get_height();
args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), static_cast<int>(height)));
});
set_prototype(isolate, prototype, "get_pixel", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), bmp->get_last_error());
return;
}
if (args.Length() < 2) {
throw_js_error(args.GetIsolate(), "x y required...");
return;
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
throw_js_error(args.GetIsolate(), "x y should be number...");
return;
}
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context>ctx = isolate->GetCurrentContext();
int x = args[0]->Int32Value(ctx).FromMaybe(0);
int y = args[1]->Int32Value(ctx).FromMaybe(0);
rgb32* pixel = bmp->get_pixel(static_cast<unsigned int>(x), static_cast<unsigned int>(y));
v8::Handle<v8::Object> v8_result = v8::Object::New(isolate);
v8_result->Set(ctx, v8_str(isolate, "r"), v8::Integer::New(isolate, static_cast<int>(pixel->r)));
v8_result->Set(ctx, v8_str(isolate, "g"), v8::Integer::New(isolate, static_cast<int>(pixel->g)));
v8_result->Set(ctx, v8_str(isolate, "b"), v8::Integer::New(isolate, static_cast<int>(pixel->b)));
v8_result->Set(ctx, v8_str(isolate, "a"), v8::Integer::New(isolate, static_cast<int>(pixel->a)));
args.GetReturnValue().Set(v8_result); v8_result.Clear();
});
set_prototype(isolate, prototype, "resize", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), bmp->get_last_error());
return;
}
if (args.Length() < 2) {
throw_js_error(args.GetIsolate(), "Height and Width required...");
return;
}
if (!args[0]->IsNumber()) {
throw_js_type_error(args.GetIsolate(), "Height required...");
return;
}
if (!args[1]->IsNumber()) {
throw_js_type_error(args.GetIsolate(), "Width required...");
return;
}
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context>ctx = isolate->GetCurrentContext();
int width = args[0]->Int32Value(ctx).FromMaybe(0);
int height = args[1]->Int32Value(ctx).FromMaybe(0);
int ret = bmp->resize(static_cast<uint32_t>(width), static_cast<uint32_t>(height));
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
}
else {
args.GetReturnValue().Set(args.Holder());
}
});
set_prototype(isolate, prototype, "create_canvas", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (args.Length() < 2) {
throw_js_error(args.GetIsolate(), "Height and Width required...");
return;
}
if (!args[0]->IsNumber()) {
throw_js_type_error(args.GetIsolate(), "Height required...");
return;
}
if (!args[1]->IsNumber()) {
throw_js_type_error(args.GetIsolate(), "Width required...");
return;
}
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context>ctx = isolate->GetCurrentContext();
int width = args[0]->Int32Value(ctx).FromMaybe(0);
int height = args[1]->Int32Value(ctx).FromMaybe(0);
int ret = bmp->create_canvas(static_cast<uint32_t>(width), static_cast<uint32_t>(height));
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
}
else {
args.GetReturnValue().Set(args.Holder());
}
});
set_prototype(isolate, prototype, "set_pixel", [](js_method_args) {
bitmap* bmp = sow_web_jsx::unwrap<bitmap>(args);
if (bmp == NULL) {
throw_js_error(args.GetIsolate(), "bitmap object disposed...");
return;
}
if (bmp->is_loaded() == FALSE) {
throw_js_error(args.GetIsolate(), bmp->get_last_error());
return;
}
if (args.Length() < 3) {
throw_js_error(args.GetIsolate(), "rgba and x y required...");
return;
}
if (!args[0]->IsObject()) {
throw_js_type_error(args.GetIsolate(), "rgba should be object...");
return;
}
if (!args[1]->IsNumber() || !args[2]->IsNumber()) {
throw_js_type_error(args.GetIsolate(), "x y should be number...");
return;
}
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> rgba = v8::Handle<v8::Object>::Cast(args[0]);
v8::Local<v8::Context>ctx = isolate->GetCurrentContext();
rgb32* pixel = new rgb32();
int val = v8_object_get_number(isolate, ctx, rgba, "r");
if (val == -500) { delete pixel; return; }
pixel->r = (uint8_t)val;
val = v8_object_get_number(isolate, ctx, rgba, "g");
if (val == -500) { delete pixel; return; }
pixel->g = (uint8_t)val;
val = v8_object_get_number(isolate, ctx, rgba, "b");
if (val == -500) { delete pixel; return; }
pixel->b = (uint8_t)val;
val = v8_object_get_number(isolate, ctx, rgba, "a");
if (val == -500) { delete pixel; return; }
pixel->a = (uint8_t)val;
int x = args[1]->Int32Value(ctx).FromMaybe(0);
int y = args[2]->Int32Value(ctx).FromMaybe(0);
int ret = bmp->set_pixel(pixel, static_cast<unsigned int>(x), static_cast<unsigned int>(y));
//delete pixel;
if (is_error_code(ret) == TRUE) {
throw_js_error(isolate, bmp->get_last_error());
}
else {
args.GetReturnValue().Set(args.Holder());
}
});
target->Set(isolate->GetCurrentContext(), v8_str(isolate, "BitMap"), bit_map_tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
} | 35.418605 | 144 | 0.660919 | [
"object",
"vector"
] |
4b562e715fbe4d0d35eb9b23a7527e6d2edd7c0f | 1,368 | cpp | C++ | source/code/programs/games/word_build/gui/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/programs/games/word_build/gui/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/programs/games/word_build/gui/main.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <string>
#include <iostream>
#include <vector>
#include <memory>
#include <SFML/Window/Joystick.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include "code/utilities/peripheral/keyboard/joycons/joycon_state_getter.hpp"
#include "code/utilities/formats/json/converters/lib.hpp"
#include "code/programs/games/word_build/gui/assets/assets_loader.hpp"
#include "code/programs/games/word_build/gui/state/game_state.hpp"
#include "code/programs/games/word_build/gui/state/game_state_getter.hpp"
#include "code/programs/games/word_build/gui/core/frame_renderer.hpp"
#include "code/programs/games/word_build/gui/core/state_updater.hpp"
#include "code/utilities/graphics/sfml/game_loop.hpp"
#include "code/utilities/graphics/sfml/standard_sfml_game_loop.hpp"
int main()
{
//get all the assets and game state
auto state = Game_State_Getter::Get();
auto assets = Assets_Loader::Load(state);
Standard_Sfml_Game_Loop::Run(
"Word Build",
[&](sf::RenderWindow & window, sf::Time const& TimePerFrame){
//std::cout << TimePerFrame.asMicroseconds() << std::endl;
State_Updater::Run_Frame_Logic(window,TimePerFrame,state,assets);
},
[&](sf::RenderWindow & window){
Frame_Renderer::Run_Frame_Render(window,state,assets);
});
return 0;
}
| 33.365854 | 77 | 0.738304 | [
"vector"
] |
4b5e8cfc65f20b6d690391dfde5dda8b297755c9 | 55,611 | cc | C++ | vm_tools/concierge/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | vm_tools/concierge/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | vm_tools/concierge/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vm_tools/concierge/service.h"
#include <arpa/inet.h>
#include <fcntl.h>
#include <net/route.h>
#include <signal.h>
#include <stdint.h>
#include <sys/mount.h>
#include <sys/sendfile.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/vm_sockets.h> // Needs to come after sys/socket.h
#include <map>
#include <utility>
#include <vector>
#include <base/base64url.h>
#include <base/bind.h>
#include <base/bind_helpers.h>
#include <base/callback.h>
#include <base/files/file_enumerator.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/location.h>
#include <base/logging.h>
#include <base/memory/ref_counted.h>
#include <base/memory/ptr_util.h>
#include <base/single_thread_task_runner.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/stringprintf.h>
#include <base/synchronization/waitable_event.h>
#include <base/threading/thread_task_runner_handle.h>
#include <base/time/time.h>
#include <base/version.h>
#include <chromeos/dbus/service_constants.h>
#include <crosvm/qcow_utils.h>
#include <dbus/object_proxy.h>
#include <vm_cicerone/proto_bindings/cicerone_service.pb.h>
#include <vm_concierge/proto_bindings/service.pb.h>
#include "vm_tools/common/constants.h"
#include "vm_tools/concierge/seneschal_server_proxy.h"
#include "vm_tools/concierge/ssh_keys.h"
#include "vm_tools/concierge/subnet.h"
using std::string;
namespace vm_tools {
namespace concierge {
namespace {
// Path to the runtime directory used by VMs.
constexpr char kRuntimeDir[] = "/run/vm";
// Default path to VM kernel image and rootfs.
constexpr char kVmDefaultPath[] = "/run/imageloader/cros-termina";
// Name of the VM kernel image.
constexpr char kVmKernelName[] = "vm_kernel";
// Name of the VM rootfs image.
constexpr char kVmRootfsName[] = "vm_rootfs.img";
// Maximum number of extra disks to be mounted inside the VM.
constexpr int kMaxExtraDisks = 10;
// How long we should wait for a VM to start up.
// While this timeout might be high, it's meant to be a final failure point, not
// the lower bound of how long it takes. On a loaded system (like extracting
// large compressed files), it could take 10 seconds to boot.
constexpr base::TimeDelta kVmStartupTimeout = base::TimeDelta::FromSeconds(30);
// crosvm directory name.
constexpr char kCrosvmDir[] = "crosvm";
// Cryptohome root base path.
constexpr char kCryptohomeRoot[] = "/home/root";
// Cryptohome user base path.
constexpr char kCryptohomeUser[] = "/home/user";
// Downloads directory for a user.
constexpr char kDownloadsDir[] = "Downloads";
// File extension for raw disk types
constexpr char kRawImageExtension[] = ".img";
// File extenstion for qcow2 disk types
constexpr char kQcowImageExtension[] = ".qcow2";
// Valid file extensions for disk images
constexpr const char* kDiskImagePatterns[] = {
"*.img", "*.qcow2",
};
// Default name to use for a container.
constexpr char kDefaultContainerName[] = "penguin";
// Path to process file descriptors.
constexpr char kProcFileDescriptorsPath[] = "/proc/self/fd/";
// Only allow hex digits in the cryptohome id.
constexpr char kValidCryptoHomeCharacters[] = "abcdefABCDEF0123456789";
// Common environment for all LXD functionality.
const std::map<string, string> kLxdEnv = {
{"LXD_DIR", "/mnt/stateful/lxd"},
{"LXD_CONF", "/mnt/stateful/lxd_conf"},
{"LXD_UNPRIVILEGED_ONLY", "true"},
};
// Passes |method_call| to |handler| and passes the response to
// |response_sender|. If |handler| returns NULL, an empty response is created
// and sent.
void HandleSynchronousDBusMethodCall(
base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
dbus::MethodCall* method_call,
dbus::ExportedObject::ResponseSender response_sender) {
std::unique_ptr<dbus::Response> response = handler.Run(method_call);
if (!response)
response = dbus::Response::FromMethodCall(method_call);
response_sender.Run(std::move(response));
}
// Posted to a grpc thread to startup a listener service. Puts a copy of
// the pointer to the grpc server in |server_copy| and then signals |event|.
// It will listen on the address specified in |listener_address|.
void RunListenerService(grpc::Service* listener,
const std::string& listener_address,
base::WaitableEvent* event,
std::shared_ptr<grpc::Server>* server_copy) {
// We are not interested in getting SIGCHLD or SIGTERM on this thread.
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigaddset(&mask, SIGTERM);
sigprocmask(SIG_BLOCK, &mask, nullptr);
// Build the grpc server.
grpc::ServerBuilder builder;
builder.AddListeningPort(listener_address, grpc::InsecureServerCredentials());
builder.RegisterService(listener);
std::shared_ptr<grpc::Server> server(builder.BuildAndStart().release());
*server_copy = server;
event->Signal();
if (server) {
server->Wait();
}
}
// Sets up a gRPC listener service by starting the |grpc_thread| and posting the
// main task to run for the thread. |listener_address| should be the address the
// gRPC server is listening on. A copy of the pointer to the server is put in
// |server_copy|. Returns true if setup & started successfully, false otherwise.
bool SetupListenerService(base::Thread* grpc_thread,
grpc::Service* listener_impl,
const std::string& listener_address,
std::shared_ptr<grpc::Server>* server_copy) {
// Start the grpc thread.
if (!grpc_thread->Start()) {
LOG(ERROR) << "Failed to start grpc thread";
return false;
}
base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
bool ret = grpc_thread->task_runner()->PostTask(
FROM_HERE, base::Bind(&RunListenerService, listener_impl,
listener_address, &event, server_copy));
if (!ret) {
LOG(ERROR) << "Failed to post server startup task to grpc thread";
return false;
}
// Wait for the VM grpc server to start.
event.Wait();
if (!server_copy) {
LOG(ERROR) << "grpc server failed to start";
return false;
}
return true;
}
// Converts an IPv4 address to a string. The result will be stored in |str|
// on success.
bool IPv4AddressToString(const uint32_t address, std::string* str) {
CHECK(str);
char result[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &address, result, sizeof(result)) != result) {
return false;
}
*str = std::string(result);
return true;
}
// Get the path to the latest available cros-termina component.
base::FilePath GetLatestVMPath() {
base::FilePath component_dir(kVmDefaultPath);
base::FileEnumerator dir_enum(component_dir, false,
base::FileEnumerator::DIRECTORIES);
base::Version latest_version("0");
base::FilePath latest_path;
for (base::FilePath path = dir_enum.Next(); !path.empty();
path = dir_enum.Next()) {
base::Version version(path.BaseName().value());
if (!version.IsValid())
continue;
if (version > latest_version) {
latest_version = version;
latest_path = path;
}
}
return latest_path;
}
// Gets the path to a VM disk given the name, user id, and location.
bool GetDiskPathFromName(
const std::string& disk_path,
const std::string& cryptohome_id,
StorageLocation storage_location,
bool create_parent_dir,
base::FilePath* path_out,
enum DiskImageType preferred_image_type = DiskImageType::DISK_IMAGE_AUTO) {
if (!base::ContainsOnlyChars(cryptohome_id, kValidCryptoHomeCharacters)) {
LOG(ERROR) << "Invalid cryptohome_id specified";
return false;
}
// Base64 encode the given disk name to ensure it only has valid characters.
std::string disk_name;
base::Base64UrlEncode(disk_path, base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&disk_name);
base::FilePath storage_path;
if (storage_location == STORAGE_CRYPTOHOME_ROOT) {
base::FilePath crosvm_dir = base::FilePath(kCryptohomeRoot)
.Append(cryptohome_id)
.Append(kCrosvmDir);
base::File::Error dir_error;
if (!base::DirectoryExists(crosvm_dir)) {
if (!create_parent_dir) {
return false;
}
if (!base::CreateDirectoryAndGetError(crosvm_dir, &dir_error)) {
LOG(ERROR) << "Failed to create crosvm directory in /home/root: "
<< base::File::ErrorToString(dir_error);
return false;
}
}
storage_path = crosvm_dir;
} else if (storage_location == STORAGE_CRYPTOHOME_DOWNLOADS) {
storage_path = base::FilePath(kCryptohomeUser)
.Append(cryptohome_id)
.Append(kDownloadsDir);
} else {
LOG(ERROR) << "Unknown storage location type";
return false;
}
auto qcow2_path = storage_path.Append(disk_name + kQcowImageExtension);
auto raw_path = storage_path.Append(disk_name + kRawImageExtension);
bool qcow2_exists = base::PathExists(qcow2_path);
bool raw_exists = base::PathExists(raw_path);
// This scenario (both <name>.img and <name>.qcow2 exist) should never happen.
// It is prevented by the later checks in this function.
// However, in case it does happen somehow (e.g. user manually created files
// in dev mode), bail out, since we can't tell which one the user wants.
if (qcow2_exists && raw_exists) {
LOG(ERROR) << "Both qcow2 and raw variants of " << disk_path
<< " already exist.";
return false;
}
// Return the path to an existing image of any type, if one exists.
// If not, generate a path based on the preferred image type.
if (qcow2_exists) {
*path_out = qcow2_path;
} else if (raw_exists) {
*path_out = raw_path;
} else if (preferred_image_type == DISK_IMAGE_QCOW2) {
*path_out = qcow2_path;
} else if (preferred_image_type == DISK_IMAGE_RAW ||
preferred_image_type == DISK_IMAGE_AUTO) {
*path_out = raw_path;
} else {
LOG(ERROR) << "Unknown image type " << preferred_image_type;
return false;
}
return true;
}
} // namespace
std::unique_ptr<Service> Service::Create(base::Closure quit_closure) {
auto service = base::WrapUnique(new Service(std::move(quit_closure)));
if (!service->Init()) {
service.reset();
}
return service;
}
Service::Service(base::Closure quit_closure)
: watcher_(FROM_HERE),
next_seneschal_server_port_(kFirstSeneschalServerPort),
quit_closure_(std::move(quit_closure)),
#ifdef __arm__
resync_vm_clocks_on_resume_(true),
#else
resync_vm_clocks_on_resume_(false),
#endif
weak_ptr_factory_(this) {
}
Service::~Service() {
if (grpc_server_vm_) {
grpc_server_vm_->Shutdown();
}
}
void Service::OnFileCanReadWithoutBlocking(int fd) {
DCHECK_EQ(signal_fd_.get(), fd);
struct signalfd_siginfo siginfo;
if (read(signal_fd_.get(), &siginfo, sizeof(siginfo)) != sizeof(siginfo)) {
PLOG(ERROR) << "Failed to read from signalfd";
return;
}
if (siginfo.ssi_signo == SIGCHLD) {
HandleChildExit();
} else if (siginfo.ssi_signo == SIGTERM) {
HandleSigterm();
} else {
LOG(ERROR) << "Received unknown signal from signal fd: "
<< strsignal(siginfo.ssi_signo);
}
}
void Service::OnFileCanWriteWithoutBlocking(int fd) {
NOTREACHED();
}
bool Service::Init() {
dbus::Bus::Options opts;
opts.bus_type = dbus::Bus::SYSTEM;
bus_ = new dbus::Bus(std::move(opts));
if (!bus_->Connect()) {
LOG(ERROR) << "Failed to connect to system bus";
return false;
}
exported_object_ =
bus_->GetExportedObject(dbus::ObjectPath(kVmConciergeServicePath));
if (!exported_object_) {
LOG(ERROR) << "Failed to export " << kVmConciergeServicePath << " object";
return false;
}
using ServiceMethod =
std::unique_ptr<dbus::Response> (Service::*)(dbus::MethodCall*);
const std::map<const char*, ServiceMethod> kServiceMethods = {
{kStartVmMethod, &Service::StartVm},
{kStopVmMethod, &Service::StopVm},
{kStopAllVmsMethod, &Service::StopAllVms},
{kGetVmInfoMethod, &Service::GetVmInfo},
{kCreateDiskImageMethod, &Service::CreateDiskImage},
{kDestroyDiskImageMethod, &Service::DestroyDiskImage},
{kExportDiskImageMethod, &Service::ExportDiskImage},
{kListVmDisksMethod, &Service::ListVmDisks},
{kGetContainerSshKeysMethod, &Service::GetContainerSshKeys},
{kSyncVmTimesMethod, &Service::SyncVmTimes},
};
for (const auto& iter : kServiceMethods) {
bool ret = exported_object_->ExportMethodAndBlock(
kVmConciergeInterface, iter.first,
base::Bind(&HandleSynchronousDBusMethodCall,
base::Bind(iter.second, base::Unretained(this))));
if (!ret) {
LOG(ERROR) << "Failed to export method " << iter.first;
return false;
}
}
if (!bus_->RequestOwnershipAndBlock(kVmConciergeServiceName,
dbus::Bus::REQUIRE_PRIMARY)) {
LOG(ERROR) << "Failed to take ownership of " << kVmConciergeServiceName;
return false;
}
// Set up the D-Bus client for shill.
shill_client_ = std::make_unique<ShillClient>(bus_);
shill_client_->RegisterResolvConfigChangedHandler(base::Bind(
&Service::OnResolvConfigChanged, weak_ptr_factory_.GetWeakPtr()));
// Get the D-Bus proxy for communicating with cicerone.
cicerone_service_proxy_ = bus_->GetObjectProxy(
vm_tools::cicerone::kVmCiceroneServiceName,
dbus::ObjectPath(vm_tools::cicerone::kVmCiceroneServicePath));
if (!cicerone_service_proxy_) {
LOG(ERROR) << "Unable to get dbus proxy for "
<< vm_tools::cicerone::kVmCiceroneServiceName;
return false;
}
cicerone_service_proxy_->ConnectToSignal(
vm_tools::cicerone::kVmCiceroneServiceName,
vm_tools::cicerone::kTremplinStartedSignal,
base::Bind(&Service::OnTremplinStartedSignal,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&Service::OnSignalConnected, weak_ptr_factory_.GetWeakPtr()));
// Get the D-Bus proxy for communicating with seneschal.
seneschal_service_proxy_ = bus_->GetObjectProxy(
vm_tools::seneschal::kSeneschalServiceName,
dbus::ObjectPath(vm_tools::seneschal::kSeneschalServicePath));
if (!seneschal_service_proxy_) {
LOG(ERROR) << "Unable to get dbus proxy for "
<< vm_tools::seneschal::kSeneschalServiceName;
return false;
}
if (resync_vm_clocks_on_resume_) {
// Get the D-Bus proxy for listening for power events.
powerd_proxy_ = bus_->GetObjectProxy(
power_manager::kPowerManagerServiceName,
dbus::ObjectPath(power_manager::kPowerManagerServicePath));
if (!powerd_proxy_) {
LOG(ERROR) << "Unable to get dbus proxy for "
<< power_manager::kPowerManagerServiceName;
return false;
}
// Register for resume notifications.
powerd_proxy_->ConnectToSignal(
power_manager::kPowerManagerInterface,
power_manager::kSuspendDoneSignal,
base::Bind(&Service::OnSuspendDone, weak_ptr_factory_.GetWeakPtr()),
base::Bind(&Service::OnSignalConnected,
weak_ptr_factory_.GetWeakPtr()));
}
// Setup & start the gRPC listener services.
if (!SetupListenerService(&grpc_thread_vm_, &startup_listener_,
base::StringPrintf("vsock:%u:%u", VMADDR_CID_ANY,
vm_tools::kStartupListenerPort),
&grpc_server_vm_)) {
LOG(ERROR) << "Failed to setup/startup the VM grpc server";
return false;
}
// Change the umask so that the runtime directory for each VM will get the
// right permissions.
umask(002);
// Set up the signalfd for receiving SIGCHLD and SIGTERM.
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigaddset(&mask, SIGTERM);
signal_fd_.reset(signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC));
if (!signal_fd_.is_valid()) {
PLOG(ERROR) << "Failed to create signalfd";
return false;
}
bool ret = base::MessageLoopForIO::current()->WatchFileDescriptor(
signal_fd_.get(), true /*persistent*/, base::MessageLoopForIO::WATCH_READ,
&watcher_, this);
if (!ret) {
LOG(ERROR) << "Failed to watch signalfd";
return false;
}
// Now block signals from the normal signal handling path so that we will get
// them via the signalfd.
if (sigprocmask(SIG_BLOCK, &mask, nullptr) < 0) {
PLOG(ERROR) << "Failed to block signals via sigprocmask";
return false;
}
return true;
}
void Service::HandleChildExit() {
DCHECK(sequence_checker_.CalledOnValidSequence());
// We can't just rely on the information in the siginfo structure because
// more than one child may have exited but only one SIGCHLD will be
// generated.
while (true) {
int status;
pid_t pid = waitpid(-1, &status, WNOHANG);
if (pid <= 0) {
if (pid == -1 && errno != ECHILD) {
PLOG(ERROR) << "Unable to reap child processes";
}
break;
}
// See if this is a process we launched.
VmMap::key_type key;
for (const auto& pair : vms_) {
if (pid == pair.second->pid()) {
key = pair.first;
break;
}
}
if (WIFEXITED(status)) {
LOG(INFO) << " Process " << pid << " exited with status "
<< WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
LOG(INFO) << " Process " << pid << " killed by signal "
<< WTERMSIG(status)
<< (WCOREDUMP(status) ? " (core dumped)" : "");
} else {
LOG(WARNING) << "Unknown exit status " << status << " for process "
<< pid;
}
// Remove this process from the our set of VMs.
vms_.erase(std::move(key));
}
}
void Service::HandleSigterm() {
LOG(INFO) << "Shutting down due to SIGTERM";
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
}
std::unique_ptr<dbus::Response> Service::StartVm(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received StartVm request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
StartVmRequest request;
StartVmResponse response;
// We change to a success status later if necessary.
response.set_status(VM_STATUS_FAILURE);
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse StartVmRequest from message";
response.set_failure_reason("Unable to parse protobuf");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Make sure the VM has a name.
if (request.name().empty()) {
LOG(ERROR) << "Ignoring request with empty name";
response.set_failure_reason("Missing VM name");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Make sure we have our signal connected if starting a Termina VM.
if (request.start_termina() && !is_tremplin_started_signal_connected_) {
LOG(ERROR) << "Can't start Termina VM without TremplinStartedSignal";
response.set_failure_reason("TremplinStartedSignal not connected");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
auto iter = FindVm(request.owner_id(), request.name());
if (iter != vms_.end()) {
LOG(INFO) << "VM with requested name is already running";
auto& vm = iter->second;
VmInfo* vm_info = response.mutable_vm_info();
vm_info->set_ipv4_address(vm->IPv4Address());
vm_info->set_pid(vm->pid());
vm_info->set_cid(vm->cid());
vm_info->set_seneschal_server_handle(vm->seneschal_server_handle());
response.set_success(true);
response.set_status(request.start_termina() && !vm->IsTremplinStarted()
? VM_STATUS_STARTING
: VM_STATUS_RUNNING);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (request.disks_size() > kMaxExtraDisks) {
LOG(ERROR) << "Rejecting request with " << request.disks_size()
<< " extra disks";
response.set_failure_reason("Too many extra disks");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
base::FilePath kernel, rootfs;
if (request.start_termina()) {
base::FilePath component_path = GetLatestVMPath();
if (component_path.empty()) {
LOG(ERROR) << "Termina component is not loaded";
response.set_failure_reason("Termina component is not loaded");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
kernel = component_path.Append(kVmKernelName);
rootfs = component_path.Append(kVmRootfsName);
} else {
kernel = base::FilePath(request.vm().kernel());
rootfs = base::FilePath(request.vm().rootfs());
}
if (!base::PathExists(kernel)) {
LOG(ERROR) << "Missing VM kernel path: " << kernel.value();
response.set_failure_reason("Kernel path does not exist");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (!base::PathExists(rootfs)) {
LOG(ERROR) << "Missing VM rootfs path: " << rootfs.value();
response.set_failure_reason("Rootfs path does not exist");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::vector<VirtualMachine::Disk> disks;
base::ScopedFD storage_fd;
// Check if an opened storage image was passed over D-BUS.
if (request.use_fd_for_storage()) {
if (!reader.PopFileDescriptor(&storage_fd)) {
LOG(ERROR) << "use_fd_for_storage is set but no fd found";
response.set_failure_reason("use_fd_for_storage is set but no fd found");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Clear close-on-exec as this FD needs to be passed to crosvm.
int raw_fd = storage_fd.get();
int flags = fcntl(raw_fd, F_GETFD);
if (flags == -1) {
LOG(ERROR) << "Failed to get flags for passed fd";
response.set_failure_reason("Failed to get flags for passed fd");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
flags &= ~FD_CLOEXEC;
if (fcntl(raw_fd, F_SETFD, flags) == -1) {
LOG(ERROR) << "Failed to clear close-on-exec flag for fd";
response.set_failure_reason("Failed to clear close-on-exec flag for fd");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
base::FilePath fd_path = base::FilePath(kProcFileDescriptorsPath)
.Append(base::IntToString(raw_fd));
disks.emplace_back(VirtualMachine::Disk{
.path = std::move(fd_path),
.writable = true,
});
}
for (const auto& disk : request.disks()) {
if (!base::PathExists(base::FilePath(disk.path()))) {
LOG(ERROR) << "Missing disk path: " << disk.path();
response.set_failure_reason("One or more disk paths do not exist");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
disks.emplace_back(VirtualMachine::Disk{
.path = base::FilePath(disk.path()),
.writable = disk.writable(),
});
}
// Create the runtime directory.
base::FilePath runtime_dir;
if (!base::CreateTemporaryDirInDir(base::FilePath(kRuntimeDir), "vm.",
&runtime_dir)) {
PLOG(ERROR) << "Unable to create runtime directory for VM";
response.set_failure_reason(
"Internal error: unable to create runtime directory");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Allocate resources for the VM.
MacAddress mac_address = mac_address_generator_.Generate();
std::unique_ptr<Subnet> subnet = subnet_pool_.AllocateVM();
if (!subnet) {
LOG(ERROR) << "No available subnets; unable to start VM";
response.set_failure_reason("No available subnets");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
uint32_t vsock_cid = vsock_cid_pool_.Allocate();
if (vsock_cid == 0) {
LOG(ERROR) << "Unable to allocate vsock context id";
response.set_failure_reason("Unable to allocate vsock cid");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
uint32_t seneschal_server_port = next_seneschal_server_port_++;
std::unique_ptr<SeneschalServerProxy> server_proxy =
SeneschalServerProxy::Create(seneschal_service_proxy_,
seneschal_server_port, vsock_cid);
if (!server_proxy) {
LOG(ERROR) << "Unable to start shared directory server";
response.set_failure_reason("Unable to start shared directory server");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
uint32_t seneschal_server_handle = server_proxy->handle();
// Associate a WaitableEvent with this VM. This needs to happen before
// starting the VM to avoid a race where the VM reports that it's ready
// before it gets added as a pending VM.
base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
startup_listener_.AddPendingVm(vsock_cid, &event);
// Start the VM and build the response.
auto vm = VirtualMachine::Create(
std::move(kernel), std::move(rootfs), std::move(disks),
std::move(mac_address), std::move(subnet), vsock_cid,
std::move(server_proxy), std::move(runtime_dir));
if (!vm) {
LOG(ERROR) << "Unable to start VM";
startup_listener_.RemovePendingVm(vsock_cid);
response.set_failure_reason("Unable to start VM");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Wait for the VM to finish starting up and for maitre'd to signal that it's
// ready.
if (!event.TimedWait(kVmStartupTimeout)) {
LOG(ERROR) << "VM failed to start in " << kVmStartupTimeout.InSeconds()
<< " seconds";
startup_listener_.RemovePendingVm(vsock_cid);
response.set_failure_reason("VM failed to start in time");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// maitre'd is ready. Finish setting up the VM.
if (!vm->ConfigureNetwork(nameservers_, search_domains_)) {
LOG(ERROR) << "Failed to configure VM network";
response.set_failure_reason("Failed to configure VM network");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Do all the mounts. Assume that the rootfs filesystem was assigned
// /dev/vda and that every subsequent image was assigned a letter in
// alphabetical order starting from 'b'.
unsigned char disk_letter = 'b';
unsigned char offset = 0;
for (const auto& disk : request.disks()) {
string src = base::StringPrintf("/dev/vd%c", disk_letter + offset);
++offset;
if (!disk.do_mount())
continue;
uint64_t flags = disk.flags();
if (!disk.writable()) {
flags |= MS_RDONLY;
}
if (!vm->Mount(std::move(src), disk.mount_point(), disk.fstype(), flags,
disk.data())) {
LOG(ERROR) << "Failed to mount " << disk.path() << " -> "
<< disk.mount_point();
response.set_failure_reason("Failed to mount extra disk");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
}
// Mount the 9p server.
if (!vm->Mount9P(seneschal_server_port, "/mnt/shared")) {
LOG(ERROR) << "Failed to mount " << request.shared_directory();
response.set_failure_reason("Failed to mount shared directory");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Notify cicerone that we have started a VM.
NotifyCiceroneOfVmStarted(request.owner_id(), request.name(),
vm->ContainerSubnet(), vm->ContainerNetmask(),
vm->IPv4Address(), vm->cid());
string failure_reason;
if (request.start_termina() && !StartTermina(vm.get(), &failure_reason)) {
response.set_failure_reason(std::move(failure_reason));
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
LOG(INFO) << "Started VM with pid " << vm->pid();
VmInfo* vm_info = response.mutable_vm_info();
response.set_success(true);
response.set_status(request.start_termina() ? VM_STATUS_STARTING
: VM_STATUS_RUNNING);
vm_info->set_ipv4_address(vm->IPv4Address());
vm_info->set_pid(vm->pid());
vm_info->set_cid(vsock_cid);
vm_info->set_seneschal_server_handle(seneschal_server_handle);
writer.AppendProtoAsArrayOfBytes(response);
vms_[std::make_pair(request.owner_id(), request.name())] = std::move(vm);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::StopVm(dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received StopVm request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
StopVmRequest request;
StopVmResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse StopVmRequest from message";
response.set_failure_reason("Unable to parse protobuf");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
auto iter = FindVm(request.owner_id(), request.name());
if (iter == vms_.end()) {
LOG(ERROR) << "Requested VM does not exist";
// This is not an error to Chrome
response.set_success(true);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (!iter->second->Shutdown()) {
LOG(ERROR) << "Unable to shut down VM";
response.set_failure_reason("Unable to shut down VM");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Notify cicerone that we have stopped a VM.
NotifyCiceroneOfVmStopped(request.owner_id(), request.name());
vms_.erase(iter);
response.set_success(true);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::StopAllVms(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received StopAllVms request";
// Spawn a thread for each VM to shut it down.
for (auto& iter : vms_) {
// Notify cicerone that we have stopped a VM.
NotifyCiceroneOfVmStopped(iter.first.first, iter.first.second);
// Resetting the unique_ptr will call the destructor for that VM, which
// will shut it down.
iter.second.reset();
}
vms_.clear();
return nullptr;
}
std::unique_ptr<dbus::Response> Service::GetVmInfo(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received GetVmInfo request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
GetVmInfoRequest request;
GetVmInfoResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse GetVmInfoRequest from message";
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
auto iter = FindVm(request.owner_id(), request.name());
if (iter == vms_.end()) {
LOG(ERROR) << "Requested VM does not exist";
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
auto& vm = iter->second;
VmInfo* vm_info = response.mutable_vm_info();
vm_info->set_ipv4_address(vm->IPv4Address());
vm_info->set_pid(vm->pid());
vm_info->set_cid(vm->cid());
vm_info->set_seneschal_server_handle(vm->seneschal_server_handle());
response.set_success(true);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::SyncVmTimes(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received SyncVmTimes request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageWriter writer(dbus_response.get());
SyncVmTimesResponse response = SyncVmTimesInternal();
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
SyncVmTimesResponse Service::SyncVmTimesInternal() {
SyncVmTimesResponse response;
int failures = 0;
int requests = 0;
for (const auto& iter : vms_) {
requests++;
grpc::Status s = iter.second->SetTime();
if (!s.ok()) {
failures++;
string* tmp = response.add_failure_reason();
*tmp = s.error_message();
}
}
response.set_requests(requests);
response.set_failures(failures);
return response;
}
bool Service::StartTermina(VirtualMachine* vm, string* failure_reason) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Starting lxd";
// Allocate the subnet for lxd's bridge to use.
std::unique_ptr<Subnet> container_subnet = subnet_pool_.AllocateContainer();
if (!container_subnet) {
LOG(ERROR) << "Could not allocate container subnet";
*failure_reason = "could not allocate container subnet";
return false;
}
vm->SetContainerSubnet(std::move(container_subnet));
// Set up a route for the container using the VM as a gateway.
uint32_t container_gateway_addr = vm->IPv4Address();
uint32_t container_netmask = vm->ContainerNetmask();
uint32_t container_subnet_addr = vm->ContainerSubnet();
struct rtentry route;
memset(&route, 0, sizeof(route));
struct sockaddr_in* gateway =
reinterpret_cast<struct sockaddr_in*>(&route.rt_gateway);
gateway->sin_family = AF_INET;
gateway->sin_addr.s_addr = static_cast<in_addr_t>(container_gateway_addr);
struct sockaddr_in* dst =
reinterpret_cast<struct sockaddr_in*>(&route.rt_dst);
dst->sin_family = AF_INET;
dst->sin_addr.s_addr = (container_subnet_addr & container_netmask);
struct sockaddr_in* genmask =
reinterpret_cast<struct sockaddr_in*>(&route.rt_genmask);
genmask->sin_family = AF_INET;
genmask->sin_addr.s_addr = container_netmask;
route.rt_flags = RTF_UP | RTF_GATEWAY;
base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
if (!fd.is_valid()) {
PLOG(ERROR) << "Failed to create socket";
*failure_reason = "failed to create socket";
return false;
}
if (HANDLE_EINTR(ioctl(fd.get(), SIOCADDRT, &route)) != 0) {
PLOG(ERROR) << "Failed to set route for container";
*failure_reason = "failed to set route for container";
return false;
}
std::string dst_addr;
IPv4AddressToString(container_subnet_addr, &dst_addr);
size_t prefix = vm->ContainerPrefix();
std::string container_subnet_cidr =
base::StringPrintf("%s/%zu", dst_addr.c_str(), prefix);
string error;
if (!vm->StartTermina(std::move(container_subnet_cidr), &error)) {
failure_reason->assign(error);
return false;
}
return true;
}
std::unique_ptr<dbus::Response> Service::CreateDiskImage(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received CreateDiskImage request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
CreateDiskImageRequest request;
CreateDiskImageResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse CreateDiskImageRequest from message";
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Unable to parse CreateImageDiskRequest");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
base::FilePath disk_path;
if (!GetDiskPathFromName(request.disk_path(), request.cryptohome_id(),
request.storage_location(),
true, /* create_parent_dir */
&disk_path, request.image_type())) {
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to create vm image");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (base::PathExists(disk_path)) {
response.set_status(DISK_STATUS_EXISTS);
response.set_disk_path(disk_path.value());
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (request.image_type() == DISK_IMAGE_RAW ||
request.image_type() == DISK_IMAGE_AUTO) {
LOG(INFO) << "Creating raw disk at: " << disk_path.value() << " size "
<< request.disk_size();
base::ScopedFD fd(
open(disk_path.value().c_str(), O_CREAT | O_NONBLOCK | O_WRONLY, 0600));
if (!fd.is_valid()) {
PLOG(ERROR) << "Failed to create raw disk";
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to create raw disk file");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
int ret = ftruncate(fd.get(), request.disk_size());
if (ret != 0) {
PLOG(ERROR) << "Failed to truncate raw disk";
unlink(disk_path.value().c_str());
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to truncate raw disk file");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// If a raw disk was explicitly requested, return early without checking
// for FALLOC_FL_PUNCH_HOLE support.
if (request.image_type() == DISK_IMAGE_RAW) {
response.set_status(DISK_STATUS_CREATED);
response.set_disk_path(disk_path.value());
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
ret = fallocate(fd.get(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
request.disk_size());
if (ret == 0) {
LOG(INFO) << "fallocate(FALLOC_FL_PUNCH_HOLE) is supported";
response.set_status(DISK_STATUS_CREATED);
response.set_disk_path(disk_path.value());
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// If hole punch is not available and the type is DISK_IMAGE_AUTO,
// try to create a qcow2 file instead.
LOG(INFO) << "fallocate(FALLOC_FL_PUNCH_HOLE) not supported for raw file: "
<< strerror(errno);
unlink(disk_path.value().c_str());
if (!GetDiskPathFromName(request.disk_path(), request.cryptohome_id(),
request.storage_location(),
true, /* create_parent_dir */
&disk_path, DISK_IMAGE_QCOW2)) {
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to create vm image");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
}
LOG(INFO) << "Creating qcow2 disk at: " << disk_path.value() << " size "
<< request.disk_size();
int ret =
create_qcow_with_size(disk_path.value().c_str(), request.disk_size());
if (ret != 0) {
LOG(ERROR) << "Failed to create qcow2 disk image: " << strerror(ret);
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to create qcow2 disk image");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
response.set_disk_path(disk_path.value());
response.set_status(DISK_STATUS_CREATED);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::DestroyDiskImage(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received DestroyDiskImage request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
DestroyDiskImageRequest request;
DestroyDiskImageResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse DestroyDiskImageRequest from message";
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Unable to parse DestroyDiskRequest");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Stop the associated VM if it is still running.
auto iter = FindVm(request.cryptohome_id(), request.disk_path());
if (iter != vms_.end()) {
LOG(INFO) << "Shutting down VM";
if (!iter->second->Shutdown()) {
LOG(ERROR) << "Unable to shut down VM";
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Unable to shut down VM");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Notify cicerone that we have stopped a VM.
NotifyCiceroneOfVmStopped(request.cryptohome_id(), request.disk_path());
vms_.erase(iter);
}
base::FilePath disk_path;
if (!GetDiskPathFromName(request.disk_path(), request.cryptohome_id(),
request.storage_location(),
false, /* create_parent_dir */
&disk_path)) {
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Failed to delete vm image");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (!EraseGuestSshKeys(request.cryptohome_id(), request.disk_path())) {
// Don't return a failure here, just log an error because this is only a
// side effect and not what the real request is about.
LOG(ERROR) << "Failed removing guest SSH keys for VM "
<< request.disk_path();
}
if (!base::PathExists(disk_path)) {
response.set_status(DISK_STATUS_DOES_NOT_EXIST);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (!base::DeleteFile(disk_path, false)) {
response.set_status(DISK_STATUS_FAILED);
response.set_failure_reason("Disk removal failed");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
response.set_status(DISK_STATUS_DESTROYED);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::ExportDiskImage(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received ExportDiskImage request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
ExportDiskImageResponse response;
response.set_status(DISK_STATUS_FAILED);
ExportDiskImageRequest request;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse ExportDiskImageRequest from message";
response.set_failure_reason("Unable to parse ExportDiskRequest");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
base::FilePath disk_path;
if (!GetDiskPathFromName(request.disk_path(), request.cryptohome_id(),
STORAGE_CRYPTOHOME_ROOT,
false, /* create_parent_dir */
&disk_path)) {
response.set_failure_reason("Failed to delete vm image");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (!base::PathExists(disk_path)) {
response.set_status(DISK_STATUS_DOES_NOT_EXIST);
response.set_failure_reason("Export image doesn't exist");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
base::ScopedFD disk_fd(HANDLE_EINTR(
open(disk_path.value().c_str(), O_RDWR | O_NOFOLLOW | O_CLOEXEC)));
if (!disk_fd.is_valid()) {
LOG(ERROR) << "Failed opening VM disk for export";
response.set_failure_reason("Failed opening VM disk for export");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
// Get the FD to fill with disk image data.
base::ScopedFD storage_fd;
if (!reader.PopFileDescriptor(&storage_fd)) {
LOG(ERROR) << "export: no fd found";
response.set_failure_reason("export: no fd found");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
int convert_res = convert_to_qcow2(disk_fd.get(), storage_fd.get());
if (convert_res < 0) {
response.set_failure_reason("convert_to_qcow2 failed");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
response.set_status(DISK_STATUS_CREATED);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::ListVmDisks(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
ListVmDisksRequest request;
ListVmDisksResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse ListVmDisksRequest from message";
response.set_success(false);
response.set_failure_reason("Unable to parse ListVmDisksRequest");
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
response.set_success(true);
base::FilePath image_dir;
if (request.storage_location() == STORAGE_CRYPTOHOME_ROOT) {
image_dir = base::FilePath(kCryptohomeRoot)
.Append(request.cryptohome_id())
.Append(kCrosvmDir);
} else if (request.storage_location() == STORAGE_CRYPTOHOME_DOWNLOADS) {
image_dir = base::FilePath(kCryptohomeUser)
.Append(request.cryptohome_id())
.Append(kDownloadsDir);
}
if (!base::DirectoryExists(image_dir)) {
// No directory means no VMs, return the empty response.
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
uint64_t total_size = 0;
// Returns disk images in the given storage area.
for (const auto& pattern : kDiskImagePatterns) {
base::FileEnumerator dir_enum(image_dir, false, base::FileEnumerator::FILES,
pattern);
for (base::FilePath path = dir_enum.Next(); !path.empty();
path = dir_enum.Next()) {
base::FilePath bare_name = path.BaseName().RemoveExtension();
if (bare_name.empty()) {
continue;
}
std::string image_name;
if (!base::Base64UrlDecode(bare_name.value(),
base::Base64UrlDecodePolicy::IGNORE_PADDING,
&image_name)) {
continue;
}
std::string* name = response.add_images();
*name = std::move(image_name);
struct stat st;
if (stat(path.value().c_str(), &st) == 0) {
total_size += st.st_blocks * 512;
}
}
}
response.set_total_size(total_size);
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::unique_ptr<dbus::Response> Service::GetContainerSshKeys(
dbus::MethodCall* method_call) {
DCHECK(sequence_checker_.CalledOnValidSequence());
LOG(INFO) << "Received GetContainerSshKeys request";
std::unique_ptr<dbus::Response> dbus_response(
dbus::Response::FromMethodCall(method_call));
dbus::MessageReader reader(method_call);
dbus::MessageWriter writer(dbus_response.get());
ContainerSshKeysRequest request;
ContainerSshKeysResponse response;
if (!reader.PopArrayOfBytesAsProto(&request)) {
LOG(ERROR) << "Unable to parse ContainerSshKeysRequest from message";
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
if (request.cryptohome_id().empty()) {
LOG(ERROR) << "Cryptohome ID is not set in ContainerSshKeysRequest";
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
auto iter = FindVm(request.cryptohome_id(), request.vm_name());
if (iter == vms_.end()) {
LOG(ERROR) << "Requested VM does not exist:" << request.vm_name();
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
std::string container_name = request.container_name().empty()
? kDefaultContainerName
: request.container_name();
response.set_container_public_key(GetGuestSshPublicKey(
request.cryptohome_id(), request.vm_name(), container_name));
response.set_container_private_key(GetGuestSshPrivateKey(
request.cryptohome_id(), request.vm_name(), container_name));
response.set_host_public_key(GetHostSshPublicKey(request.cryptohome_id()));
response.set_host_private_key(GetHostSshPrivateKey(request.cryptohome_id()));
response.set_hostname(base::StringPrintf(
"%s.%s.linux.test", container_name.c_str(), request.vm_name().c_str()));
writer.AppendProtoAsArrayOfBytes(response);
return dbus_response;
}
void Service::OnResolvConfigChanged(std::vector<string> nameservers,
std::vector<string> search_domains) {
nameservers_ = std::move(nameservers);
search_domains_ = std::move(search_domains);
for (auto& iter : vms_) {
iter.second->SetResolvConfig(nameservers_, search_domains_);
}
}
void Service::NotifyCiceroneOfVmStarted(const std::string& owner_id,
const std::string& vm_name,
uint32_t container_subnet,
uint32_t container_netmask,
uint32_t ipv4_address,
uint32_t cid) {
DCHECK(sequence_checker_.CalledOnValidSequence());
dbus::MethodCall method_call(vm_tools::cicerone::kVmCiceroneInterface,
vm_tools::cicerone::kNotifyVmStartedMethod);
dbus::MessageWriter writer(&method_call);
vm_tools::cicerone::NotifyVmStartedRequest request;
request.set_owner_id(owner_id);
request.set_vm_name(vm_name);
request.set_container_ipv4_subnet(container_subnet);
request.set_container_ipv4_netmask(container_netmask);
request.set_ipv4_address(ipv4_address);
request.set_cid(cid);
writer.AppendProtoAsArrayOfBytes(request);
std::unique_ptr<dbus::Response> dbus_response =
cicerone_service_proxy_->CallMethodAndBlock(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
if (!dbus_response) {
LOG(ERROR) << "Failed notifying cicerone of VM startup";
}
}
void Service::NotifyCiceroneOfVmStopped(const std::string& owner_id,
const std::string& vm_name) {
DCHECK(sequence_checker_.CalledOnValidSequence());
dbus::MethodCall method_call(vm_tools::cicerone::kVmCiceroneInterface,
vm_tools::cicerone::kNotifyVmStoppedMethod);
dbus::MessageWriter writer(&method_call);
vm_tools::cicerone::NotifyVmStoppedRequest request;
request.set_owner_id(owner_id);
request.set_vm_name(vm_name);
writer.AppendProtoAsArrayOfBytes(request);
std::unique_ptr<dbus::Response> dbus_response =
cicerone_service_proxy_->CallMethodAndBlock(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
if (!dbus_response) {
LOG(ERROR) << "Failed notifying cicerone of VM stopped";
}
}
std::string Service::GetContainerToken(const std::string& owner_id,
const std::string& vm_name,
const std::string& container_name) {
DCHECK(sequence_checker_.CalledOnValidSequence());
dbus::MethodCall method_call(vm_tools::cicerone::kVmCiceroneInterface,
vm_tools::cicerone::kGetContainerTokenMethod);
dbus::MessageWriter writer(&method_call);
vm_tools::cicerone::ContainerTokenRequest request;
vm_tools::cicerone::ContainerTokenResponse response;
request.set_owner_id(owner_id);
request.set_vm_name(vm_name);
request.set_container_name(container_name);
writer.AppendProtoAsArrayOfBytes(request);
std::unique_ptr<dbus::Response> dbus_response =
cicerone_service_proxy_->CallMethodAndBlock(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
if (!dbus_response) {
LOG(ERROR) << "Failed getting container token from cicerone";
return "";
}
dbus::MessageReader reader(dbus_response.get());
if (!reader.PopArrayOfBytesAsProto(&response)) {
LOG(ERROR) << "Failed parsing proto response";
return "";
}
return response.container_token();
}
void Service::OnTremplinStartedSignal(dbus::Signal* signal) {
DCHECK_EQ(signal->GetInterface(), vm_tools::cicerone::kVmCiceroneInterface);
DCHECK_EQ(signal->GetMember(), vm_tools::cicerone::kTremplinStartedSignal);
vm_tools::cicerone::TremplinStartedSignal tremplin_started_signal;
dbus::MessageReader reader(signal);
if (!reader.PopArrayOfBytesAsProto(&tremplin_started_signal)) {
LOG(ERROR) << "Failed to parse TremplinStartedSignal from DBus Signal";
return;
}
auto iter = FindVm(tremplin_started_signal.owner_id(),
tremplin_started_signal.vm_name());
if (iter == vms_.end()) {
LOG(ERROR) << "Received signal from an unknown vm.";
return;
}
LOG(INFO) << "Received TremplinStartedSignal for owner: "
<< tremplin_started_signal.owner_id()
<< ", vm: " << tremplin_started_signal.vm_name();
iter->second->SetTremplinStarted();
}
void Service::OnSignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool is_connected) {
if (!is_connected) {
LOG(ERROR) << "Failed to connect to interface name: " << interface_name
<< " for signal " << signal_name;
} else {
LOG(INFO) << "Connected to interface name: " << interface_name
<< " for signal " << signal_name;
}
if (interface_name == vm_tools::cicerone::kVmCiceroneInterface) {
DCHECK_EQ(signal_name, vm_tools::cicerone::kTremplinStartedSignal);
is_tremplin_started_signal_connected_ = is_connected;
}
}
void Service::OnSuspendDone(dbus::Signal* signal) {
SyncVmTimesResponse response = SyncVmTimesInternal();
if (response.failures() != 0) {
LOG(ERROR) << "Failed to set " << response.failures() << " out of "
<< response.requests() << " VM clocks:";
for (const string& error : response.failure_reason()) {
LOG(ERROR) << error;
}
} else {
LOG(INFO) << "Successfully set " << response.requests() << " VM clocks.";
}
}
Service::VmMap::iterator Service::FindVm(std::string owner_id,
std::string vm_name) {
auto it = vms_.find(std::make_pair(owner_id, vm_name));
// TODO(nverne): remove this fallback when Chrome is correctly seting owner_id
if (it == vms_.end()) {
return vms_.find(std::make_pair("", vm_name));
}
return it;
}
} // namespace concierge
} // namespace vm_tools
| 34.45539 | 80 | 0.685458 | [
"object",
"vector"
] |
4b5f72ac57fd6ec36d16182acb6b7ed96d03b9c6 | 5,755 | cc | C++ | alidns/src/model/DescribeDnsProductInstancesResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | alidns/src/model/DescribeDnsProductInstancesResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | alidns/src/model/DescribeDnsProductInstancesResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/alidns/model/DescribeDnsProductInstancesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Alidns;
using namespace AlibabaCloud::Alidns::Model;
DescribeDnsProductInstancesResult::DescribeDnsProductInstancesResult() :
ServiceResult()
{}
DescribeDnsProductInstancesResult::DescribeDnsProductInstancesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDnsProductInstancesResult::~DescribeDnsProductInstancesResult()
{}
void DescribeDnsProductInstancesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allDnsProducts = value["DnsProducts"]["DnsProduct"];
for (auto value : allDnsProducts)
{
DnsProduct dnsProductsObject;
if(!value["InstanceId"].isNull())
dnsProductsObject.instanceId = value["InstanceId"].asString();
if(!value["VersionCode"].isNull())
dnsProductsObject.versionCode = value["VersionCode"].asString();
if(!value["VersionName"].isNull())
dnsProductsObject.versionName = value["VersionName"].asString();
if(!value["StartTime"].isNull())
dnsProductsObject.startTime = value["StartTime"].asString();
if(!value["EndTime"].isNull())
dnsProductsObject.endTime = value["EndTime"].asString();
if(!value["StartTimestamp"].isNull())
dnsProductsObject.startTimestamp = std::stol(value["StartTimestamp"].asString());
if(!value["EndTimestamp"].isNull())
dnsProductsObject.endTimestamp = std::stol(value["EndTimestamp"].asString());
if(!value["Domain"].isNull())
dnsProductsObject.domain = value["Domain"].asString();
if(!value["BindCount"].isNull())
dnsProductsObject.bindCount = std::stol(value["BindCount"].asString());
if(!value["BindUsedCount"].isNull())
dnsProductsObject.bindUsedCount = std::stol(value["BindUsedCount"].asString());
if(!value["TTLMinValue"].isNull())
dnsProductsObject.tTLMinValue = std::stol(value["TTLMinValue"].asString());
if(!value["SubDomainLevel"].isNull())
dnsProductsObject.subDomainLevel = std::stol(value["SubDomainLevel"].asString());
if(!value["DnsSLBCount"].isNull())
dnsProductsObject.dnsSLBCount = std::stol(value["DnsSLBCount"].asString());
if(!value["URLForwardCount"].isNull())
dnsProductsObject.uRLForwardCount = std::stol(value["URLForwardCount"].asString());
if(!value["DDosDefendFlow"].isNull())
dnsProductsObject.dDosDefendFlow = std::stol(value["DDosDefendFlow"].asString());
if(!value["DDosDefendQuery"].isNull())
dnsProductsObject.dDosDefendQuery = std::stol(value["DDosDefendQuery"].asString());
if(!value["OverseaDDosDefendFlow"].isNull())
dnsProductsObject.overseaDDosDefendFlow = std::stol(value["OverseaDDosDefendFlow"].asString());
if(!value["SearchEngineLines"].isNull())
dnsProductsObject.searchEngineLines = value["SearchEngineLines"].asString();
if(!value["ISPLines"].isNull())
dnsProductsObject.iSPLines = value["ISPLines"].asString();
if(!value["ISPRegionLines"].isNull())
dnsProductsObject.iSPRegionLines = value["ISPRegionLines"].asString();
if(!value["OverseaLine"].isNull())
dnsProductsObject.overseaLine = value["OverseaLine"].asString();
if(!value["MonitorNodeCount"].isNull())
dnsProductsObject.monitorNodeCount = std::stol(value["MonitorNodeCount"].asString());
if(!value["MonitorFrequency"].isNull())
dnsProductsObject.monitorFrequency = std::stol(value["MonitorFrequency"].asString());
if(!value["MonitorTaskCount"].isNull())
dnsProductsObject.monitorTaskCount = std::stol(value["MonitorTaskCount"].asString());
if(!value["RegionLines"].isNull())
dnsProductsObject.regionLines = value["RegionLines"].asString() == "true";
if(!value["Gslb"].isNull())
dnsProductsObject.gslb = value["Gslb"].asString() == "true";
if(!value["InClean"].isNull())
dnsProductsObject.inClean = value["InClean"].asString() == "true";
if(!value["InBlackHole"].isNull())
dnsProductsObject.inBlackHole = value["InBlackHole"].asString() == "true";
if(!value["BindDomainCount"].isNull())
dnsProductsObject.bindDomainCount = std::stol(value["BindDomainCount"].asString());
if(!value["BindDomainUsedCount"].isNull())
dnsProductsObject.bindDomainUsedCount = std::stol(value["BindDomainUsedCount"].asString());
if(!value["DnsSecurity"].isNull())
dnsProductsObject.dnsSecurity = value["DnsSecurity"].asString();
dnsProducts_.push_back(dnsProductsObject);
}
if(!value["TotalCount"].isNull())
totalCount_ = std::stol(value["TotalCount"].asString());
if(!value["PageNumber"].isNull())
pageNumber_ = std::stol(value["PageNumber"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stol(value["PageSize"].asString());
}
long DescribeDnsProductInstancesResult::getTotalCount()const
{
return totalCount_;
}
long DescribeDnsProductInstancesResult::getPageSize()const
{
return pageSize_;
}
long DescribeDnsProductInstancesResult::getPageNumber()const
{
return pageNumber_;
}
std::vector<DescribeDnsProductInstancesResult::DnsProduct> DescribeDnsProductInstancesResult::getDnsProducts()const
{
return dnsProducts_;
}
| 41.107143 | 115 | 0.742137 | [
"vector",
"model"
] |
4b64da5547e3a1aa8aa15042a330d49b485db9ea | 4,365 | cpp | C++ | Sources/Apps/Source/TodoList/TodoListDBHelper.cpp | ierturk/qt-qml-ai-collection | ccabe3bee3e3659ef88ea1195cc7a7836118672b | [
"MIT"
] | null | null | null | Sources/Apps/Source/TodoList/TodoListDBHelper.cpp | ierturk/qt-qml-ai-collection | ccabe3bee3e3659ef88ea1195cc7a7836118672b | [
"MIT"
] | 1 | 2021-12-30T17:15:28.000Z | 2021-12-30T17:15:28.000Z | Sources/Apps/Source/TodoList/TodoListDBHelper.cpp | ierturk/qt-qml-ai-collection | ccabe3bee3e3659ef88ea1195cc7a7836118672b | [
"MIT"
] | null | null | null | #include <QSqlQuery>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QtDebug>
#include "TodoListDBHelper.h"
TodoListDBHelper::TodoListDBHelper() {
ConnectToDb();
}
void TodoListDBHelper::ConnectToDb()
{
if (QSqlDatabase::contains(connectionName))
{
db = QSqlDatabase::database(connectionName);
}
else
{
db = QSqlDatabase::addDatabase("QSQLITE");
}
db.setDatabaseName(connectionString);
if (!db.open()) {
qDebug() << "Error: connection with database failed";
return;
} else {
qDebug() << "Database: connection opened";
}
// Init
QSqlQuery query(db);
if (!db.tables().contains( QLatin1String("todo_list"))) {
bool created = query.exec("CREATE TABLE IF NOT EXISTS todo_list ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"description VARCHAR (320), "
"isdeleted BOOLEAN DEFAULT (0), "
"done BOOLEAN DEFAULT (0), "
"addedtime TIMESTAMP DEFAULT NULL)");
qDebug() << "Database: inititialized." << created;
if(!query.exec("INSERT INTO todo_list(description) VALUES('Wake up')"))
qWarning() << "MainWindow::DatabasePopulate - ERROR: " << query.lastError().text();
if(!query.exec("INSERT INTO todo_list(description) VALUES('Have breakfast')"))
qWarning() << "MainWindow::DatabasePopulate - ERROR: " << query.lastError().text();
}
}
TodoListDBHelper::~TodoListDBHelper()
{
if (db.isOpen())
{
db.close();
qDebug() << "Database: connection closed";
removeDb(connectionName);
}
}
bool TodoListDBHelper::isOpen() const
{
return db.isOpen();
}
void TodoListDBHelper::removeDb(const QString &conName)
{
QSqlDatabase::removeDatabase(conName);
qDebug() << "Database: connection removed";
}
QSqlQueryModel* TodoListDBHelper::getRecords() const
{
QSqlQueryModel* model = new QSqlQueryModel;
QString q = "SELECT id, done, description FROM todo_list WHERE isdeleted = 0";
model->setQuery(q);
return model;
}
bool TodoListDBHelper::updateRecords(const TodoItem &item)
{
bool success = false;
if (!item.description.isEmpty())
{
QSqlQuery query(db);
QString strQuery = "UPDATE todo_list SET done = :done, description = :description, addedtime = datetime(CURRENT_TIMESTAMP, 'localtime') "
"WHERE id = :id";
query.prepare(strQuery);
query.bindValue(":done", QString::number(item.done));
query.bindValue(":description", item.description);
query.bindValue(":id", item.id);
if (!query.exec())
{
qDebug() << query.lastError();
}
else
{
success = true;
qDebug() << "Updated: id#" << item.id;
}
}
else
{
qDebug() << "Update failed: description cannot be empty";
}
return success;
}
bool TodoListDBHelper::insertRecords(const TodoItem& item)
{
bool success = false;
if (!item.description.isEmpty())
{
QSqlQuery queryAdd;
queryAdd.prepare("INSERT INTO todo_list(done, description, addedtime) "
"VALUES (:done, :description, datetime(CURRENT_TIMESTAMP, 'localtime'))");
queryAdd.bindValue(":done", item.done);
queryAdd.bindValue(":description", item.description);
if (queryAdd.exec())
{
success = true;
qDebug() << "Inserted!";
}
else
{
qDebug() << "Insertion failed: " << queryAdd.lastError();
}
}
else
{
qDebug() << "Insertion failed: description cannot be empty";
}
return success;
}
bool TodoListDBHelper::deleteRecordByID(const quint32 itemId)
{
bool success = false;
QSqlQuery query(db);
QString strQuery = "UPDATE todo_list SET isdeleted = 1, addedtime = datetime(CURRENT_TIMESTAMP, 'localtime') "
"WHERE id = :id";
query.prepare(strQuery);
query.bindValue(":id", itemId);
if (!query.exec())
{
qDebug() << query.lastError();
}
else
{
success = true;
qDebug() << "Deleted: id#" << itemId;
}
return success;
} | 25.676471 | 145 | 0.576861 | [
"model"
] |
4b64f64f35290738b445ce2dc93048c33476eaf1 | 50,292 | cpp | C++ | exiv2-0.24/src/crwimage.cpp | sdrpa/Exiv2Framework | 76b2dd9a906ab08d39bf97c8f3d97037eb39c69d | [
"MIT"
] | 6 | 2016-10-04T10:12:11.000Z | 2021-09-18T22:37:29.000Z | exiv2-0.24/src/crwimage.cpp | sdrpa/Exiv2Framework | 76b2dd9a906ab08d39bf97c8f3d97037eb39c69d | [
"MIT"
] | null | null | null | exiv2-0.24/src/crwimage.cpp | sdrpa/Exiv2Framework | 76b2dd9a906ab08d39bf97c8f3d97037eb39c69d | [
"MIT"
] | 2 | 2018-05-20T08:32:40.000Z | 2019-07-06T18:27:19.000Z | // ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2013 Andreas Huggel <ahuggel@gmx.net>
*
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
File: crwimage.cpp
Version: $Rev: 3091 $
Author(s): Andreas Huggel (ahu) <ahuggel@gmx.net>
History: 28-Aug-05, ahu: created
*/
// *****************************************************************************
#include "rcsid_int.hpp"
EXIV2_RCSID("@(#) $Id: crwimage.cpp 3091 2013-07-24 05:15:04Z robinwmills $")
// Define DEBUG to output debug information to std::cerr, e.g, by calling make
// like this: make DEFS=-DDEBUG crwimage.o
//#define DEBUG 1
// *****************************************************************************
// included header files
#ifdef _MSC_VER
# include "exv_msvc.h"
#else
# include "exv_conf.h"
#endif
#include "crwimage.hpp"
#include "crwimage_int.hpp"
#include "error.hpp"
#include "futils.hpp"
#include "value.hpp"
#include "tags.hpp"
#include "tags_int.hpp"
#include "canonmn_int.hpp"
#include "i18n.h" // NLS support.
// + standard includes
#include <iostream>
#include <iomanip>
#include <stack>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <cassert>
#ifndef EXV_HAVE_TIMEGM
# include "timegm.h"
#endif
// *****************************************************************************
// local declarations
namespace {
//! Helper class to map Exif orientation values to CRW rotation degrees
class RotationMap {
public:
//! Get the orientation number for a degree value
static uint16_t orientation(int32_t degrees);
//! Get the degree value for an orientation number
static int32_t degrees(uint16_t orientation);
private:
//! Helper structure for the mapping list
struct OmList {
uint16_t orientation; //!< Exif orientation value
int32_t degrees; //!< CRW Rotation degrees
};
// DATA
static const OmList omList_[];
}; // class RotationMap
}
// *****************************************************************************
// class member definitions
namespace Exiv2 {
using namespace Internal;
CrwImage::CrwImage(BasicIo::AutoPtr io, bool /*create*/)
: Image(ImageType::crw, mdExif | mdComment, io)
{
} // CrwImage::CrwImage
std::string CrwImage::mimeType() const
{
return "image/x-canon-crw";
}
int CrwImage::pixelWidth() const
{
Exiv2::ExifData::const_iterator widthIter = exifData_.findKey(Exiv2::ExifKey("Exif.Photo.PixelXDimension"));
if (widthIter != exifData_.end() && widthIter->count() > 0) {
return widthIter->toLong();
}
return 0;
}
int CrwImage::pixelHeight() const
{
Exiv2::ExifData::const_iterator heightIter = exifData_.findKey(Exiv2::ExifKey("Exif.Photo.PixelYDimension"));
if (heightIter != exifData_.end() && heightIter->count() > 0) {
return heightIter->toLong();
}
return 0;
}
void CrwImage::setIptcData(const IptcData& /*iptcData*/)
{
// not supported
throw(Error(32, "IPTC metadata", "CRW"));
}
void CrwImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Reading CRW file " << io_->path() << "\n";
#endif
if (io_->open() != 0) {
throw Error(9, io_->path(), strError());
}
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isCrwType(*io_, false)) {
if (io_->error() || io_->eof()) throw Error(14);
throw Error(33);
}
clearMetadata();
CrwParser::decode(this, io_->mmap(), io_->size());
} // CrwImage::readMetadata
void CrwImage::writeMetadata()
{
#ifdef DEBUG
std::cerr << "Writing CRW file " << io_->path() << "\n";
#endif
// Read existing image
DataBuf buf;
if (io_->open() == 0) {
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (isCrwType(*io_, false)) {
// Read the image into a memory buffer
buf.alloc(io_->size());
io_->read(buf.pData_, buf.size_);
if (io_->error() || io_->eof()) {
buf.reset();
}
}
}
Blob blob;
CrwParser::encode(blob, buf.pData_, buf.size_, this);
// Write new buffer to file
BasicIo::AutoPtr tempIo(io_->temporary()); // may throw
assert(tempIo.get() != 0);
tempIo->write((blob.size() > 0 ? &blob[0] : 0), static_cast<long>(blob.size()));
io_->close();
io_->transfer(*tempIo); // may throw
} // CrwImage::writeMetadata
void CrwParser::decode(CrwImage* pCrwImage, const byte* pData, uint32_t size)
{
assert(pCrwImage != 0);
assert(pData != 0);
// Parse the image, starting with a CIFF header component
CiffHeader::AutoPtr head(new CiffHeader);
head->read(pData, size);
#ifdef DEBUG
head->print(std::cerr);
#endif
head->decode(*pCrwImage);
// a hack to get absolute offset of preview image inside CRW structure
CiffComponent* preview = head->findComponent(0x2007, 0x0000);
if (preview) {
(pCrwImage->exifData())["Exif.Image2.JPEGInterchangeFormat"] = uint32_t(preview->pData() - pData);
(pCrwImage->exifData())["Exif.Image2.JPEGInterchangeFormatLength"] = preview->size();
}
} // CrwParser::decode
void CrwParser::encode(
Blob& blob,
const byte* pData,
uint32_t size,
const CrwImage* pCrwImage
)
{
// Parse image, starting with a CIFF header component
CiffHeader::AutoPtr head(new CiffHeader);
if (size != 0) {
head->read(pData, size);
}
// Encode Exif tags from image into the CRW parse tree and write the
// structure to the binary image blob
CrwMap::encode(head.get(), *pCrwImage);
head->write(blob);
} // CrwParser::encode
// *************************************************************************
// free functions
Image::AutoPtr newCrwInstance(BasicIo::AutoPtr io, bool create)
{
Image::AutoPtr image(new CrwImage(io, create));
if (!image->good()) {
image.reset();
}
return image;
}
bool isCrwType(BasicIo& iIo, bool advance)
{
bool result = true;
byte tmpBuf[14];
iIo.read(tmpBuf, 14);
if (iIo.error() || iIo.eof()) {
return false;
}
if (!( ('I' == tmpBuf[0] && 'I' == tmpBuf[1])
|| ('M' == tmpBuf[0] && 'M' == tmpBuf[1]))) {
result = false;
}
if ( true == result
&& std::memcmp(tmpBuf + 6, CiffHeader::signature(), 8) != 0) {
result = false;
}
if (!advance || !result) iIo.seek(-14, BasicIo::cur);
return result;
}
} // namespace Exiv2
namespace Exiv2 {
namespace Internal {
/*
Mapping table used to decode and encode CIFF tags to/from Exif tags. Only
a subset of the Exif tags can be mapped to known tags found in CRW files
and not all CIFF tags in the CRW files have a corresponding Exif tag. Tags
which are not mapped in the table below are ignored.
When decoding, each CIFF tag/directory pair in the CRW image is looked up
in the table and if it has an entry, the corresponding decode function is
called (CrwMap::decode). This function may or may not make use of the
other parameters in the structure (such as the Exif tag and Ifd id).
Encoding is done in a loop over the mapping table (CrwMap::encode). For
each entry, the encode function is called, which looks up the (Exif)
metadata to encode in the image. This function may or may not make use of
the other parameters in the mapping structure.
*/
const CrwMapping CrwMap::crwMapping_[] = {
// CrwTag CrwDir Size ExifTag IfdId decodeFct encodeFct
// ------ ------ ---- ------- ----- --------- ---------
CrwMapping(0x0805, 0x300a, 0, 0, canonId, decode0x0805, encode0x0805),
CrwMapping(0x080a, 0x2807, 0, 0, canonId, decode0x080a, encode0x080a),
CrwMapping(0x080b, 0x3004, 0, 0x0007, canonId, decodeBasic, encodeBasic),
CrwMapping(0x0810, 0x2807, 0, 0x0009, canonId, decodeBasic, encodeBasic),
CrwMapping(0x0815, 0x2804, 0, 0x0006, canonId, decodeBasic, encodeBasic),
CrwMapping(0x1029, 0x300b, 0, 0x0002, canonId, decodeBasic, encodeBasic),
CrwMapping(0x102a, 0x300b, 0, 0x0004, canonId, decodeArray, encodeArray),
CrwMapping(0x102d, 0x300b, 0, 0x0001, canonId, decodeArray, encodeArray),
CrwMapping(0x1033, 0x300b, 0, 0x000f, canonId, decodeArray, encodeArray),
CrwMapping(0x1038, 0x300b, 0, 0x0012, canonId, decodeArray, encodeArray),
CrwMapping(0x10a9, 0x300b, 0, 0x00a9, canonId, decodeBasic, encodeBasic),
// Mapped to Exif.Photo.ColorSpace instead (see below)
//CrwMapping(0x10b4, 0x300b, 0, 0x00b4, canonId, decodeBasic, encodeBasic),
CrwMapping(0x10b4, 0x300b, 0, 0xa001, exifId, decodeBasic, encodeBasic),
CrwMapping(0x10b5, 0x300b, 0, 0x00b5, canonId, decodeBasic, encodeBasic),
CrwMapping(0x10c0, 0x300b, 0, 0x00c0, canonId, decodeBasic, encodeBasic),
CrwMapping(0x10c1, 0x300b, 0, 0x00c1, canonId, decodeBasic, encodeBasic),
CrwMapping(0x1807, 0x3002, 0, 0x9206, exifId, decodeBasic, encodeBasic),
CrwMapping(0x180b, 0x3004, 0, 0x000c, canonId, decodeBasic, encodeBasic),
CrwMapping(0x180e, 0x300a, 0, 0x9003, exifId, decode0x180e, encode0x180e),
CrwMapping(0x1810, 0x300a, 0, 0xa002, exifId, decode0x1810, encode0x1810),
CrwMapping(0x1817, 0x300a, 4, 0x0008, canonId, decodeBasic, encodeBasic),
//CrwMapping(0x1818, 0x3002, 0, 0x9204, exifId, decodeBasic, encodeBasic),
CrwMapping(0x183b, 0x300b, 0, 0x0015, canonId, decodeBasic, encodeBasic),
CrwMapping(0x2008, 0x0000, 0, 0, ifd1Id, decode0x2008, encode0x2008),
// End of list marker
CrwMapping(0x0000, 0x0000, 0, 0x0000, ifdIdNotSet, 0, 0)
}; // CrwMap::crwMapping_[]
/*
CIFF directory hierarchy
root
|
300a
|
+----+----+----+----+
| | | | |
2804 2807 3002 3003 300b
|
3004
The array is arranged bottom-up so that starting with a directory at the
bottom, the (unique) path to root can be determined in a single loop.
*/
const CrwSubDir CrwMap::crwSubDir_[] = {
// dir, parent
{ 0x3004, 0x2807 },
{ 0x300b, 0x300a },
{ 0x3003, 0x300a },
{ 0x3002, 0x300a },
{ 0x2807, 0x300a },
{ 0x2804, 0x300a },
{ 0x300a, 0x0000 },
{ 0x0000, 0xffff },
// End of list marker
{ 0xffff, 0xffff }
};
const char CiffHeader::signature_[] = "HEAPCCDR";
CiffHeader::~CiffHeader()
{
delete pRootDir_;
delete[] pPadding_;
}
CiffComponent::~CiffComponent()
{
if (isAllocated_) delete[] pData_;
}
CiffEntry::~CiffEntry()
{
}
CiffDirectory::~CiffDirectory()
{
Components::iterator b = components_.begin();
Components::iterator e = components_.end();
for (Components::iterator i = b; i != e; ++i) {
delete *i;
}
}
void CiffComponent::add(AutoPtr component)
{
doAdd(component);
}
void CiffEntry::doAdd(AutoPtr /*component*/)
{
throw Error(34, "CiffEntry::add");
} // CiffEntry::doAdd
void CiffDirectory::doAdd(AutoPtr component)
{
components_.push_back(component.release());
} // CiffDirectory::doAdd
void CiffHeader::read(const byte* pData, uint32_t size)
{
if (size < 14) throw Error(33);
if (pData[0] == 0x49 && pData[1] == 0x49) {
byteOrder_ = littleEndian;
}
else if (pData[0] == 0x4d && pData[1] == 0x4d) {
byteOrder_ = bigEndian;
}
else {
throw Error(33);
}
offset_ = getULong(pData + 2, byteOrder_);
if (offset_ < 14 || offset_ > size) throw Error(33);
if (std::memcmp(pData + 6, signature(), 8) != 0) {
throw Error(33);
}
delete pPadding_;
pPadding_ = new byte[offset_ - 14];
padded_ = offset_ - 14;
std::memcpy(pPadding_, pData + 14, padded_);
pRootDir_ = new CiffDirectory;
pRootDir_->readDirectory(pData + offset_, size - offset_, byteOrder_);
} // CiffHeader::read
void CiffComponent::read(const byte* pData,
uint32_t size,
uint32_t start,
ByteOrder byteOrder)
{
doRead(pData, size, start, byteOrder);
}
void CiffComponent::doRead(const byte* pData,
uint32_t size,
uint32_t start,
ByteOrder byteOrder)
{
if (size < 10) throw Error(33);
tag_ = getUShort(pData + start, byteOrder);
DataLocId dl = dataLocation();
assert(dl == directoryData || dl == valueData);
if (dl == valueData) {
size_ = getULong(pData + start + 2, byteOrder);
offset_ = getULong(pData + start + 6, byteOrder);
}
if (dl == directoryData) {
size_ = 8;
offset_ = start + 2;
}
pData_ = pData + offset_;
#ifdef DEBUG
std::cout << " Entry for tag 0x"
<< std::hex << tagId() << " (0x" << tag()
<< "), " << std::dec << size_
<< " Bytes, Offset is " << offset_ << "\n";
#endif
} // CiffComponent::doRead
void CiffDirectory::doRead(const byte* pData,
uint32_t size,
uint32_t start,
ByteOrder byteOrder)
{
CiffComponent::doRead(pData, size, start, byteOrder);
#ifdef DEBUG
std::cout << "Reading directory 0x" << std::hex << tag() << "\n";
#endif
readDirectory(pData + offset(), this->size(), byteOrder);
#ifdef DEBUG
std::cout << "<---- 0x" << std::hex << tag() << "\n";
#endif
} // CiffDirectory::doRead
void CiffDirectory::readDirectory(const byte* pData,
uint32_t size,
ByteOrder byteOrder)
{
uint32_t o = getULong(pData + size - 4, byteOrder);
if (o + 2 > size) throw Error(33);
uint16_t count = getUShort(pData + o, byteOrder);
#ifdef DEBUG
std::cout << "Directory at offset " << std::dec << o
<<", " << count << " entries \n";
#endif
o += 2;
for (uint16_t i = 0; i < count; ++i) {
if (o + 10 > size) throw Error(33);
uint16_t tag = getUShort(pData + o, byteOrder);
CiffComponent::AutoPtr m;
switch (CiffComponent::typeId(tag)) {
case directory: m = CiffComponent::AutoPtr(new CiffDirectory); break;
default: m = CiffComponent::AutoPtr(new CiffEntry); break;
}
m->setDir(this->tag());
m->read(pData, size, o, byteOrder);
add(m);
o += 10;
}
} // CiffDirectory::readDirectory
void CiffHeader::decode(Image& image) const
{
// Nothing to decode from the header itself, just add correct byte order
if (pRootDir_) pRootDir_->decode(image, byteOrder_);
} // CiffHeader::decode
void CiffComponent::decode(Image& image, ByteOrder byteOrder) const
{
doDecode(image, byteOrder);
}
void CiffEntry::doDecode(Image& image, ByteOrder byteOrder) const
{
CrwMap::decode(*this, image, byteOrder);
} // CiffEntry::doDecode
void CiffDirectory::doDecode(Image& image, ByteOrder byteOrder) const
{
Components::const_iterator b = components_.begin();
Components::const_iterator e = components_.end();
for (Components::const_iterator i = b; i != e; ++i) {
(*i)->decode(image, byteOrder);
}
} // CiffDirectory::doDecode
void CiffHeader::write(Blob& blob) const
{
assert( byteOrder_ == littleEndian
|| byteOrder_ == bigEndian);
if (byteOrder_ == littleEndian) {
blob.push_back(0x49);
blob.push_back(0x49);
}
else {
blob.push_back(0x4d);
blob.push_back(0x4d);
}
uint32_t o = 2;
byte buf[4];
ul2Data(buf, offset_, byteOrder_);
append(blob, buf, 4);
o += 4;
append(blob, reinterpret_cast<const byte*>(signature_), 8);
o += 8;
// Pad as needed
if (pPadding_) {
assert(padded_ == offset_ - o);
append(blob, pPadding_, padded_);
}
else {
for (uint32_t i = o; i < offset_; ++i) {
blob.push_back(0);
++o;
}
}
if (pRootDir_) {
pRootDir_->write(blob, byteOrder_, offset_);
}
}
uint32_t CiffComponent::write(Blob& blob,
ByteOrder byteOrder,
uint32_t offset)
{
return doWrite(blob, byteOrder, offset);
}
uint32_t CiffEntry::doWrite(Blob& blob,
ByteOrder /*byteOrder*/,
uint32_t offset)
{
return writeValueData(blob, offset);
} // CiffEntry::doWrite
uint32_t CiffComponent::writeValueData(Blob& blob, uint32_t offset)
{
if (dataLocation() == valueData) {
#ifdef DEBUG
std::cout << " Data for tag 0x" << std::hex << tagId()
<< ", " << std::dec << size_ << " Bytes\n";
#endif
offset_ = offset;
append(blob, pData_, size_);
offset += size_;
// Pad the value to an even number of bytes
if (size_ % 2 == 1) {
blob.push_back(0);
++offset;
}
}
return offset;
} // CiffComponent::writeValueData
uint32_t CiffDirectory::doWrite(Blob& blob,
ByteOrder byteOrder,
uint32_t offset)
{
#ifdef DEBUG
std::cout << "Writing directory 0x" << std::hex << tag() << "---->\n";
#endif
// Ciff offsets are relative to the start of the directory
uint32_t dirOffset = 0;
// Value data
const Components::iterator b = components_.begin();
const Components::iterator e = components_.end();
for (Components::iterator i = b; i != e; ++i) {
dirOffset = (*i)->write(blob, byteOrder, dirOffset);
}
const uint32_t dirStart = dirOffset;
// Number of directory entries
byte buf[4];
us2Data(buf, static_cast<uint16_t>(components_.size()), byteOrder);
append(blob, buf, 2);
dirOffset += 2;
// Directory entries
for (Components::iterator i = b; i != e; ++i) {
(*i)->writeDirEntry(blob, byteOrder);
dirOffset += 10;
}
// Offset of directory
ul2Data(buf, dirStart, byteOrder);
append(blob, buf, 4);
dirOffset += 4;
// Update directory entry
setOffset(offset);
setSize(dirOffset);
#ifdef DEBUG
std::cout << "Directory is at offset " << std::dec << dirStart
<< ", " << components_.size() << " entries\n"
<< "<---- 0x" << std::hex << tag() << "\n";
#endif
return offset + dirOffset;
} // CiffDirectory::doWrite
void CiffComponent::writeDirEntry(Blob& blob, ByteOrder byteOrder) const
{
#ifdef DEBUG
std::cout << " Directory entry for tag 0x"
<< std::hex << tagId() << " (0x" << tag()
<< "), " << std::dec << size_
<< " Bytes, Offset is " << offset_ << "\n";
#endif
byte buf[4];
DataLocId dl = dataLocation();
assert(dl == directoryData || dl == valueData);
if (dl == valueData) {
us2Data(buf, tag_, byteOrder);
append(blob, buf, 2);
ul2Data(buf, size_, byteOrder);
append(blob, buf, 4);
ul2Data(buf, offset_, byteOrder);
append(blob, buf, 4);
}
if (dl == directoryData) {
// Only 8 bytes fit in the directory entry
assert(size_ <= 8);
us2Data(buf, tag_, byteOrder);
append(blob, buf, 2);
// Copy value instead of size and offset
append(blob, pData_, size_);
// Pad with 0s
for (uint32_t i = size_; i < 8; ++i) {
blob.push_back(0);
}
}
} // CiffComponent::writeDirEntry
void CiffHeader::print(std::ostream& os, const std::string& prefix) const
{
os << prefix
<< _("Header, offset") << " = 0x" << std::setw(8) << std::setfill('0')
<< std::hex << std::right << offset_ << "\n";
if (pRootDir_) pRootDir_->print(os, byteOrder_, prefix);
} // CiffHeader::print
void CiffComponent::print(std::ostream& os,
ByteOrder byteOrder,
const std::string& prefix) const
{
doPrint(os, byteOrder, prefix);
}
void CiffComponent::doPrint(std::ostream& os,
ByteOrder byteOrder,
const std::string& prefix) const
{
os << prefix
<< _("tag") << " = 0x" << std::setw(4) << std::setfill('0')
<< std::hex << std::right << tagId()
<< ", " << _("dir") << " = 0x" << std::setw(4) << std::setfill('0')
<< std::hex << std::right << dir()
<< ", " << _("type") << " = " << TypeInfo::typeName(typeId())
<< ", " << _("size") << " = " << std::dec << size_
<< ", " << _("offset") << " = " << offset_ << "\n";
Value::AutoPtr value;
if (typeId() != directory) {
value = Value::create(typeId());
value->read(pData_, size_, byteOrder);
if (value->size() < 100) {
os << prefix << *value << "\n";
}
}
} // CiffComponent::doPrint
void CiffDirectory::doPrint(std::ostream& os,
ByteOrder byteOrder,
const std::string& prefix) const
{
CiffComponent::doPrint(os, byteOrder, prefix);
Components::const_iterator b = components_.begin();
Components::const_iterator e = components_.end();
for (Components::const_iterator i = b; i != e; ++i) {
(*i)->print(os, byteOrder, prefix + " ");
}
} // CiffDirectory::doPrint
void CiffComponent::setValue(DataBuf buf)
{
if (isAllocated_) {
delete pData_;
pData_ = 0;
size_ = 0;
}
isAllocated_ = true;
std::pair<byte *, long> p = buf.release();
pData_ = p.first;
size_ = p.second;
if (size_ > 8 && dataLocation() == directoryData) {
tag_ &= 0x3fff;
}
} // CiffComponent::setValue
TypeId CiffComponent::typeId(uint16_t tag)
{
TypeId ti = invalidTypeId;
switch (tag & 0x3800) {
case 0x0000: ti = unsignedByte; break;
case 0x0800: ti = asciiString; break;
case 0x1000: ti = unsignedShort; break;
case 0x1800: ti = unsignedLong; break;
case 0x2000: ti = undefined; break;
case 0x2800: // fallthrough
case 0x3000: ti = directory; break;
}
return ti;
} // CiffComponent::typeId
DataLocId CiffComponent::dataLocation(uint16_t tag)
{
DataLocId di = invalidDataLocId;
switch (tag & 0xc000) {
case 0x0000: di = valueData; break;
case 0x4000: di = directoryData; break;
}
return di;
} // CiffComponent::dataLocation
/*!
@brief Finds \em crwTagId in directory \em crwDir, returning a pointer to
the component or 0 if not found.
*/
CiffComponent* CiffHeader::findComponent(uint16_t crwTagId,
uint16_t crwDir) const
{
if (pRootDir_ == 0) return 0;
return pRootDir_->findComponent(crwTagId, crwDir);
} // CiffHeader::findComponent
CiffComponent* CiffComponent::findComponent(uint16_t crwTagId,
uint16_t crwDir) const
{
return doFindComponent(crwTagId, crwDir);
} // CiffComponent::findComponent
CiffComponent* CiffComponent::doFindComponent(uint16_t crwTagId,
uint16_t crwDir) const
{
if (tagId() == crwTagId && dir() == crwDir) {
return const_cast<CiffComponent*>(this);
}
return 0;
} // CiffComponent::doFindComponent
CiffComponent* CiffDirectory::doFindComponent(uint16_t crwTagId,
uint16_t crwDir) const
{
CiffComponent* cc = 0;
const Components::const_iterator b = components_.begin();
const Components::const_iterator e = components_.end();
for (Components::const_iterator i = b; i != e; ++i) {
cc = (*i)->findComponent(crwTagId, crwDir);
if (cc) return cc;
}
return 0;
} // CiffDirectory::doFindComponent
void CiffHeader::add(uint16_t crwTagId, uint16_t crwDir, DataBuf buf)
{
CrwDirs crwDirs;
CrwMap::loadStack(crwDirs, crwDir);
uint16_t rootDirectory = crwDirs.top().crwDir_;
assert(rootDirectory == 0x0000);
crwDirs.pop();
if (!pRootDir_) pRootDir_ = new CiffDirectory;
CiffComponent* cc = pRootDir_->add(crwDirs, crwTagId);
cc->setValue(buf);
} // CiffHeader::add
CiffComponent* CiffComponent::add(CrwDirs& crwDirs, uint16_t crwTagId)
{
return doAdd(crwDirs, crwTagId);
} // CiffComponent::add
CiffComponent* CiffComponent::doAdd(CrwDirs& /*crwDirs*/, uint16_t /*crwTagId*/)
{
return 0;
} // CiffComponent::doAdd
CiffComponent* CiffDirectory::doAdd(CrwDirs& crwDirs, uint16_t crwTagId)
{
/*
add()
if stack not empty
pop from stack
find dir among components
if not found, create it
add()
else
find tag among components
if not found, create it
set value
*/
AutoPtr m;
CiffComponent* cc = 0;
const Components::iterator b = components_.begin();
const Components::iterator e = components_.end();
if (!crwDirs.empty()) {
CrwSubDir csd = crwDirs.top();
crwDirs.pop();
// Find the directory
for (Components::iterator i = b; i != e; ++i) {
if ((*i)->tag() == csd.crwDir_) {
cc = *i;
break;
}
}
if (cc == 0) {
// Directory doesn't exist yet, add it
m = AutoPtr(new CiffDirectory(csd.crwDir_, csd.parent_));
cc = m.get();
add(m);
}
// Recursive call to next lower level directory
cc = cc->add(crwDirs, crwTagId);
}
else {
// Find the tag
for (Components::iterator i = b; i != e; ++i) {
if ((*i)->tagId() == crwTagId) {
cc = *i;
break;
}
}
if (cc == 0) {
// Tag doesn't exist yet, add it
m = AutoPtr(new CiffEntry(crwTagId, tag()));
cc = m.get();
add(m);
}
}
return cc;
} // CiffDirectory::doAdd
void CiffHeader::remove(uint16_t crwTagId, uint16_t crwDir)
{
if (pRootDir_) {
CrwDirs crwDirs;
CrwMap::loadStack(crwDirs, crwDir);
uint16_t rootDirectory = crwDirs.top().crwDir_;
assert(rootDirectory == 0x0000);
crwDirs.pop();
pRootDir_->remove(crwDirs, crwTagId);
}
} // CiffHeader::remove
void CiffComponent::remove(CrwDirs& crwDirs, uint16_t crwTagId)
{
return doRemove(crwDirs, crwTagId);
} // CiffComponent::remove
void CiffComponent::doRemove(CrwDirs& /*crwDirs*/, uint16_t /*crwTagId*/)
{
// do nothing
} // CiffComponent::doRemove
void CiffDirectory::doRemove(CrwDirs& crwDirs, uint16_t crwTagId)
{
const Components::iterator b = components_.begin();
const Components::iterator e = components_.end();
Components::iterator i;
if (!crwDirs.empty()) {
CrwSubDir csd = crwDirs.top();
crwDirs.pop();
// Find the directory
for (i = b; i != e; ++i) {
if ((*i)->tag() == csd.crwDir_) {
// Recursive call to next lower level directory
(*i)->remove(crwDirs, crwTagId);
if ((*i)->empty()) components_.erase(i);
break;
}
}
}
else {
// Find the tag
for (i = b; i != e; ++i) {
if ((*i)->tagId() == crwTagId) {
// Remove the entry and abort the loop
delete *i;
components_.erase(i);
break;
}
}
}
} // CiffDirectory::doRemove
bool CiffComponent::empty() const
{
return doEmpty();
}
bool CiffComponent::doEmpty() const
{
return size_ == 0;
}
bool CiffDirectory::doEmpty() const
{
return components_.empty();
}
void CrwMap::decode(const CiffComponent& ciffComponent,
Image& image,
ByteOrder byteOrder)
{
const CrwMapping* cmi = crwMapping(ciffComponent.dir(),
ciffComponent.tagId());
if (cmi && cmi->toExif_) {
cmi->toExif_(ciffComponent, cmi, image, byteOrder);
}
} // CrwMap::decode
const CrwMapping* CrwMap::crwMapping(uint16_t crwDir, uint16_t crwTagId)
{
for (int i = 0; crwMapping_[i].ifdId_ != ifdIdNotSet; ++i) {
if ( crwMapping_[i].crwDir_ == crwDir
&& crwMapping_[i].crwTagId_ == crwTagId) {
return &(crwMapping_[i]);
}
}
return 0;
} // CrwMap::crwMapping
void CrwMap::decode0x0805(const CiffComponent& ciffComponent,
const CrwMapping* /*pCrwMapping*/,
Image& image,
ByteOrder /*byteOrder*/)
{
std::string s(reinterpret_cast<const char*>(ciffComponent.pData()));
image.setComment(s);
} // CrwMap::decode0x0805
void CrwMap::decode0x080a(const CiffComponent& ciffComponent,
const CrwMapping* /*pCrwMapping*/,
Image& image,
ByteOrder byteOrder)
{
if (ciffComponent.typeId() != asciiString) return;
// Make
ExifKey key1("Exif.Image.Make");
Value::AutoPtr value1 = Value::create(ciffComponent.typeId());
uint32_t i = 0;
for (; i < ciffComponent.size()
&& ciffComponent.pData()[i] != '\0'; ++i) {
// empty
}
value1->read(ciffComponent.pData(), ++i, byteOrder);
image.exifData().add(key1, value1.get());
// Model
ExifKey key2("Exif.Image.Model");
Value::AutoPtr value2 = Value::create(ciffComponent.typeId());
uint32_t j = i;
for (; i < ciffComponent.size()
&& ciffComponent.pData()[i] != '\0'; ++i) {
// empty
}
value2->read(ciffComponent.pData() + j, i - j + 1, byteOrder);
image.exifData().add(key2, value2.get());
} // CrwMap::decode0x080a
void CrwMap::decodeArray(const CiffComponent& ciffComponent,
const CrwMapping* pCrwMapping,
Image& image,
ByteOrder byteOrder)
{
if (ciffComponent.typeId() != unsignedShort) {
return decodeBasic(ciffComponent, pCrwMapping, image, byteOrder);
}
long aperture = 0;
long shutterSpeed = 0;
IfdId ifdId = ifdIdNotSet;
switch (pCrwMapping->tag_) {
case 0x0001: ifdId = canonCsId; break;
case 0x0004: ifdId = canonSiId; break;
case 0x000f: ifdId = canonCfId; break;
case 0x0012: ifdId = canonPiId; break;
}
assert(ifdId != ifdIdNotSet);
std::string groupName(Internal::groupName(ifdId));
uint16_t c = 1;
while (uint32_t(c)*2 < ciffComponent.size()) {
uint16_t n = 1;
ExifKey key(c, groupName);
UShortValue value;
if (ifdId == canonCsId && c == 23 && ciffComponent.size() > 50) n = 3;
value.read(ciffComponent.pData() + c*2, n*2, byteOrder);
image.exifData().add(key, &value);
if (ifdId == canonSiId && c == 21) aperture = value.toLong();
if (ifdId == canonSiId && c == 22) shutterSpeed = value.toLong();
c += n;
}
if (ifdId == canonSiId) {
// Exif.Photo.FNumber
float f = fnumber(canonEv(aperture));
Rational r = floatToRationalCast(f);
URational ur(r.first, r.second);
URationalValue fn;
fn.value_.push_back(ur);
image.exifData().add(ExifKey("Exif.Photo.FNumber"), &fn);
// Exif.Photo.ExposureTime
ur = exposureTime(canonEv(shutterSpeed));
URationalValue et;
et.value_.push_back(ur);
image.exifData().add(ExifKey("Exif.Photo.ExposureTime"), &et);
}
} // CrwMap::decodeArray
void CrwMap::decode0x180e(const CiffComponent& ciffComponent,
const CrwMapping* pCrwMapping,
Image& image,
ByteOrder byteOrder)
{
if (ciffComponent.size() < 8 || ciffComponent.typeId() != unsignedLong) {
return decodeBasic(ciffComponent, pCrwMapping, image, byteOrder);
}
assert(pCrwMapping != 0);
ULongValue v;
v.read(ciffComponent.pData(), 8, byteOrder);
time_t t = v.value_[0];
#ifdef EXV_HAVE_GMTIME_R
struct tm tms;
struct tm* tm = &tms;
tm = gmtime_r(&t, tm);
#else
struct tm* tm = std::gmtime(&t);
#endif
if (tm) {
const size_t m = 20;
char s[m];
std::strftime(s, m, "%Y:%m:%d %H:%M:%S", tm);
ExifKey key(pCrwMapping->tag_, Internal::groupName(pCrwMapping->ifdId_));
AsciiValue value;
value.read(std::string(s));
image.exifData().add(key, &value);
}
} // CrwMap::decode0x180e
void CrwMap::decode0x1810(const CiffComponent& ciffComponent,
const CrwMapping* pCrwMapping,
Image& image,
ByteOrder byteOrder)
{
if (ciffComponent.typeId() != unsignedLong || ciffComponent.size() < 28) {
return decodeBasic(ciffComponent, pCrwMapping, image, byteOrder);
}
ExifKey key1("Exif.Photo.PixelXDimension");
ULongValue value1;
value1.read(ciffComponent.pData(), 4, byteOrder);
image.exifData().add(key1, &value1);
ExifKey key2("Exif.Photo.PixelYDimension");
ULongValue value2;
value2.read(ciffComponent.pData() + 4, 4, byteOrder);
image.exifData().add(key2, &value2);
int32_t r = getLong(ciffComponent.pData() + 12, byteOrder);
uint16_t o = RotationMap::orientation(r);
image.exifData()["Exif.Image.Orientation"] = o;
} // CrwMap::decode0x1810
void CrwMap::decode0x2008(const CiffComponent& ciffComponent,
const CrwMapping* /*pCrwMapping*/,
Image& image,
ByteOrder /*byteOrder*/)
{
ExifThumb exifThumb(image.exifData());
exifThumb.setJpegThumbnail(ciffComponent.pData(), ciffComponent.size());
} // CrwMap::decode0x2008
void CrwMap::decodeBasic(const CiffComponent& ciffComponent,
const CrwMapping* pCrwMapping,
Image& image,
ByteOrder byteOrder)
{
assert(pCrwMapping != 0);
// create a key and value pair
ExifKey key(pCrwMapping->tag_, Internal::groupName(pCrwMapping->ifdId_));
Value::AutoPtr value;
if (ciffComponent.typeId() != directory) {
value = Value::create(ciffComponent.typeId());
uint32_t size = 0;
if (pCrwMapping->size_ != 0) {
// size in the mapping table overrides all
size = pCrwMapping->size_;
}
else if (ciffComponent.typeId() == asciiString) {
// determine size from the data, by looking for the first 0
uint32_t i = 0;
for (; i < ciffComponent.size()
&& ciffComponent.pData()[i] != '\0'; ++i) {
// empty
}
size = ++i;
}
else {
// by default, use the size from the directory entry
size = ciffComponent.size();
}
value->read(ciffComponent.pData(), size, byteOrder);
}
// Add metadatum to exif data
image.exifData().add(key, value.get());
} // CrwMap::decodeBasic
void CrwMap::loadStack(CrwDirs& crwDirs, uint16_t crwDir)
{
for (int i = 0; crwSubDir_[i].crwDir_ != 0xffff; ++i) {
if (crwSubDir_[i].crwDir_ == crwDir) {
crwDirs.push(crwSubDir_[i]);
crwDir = crwSubDir_[i].parent_;
}
}
} // CrwMap::loadStack
void CrwMap::encode(CiffHeader* pHead, const Image& image)
{
for (const CrwMapping* cmi = crwMapping_; cmi->ifdId_ != ifdIdNotSet; ++cmi) {
if (cmi->fromExif_ != 0) {
cmi->fromExif_(image, cmi, pHead);
}
}
} // CrwMap::encode
void CrwMap::encodeBasic(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
// Determine the source Exif metadatum
ExifKey ek(pCrwMapping->tag_, Internal::groupName(pCrwMapping->ifdId_));
ExifData::const_iterator ed = image.exifData().findKey(ek);
// Set the new value or remove the entry
if (ed != image.exifData().end()) {
DataBuf buf(ed->size());
ed->copy(buf.pData_, pHead->byteOrder());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encodeBasic
void CrwMap::encode0x0805(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
std::string comment = image.comment();
CiffComponent* cc = pHead->findComponent(pCrwMapping->crwTagId_,
pCrwMapping->crwDir_);
if (!comment.empty()) {
uint32_t size = static_cast<uint32_t>(comment.size());
if (cc && cc->size() > size) size = cc->size();
DataBuf buf(size);
std::memset(buf.pData_, 0x0, buf.size_);
std::memcpy(buf.pData_, comment.data(), comment.size());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
if (cc) {
// Just delete the value, do not remove the tag
DataBuf buf(cc->size());
std::memset(buf.pData_, 0x0, buf.size_);
cc->setValue(buf);
}
}
} // CrwMap::encode0x0805
void CrwMap::encode0x080a(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
const ExifKey k1("Exif.Image.Make");
const ExifKey k2("Exif.Image.Model");
const ExifData::const_iterator ed1 = image.exifData().findKey(k1);
const ExifData::const_iterator ed2 = image.exifData().findKey(k2);
const ExifData::const_iterator edEnd = image.exifData().end();
long size = 0;
if (ed1 != edEnd) size += ed1->size();
if (ed2 != edEnd) size += ed2->size();
if (size != 0) {
DataBuf buf(size);
if (ed1 != edEnd) ed1->copy(buf.pData_, pHead->byteOrder());
if (ed2 != edEnd) ed2->copy(buf.pData_ + ed1->size(), pHead->byteOrder());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encode0x080a
void CrwMap::encodeArray(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
IfdId ifdId = ifdIdNotSet;
switch (pCrwMapping->tag_) {
case 0x0001: ifdId = canonCsId; break;
case 0x0004: ifdId = canonSiId; break;
case 0x000f: ifdId = canonCfId; break;
case 0x0012: ifdId = canonPiId; break;
}
assert(ifdId != ifdIdNotSet);
DataBuf buf = packIfdId(image.exifData(), ifdId, pHead->byteOrder());
if (buf.size_ == 0) {
// Try the undecoded tag
encodeBasic(image, pCrwMapping, pHead);
}
if (buf.size_ > 0) {
// Write the number of shorts to the beginning of buf
us2Data(buf.pData_, static_cast<uint16_t>(buf.size_), pHead->byteOrder());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encodeArray
void CrwMap::encode0x180e(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
time_t t = 0;
const ExifKey key(pCrwMapping->tag_, Internal::groupName(pCrwMapping->ifdId_));
const ExifData::const_iterator ed = image.exifData().findKey(key);
if (ed != image.exifData().end()) {
struct tm tm;
std::memset(&tm, 0x0, sizeof(tm));
int rc = exifTime(ed->toString().c_str(), &tm);
if (rc == 0) t = timegm(&tm);
}
if (t != 0) {
DataBuf buf(12);
std::memset(buf.pData_, 0x0, 12);
ul2Data(buf.pData_, static_cast<uint32_t>(t), pHead->byteOrder());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encode0x180e
void CrwMap::encode0x1810(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
const ExifKey kX("Exif.Photo.PixelXDimension");
const ExifKey kY("Exif.Photo.PixelYDimension");
const ExifKey kO("Exif.Image.Orientation");
const ExifData::const_iterator edX = image.exifData().findKey(kX);
const ExifData::const_iterator edY = image.exifData().findKey(kY);
const ExifData::const_iterator edO = image.exifData().findKey(kO);
const ExifData::const_iterator edEnd = image.exifData().end();
CiffComponent* cc = pHead->findComponent(pCrwMapping->crwTagId_,
pCrwMapping->crwDir_);
if (edX != edEnd || edY != edEnd || edO != edEnd) {
uint32_t size = 28;
if (cc && cc->size() > size) size = cc->size();
DataBuf buf(size);
std::memset(buf.pData_, 0x0, buf.size_);
if (cc) std::memcpy(buf.pData_ + 8, cc->pData() + 8, cc->size() - 8);
if (edX != edEnd && edX->size() == 4) {
edX->copy(buf.pData_, pHead->byteOrder());
}
if (edY != edEnd && edY->size() == 4) {
edY->copy(buf.pData_ + 4, pHead->byteOrder());
}
int32_t d = 0;
if (edO != edEnd && edO->count() > 0 && edO->typeId() == unsignedShort) {
d = RotationMap::degrees(static_cast<uint16_t>(edO->toLong()));
}
l2Data(buf.pData_ + 12, d, pHead->byteOrder());
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encode0x1810
void CrwMap::encode0x2008(const Image& image,
const CrwMapping* pCrwMapping,
CiffHeader* pHead)
{
assert(pCrwMapping != 0);
assert(pHead != 0);
ExifThumbC exifThumb(image.exifData());
DataBuf buf = exifThumb.copy();
if (buf.size_ != 0) {
pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
}
else {
pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
}
} // CrwMap::encode0x2008
// *************************************************************************
// free functions
DataBuf packIfdId(const ExifData& exifData,
IfdId ifdId,
ByteOrder byteOrder)
{
const uint16_t size = 1024;
DataBuf buf(size);
std::memset(buf.pData_, 0x0, buf.size_);
uint16_t len = 0;
const ExifData::const_iterator b = exifData.begin();
const ExifData::const_iterator e = exifData.end();
for (ExifData::const_iterator i = b; i != e; ++i) {
if (i->ifdId() != ifdId) continue;
const uint16_t s = i->tag()*2 + static_cast<uint16_t>(i->size());
assert(s <= size);
if (len < s) len = s;
i->copy(buf.pData_ + i->tag()*2, byteOrder);
}
// Round the size to make it even.
buf.size_ = len + len%2;
return buf;
}
}} // namespace Internal, Exiv2
// *****************************************************************************
// local definitions
namespace {
//! @cond IGNORE
const RotationMap::OmList RotationMap::omList_[] = {
{ 1, 0 },
{ 3, 180 },
{ 3, -180 },
{ 6, 90 },
{ 6, -270 },
{ 8, 270 },
{ 8, -90 },
// last entry
{ 0, 0 }
};
uint16_t RotationMap::orientation(int32_t degrees)
{
uint16_t o = 1;
for (int i = 0; omList_[i].orientation != 0; ++i) {
if (omList_[i].degrees == degrees) {
o = omList_[i].orientation;
break;
}
}
return o;
}
int32_t RotationMap::degrees(uint16_t orientation)
{
int32_t d = 0;
for (int i = 0; omList_[i].orientation != 0; ++i) {
if (omList_[i].orientation == orientation) {
d = omList_[i].degrees;
break;
}
}
return d;
}
//! @endcond
}
| 35.120112 | 117 | 0.518253 | [
"model"
] |
4b670622d63677f5f2a0b923dd08a09193b4e623 | 1,820 | hpp | C++ | projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/State.hpp | yjf18340/webots | 60d441c362031ab8fde120cc0cd97bdb1a31a3d5 | [
"Apache-2.0"
] | 1 | 2019-11-13T08:12:02.000Z | 2019-11-13T08:12:02.000Z | projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/State.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | null | null | null | projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/State.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | 1 | 2020-09-25T02:01:45.000Z | 2020-09-25T02:01:45.000Z | // Copyright 1996-2019 Cyberbotics 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.
/*
* Description: Class defining the model of the state
*/
#ifndef STATE_HPP
#define STATE_HPP
#include "AutomatonObject.hpp"
#include <QtCore/QList>
#include <QtCore/QTextStream>
class Transition;
class RobotActuatorCommand;
QT_BEGIN_NAMESPACE
class QPointF;
QT_END_NAMESPACE
class State : public AutomatonObject {
Q_OBJECT
public:
explicit State(const QPointF &position);
virtual ~State();
bool isInitial() const { return mIsInitial; }
bool isCurrent() const { return mIsCurrent; }
RobotActuatorCommand *actuatorCommand() const { return mActuatorCommand; }
void setInitial(bool isInitial);
void setCurrent(bool isCurrent);
void addTransition(Transition *t);
void removeTransition(Transition *t);
void removeTransitionAt(int i);
void removeAllTransitions();
QList<Transition *> transitions() const { return mTransition; }
void fromString(const QString &string);
void fromStringVersion3(const QString &string); // backward compatibility code
QString toString() const;
signals:
void initialStateChanged();
void currentStateChanged();
private:
QList<Transition *> mTransition;
bool mIsInitial;
bool mIsCurrent;
RobotActuatorCommand *mActuatorCommand;
};
#endif
| 26 | 81 | 0.755495 | [
"model"
] |
b49c56f8ada0b0e77c36347b7835503f2e006551 | 4,884 | hpp | C++ | src/UI/Dlg/DlgSongProperties.hpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 1 | 2018-05-02T11:51:35.000Z | 2018-05-02T11:51:35.000Z | src/UI/Dlg/DlgSongProperties.hpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 181 | 2018-01-06T08:39:30.000Z | 2019-12-02T09:25:24.000Z | src/UI/Dlg/DlgSongProperties.hpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 1 | 2022-03-10T05:25:04.000Z | 2022-03-10T05:25:04.000Z | #pragma once
#include <memory>
#include <QDialog>
#include "../../Song.hpp"
#include "../../MetadataScanner.hpp"
// fwd:
class ComponentCollection;
namespace Ui
{
class DlgSongProperties;
}
class DlgSongProperties:
public QDialog
{
Q_OBJECT
using Super = QDialog;
public:
/** Creates a new instance of the dialog.
aSong is the song that the user requested to edit. */
explicit DlgSongProperties(
ComponentCollection & aComponents,
SongPtr aSong,
QWidget * aParent = nullptr
);
~DlgSongProperties();
private:
/** The Qt-managed UI. */
std::unique_ptr<Ui::DlgSongProperties> mUI;
/** The components of the entire program. */
ComponentCollection & mComponents;
/** The song being currently displayed. */
SongPtr mSong;
/** All songs that have the same hash as mSong. */
std::vector<Song *> mDuplicates;
/** Set to true before the code changes any values.
Used to determine whether a change-event from a control was generated by the user or by code.
Changes generated by the user are stored for saving later, when requested. */
bool mIsInternalChange;
/** The ID3 tag contents, as read from the file.
Filled in the background while opening the dialog.
The bool part indicates whether the tag reading was successful (when false, ID3 tag cannot be written back). */
std::map<const Song *, std::pair<bool, MetadataScanner::Tag>> mOriginalID3;
/** The user-made changes to be made to each song out of mDuplicates when accepting the dialog.
Each member of the tag is independently tracked, if present, then it will be updated upon accepting the dialog.
If there are no changes for a song, it will not have an entry in this map. */
std::map<const Song *, MetadataScanner::Tag> mTagID3Changes;
/** The changes to the manual tag to be applied to the SharedData when accepting the dialog. */
Song::Tag mTagManual;
/** The changes to Notes to be applied to the SharedData when accepting the dialog. */
DatedOptional<QString> mNotes;
/** Fills in all the duplicates into tblDuplicates. */
void fillDuplicates();
/** Updates the UI with the specified song.
Used when switching duplicates. Updates mSong. */
void selectSong(const Song & aSong);
/** Returns the Song pointer out of mDuplicates representing the specified song. */
SongPtr songPtrFromRef(const Song & aSong);
/** Updates the ParsedID3 values from the current ID3 values (originals + user edits). */
void updateParsedId3();
private slots:
/** Applies all changesets in mChageSets and closes the dialog. */
void applyAndClose();
/** The user has edited the manual author entry, update the current changeset. */
void authorTextEdited(const QString & aNewText);
/** The user has edited the manual title entry, update the current changeset. */
void titleTextEdited(const QString & aNewText);
/** The user has selected a manual genre, update the current changeset. */
void genreSelected(const QString & aNewGenre);
/** The user has edited the manual MPM entry, update the current changeset. */
void measuresPerMinuteTextEdited(const QString & aNewText);
/** The user has edited the notes, update the current changeset. */
void notesChanged();
/** The user has selected the duplicate at the specified row, switch data to that duplicate. */
void switchDuplicate(int aRow);
/** The user has edited the ID3 author, update the current changeset and parsed ID3 values. */
void id3AuthorEdited(const QString & aNewText);
/** The user has edited the ID3 title, update the current changeset and parsed ID3 values. */
void id3TitleEdited(const QString & aNewText);
/** The user has edited the ID3 genre, update the current changeset and parsed ID3 values. */
void id3GenreEdited(const QString & aNewText);
/** The user has edited the ID3 comment, update the current changeset and parsed ID3 values. */
void id3CommentEdited(const QString & aNewText);
/** The user has edited the ID3 mpm, update the current changeset and parsed ID3 values. */
void id3MeasuresPerMinuteEdited(const QString & aNewText);
/** Displays the save-as dialog, then moves the file to the new location. */
void renameFile();
/** Asks for confirmation, then removes the selected duplicate from the library. */
void removeFromLibrary();
/** Asks for confirmation, then deletes the selected duplicate from the disk. */
void deleteFromDisk();
/** Copies to clipboard the ID3 tag contents. */
void copyId3Tag();
/** Copies to clipboard the Parsed tag contents. */
void copyPid3Tag();
/** Copies to clipboard the Filename-based tag contents. */
void copyFilenameTag();
/** Shows the TapTempo dialog, and if saved, updates the manual tempo. */
void showTapTempo();
/** The specified song has had its detected tempo updated.
If this is the shown song, updates the UI to show the tempo. */
void songTempoDetected(Song::SharedDataPtr aSongSD);
};
| 31.10828 | 112 | 0.736691 | [
"vector"
] |
b49c73dc552a98ab17764aa2fb337c005ff69cca | 12,369 | cpp | C++ | src/tests/functional/inference_engine/lp_transformations/mvn_transformation.cpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | null | null | null | src/tests/functional/inference_engine/lp_transformations/mvn_transformation.cpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | src/tests/functional/inference_engine/lp_transformations/mvn_transformation.cpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "layer_transformation.hpp"
#include <string>
#include <sstream>
#include <memory>
#include <gtest/gtest.h>
#include <transformations/utils/utils.hpp>
#include <transformations/init_node_info.hpp>
#include "low_precision/mvn.hpp"
#include "common_test_utils/ngraph_test_utils.hpp"
#include "lpt_ngraph_functions/common/dequantization_operations.hpp"
#include "simple_low_precision_transformer.hpp"
#include "lpt_ngraph_functions/mvn_function.hpp"
namespace {
using namespace testing;
using namespace ngraph;
using namespace ngraph::pass;
using namespace ngraph::builder::subgraph;
class MVNTransformationTestValues {
public:
class Actual {
public:
ngraph::element::Type precisionBeforeDequantization;
ngraph::builder::subgraph::DequantizationOperations dequantization;
};
class Expected {
public:
ngraph::element::Type precisionBeforeDequantization;
ngraph::builder::subgraph::DequantizationOperations dequantizationBefore;
ngraph::element::Type precisionAfterOperation;
ngraph::builder::subgraph::DequantizationOperations dequantizationAfter;
};
ngraph::AxisSet reductionAxes;
bool normalizeVariance;
TestTransformationParams params;
Actual actual;
Expected expected;
};
typedef std::tuple<
ngraph::element::Type,
ngraph::PartialShape,
MVNTransformationTestValues,
int
> MVNTransformationParams;
class MVNTransformation : public LayerTransformation, public testing::WithParamInterface<MVNTransformationParams> {
public:
void SetUp() override {
const ngraph::element::Type precision = std::get<0>(GetParam());
const ngraph::PartialShape inputShape = std::get<1>(GetParam());
const MVNTransformationTestValues testValues = std::get<2>(GetParam());
const int opset_version = std::get<3>(GetParam());
actualFunction = ngraph::builder::subgraph::MVNFunction::getOriginal(
precision,
inputShape,
testValues.reductionAxes,
testValues.normalizeVariance,
testValues.actual.precisionBeforeDequantization,
testValues.actual.dequantization,
opset_version);
SimpleLowPrecisionTransformer transformer;
transformer.add<ngraph::pass::low_precision::MVNTransformation, ngraph::opset1::Interpolate>(testValues.params);
transformer.transform(actualFunction);
referenceFunction = ngraph::builder::subgraph::MVNFunction::getReference(
precision,
inputShape,
testValues.reductionAxes,
testValues.normalizeVariance,
testValues.expected.precisionBeforeDequantization,
testValues.expected.dequantizationBefore,
testValues.expected.precisionAfterOperation,
testValues.expected.dequantizationAfter,
opset_version);
}
static std::string getTestCaseName(testing::TestParamInfo<MVNTransformationParams> obj) {
const ngraph::element::Type precision = std::get<0>(obj.param);
const ngraph::PartialShape inputShape = std::get<1>(obj.param);
const MVNTransformationTestValues testValues = std::get<2>(obj.param);
const int opset_version = std::get<3>(obj.param);
std::ostringstream result;
result <<
precision << "_" <<
toString(testValues.params) << "_" <<
inputShape << "_" <<
testValues.reductionAxes << "_" <<
testValues.normalizeVariance << "_" <<
testValues.actual.precisionBeforeDequantization << "_" <<
testValues.actual.dequantization << "_" <<
testValues.expected.dequantizationBefore << "_" <<
opset_version;
return result.str();
}
};
TEST_P(MVNTransformation, CompareFunctions) {
actualFunction->validate_nodes_and_infer_types();
auto res = compare_functions(referenceFunction, actualFunction, true, true, true);
ASSERT_TRUE(res.first) << res.second;
ASSERT_TRUE(LayerTransformation::allNamesAreUnique(actualFunction)) << "Not all names are unique";
}
const std::vector<ngraph::element::Type> precisions = {
ngraph::element::f32,
ngraph::element::f16
};
const std::vector<int> opset_version = {
2, 6
};
namespace testValues1 {
const std::vector<ngraph::PartialShape> inputShapes = {
{ 1, 4, 16, 16 },
{ Dimension::dynamic(), 4, Dimension::dynamic(), Dimension::dynamic() },
};
const std::vector<MVNTransformationTestValues> testValues = {
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(false),
{
ngraph::element::u8,
{{ngraph::element::f32}, {-0.32f}, {0.45f}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {-0.32f}, {0.45f}},
ngraph::element::f32,
{ }
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(false),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {0.45f}}
},
{
ngraph::element::u8,
{ },
ngraph::element::f32,
{{}, {}, {1.f}}
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(true),
{
ngraph::element::u8,
{{ngraph::element::f32}, {127.f}, {0.45f}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {127.f}, {0.45f}},
ngraph::element::f32,
{{}, {}, {}}
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(true),
{
ngraph::element::u8,
{{ngraph::element::f32}, {12.5f}, {0.45f}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {12.5f}, {0.45f}},
ngraph::element::f32,
{{}, {}, {}}
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(false),
{
ngraph::element::u8,
{{ngraph::element::f32}, {127.f}, {0.45f}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {127.f}, {0.45f}},
ngraph::element::f32,
{}
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {-0.5f}}
},
{
ngraph::element::u8,
{{}, {}, {}},
ngraph::element::f32,
{{}, {}, {-1.f}}
}
},
{
{1, 2, 3},
false,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {0.45f}}
},
{
ngraph::element::u8,
{{}, {}, {}},
ngraph::element::f32,
{{}, {}, {0.45f}}
}
},
{
{1, 2, 3},
false,
LayerTransformation::createParamsU8I8().setUpdatePrecisions(false),
{
ngraph::element::f32,
{{}, {}, {0.45f}}
},
{
ngraph::element::f32,
{{}, {}, {}},
ngraph::element::f32,
{{}, {}, {0.45f}}
}
},
};
INSTANTIATE_TEST_SUITE_P(
smoke_LPT,
MVNTransformation,
::testing::Combine(
::testing::ValuesIn(precisions),
::testing::ValuesIn(inputShapes),
::testing::ValuesIn(testValues),
::testing::ValuesIn(opset_version)),
MVNTransformation::getTestCaseName);
} // namespace testValues1
namespace testValues2 {
const std::vector<ngraph::PartialShape> inputShapes = {
{ 1, 2, 2, 2 },
{ Dimension::dynamic(), 2, Dimension::dynamic(), Dimension::dynamic()}
};
const std::vector<MVNTransformationTestValues> testValues = {
{
{1, 2, 3},
false,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, 0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
},
{
ngraph::element::u8,
{{}, {}, {}},
ngraph::element::f32,
{{}, {}, {{0.45f, 0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
}
},
{
{2, 3},
true,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, -0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
},
{
ngraph::element::u8,
{{}, {}, {}},
ngraph::element::f32,
{{}, {}, {{1.f, -1.f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
}
},
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, -0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, -0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}},
ngraph::element::f32,
{{}, {}, {}}
}
},
};
INSTANTIATE_TEST_SUITE_P(
smoke_LPT,
MVNTransformation,
::testing::Combine(
::testing::ValuesIn(precisions),
::testing::ValuesIn(inputShapes),
::testing::ValuesIn(testValues),
::testing::ValuesIn(opset_version)),
MVNTransformation::getTestCaseName);
} // namespace testValues2
namespace testValues3 {
const std::vector<ngraph::PartialShape> inputShapesWithDynamicChannels = {
{ Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()},
};
const std::vector<MVNTransformationTestValues> testValues = {
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(false),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {0.45f}}
},
{
ngraph::element::u8,
{ },
ngraph::element::f32,
{{}, {}, {1.f}}
}
},
{
{1, 2, 3},
false,
LayerTransformation::createParamsU8I8(),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, 0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {{0.45f, 0.45f}, ngraph::element::f32, ngraph::Shape{ 1, 2, 1, 1 }}},
ngraph::element::f32,
{{}, {}, {}}
}
},
};
INSTANTIATE_TEST_SUITE_P(
smoke_LPT,
MVNTransformation,
::testing::Combine(
::testing::ValuesIn(precisions),
::testing::ValuesIn(inputShapesWithDynamicChannels),
::testing::ValuesIn(testValues),
::testing::ValuesIn(opset_version)),
MVNTransformation::getTestCaseName);
} // namespace testValues3
namespace testValues4 {
const std::vector<ngraph::PartialShape> inputShapesWithDynamicRank = {
PartialShape::dynamic(),
};
const std::vector<MVNTransformationTestValues> testValues = {
{
{1, 2, 3},
true,
LayerTransformation::createParamsU8I8().setSupportAsymmetricQuantization(false),
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {0.45f}}
},
{
ngraph::element::u8,
{{ngraph::element::f32}, {}, {0.45f}},
ngraph::element::f32,
{}
}
},
};
INSTANTIATE_TEST_SUITE_P(
smoke_LPT,
MVNTransformation,
::testing::Combine(
::testing::ValuesIn(precisions),
::testing::ValuesIn(inputShapesWithDynamicRank),
::testing::ValuesIn(testValues),
::testing::ValuesIn(opset_version)),
MVNTransformation::getTestCaseName);
} // namespace testValues4
} // namespace
| 29.590909 | 120 | 0.557927 | [
"shape",
"vector",
"transform"
] |
b49c840305f7c597c9a8aba79ef10878f64d05a5 | 3,290 | cpp | C++ | src/tests/functional/shared_test_classes/src/single_layer/low_precision.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/tests/functional/shared_test_classes/src/single_layer/low_precision.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/tests/functional/shared_test_classes/src/single_layer/low_precision.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2019-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "shared_test_classes/single_layer/low_precision.hpp"
#include "ngraph_functions/builders.hpp"
namespace LowPrecisionTestDefinitions {
std::string LowPrecisionTest::getTestCaseName(const testing::TestParamInfo<lowPrecisionTestParamsSet>& obj) {
InferenceEngine::Precision netPrecision;
std::string targetDevice;
std::pair<std::string, std::map<std::string, std::string>> config;
std::tie(netPrecision, targetDevice, config) = obj.param;
std::ostringstream result;
result << "netPRC=" << netPrecision.name() << "_";
result << "trgDev=" << targetDevice;
if (!config.first.empty()) {
result << "_targetConfig=" << config.first;
}
return result.str();
}
void LowPrecisionTest::SetUp() {
InferenceEngine::Precision netPrecision;
std::pair<std::string, std::map<std::string, std::string>> config;
std::tie(netPrecision, targetDevice, config) = this->GetParam();
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto inputShape = ngraph::Shape{ 1, 16 };
auto weights1Shape = ngraph::Shape{ 16, 16 };
auto weights2Shape = ngraph::Shape{ 128, 32 };
// fully connected 1
auto input = std::make_shared<ngraph::opset1::Parameter>(ngPrc, inputShape);
std::vector<float> weights1Data(ngraph::shape_size(weights1Shape), 0.0f);
for (size_t i = 0; i < 16; i++) {
weights1Data[i * 17] = 10.0f + i;
}
auto weights1 = ngraph::builder::makeConstant<float>(ngPrc, weights1Shape, weights1Data);
auto fc1 = std::make_shared<ngraph::opset1::MatMul>(input, weights1);
fc1->set_friendly_name("FullyConnected_1");
// bias 1
std::vector<float> bias1Data(ngraph::shape_size(inputShape), 0.0f);
auto bias1 = ngraph::builder::makeConstant<float>(ngPrc, inputShape, bias1Data);
auto add1 = std::make_shared<ngraph::opset1::Add>(fc1, bias1);
add1->set_friendly_name("Add_1");
#if 0
// ReLU 1
auto relu1 = std::make_shared<ngraph::opset1::Relu>(add1);
relu1->set_friendly_name("Relu_1");
//// fully connected 2
std::vector<float> weights2Data(ngraph::shape_size(weights2Shape), 0.0f);
std::fill(weights2Data.begin(), weights2Data.end(), 0.0001f);
auto weights2 = ngraph::builder::makeConstant<float>(ngPrc, weights2Shape, weights2Data);
auto fc2 = std::make_shared<ngraph::opset1::MatMul>(relu1, weights2);
fc2->set_friendly_name("FullyConnected_2");
//// bias 2
std::vector<float> bias2Data(ngraph::shape_size(weights2Shape), 0.0f);
auto bias2 = ngraph::builder::makeConstant<float>(ngPrc, weights2Shape, bias2Data);
auto add2 = std::make_shared<ngraph::opset1::Add>(fc2, bias2);
add2->set_friendly_name("Add_2");
//// ReLU 2
auto relu2 = std::make_shared<ngraph::opset1::Relu>(add2);
relu2->set_friendly_name("Relu_2");
#endif
configuration = config.second;
function = std::make_shared<ngraph::Function>(ngraph::ResultVector{std::make_shared<ngraph::opset1::Result>(add1)},
ngraph::ParameterVector{input},
"LowPrecisionTest");
}
} // namespace LowPrecisionTestDefinitions
| 41.125 | 119 | 0.676596 | [
"shape",
"vector"
] |
b49e5ca3e600f9751eb3abfc4a31063f7443b2eb | 19,602 | cpp | C++ | openstudiocore/src/analysis/SequentialSearch.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | openstudiocore/src/analysis/SequentialSearch.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | openstudiocore/src/analysis/SequentialSearch.cpp | zhouchong90/OpenStudio | f8570cb8297547b5e9cc80fde539240d8f7b9c24 | [
"BSL-1.0",
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "SequentialSearch.hpp"
#include "SequentialSearch_Impl.hpp"
#include "SequentialSearchOptions.hpp"
#include "SequentialSearchOptions_Impl.hpp"
#include "Analysis.hpp"
#include "DataPoint.hpp"
#include "OptimizationProblem.hpp"
#include "OptimizationProblem_Impl.hpp"
#include "OptimizationDataPoint.hpp"
#include "OptimizationDataPoint_Impl.hpp"
#include "DiscreteVariable.hpp"
#include "DiscreteVariable_Impl.hpp"
#include "../utilities/math/FloatCompare.hpp"
#include "../utilities/core/Assert.hpp"
#include "../utilities/core/Containers.hpp"
namespace openstudio {
namespace analysis {
namespace detail {
SequentialSearch_Impl::SequentialSearch_Impl(const SequentialSearchOptions& options)
: OpenStudioAlgorithm_Impl(SequentialSearch::standardName(),options)
{}
SequentialSearch_Impl::SequentialSearch_Impl(const UUID& uuid,
const UUID& versionUUID,
const std::string& displayName,
const std::string& description,
bool complete,
bool failed,
int iter,
const SequentialSearchOptions& options)
: OpenStudioAlgorithm_Impl(uuid,
versionUUID,
SequentialSearch::standardName(),
displayName,
description,
complete,
failed,
iter,
options)
{}
SequentialSearch_Impl::SequentialSearch_Impl(const SequentialSearch_Impl& other)
: OpenStudioAlgorithm_Impl(other)
{}
AnalysisObject SequentialSearch_Impl::clone() const {
std::shared_ptr<SequentialSearch_Impl> impl(new SequentialSearch_Impl(*this));
return SequentialSearch(impl);
}
bool SequentialSearch_Impl::isCompatibleProblemType(const Problem& problem) const {
OptionalOptimizationProblem optimizationProblem = problem.optionalCast<OptimizationProblem>();
if (!optimizationProblem) {
return false;
}
if (!optimizationProblem->allVariablesAreDiscrete()) {
return false;
}
if (optimizationProblem->numObjectives() != 2) {
return false;
}
return true;
}
int SequentialSearch_Impl::createNextIteration(Analysis& analysis) {
OS_ASSERT(analysis.algorithm().get() == getPublicObject<SequentialSearch>());
int numAdded(0);
if (isComplete()) {
LOG(Info,"Algorithm is already marked as complete. Returning without creating new points.");
return numAdded;
}
SequentialSearchOptions options = sequentialSearchOptions();
OptionalInt maxIter = options.maxIter();
OptionalInt maxSims = options.maxSims();
DataPointVector ssDataPoints = analysis.getDataPoints("ss");
// return without doing anything if any ssDataPoints are incomplete
DataPointVector incompletePoints = analysis.dataPointsToQueue();
DataPointVector::const_iterator it = std::find_if(incompletePoints.begin(),
incompletePoints.end(),
std::bind(&DataPoint::isTag,std::placeholders::_1,"ss"));
if (it != incompletePoints.end()) {
LOG(Info,"Returning because the last iteration has not yet been run.");
return numAdded;
}
// last iteration appears complete
int nSims = ssDataPoints.size();
if (maxSims && (nSims >= *maxSims)) {
LOG(Info,"Returning because maxSims " << *maxSims << " reached. No DataPoints will be added "
<< "to Analysis '"<< analysis.name() << "', and the Algorithm will be marked complete.");
markComplete();
return numAdded;
}
if (maxIter && (m_iter+1 == *maxIter)) {
LOG(Info,"Returning because maxIter " << *maxIter << " reached. No DataPoints will be added "
<< "to Analysis '"<< analysis.name() << "', and the Algorithm will be marked complete.");
markComplete();
return numAdded;
}
onChange(AnalysisObject_Impl::Benign);
++m_iter;
if (m_iter == 0) {
// run baseline point, which is just the 0th perturbation of each variable.
OptimizationProblem problem = analysis.problem().cast<OptimizationProblem>();
std::vector<QVariant> baselineValues(problem.numVariables(),0);
// see if already in analysis
DataPointVector baselines = analysis.getDataPoints(baselineValues);
if (!baselines.empty()) {
OS_ASSERT(baselines.size() == 1u);
DataPoint baseline = baselines[0];
OS_ASSERT(baseline.optionalCast<OptimizationDataPoint>());
OS_ASSERT(baseline.problem() == problem);
if (!baseline.isTag("ss")) {
baseline.addTag("ss");
}
if (!baseline.isTag("iter0")) {
baseline.addTag("iter0");
}
if (!baseline.isTag("current")) {
baseline.addTag("current");
}
if (!baseline.isComplete()) {
++numAdded;
}
}
else {
OptimizationDataPoint dataPoint = problem.createDataPoint(baselineValues).get().cast<OptimizationDataPoint>();
dataPoint.addTag("ss");
dataPoint.addTag("iter0");
dataPoint.addTag("current");
analysis.addDataPoint(dataPoint);
++numAdded;
}
}
else {
OptimizationDataPointVector minimumCurve =
getMinimumCurve(options.objectiveToMinimizeFirst(),analysis);
OS_ASSERT(!minimumCurve.empty());
OS_ASSERT(minimumCurve.back().isTag("current"));
if (!minimumCurve.back().isTag("explored")) {
std::vector< std::vector<QVariant> > candidateVariableValues = getCandidateCombinations(minimumCurve.back());
std::stringstream ss;
ss << "iter" << m_iter;
std::string iterTag(ss.str()); ss.str("");
for (const std::vector<QVariant>& candidate : candidateVariableValues) {
DataPoint newDataPoint = analysis.problem().createDataPoint(candidate).get();
OS_ASSERT(newDataPoint.optionalCast<OptimizationDataPoint>());
newDataPoint.addTag("ss");
newDataPoint.addTag(iterTag);
bool added = analysis.addDataPoint(newDataPoint);
if (added) {
++numAdded;
if (maxSims && (nSims + numAdded == *maxSims)) {
break;
}
}
}
minimumCurve.back().addTag("explored");
}
}
if (numAdded == 0) {
LOG(Trace,"No new points were added, so marking this SequentialSearch complete.");
markComplete();
}
return numAdded;
}
SequentialSearchOptions SequentialSearch_Impl::sequentialSearchOptions() const {
return options().cast<SequentialSearchOptions>();
}
std::vector<OptimizationDataPoint> SequentialSearch_Impl::getMinimumCurve(
unsigned i, Analysis& analysis) const
{
std::stringstream ss;
ss << "curve" << i;
std::string curveTag(ss.str()); ss.str("");
OptimizationDataPointVector lastCurve = castVector<OptimizationDataPoint>(
analysis.getDataPoints(curveTag));
OptimizationDataPointVector lastCurrent = castVector<OptimizationDataPoint>(
analysis.getDataPoints("current"));
OptimizationDataPointVector result = castVector<OptimizationDataPoint>(
analysis.getDataPoints("iter0")); // baseline point
OS_ASSERT(result.size() < 2);
OptimizationDataPointVector successfulPoints = castVector<OptimizationDataPoint>(
analysis.successfulDataPoints());
// construct curve
OptionalOptimizationDataPoint current;
if (!result.empty()) {
current = result.back();
if (!current->isTag(curveTag)) {
current->addTag(curveTag);
}
auto it = std::find(successfulPoints.begin(),
successfulPoints.end(),
result.back());
successfulPoints.erase(it);
}
int otherIndex(0);
if (i == 0) {
otherIndex = 1;
}
else {
OS_ASSERT(i == 1);
}
while (current) {
OptionalOptimizationDataPoint candidate;
if (current->isTag("explored") && current->isComplete() && !current->failed()) {
// candidates have objective function at otherIndex < current's
DoubleVector currentValues = current->objectiveValues();
OptionalDouble candidateSlope;
DoubleVector candidateValues;
for (auto it = successfulPoints.begin();
it != successfulPoints.end(); )
{
DoubleVector values = it->objectiveValues();
if (lessThanOrEqual(values[otherIndex],currentValues[otherIndex])) {
// take maximum slope as calculated on graph i vs. otherIndex
double slope = (values[i] - currentValues[i])/
(values[otherIndex] - currentValues[otherIndex]);
// infinite slope exception for start of algorithm
bool infiniteSlopeException =
current->isTag("iter0") &&
equal(values[otherIndex],currentValues[otherIndex]) &&
(values[i] < currentValues[i]);
if (infiniteSlopeException && candidateSlope) {
infiniteSlopeException = infiniteSlopeException &&
((candidateValues[otherIndex] < values[otherIndex]) ||
(values[i] < candidateValues[i]));
}
if (infiniteSlopeException ||
(!equal(values[otherIndex],currentValues[otherIndex]) &&
((!candidateSlope) || (slope > *candidateSlope) ||
(equal(slope,*candidateSlope) && (values[i] < candidateValues[i])))))
{
candidate = *it;
candidateSlope = slope;
candidateValues = values;
if (infiniteSlopeException) {
candidateSlope = std::numeric_limits<double>::max();
}
}
++it;
}
else {
// erase it from consideration--with other objective function > current,
// will never be candidate.
it = successfulPoints.erase(it);
}
}
}
if (candidate) {
result.push_back(*candidate);
if (!result.back().isTag(curveTag)) {
result.back().addTag(curveTag);
}
auto it = std::find(successfulPoints.begin(),
successfulPoints.end(),
result.back());
successfulPoints.erase(it);
}
current = candidate;
}
// remove outdated tags
for (OptimizationDataPoint& point : lastCurve) {
OptimizationDataPointVector::const_iterator it = std::find(result.begin(),result.end(),point);
if (it == result.end()) {
point.deleteTag(curveTag);
}
}
if (!lastCurrent.empty()) {
OS_ASSERT(lastCurrent.size() == 1u);
if (lastCurrent[0] != result.back()) {
lastCurrent[0].deleteTag("current");
}
}
// add current tag
if (!result.empty() && !result.back().isTag("current")) {
result.back().addTag("current");
}
return result;
}
std::vector<OptimizationDataPoint> SequentialSearch_Impl::getParetoFront(
Analysis& analysis) const
{
DataPointVector temp = analysis.getDataPoints("pareto");
OptimizationDataPointVector lastParetoFront = castVector<OptimizationDataPoint>(temp);
OptimizationDataPointVector result;
temp = analysis.successfulDataPoints();
OptimizationDataPointVector successfulPoints = castVector<OptimizationDataPoint>(temp);
// sort by objective function options().objectiveToMinimizeFirst()
int i = sequentialSearchOptions().objectiveToMinimizeFirst();
int otherIndex(0);
if (i == 0) {
otherIndex = 1;
}
else {
OS_ASSERT(i == 1);
}
OptimizationDataPointObjectiveFunctionLess predicate(i);
std::sort(successfulPoints.begin(),successfulPoints.end(),predicate);
// non-dominated means that you cannot improve one objective without harming the other
auto it = successfulPoints.begin();
DoubleVector currentValues;
while (it != successfulPoints.end()) {
// it has next-worst objective i
DoubleVector candidateValues = it->objectiveValues();
if (!currentValues.empty()) {
OS_ASSERT(greaterThanOrEqual(candidateValues[i],currentValues[i]));
}
// is Pareto if improves objective otherIndex, and
if (!currentValues.empty() &&
greaterThanOrEqual(candidateValues[otherIndex],currentValues[otherIndex]))
{
it = successfulPoints.erase(it);
continue;
}
// is Pareto if there is no other point with same objective i and better objective otherIndex
OptimizationDataPointVector::const_iterator jt = it; ++jt;
bool erasedIt(false);
while (jt != successfulPoints.end()) {
DoubleVector nextValues = jt->objectiveValues();
if (equal(candidateValues[i],nextValues[i])) {
if (nextValues[otherIndex] < candidateValues[otherIndex]) {
it = successfulPoints.erase(it);
erasedIt = true;
break;
}
++jt;
}
else {
break;
}
}
if (erasedIt) {
continue;
}
result.push_back(*it);
it = successfulPoints.erase(it);
currentValues = result.back().objectiveValues();
if (!result.back().isTag("pareto")) {
result.back().addTag("pareto");
}
}
// remove outdated tags
for (OptimizationDataPoint& point : lastParetoFront) {
OptimizationDataPointVector::const_iterator it = std::find(result.begin(),result.end(),point);
if (it == result.end()) {
point.deleteTag("pareto");
}
}
return result;
}
std::vector< std::vector<QVariant> > SequentialSearch_Impl::getCandidateCombinations(
const DataPoint& dataPoint) const
{
Problem problem = dataPoint.problem();
std::vector<QVariant> currentValues = dataPoint.variableValues();
std::vector< std::vector<QVariant> > result;
for (int i = 0, n = problem.numVariables(); i < n; ++i) {
DiscreteVariable variable = problem.getVariable(i).cast<DiscreteVariable>();
// only use selected items
int currentValue = currentValues[i].toInt();
for (int j : variable.validValues(true)) {
if (currentValue != j) {
std::vector<QVariant> newValues = currentValues;
newValues[i] = j;
result.push_back(newValues);
}
}
}
return result;
}
QVariant SequentialSearch_Impl::toVariant() const {
QVariantMap map = Algorithm_Impl::toVariant().toMap();
map["algorithm_type"] = QString("SequentialSearch");
return QVariant(map);
}
SequentialSearch SequentialSearch_Impl::fromVariant(const QVariant& variant, const VersionString& version) {
QVariantMap map = variant.toMap();
SequentialSearchOptions options = SequentialSearchOptions_Impl::fromVariant(map["options"],version);
return SequentialSearch(toUUID(map["uuid"].toString().toStdString()),
toUUID(map["version_uuid"].toString().toStdString()),
map.contains("display_name") ? map["display_name"].toString().toStdString() : std::string(),
map.contains("description") ? map["description"].toString().toStdString() : std::string(),
map["complete"].toBool(),
map["failed"].toBool(),
map["iter"].toInt(),
options);
}
} // detail
SequentialSearch::SequentialSearch(const SequentialSearchOptions& options)
: OpenStudioAlgorithm(std::shared_ptr<detail::SequentialSearch_Impl>(
new detail::SequentialSearch_Impl(options)))
{
createCallbackForOptions();
}
SequentialSearch::SequentialSearch(const UUID& uuid,
const UUID& versionUUID,
const std::string& displayName,
const std::string& description,
bool complete,
bool failed,
int iter,
const SequentialSearchOptions& options)
: OpenStudioAlgorithm(std::shared_ptr<detail::SequentialSearch_Impl>(
new detail::SequentialSearch_Impl(uuid,
versionUUID,
displayName,
description,
complete,
failed,
iter,
options)))
{
createCallbackForOptions();
}
std::string SequentialSearch::standardName() {
return std::string("Sequential Search");
}
SequentialSearchOptions SequentialSearch::sequentialSearchOptions() const {
return getImpl<detail::SequentialSearch_Impl>()->sequentialSearchOptions();
}
std::vector<OptimizationDataPoint> SequentialSearch::getMinimumCurve(
unsigned i, Analysis& analysis) const
{
return getImpl<detail::SequentialSearch_Impl>()->getMinimumCurve(i,analysis);
}
std::vector<OptimizationDataPoint> SequentialSearch::getParetoFront(
Analysis& analysis) const
{
return getImpl<detail::SequentialSearch_Impl>()->getParetoFront(analysis);
}
std::vector< std::vector<QVariant> > SequentialSearch::getCandidateCombinations(
const DataPoint& dataPoint) const
{
return getImpl<detail::SequentialSearch_Impl>()->getCandidateCombinations(dataPoint);
}
/// @cond
SequentialSearch::SequentialSearch(std::shared_ptr<detail::SequentialSearch_Impl> impl)
: OpenStudioAlgorithm(impl)
{}
/// @endcond
} // analysis
} // openstudio
| 39.125749 | 121 | 0.592133 | [
"vector"
] |
b49ff394679f1b64f6921add28f86bbc13f65bf6 | 6,485 | hpp | C++ | libvast_test/vast/test/fixtures/table_slices.hpp | rdettai/vast | 0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa | [
"BSD-3-Clause"
] | 63 | 2016-04-22T01:50:03.000Z | 2019-07-31T15:50:36.000Z | libvast_test/vast/test/fixtures/table_slices.hpp | rdettai/vast | 0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa | [
"BSD-3-Clause"
] | 216 | 2017-01-24T16:25:43.000Z | 2019-08-01T19:37:00.000Z | libvast_test/vast/test/fixtures/table_slices.hpp | rdettai/vast | 0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa | [
"BSD-3-Clause"
] | 28 | 2016-05-19T13:09:19.000Z | 2019-04-12T15:11:42.000Z | // _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2019 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include "vast/fwd.hpp"
#include "vast/aliases.hpp"
#include "vast/atoms.hpp"
#include "vast/table_slice.hpp"
#include "vast/table_slice_builder.hpp"
#include "vast/table_slice_builder_factory.hpp"
#include "vast/test/fixtures/actor_system_and_events.hpp"
#include "vast/test/test.hpp"
#include "vast/type.hpp"
#include "vast/view.hpp"
#include <caf/binary_serializer.hpp>
#include <string>
#include <tuple>
#include <vector>
/// Helper macro to define a table-slice unit test.
#define TEST_TABLE_SLICE(builder, id) \
TEST(type) { \
initialize<builder>(table_slice_encoding::id); \
run(); \
}
namespace vast {
/// Constructs table slices filled with random content for testing purposes.
/// @param num_slices The number of table slices to generate.
/// @param slice_size The number of rows per table slices.
/// @param layout The layout of the table slice.
/// @param offset The offset of the first table slize.
/// @param seed The seed value for initializing the random-number generator.
/// @returns a list of randomnly filled table slices or an error.
/// @relates table_slice
caf::expected<std::vector<table_slice>>
make_random_table_slices(size_t num_slices, size_t slice_size, type layout,
id offset = 0, size_t seed = 0);
/// Converts the table slice into a 2-D matrix in row-major order such that
/// each row represents an event.
/// @param slice The table slice to convert.
/// @param first_row An offset to the first row to consider.
/// @param num_rows Then number of rows to consider. (0 = all rows)
/// @returns a 2-D matrix of data instances corresponding to *slice*.
/// @requires first_row < slice.rows()
/// @requires num_rows <= slice.rows() - first_row
/// @note This function exists primarily for unit testing because it performs
/// excessive memory allocations.
std::vector<std::vector<data>>
make_data(const table_slice& slice, size_t first_row = 0, size_t num_rows = 0);
std::vector<std::vector<data>>
make_data(const std::vector<table_slice>& slices);
} // namespace vast
namespace fixtures {
class table_slices : public deterministic_actor_system_and_events {
public:
explicit table_slices(std::string_view suite);
/// Registers a table slice implementation.
template <class Builder>
void initialize(vast::table_slice_encoding id) {
using namespace vast;
factory<table_slice_builder>::add<Builder>(id);
builder = factory<table_slice_builder>::make(id, layout);
if (builder == nullptr)
FAIL("builder factory could not construct a valid instance");
}
// FIXME: Remove when removing legacy table slices.
/// Registers a table slice implementation.
template <class T, class Builder>
void legacy_initialize() {
using namespace vast;
factory<table_slice_builder>::add<Builder>(T::class_id);
builder = factory<table_slice_builder>::make(T::class_id, layout);
if (builder == nullptr)
FAIL("builder factory could not construct a valid instance");
}
// Run all tests in the fixture.
void run();
private:
using triple = std::tuple<vast::integer, std::string, vast::real>;
caf::binary_serializer make_sink();
vast::table_slice make_slice();
vast::data_view at(size_t row, size_t col) const;
void test_add();
void test_equality();
void test_copy();
void test_manual_serialization();
void test_smart_pointer_serialization();
void test_message_serialization();
void test_append_column_to_index();
vast::type layout = type{
"test",
record_type{
{"a", bool_type{}},
{"b", integer_type{}},
{"c", count_type{}},
{"d", real_type{}},
{"e", duration_type{}},
{"f", time_type{}},
{"g", string_type{}},
{"h", pattern_type{}},
{"i", address_type{}},
{"j", subnet_type{}},
{"l", list_type{count_type{}}},
{"n", map_type{count_type{}, bool_type{}}},
// test_lists
{"va", list_type{bool_type{}}},
{"vb", list_type{integer_type{}}},
{"vc", list_type{count_type{}}},
{"vd", list_type{real_type{}}},
{"ve", list_type{duration_type{}}},
{"vf", list_type{time_type{}}},
{"vg", list_type{string_type{}}},
{"vh", list_type{pattern_type{}}},
{"vi", list_type{address_type{}}},
{"vj", list_type{subnet_type{}}},
// {"vl", list_type{list_type{count_type{}}}},
// {"vm", list_type{map_type{count_type{}, bool_type{}}}},
// -- test_maps_left
{"maa", map_type{bool_type{}, bool_type{}}},
{"mba", map_type{integer_type{}, bool_type{}}},
{"mca", map_type{count_type{}, bool_type{}}},
{"mda", map_type{real_type{}, bool_type{}}},
{"mea", map_type{duration_type{}, bool_type{}}},
{"mfa", map_type{time_type{}, bool_type{}}},
{"mga", map_type{string_type{}, bool_type{}}},
{"mha", map_type{pattern_type{}, bool_type{}}},
{"mia", map_type{address_type{}, bool_type{}}},
{"mja", map_type{subnet_type{}, bool_type{}}},
// {"mla", map_type{list_type{count_type{}}, bool_type{}}},
// {"mna", map_type{map_type{count_type{}, bool_type{}}, bool_type{}}},
// -- test_maps_right (intentionally no maa)
{"mab", map_type{bool_type{}, integer_type{}}},
{"mac", map_type{bool_type{}, count_type{}}},
{"mad", map_type{bool_type{}, real_type{}}},
{"mae", map_type{bool_type{}, duration_type{}}},
{"maf", map_type{bool_type{}, time_type{}}},
{"mag", map_type{bool_type{}, string_type{}}},
{"mah", map_type{bool_type{}, pattern_type{}}},
{"mai", map_type{bool_type{}, address_type{}}},
{"maj", map_type{bool_type{}, subnet_type{}}},
// {"mal", map_type{bool_type{}, list_type{count_type{}}}},
// {"man", map_type{bool_type{}, map_type{count_type{}, bool_type{}}}},
{"aas", type{"aas", type{"as", string_type{}}}},
},
};
vast::table_slice_builder_ptr builder;
std::vector<std::vector<vast::data>> test_data;
std::vector<char> buf;
};
} // namespace fixtures
| 34.865591 | 80 | 0.632537 | [
"vector"
] |
b4a28eb7f2aedc060b545d494105019152a3d55f | 2,500 | cpp | C++ | Chapter4-TreesAndGraphs/Chapter4-TreesAndGraphs.cpp | thlvu/CrackingTheCodeInterview | 991c523215406f74c9f8e02c0a91a7fb7c1f04de | [
"MIT"
] | null | null | null | Chapter4-TreesAndGraphs/Chapter4-TreesAndGraphs.cpp | thlvu/CrackingTheCodeInterview | 991c523215406f74c9f8e02c0a91a7fb7c1f04de | [
"MIT"
] | null | null | null | Chapter4-TreesAndGraphs/Chapter4-TreesAndGraphs.cpp | thlvu/CrackingTheCodeInterview | 991c523215406f74c9f8e02c0a91a7fb7c1f04de | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct GraphNode {
int data;
int visited;
vector<GraphNode> adjacents;
};
struct Graph {
vector<GraphNode> nodes;
};
bool routeBetweenNodes(GraphNode node1, GraphNode node2)
{
queue<GraphNode> q1;
queue<GraphNode> q2;
q1.push(node1);
q2.push(node2);
while (true)
{
if (q1.empty()) { return false; }
GraphNode n = q1.front();
q1.pop();
if (n.visited == 2) { return true; }
else { n.visited = 1; }
for (int i = 0; i < n.adjacents.size(); ++i)
{
if (n.adjacents[i].visited != 1) { q1.push(n.adjacents[i]); }
}
if (q2.empty()) { return false; }
n = q2.front();
q1.pop();
if (n.visited == 1) { return true; }
else { n.visited = 2; }
for (int i = 0; i < n.adjacents.size(); ++i)
{
if (n.adjacents[i].visited != 2) { q2.push(n.adjacents[i]); }
}
}
return true;
}
/* Route between nodes - Solution in the book.
*
* Solution suggets just traverse from one start node, not for both sides.
* The reason, I thought, is that it is just a simple question to check interviewee knows DFS and BFS.
* But as book introduced, run bfs for both sides are more effective if implementing BFS.
* BFS family advantages over DFS in efficiency and shortest path recognition,
* except that DFS is more easy to implement.
*/
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
};
TreeNode* minimalTree(vector<int> & arr, int start, int end)
{
if (start > end) { return nullptr; }
int mid = (start + end) / 2;
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->data = arr[mid];
root->left = minimalTree(arr, start, mid-1);
root->right = minimalTree(arr, mid+1, end);
return root;
}
void inorderTraverse(TreeNode* root, int i)
{
if (root != nullptr)
{
inorderTraverse(root->left, i+1);
printf("%d(%d) ", root->data, i);
inorderTraverse(root->right, i+1);
}
}
/* Minimal Tree - Solution in the book
*
* Suggested solution in the book is same to my implementation.
* But one thing I regret is that it does not construct complete binary tree.
*/
int main(void)
{
vector<int> arr;
for (int i = 0; i < 15; ++i) { arr.push_back(i); }
TreeNode* root = minimalTree(arr, 0, 14);
inorderTraverse(root, 0);
return 0;
} | 22.522523 | 101 | 0.5932 | [
"vector"
] |
b4a29731f732871ed83a9d3ff6f5be9ef95006ac | 14,639 | cpp | C++ | src/gallium/drivers/r600/sfn/sfn_nir_lower_fs_out_to_vector.cpp | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | src/gallium/drivers/r600/sfn/sfn_nir_lower_fs_out_to_vector.cpp | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | src/gallium/drivers/r600/sfn/sfn_nir_lower_fs_out_to_vector.cpp | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | /* -*- mesa-c++ -*-
*
* Copyright (c) 2019 Collabora LTD
*
* Author: Gert Wollny <gert.wollny@collabora.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* on the rights to use, copy, modify, merge, publish, distribute, sub
* license, 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE AUTHOR(S) AND/OR THEIR SUPPLIERS 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 "sfn_nir_lower_fs_out_to_vector.h"
#include "nir_builder.h"
#include "nir_deref.h"
#include "util/u_math.h"
#include <set>
#include <vector>
#include <array>
#include <algorithm>
namespace r600 {
using std::multiset;
using std::vector;
using std::array;
struct nir_intrinsic_instr_less {
bool operator () (const nir_intrinsic_instr *lhs, const nir_intrinsic_instr *rhs) const
{
nir_variable *vlhs = nir_deref_instr_get_variable(nir_src_as_deref(lhs->src[0]));
nir_variable *vrhs = nir_deref_instr_get_variable(nir_src_as_deref(rhs->src[0]));
auto ltype = glsl_get_base_type(vlhs->type);
auto rtype = glsl_get_base_type(vrhs->type);
if (ltype != rtype)
return ltype < rtype;
return vlhs->data.location < vrhs->data.location;
}
};
class NirLowerIOToVector {
public:
NirLowerIOToVector(int base_slot);
bool run(nir_function_impl *shader);
protected:
bool var_can_merge(const nir_variable *lhs, const nir_variable *rhs);
bool var_can_rewrite(nir_variable *var) const;
void create_new_io_vars(nir_shader *shader);
void create_new_io_var(nir_shader *shader, unsigned location, unsigned comps);
nir_deref_instr *clone_deref_array(nir_builder *b, nir_deref_instr *dst_tail,
const nir_deref_instr *src_head);
bool vectorize_block(nir_builder *b, nir_block *block);
bool instr_can_rewrite(nir_instr *instr);
bool vec_instr_set_remove(nir_builder *b,nir_instr *instr);
using InstrSet = multiset<nir_intrinsic_instr *, nir_intrinsic_instr_less>;
using InstrSubSet = std::pair<InstrSet::iterator, InstrSet::iterator>;
bool vec_instr_stack_pop(nir_builder *b, InstrSubSet& ir_set,
nir_intrinsic_instr *instr);
array<array<nir_variable *, 4>, 16> m_vars;
InstrSet m_block_io;
int m_next_index;
private:
virtual nir_variable_mode get_io_mode(nir_shader *shader) const = 0;
virtual bool instr_can_rewrite_type(nir_intrinsic_instr *intr) const = 0;
virtual bool var_can_rewrite_slot(nir_variable *var) const = 0;
virtual void create_new_io(nir_builder *b, nir_intrinsic_instr *intr, nir_variable *var,
nir_ssa_def **srcs, unsigned first_comp, unsigned num_comps) = 0;
int m_base_slot;
};
class NirLowerFSOutToVector : public NirLowerIOToVector {
public:
NirLowerFSOutToVector();
private:
nir_variable_mode get_io_mode(nir_shader *shader) const override;
bool var_can_rewrite_slot(nir_variable *var) const override;
void create_new_io(nir_builder *b, nir_intrinsic_instr *intr, nir_variable *var,
nir_ssa_def **srcs, unsigned first_comp, unsigned num_comps) override;
bool instr_can_rewrite_type(nir_intrinsic_instr *intr) const override;
nir_ssa_def *create_combined_vector(nir_builder *b, nir_ssa_def **srcs,
int first_comp, int num_comp);
};
bool r600_lower_fs_out_to_vector(nir_shader *shader)
{
NirLowerFSOutToVector processor;
assert(shader->info.stage == MESA_SHADER_FRAGMENT);
bool progress = false;
nir_foreach_function(function, shader) {
if (function->impl)
progress |= processor.run(function->impl);
}
return progress;
}
NirLowerIOToVector::NirLowerIOToVector(int base_slot):
m_next_index(0),
m_base_slot(base_slot)
{
for(auto& a : m_vars)
for(auto& aa : a)
aa = nullptr;
}
bool NirLowerIOToVector::run(nir_function_impl *impl)
{
nir_builder b;
nir_builder_init(&b, impl);
nir_metadata_require(impl, nir_metadata_dominance);
create_new_io_vars(impl->function->shader);
bool progress = vectorize_block(&b, nir_start_block(impl));
if (progress) {
nir_metadata_preserve(impl, nir_metadata_block_index | nir_metadata_dominance);
} else {
nir_metadata_preserve(impl, nir_metadata_all);
}
return progress;
}
void NirLowerIOToVector::create_new_io_vars(nir_shader *shader)
{
nir_variable_mode mode = get_io_mode(shader);
bool can_rewrite_vars = false;
nir_foreach_variable_with_modes(var, shader, mode) {
if (var_can_rewrite(var)) {
can_rewrite_vars = true;
unsigned loc = var->data.location - m_base_slot;
m_vars[loc][var->data.location_frac] = var;
}
}
if (!can_rewrite_vars)
return;
/* We don't handle combining vars of different type e.g. different array
* lengths.
*/
for (unsigned i = 0; i < 16; i++) {
unsigned comps = 0;
for (unsigned j = 0; j < 3; j++) {
if (!m_vars[i][j])
continue;
for (unsigned k = j + 1; k < 4; k++) {
if (!m_vars[i][k])
continue;
if (!var_can_merge(m_vars[i][j], m_vars[i][k]))
continue;
/* Set comps */
for (unsigned n = 0; n < glsl_get_components(m_vars[i][j]->type); ++n)
comps |= 1 << (m_vars[i][j]->data.location_frac + n);
for (unsigned n = 0; n < glsl_get_components(m_vars[i][k]->type); ++n)
comps |= 1 << (m_vars[i][k]->data.location_frac + n);
}
}
if (comps)
create_new_io_var(shader, i, comps);
}
}
bool
NirLowerIOToVector::var_can_merge(const nir_variable *lhs,
const nir_variable *rhs)
{
return (glsl_get_base_type(lhs->type) == glsl_get_base_type(rhs->type));
}
void
NirLowerIOToVector::create_new_io_var(nir_shader *shader,
unsigned location, unsigned comps)
{
unsigned num_comps = util_bitcount(comps);
assert(num_comps > 1);
/* Note: u_bit_scan() strips a component of the comps bitfield here */
unsigned first_comp = u_bit_scan(&comps);
nir_variable *var = nir_variable_clone(m_vars[location][first_comp], shader);
var->data.location_frac = first_comp;
var->type = glsl_replace_vector_type(var->type, num_comps);
nir_shader_add_variable(shader, var);
m_vars[location][first_comp] = var;
while (comps) {
const int comp = u_bit_scan(&comps);
if (m_vars[location][comp]) {
m_vars[location][comp] = var;
}
}
}
bool NirLowerIOToVector::var_can_rewrite(nir_variable *var) const
{
/* Skip complex types we don't split in the first place */
if (!glsl_type_is_vector_or_scalar(glsl_without_array(var->type)))
return false;
if (glsl_get_bit_size(glsl_without_array(var->type)) != 32)
return false;
return var_can_rewrite_slot(var);
}
bool
NirLowerIOToVector::vectorize_block(nir_builder *b, nir_block *block)
{
bool progress = false;
nir_foreach_instr_safe(instr, block) {
if (instr_can_rewrite(instr)) {
instr->index = m_next_index++;
nir_intrinsic_instr *ir = nir_instr_as_intrinsic(instr);
m_block_io.insert(ir);
}
}
for (unsigned i = 0; i < block->num_dom_children; i++) {
nir_block *child = block->dom_children[i];
progress |= vectorize_block(b, child);
}
nir_foreach_instr_reverse_safe(instr, block) {
progress |= vec_instr_set_remove(b, instr);
}
m_block_io.clear();
return progress;
}
bool NirLowerIOToVector::instr_can_rewrite(nir_instr *instr)
{
if (instr->type != nir_instr_type_intrinsic)
return false;
nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
if (intr->num_components > 3)
return false;
return instr_can_rewrite_type(intr);
}
bool NirLowerIOToVector::vec_instr_set_remove(nir_builder *b,nir_instr *instr)
{
if (!instr_can_rewrite(instr))
return false;
nir_intrinsic_instr *ir = nir_instr_as_intrinsic(instr);
auto entry = m_block_io.equal_range(ir);
if (entry.first != m_block_io.end()) {
vec_instr_stack_pop(b, entry, ir);
}
return true;
}
nir_deref_instr *
NirLowerIOToVector::clone_deref_array(nir_builder *b, nir_deref_instr *dst_tail,
const nir_deref_instr *src_head)
{
const nir_deref_instr *parent = nir_deref_instr_parent(src_head);
if (!parent)
return dst_tail;
assert(src_head->deref_type == nir_deref_type_array);
dst_tail = clone_deref_array(b, dst_tail, parent);
return nir_build_deref_array(b, dst_tail,
nir_ssa_for_src(b, src_head->arr.index, 1));
}
NirLowerFSOutToVector::NirLowerFSOutToVector():
NirLowerIOToVector(FRAG_RESULT_COLOR)
{
}
bool NirLowerFSOutToVector::var_can_rewrite_slot(nir_variable *var) const
{
return ((var->data.mode == nir_var_shader_out) &&
((var->data.location == FRAG_RESULT_COLOR) ||
((var->data.location >= FRAG_RESULT_DATA0) &&
(var->data.location <= FRAG_RESULT_DATA7))));
}
bool NirLowerIOToVector::vec_instr_stack_pop(nir_builder *b, InstrSubSet &ir_set,
nir_intrinsic_instr *instr)
{
vector< nir_intrinsic_instr *> ir_sorted_set(ir_set.first, ir_set.second);
std::sort(ir_sorted_set.begin(), ir_sorted_set.end(),
[](const nir_intrinsic_instr *lhs, const nir_intrinsic_instr *rhs) {
return lhs->instr.index > rhs->instr.index;
}
);
nir_intrinsic_instr *intr = *ir_sorted_set.begin();
nir_variable *var = nir_deref_instr_get_variable(nir_src_as_deref(intr->src[0]));
unsigned loc = var->data.location - m_base_slot;
nir_variable *new_var = m_vars[loc][var->data.location_frac];
unsigned num_comps = glsl_get_vector_elements(glsl_without_array(new_var->type));
unsigned old_num_comps = glsl_get_vector_elements(glsl_without_array(var->type));
/* Don't bother walking the stack if this component can't be vectorised. */
if (old_num_comps > 3) {
return false;
}
if (new_var == var) {
return false;
}
b->cursor = nir_after_instr(&intr->instr);
nir_ssa_undef_instr *instr_undef =
nir_ssa_undef_instr_create(b->shader, 1, 32);
nir_builder_instr_insert(b, &instr_undef->instr);
nir_ssa_def *srcs[4];
for (int i = 0; i < 4; i++) {
srcs[i] = &instr_undef->def;
}
srcs[var->data.location_frac] = intr->src[1].ssa;
for (auto k = ir_sorted_set.begin() + 1; k != ir_sorted_set.end(); ++k) {
nir_intrinsic_instr *intr2 = *k;
nir_variable *var2 =
nir_deref_instr_get_variable(nir_src_as_deref(intr2->src[0]));
unsigned loc2 = var->data.location - m_base_slot;
if (m_vars[loc][var->data.location_frac] !=
m_vars[loc2][var2->data.location_frac]) {
continue;
}
assert(glsl_get_vector_elements(glsl_without_array(var2->type)) < 4);
if (srcs[var2->data.location_frac] == &instr_undef->def) {
assert(intr2->src[1].is_ssa);
assert(intr2->src[1].ssa);
srcs[var2->data.location_frac] = intr2->src[1].ssa;
}
nir_instr_remove(&intr2->instr);
}
create_new_io(b, intr, new_var, srcs, new_var->data.location_frac,
num_comps);
return true;
}
nir_variable_mode NirLowerFSOutToVector::get_io_mode(nir_shader *shader) const
{
return nir_var_shader_out;
}
void
NirLowerFSOutToVector::create_new_io(nir_builder *b, nir_intrinsic_instr *intr, nir_variable *var,
nir_ssa_def **srcs, unsigned first_comp, unsigned num_comps)
{
b->cursor = nir_before_instr(&intr->instr);
nir_intrinsic_instr *new_intr =
nir_intrinsic_instr_create(b->shader, intr->intrinsic);
new_intr->num_components = num_comps;
nir_intrinsic_set_write_mask(new_intr, (1 << num_comps) - 1);
nir_deref_instr *deref = nir_build_deref_var(b, var);
deref = clone_deref_array(b, deref, nir_src_as_deref(intr->src[0]));
new_intr->src[0] = nir_src_for_ssa(&deref->dest.ssa);
new_intr->src[1] = nir_src_for_ssa(create_combined_vector(b, srcs, first_comp, num_comps));
nir_builder_instr_insert(b, &new_intr->instr);
/* Remove the old store intrinsic */
nir_instr_remove(&intr->instr);
}
bool NirLowerFSOutToVector::instr_can_rewrite_type(nir_intrinsic_instr *intr) const
{
if (intr->intrinsic != nir_intrinsic_store_deref)
return false;
nir_deref_instr *deref = nir_src_as_deref(intr->src[0]);
if (!nir_deref_mode_is(deref, nir_var_shader_out))
return false;
return var_can_rewrite(nir_deref_instr_get_variable(deref));
}
nir_ssa_def *NirLowerFSOutToVector::create_combined_vector(nir_builder *b, nir_ssa_def **srcs,
int first_comp, int num_comp)
{
nir_op op;
switch (num_comp) {
case 2: op = nir_op_vec2; break;
case 3: op = nir_op_vec3; break;
case 4: op = nir_op_vec4; break;
default:
unreachable("combined vector must have 2 to 4 components");
}
nir_alu_instr * instr = nir_alu_instr_create(b->shader, op);
instr->exact = b->exact;
int i = 0;
unsigned k = 0;
while (i < num_comp) {
nir_ssa_def *s = srcs[first_comp + k];
for(uint8_t kk = 0; kk < s->num_components && i < num_comp; ++kk) {
instr->src[i].src = nir_src_for_ssa(s);
instr->src[i].swizzle[0] = kk;
++i;
}
k += s->num_components;
}
nir_ssa_dest_init(&instr->instr, &instr->dest.dest, num_comp, 32, NULL);
instr->dest.write_mask = (1 << num_comp) - 1;
nir_builder_instr_insert(b, &instr->instr);
return &instr->dest.dest.ssa;
}
}
| 31.48172 | 100 | 0.675251 | [
"vector"
] |
b4a2c2eb8c56e0882864a9aadf40866f9ada743a | 14,586 | cpp | C++ | src/tests/test_modes.cpp | clayne/botan | 1f16adea08c4c9bf3fb0fbf699d284cb48150898 | [
"BSD-2-Clause"
] | 1,988 | 2015-01-04T02:58:16.000Z | 2022-03-31T18:03:37.000Z | src/tests/test_modes.cpp | clayne/botan | 1f16adea08c4c9bf3fb0fbf699d284cb48150898 | [
"BSD-2-Clause"
] | 2,455 | 2015-01-04T17:53:39.000Z | 2022-03-30T18:15:31.000Z | src/tests/test_modes.cpp | clayne/botan | 1f16adea08c4c9bf3fb0fbf699d284cb48150898 | [
"BSD-2-Clause"
] | 590 | 2015-01-07T04:05:12.000Z | 2022-03-30T20:42:05.000Z | /*
* (C) 2014,2015,2017 Jack Lloyd
* (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity
* (C) 2018 Ribose Inc
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_CIPHER_MODES)
#include <botan/cipher_mode.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_CIPHER_MODES)
class Cipher_Mode_Tests final : public Text_Based_Test
{
public:
Cipher_Mode_Tests()
: Text_Based_Test("modes", "Key,Nonce,In,Out") {}
std::vector<std::string> possible_providers(const std::string& algo) override
{
return provider_filter(Botan::Cipher_Mode::providers(algo));
}
Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
{
const std::vector<uint8_t> key = vars.get_req_bin("Key");
const std::vector<uint8_t> nonce = vars.get_req_bin("Nonce");
const std::vector<uint8_t> input = vars.get_req_bin("In");
const std::vector<uint8_t> expected = vars.get_req_bin("Out");
Test::Result result(algo);
const std::vector<std::string> providers = possible_providers(algo);
if(providers.empty())
{
result.note_missing("cipher mode " + algo);
return result;
}
for(auto&& provider_ask : providers)
{
std::unique_ptr<Botan::Cipher_Mode> enc(Botan::Cipher_Mode::create(
algo, Botan::ENCRYPTION, provider_ask));
std::unique_ptr<Botan::Cipher_Mode> dec(Botan::Cipher_Mode::create(
algo, Botan::DECRYPTION, provider_ask));
if(!enc || !dec)
{
if(enc)
result.test_failure("Provider " + provider_ask + " has encrypt but not decrypt");
if(dec)
result.test_failure("Provider " + provider_ask + " has decrypt but not encrypt");
result.note_missing(algo);
return result;
}
result.test_eq("enc and dec granularity is the same",
enc->update_granularity(), dec->update_granularity());
try
{
test_mode(result, algo, provider_ask, "encryption", *enc, key, nonce, input, expected);
}
catch(Botan::Exception& e)
{
result.test_failure("Encryption tests failed", e.what());
}
try
{
test_mode(result, algo, provider_ask, "decryption", *dec, key, nonce, expected, input);
}
catch(Botan::Exception& e)
{
result.test_failure("Decryption tests failed", e.what());
}
}
return result;
}
private:
void test_mode(Test::Result& result,
const std::string& algo,
const std::string& provider,
const std::string& direction,
Botan::Cipher_Mode& mode,
const std::vector<uint8_t>& key,
const std::vector<uint8_t>& nonce,
const std::vector<uint8_t>& input,
const std::vector<uint8_t>& expected)
{
const bool is_cbc = (algo.find("/CBC") != std::string::npos);
const bool is_ctr = (algo.find("CTR") != std::string::npos);
result.test_eq("name", mode.name(), algo);
// Some modes report base even if got from another provider
if(mode.provider() != "base")
{
result.test_eq("provider", mode.provider(), provider);
}
result.test_eq("mode not authenticated", mode.authenticated(), false);
const size_t update_granularity = mode.update_granularity();
const size_t min_final_bytes = mode.minimum_final_size();
// FFI currently requires this, so assure it is true for all modes
result.test_gt("buffer sizes ok", update_granularity, min_final_bytes);
result.test_throws("Unkeyed object throws", [&]() {
Botan::secure_vector<uint8_t> bad(update_granularity);
mode.finish(bad);
});
if(is_cbc)
{
// can't test equal due to CBC padding
if(direction == "encryption")
{
result.test_lte("output_length", mode.output_length(input.size()), expected.size());
}
else
{
result.test_gte("output_length", mode.output_length(input.size()), expected.size());
}
}
else
{
// assume all other modes are not expanding (currently true)
result.test_eq("output_length", mode.output_length(input.size()), expected.size());
}
result.confirm("default nonce size is allowed",
mode.valid_nonce_length(mode.default_nonce_length()));
// Test that disallowed nonce sizes result in an exception
static constexpr size_t large_nonce_size = 65000;
result.test_eq("Large nonce not allowed", mode.valid_nonce_length(large_nonce_size), false);
result.test_throws("Large nonce causes exception",
[&mode]() { mode.start(nullptr, large_nonce_size); });
Botan::secure_vector<uint8_t> garbage = Test::rng().random_vec(update_granularity);
// Test to make sure reset() resets what we need it to
result.test_throws("Cannot process data (update) until key is set",
[&]() { mode.update(garbage); });
result.test_throws("Cannot process data (finish) until key is set",
[&]() { mode.finish(garbage); });
mode.set_key(mutate_vec(key));
if(is_ctr == false)
{
result.test_throws("Cannot process data until nonce is set",
[&]() { mode.update(garbage); });
}
mode.start(mutate_vec(nonce));
mode.reset();
if(is_ctr == false)
{
result.test_throws("Cannot process data until nonce is set (after start/reset)",
[&]() { mode.update(garbage); });
}
mode.start(mutate_vec(nonce));
mode.update(garbage);
mode.reset();
mode.set_key(key);
mode.start(nonce);
Botan::secure_vector<uint8_t> buf;
buf.assign(input.begin(), input.end());
mode.finish(buf);
result.test_eq(direction + " all-in-one", buf, expected);
// additionally test update() and process() if possible
if(input.size() >= update_granularity + min_final_bytes)
{
const size_t max_blocks_to_process = (input.size() - min_final_bytes) / update_granularity;
const size_t bytes_to_process = max_blocks_to_process * update_granularity;
// test update, 1 block at a time
if(max_blocks_to_process > 1)
{
Botan::secure_vector<uint8_t> block(update_granularity);
buf.clear();
mode.start(nonce);
for(size_t i = 0; i != max_blocks_to_process; ++i)
{
block.assign(input.data() + i*update_granularity,
input.data() + (i+1)*update_granularity);
mode.update(block);
buf += block;
}
Botan::secure_vector<uint8_t> last_bits(input.data() + bytes_to_process, input.data() + input.size());
mode.finish(last_bits);
buf += last_bits;
result.test_eq(direction + " update-1", buf, expected);
}
// test update with maximum length input
buf.assign(input.data(), input.data() + bytes_to_process);
Botan::secure_vector<uint8_t> last_bits(input.data() + bytes_to_process, input.data() + input.size());
mode.start(nonce);
mode.update(buf);
mode.finish(last_bits);
buf += last_bits;
result.test_eq(direction + " update-all", buf, expected);
// test process with maximum length input
mode.start(nonce);
buf.assign(input.begin(), input.end());
const size_t bytes_written = mode.process(buf.data(), bytes_to_process);
result.test_eq("correct number of bytes processed", bytes_written, bytes_to_process);
mode.finish(buf, bytes_to_process);
result.test_eq(direction + " process", buf, expected);
}
mode.clear();
result.test_throws("Unkeyed object throws after clear", [&]() {
Botan::secure_vector<uint8_t> bad(update_granularity);
mode.finish(bad);
});
}
};
BOTAN_REGISTER_TEST("modes", "modes", Cipher_Mode_Tests);
class Cipher_Mode_IV_Carry_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
results.push_back(test_cbc_iv_carry());
results.push_back(test_cfb_iv_carry());
results.push_back(test_ctr_iv_carry());
return results;
}
private:
Test::Result test_cbc_iv_carry()
{
Test::Result result("CBC IV carry");
#if defined(BOTAN_HAS_MODE_CBC) && defined(BOTAN_HAS_AES)
std::unique_ptr<Botan::Cipher_Mode> enc(
Botan::Cipher_Mode::create("AES-128/CBC/PKCS7", Botan::ENCRYPTION));
std::unique_ptr<Botan::Cipher_Mode> dec(
Botan::Cipher_Mode::create("AES-128/CBC/PKCS7", Botan::DECRYPTION));
const std::vector<uint8_t> key(16, 0xAA);
const std::vector<uint8_t> iv(16, 0xAA);
Botan::secure_vector<uint8_t> msg1 =
Botan::hex_decode_locked("446F6E27742075736520706C61696E20434243206D6F6465");
Botan::secure_vector<uint8_t> msg2 =
Botan::hex_decode_locked("49562063617272796F766572");
Botan::secure_vector<uint8_t> msg3 =
Botan::hex_decode_locked("49562063617272796F76657232");
enc->set_key(key);
dec->set_key(key);
enc->start(iv);
enc->finish(msg1);
result.test_eq("First ciphertext", msg1,
"9BDD7300E0CB61CA71FFF957A71605DB6836159C36781246A1ADF50982757F4B");
enc->start();
enc->finish(msg2);
result.test_eq("Second ciphertext", msg2,
"AA8D682958A4A044735DAC502B274DB2");
enc->start();
enc->finish(msg3);
result.test_eq("Third ciphertext", msg3,
"1241B9976F73051BCF809525D6E86C25");
dec->start(iv);
dec->finish(msg1);
dec->start();
dec->finish(msg2);
dec->start();
dec->finish(msg3);
result.test_eq("Third plaintext", msg3, "49562063617272796F76657232");
#endif
return result;
}
Test::Result test_cfb_iv_carry()
{
Test::Result result("CFB IV carry");
#if defined(BOTAN_HAS_MODE_CFB) && defined(BOTAN_HAS_AES)
std::unique_ptr<Botan::Cipher_Mode> enc(
Botan::Cipher_Mode::create("AES-128/CFB(8)", Botan::ENCRYPTION));
std::unique_ptr<Botan::Cipher_Mode> dec(
Botan::Cipher_Mode::create("AES-128/CFB(8)", Botan::DECRYPTION));
const std::vector<uint8_t> key(16, 0xAA);
const std::vector<uint8_t> iv(16, 0xAB);
Botan::secure_vector<uint8_t> msg1 = Botan::hex_decode_locked("ABCDEF01234567");
Botan::secure_vector<uint8_t> msg2 = Botan::hex_decode_locked("0000123456ABCDEF");
Botan::secure_vector<uint8_t> msg3 = Botan::hex_decode_locked("012345");
enc->set_key(key);
dec->set_key(key);
enc->start(iv);
enc->finish(msg1);
result.test_eq("First ciphertext", msg1, "a51522387c4c9b");
enc->start();
enc->finish(msg2);
result.test_eq("Second ciphertext", msg2, "105457dc2e0649d4");
enc->start();
enc->finish(msg3);
result.test_eq("Third ciphertext", msg3, "53bd65");
dec->start(iv);
dec->finish(msg1);
result.test_eq("First plaintext", msg1, "ABCDEF01234567");
dec->start();
dec->finish(msg2);
result.test_eq("Second plaintext", msg2, "0000123456ABCDEF");
dec->start();
dec->finish(msg3);
result.test_eq("Third plaintext", msg3, "012345");
#endif
return result;
}
Test::Result test_ctr_iv_carry()
{
Test::Result result("CTR IV carry");
#if defined(BOTAN_HAS_CTR_BE) && defined(BOTAN_HAS_AES)
std::unique_ptr<Botan::Cipher_Mode> enc(
Botan::Cipher_Mode::create("AES-128/CTR-BE", Botan::ENCRYPTION));
std::unique_ptr<Botan::Cipher_Mode> dec(
Botan::Cipher_Mode::create("AES-128/CTR-BE", Botan::DECRYPTION));
const std::vector<uint8_t> key =
Botan::hex_decode("2B7E151628AED2A6ABF7158809CF4F3C");
const std::vector<uint8_t> iv =
Botan::hex_decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF");
enc->set_key(key);
dec->set_key(key);
const std::vector<std::string> exp_ciphertext = {
"EC",
"8CDF",
"739860",
"7CB0F2D2",
"1675EA9EA1",
"E4362B7C3C67",
"73516318A077D7",
"FC5073AE6A2CC378",
"7889374FBEB4C81B17",
"BA6C44E89C399FF0F198C",
};
for(size_t i = 1; i != 10; ++i)
{
if(i == 1)
{
enc->start(iv);
dec->start(iv);
}
else
{
enc->start();
dec->start();
}
Botan::secure_vector<uint8_t> msg(i, 0);
enc->finish(msg);
result.test_eq("Ciphertext", msg, exp_ciphertext[i-1].c_str());
dec->finish(msg);
for(size_t j = 0; j != msg.size(); ++j)
result.test_eq("Plaintext zeros", static_cast<size_t>(msg[j]), 0);
}
#endif
return result;
}
};
BOTAN_REGISTER_TEST("modes", "iv_carryover", Cipher_Mode_IV_Carry_Tests);
#endif
}
| 33.30137 | 117 | 0.552379 | [
"object",
"vector"
] |
b4a5cf7217670144805f306bb276721e61c884e1 | 12,188 | cpp | C++ | src/ParserRVM.cpp | liweimax/rvmparser | 3cb5311ca3d76dc02811510bacf2d0fb261edc1f | [
"MIT"
] | 1 | 2019-09-19T08:40:16.000Z | 2019-09-19T08:40:16.000Z | src/ParserRVM.cpp | cyanxwh/rvmparser | 3f188025eb407a416ed11303751eb0ab0dd43f7f | [
"MIT"
] | null | null | null | src/ParserRVM.cpp | cyanxwh/rvmparser | 3f188025eb407a416ed11303751eb0ab0dd43f7f | [
"MIT"
] | null | null | null | #include "Parser.h"
#include "StoreVisitor.h"
#include "Store.h"
#include <iostream>
#include <string>
#include <cstdio>
#include <cctype>
#include <vector>
#include <cassert>
#include "LinAlgOps.h"
namespace {
struct Context
{
Store* store;
char* buf;
size_t buf_size;
std::vector<Group*> group_stack;
};
const char* read_uint32_be(uint32_t& rv, const char* p, const char* e)
{
auto * q = reinterpret_cast<const uint8_t*>(p);
rv = q[0] << 24 | q[1] << 16 | q[2] << 8 | q[3];
return p + 4;
}
const char* read_float32_be(float& rv, const char* p, const char* e)
{
union {
float f;
uint32_t u;
};
auto * q = reinterpret_cast<const uint8_t*>(p);
u = q[0] << 24 | q[1] << 16 | q[2] << 8 | q[3];
rv = f;
return p + 4;
}
constexpr uint32_t id(const char* str)
{
return str[3] << 24 | str[2] << 16 | str[1] << 8 | str[0];
}
const char* read_string(const char** dst, Store* store, const char* p, const char* e)
{
uint32_t len;
p = read_uint32_be(len, p, e);
unsigned l = 4 * len;
for (unsigned i = 0; i < l; i++) {
if (p[i] == 0) {
l = i;
break;
}
}
*dst = store->strings.intern(p, p + l);
return p + 4 * len;
}
const char* parse_chunk_header(char* id, uint32_t& len, uint32_t& dunno, const char* p, const char* e)
{
unsigned i = 0;
for (i = 0; i < 4 && p + 4 <= e; i++) {
assert(p[0] == 0);
assert(p[1] == 0);
assert(p[2] == 0);
id[i] = p[3];
p += 4;
}
for (; i < 4; i++) {
id[i] = ' ';
}
if (p + 8 <= e) {
p = read_uint32_be(len, p, e);
p = read_uint32_be(dunno, p, e);
}
else {
len = ~0;
dunno = ~0;
fprintf(stderr, "Chunk '%s' EOF after %zd bytes\n", id, e - p);
p = e;
}
return p;
}
const char* parse_head(Context* ctx, const char* p, const char* e)
{
assert(ctx->group_stack.empty());
auto * g = ctx->store->newGroup(nullptr, Group::Kind::File);
ctx->group_stack.push_back(g);
uint32_t version;
p = read_uint32_be(version, p, e);
p = read_string(&g->file.info, ctx->store, p, e);
p = read_string(&g->file.note, ctx->store, p, e);
p = read_string(&g->file.date, ctx->store, p, e);
p = read_string(&g->file.user, ctx->store, p, e);
if (2 <= version) {
p = read_string(&g->file.encoding, ctx->store, p, e);
}
else {
g->file.encoding = ctx->store->strings.intern("");
}
return p;
}
const char* parse_modl(Context* ctx, const char* p, const char* e)
{
assert(!ctx->group_stack.empty());
auto * g = ctx->store->newGroup(ctx->group_stack.back(), Group::Kind::Model);
ctx->group_stack.push_back(g);
uint32_t version;
p = read_uint32_be(version, p, e);
p = read_string(&g->model.project, ctx->store, p, e);
p = read_string(&g->model.name, ctx->store, p, e);
//fprintf(stderr, "modl project='%s', name='%s'\n", g->model.project, g->model.name);
return p;
}
const char* parse_prim(Context* ctx, const char* p, const char* e)
{
assert(!ctx->group_stack.empty());
if (ctx->group_stack.back()->kind != Group::Kind::Group) {
ctx->store->setErrorString("In PRIM, parent chunk is not CNTB");
return nullptr;
}
uint32_t version, kind;
p = read_uint32_be(version, p, e);
p = read_uint32_be(kind, p, e);
auto * g = ctx->store->newGeometry(ctx->group_stack.back());
for (unsigned i = 0; i < 12; i++) {
p = read_float32_be(g->M_3x4.data[i], p, e);
}
for (unsigned i = 0; i < 6; i++) {
p = read_float32_be(g->bboxLocal.data[i], p, e);
}
g->bboxWorld = transform(g->M_3x4, g->bboxLocal);
switch (kind) {
case 1:
g->kind = Geometry::Kind::Pyramid;
p = read_float32_be(g->pyramid.bottom[0], p, e);
p = read_float32_be(g->pyramid.bottom[1], p, e);
p = read_float32_be(g->pyramid.top[0], p, e);
p = read_float32_be(g->pyramid.top[1], p, e);
p = read_float32_be(g->pyramid.offset[0], p, e);
p = read_float32_be(g->pyramid.offset[1], p, e);
p = read_float32_be(g->pyramid.height, p, e);
break;
case 2:
g->kind = Geometry::Kind::Box;
p = read_float32_be(g->box.lengths[0], p, e);
p = read_float32_be(g->box.lengths[1], p, e);
p = read_float32_be(g->box.lengths[2], p, e);
break;
case 3:
g->kind = Geometry::Kind::RectangularTorus;
p = read_float32_be(g->rectangularTorus.inner_radius, p, e);
p = read_float32_be(g->rectangularTorus.outer_radius, p, e);
p = read_float32_be(g->rectangularTorus.height, p, e);
p = read_float32_be(g->rectangularTorus.angle, p, e);
break;
case 4:
g->kind = Geometry::Kind::CircularTorus;
p = read_float32_be(g->circularTorus.offset, p, e);
p = read_float32_be(g->circularTorus.radius, p, e);
p = read_float32_be(g->circularTorus.angle, p, e);
break;
case 5:
g->kind = Geometry::Kind::EllipticalDish;
p = read_float32_be(g->ellipticalDish.baseRadius, p, e);
p = read_float32_be(g->ellipticalDish.height, p, e);
break;
case 6:
g->kind = Geometry::Kind::SphericalDish;
p = read_float32_be(g->sphericalDish.baseRadius, p, e);
p = read_float32_be(g->sphericalDish.height, p, e);
break;
case 7:
g->kind = Geometry::Kind::Snout;
p = read_float32_be(g->snout.radius_b, p, e);
p = read_float32_be(g->snout.radius_t, p, e);
p = read_float32_be(g->snout.height, p, e);
p = read_float32_be(g->snout.offset[0], p, e);
p = read_float32_be(g->snout.offset[1], p, e);
p = read_float32_be(g->snout.bshear[0], p, e);
p = read_float32_be(g->snout.bshear[1], p, e);
p = read_float32_be(g->snout.tshear[0], p, e);
p = read_float32_be(g->snout.tshear[1], p, e);
break;
case 8:
g->kind = Geometry::Kind::Cylinder;
p = read_float32_be(g->cylinder.radius, p, e);
p = read_float32_be(g->cylinder.height, p, e);
break;
case 9:
g->kind = Geometry::Kind::Cylinder;
p = read_float32_be(g->sphere.diameter, p, e);
break;
case 10:
g->kind = Geometry::Kind::Line;
p = read_float32_be(g->line.a, p, e);
p = read_float32_be(g->line.b, p, e);
break;
case 11:
g->kind = Geometry::Kind::FacetGroup;
p = read_uint32_be(g->facetGroup.polygons_n, p, e);
g->facetGroup.polygons = (Polygon*)ctx->store->arena.alloc(sizeof(Polygon)*g->facetGroup.polygons_n);
for (unsigned pi = 0; pi < g->facetGroup.polygons_n; pi++) {
auto & poly = g->facetGroup.polygons[pi];
p = read_uint32_be(poly.contours_n, p, e);
poly.contours = (Contour*)ctx->store->arena.alloc(sizeof(Contour)*poly.contours_n);
for (unsigned gi = 0; gi < poly.contours_n; gi++) {
auto & cont = poly.contours[gi];
p = read_uint32_be(cont.vertices_n, p, e);
cont.vertices = (float*)ctx->store->arena.alloc(3 * sizeof(float)*cont.vertices_n);
cont.normals = (float*)ctx->store->arena.alloc(3 * sizeof(float)*cont.vertices_n);
for (unsigned vi = 0; vi < cont.vertices_n; vi++) {
for (unsigned i = 0; i < 3; i++) {
p = read_float32_be(cont.vertices[3 * vi + i], p, e);
}
for (unsigned i = 0; i < 3; i++) {
p = read_float32_be(cont.normals[3 * vi + i], p, e);
}
}
}
}
break;
default:
snprintf(ctx->buf, ctx->buf_size, "In PRIM, unknown primitive kind %d", kind);
ctx->store->setErrorString(ctx->buf);
return nullptr;
}
return p;
}
const char* parse_cntb(Context* ctx, const char* p, const char* e)
{
assert(!ctx->group_stack.empty());
auto * g = ctx->store->newGroup(ctx->group_stack.back(), Group::Kind::Group);
ctx->group_stack.push_back(g);
uint32_t version;
p = read_uint32_be(version, p, e);
p = read_string(&g->group.name, ctx->store, p, e);
//fprintf(stderr, "group '%s' %p\n", g->group.name, g->group.name);
// Translation seems to be a reference point that can be used as a local frame for objects in the group.
// The transform is not relative to this reference point.
for (unsigned i = 0; i < 3; i++) {
p = read_float32_be(g->group.translation[i], p, e);
g->group.translation[i] *= 0.001f;
}
p = read_uint32_be(g->group.material, p, e);
uint32_t translucency_code = 0;
float translucency = 0.0;
if (p[0] != 0)
{
p = read_uint32_be(translucency_code, p, e);
translucency_code = translucency_code >> 16;
for (int i = 16; i > 0; --i)
{
if (translucency_code & 1)
translucency += pow(2, -i);
translucency_code = translucency_code >> 1;
}
g->group.translucency = translucency;
}
// process children
char chunk_id[5] = { 0, 0, 0, 0, 0 };
auto l = p;
uint32_t len, dunno;
p = parse_chunk_header(chunk_id, len, dunno, p, e);
auto id_chunk_id = id(chunk_id);
while (p < e && id_chunk_id != id("CNTE")) {
switch (id_chunk_id) {
case id("CNTB"):
p = parse_cntb(ctx, p, e);
if (p == nullptr) return p;
break;
case id("PRIM"):
p = parse_prim(ctx, p, e);
if (p == nullptr) return p;
break;
default:
snprintf(ctx->buf, ctx->buf_size, "In CNTB, unknown chunk id %s", chunk_id);
ctx->store->setErrorString(ctx->buf);
return nullptr;
}
l = p;
p = parse_chunk_header(chunk_id, len, dunno, p, e);
id_chunk_id = id(chunk_id);
}
if (id_chunk_id == id("CNTE")) {
uint32_t version;
p = read_uint32_be(version, p, e);
}
ctx->group_stack.pop_back();
//ctx->v->EndGroup();
return p;
}
const char* parse_colr(Context* ctx, const char* p, const char* e)
{
//uint32_t dunno1, dunno2;
//p = read_uint32_be(dunno1, p, e);
//p = read_uint32_be(dunno2, p, e);
uint32_t version, index, color;
p = read_uint32_be(version, p, e);
p = read_uint32_be(index, p, e);
p = read_uint32_be(color, p, e);
uint64_t colorValue = color >> 8;
ctx->store->colorTable.insert(index, colorValue);
//ctx->v->EndGroup();
return p;
}
}
bool parseRVM(class Store* store, const void * ptr, size_t size)
{
char buf[1024];
Context ctx = { store, buf, sizeof(buf) };
auto * p = reinterpret_cast<const char*>(ptr);
auto * e = p + size;
uint32_t len, dunno;
auto l = p;
char chunk_id[5] = { 0, 0, 0, 0, 0 };
p = parse_chunk_header(chunk_id, len, dunno, p, e);
if (id(chunk_id) != id("HEAD")) {
snprintf(ctx.buf, ctx.buf_size, "Expected chunk HEAD, got %s", chunk_id);
store->setErrorString(buf);
return false;
}
p = parse_head(&ctx, p, e);
if (p - l != len) {
snprintf(ctx.buf, ctx.buf_size, "Expected length %d, got %zd", len, p - l);
store->setErrorString(buf);
return false;
}
l = p;
p = parse_chunk_header(chunk_id, len, dunno, p, e);
if (id(chunk_id) != id("MODL")) {
snprintf(ctx.buf, ctx.buf_size, "Expected chunk MODL, got %s",chunk_id);
store->setErrorString(buf);
return false;
}
p = parse_modl(&ctx, p, e);
l = p;
p = parse_chunk_header(chunk_id, len, dunno, p, e);
auto id_chunk_id = id(chunk_id);
while (p < e && id_chunk_id != id("END:")) {
switch (id_chunk_id) {
case id("CNTB"):
p = parse_cntb(&ctx, p, e);
if (p == nullptr) return false;
break;
case id("PRIM"):
p = parse_prim(&ctx, p, e);
if (p == nullptr) return false;
break;
case id("COLR"):
p = parse_colr(&ctx, p, e);
if (p == nullptr) return false;
break;
default:
snprintf(ctx.buf, ctx.buf_size, "Unrecognized chunk %s", chunk_id);
store->setErrorString(buf);
return false;
}
l = p;
p = parse_chunk_header(chunk_id, len, dunno, p, e);
id_chunk_id = id(chunk_id);
}
assert(ctx.group_stack.size() == 2);
ctx.group_stack.pop_back();
ctx.group_stack.pop_back();
store->updateCounts();
return true;
}
| 27.826484 | 108 | 0.574828 | [
"geometry",
"vector",
"model",
"transform"
] |
b4aadcbbaf4dc25c68e3c4bb7ee19b1193e5dccd | 6,944 | hpp | C++ | thirdparty/fluid/modules/gapi/src/executor/gstreamingexecutor.hpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 56,632 | 2016-07-04T16:36:08.000Z | 2022-03-31T18:38:14.000Z | modules/gapi/src/executor/gstreamingexecutor.hpp | yusufm423/opencv | 6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067 | [
"Apache-2.0"
] | 13,593 | 2016-07-04T13:59:03.000Z | 2022-03-31T21:04:51.000Z | modules/gapi/src/executor/gstreamingexecutor.hpp | yusufm423/opencv | 6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067 | [
"Apache-2.0"
] | 54,986 | 2016-07-04T14:24:38.000Z | 2022-03-31T22:51:18.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2019-2020 Intel Corporation
#ifndef OPENCV_GAPI_GSTREAMING_EXECUTOR_HPP
#define OPENCV_GAPI_GSTREAMING_EXECUTOR_HPP
#ifdef _MSC_VER
#pragma warning(disable: 4503) // "decorated name length exceeded"
// on concurrent_bounded_queue
#endif
#include <memory> // unique_ptr, shared_ptr
#include <thread> // thread
#include <vector>
#include <unordered_map>
#if defined(HAVE_TBB)
# include <tbb/concurrent_queue.h> // FIXME: drop it from here!
template<typename T> using QueueClass = tbb::concurrent_bounded_queue<T>;
#else
# include "executor/conc_queue.hpp"
template<typename T> using QueueClass = cv::gapi::own::concurrent_bounded_queue<T>;
#endif // TBB
#include "executor/last_value.hpp"
#include <ade/graph.hpp>
#include "backends/common/gbackend.hpp"
namespace cv {
namespace gimpl {
namespace stream {
struct Start {};
struct Stop {
enum class Kind {
HARD, // a hard-stop: end-of-pipeline reached or stop() called
CNST, // a soft-stop emitted for/by constant sources (see QueueReader)
} kind = Kind::HARD;
cv::GRunArg cdata; // const data for CNST stop
};
struct Result {
cv::GRunArgs args; // Full results vector
std::vector<bool> flags; // Availability flags (in case of desync)
};
using Cmd = cv::util::variant
< cv::util::monostate
, Start // Tells emitters to start working. Not broadcasted to workers.
, Stop // Tells emitters to stop working. Broadcasted to workers.
, cv::GRunArg // Workers data payload to process.
, Result // Pipeline's data for gout()
>;
// Interface over a queue. The underlying queue implementation may be
// different. This class is mainly introduced to bring some
// abstraction over the real queues (bounded in-order) and a
// desynchronized data slots (see required to implement
// cv::gapi::desync)
class Q {
public:
virtual void push(const Cmd &cmd) = 0;
virtual void pop(Cmd &cmd) = 0;
virtual bool try_pop(Cmd &cmd) = 0;
virtual void clear() = 0;
virtual ~Q() = default;
};
// A regular queue implementation
class SyncQueue final: public Q {
QueueClass<Cmd> m_q; // FIXME: OWN or WRAP??
public:
virtual void push(const Cmd &cmd) override { m_q.push(cmd); }
virtual void pop(Cmd &cmd) override { m_q.pop(cmd); }
virtual bool try_pop(Cmd &cmd) override { return m_q.try_pop(cmd); }
virtual void clear() override { m_q.clear(); }
void set_capacity(std::size_t c) { m_q.set_capacity(c);}
};
// Desynchronized "queue" implementation
// Every push overwrites value which is not yet popped
// This container can hold 0 or 1 element
// Special handling for Stop is implemented (FIXME: not really)
class DesyncQueue final: public Q {
cv::gapi::own::last_written_value<Cmd> m_v;
public:
virtual void push(const Cmd &cmd) override { m_v.push(cmd); }
virtual void pop(Cmd &cmd) override { m_v.pop(cmd); }
virtual bool try_pop(Cmd &cmd) override { return m_v.try_pop(cmd); }
virtual void clear() override { m_v.clear(); }
};
} // namespace stream
// FIXME: Currently all GExecutor comments apply also
// to this one. Please document it separately in the future.
class GStreamingExecutor final
{
protected:
// GStreamingExecutor is a state machine described as follows
//
// setSource() called
// STOPPED: - - - - - - - - - ->READY:
// -------- ------
// Initial state Input data specified
// No threads running Threads are created and IDLE
// ^ (Currently our emitter threads
// : are bounded to input data)
// : stop() called No processing happending
// : OR :
// : end-of-stream reached : start() called
// : during pull()/try_pull() V
// : RUNNING:
// : --------
// : Actual pipeline execution
// - - - - - - - - - - - - - - Threads are running
//
enum class State {
STOPPED,
READY,
RUNNING,
} state = State::STOPPED;
std::unique_ptr<ade::Graph> m_orig_graph;
std::shared_ptr<ade::Graph> m_island_graph;
cv::GCompileArgs m_comp_args;
cv::GMetaArgs m_last_metas;
util::optional<bool> m_reshapable;
cv::gimpl::GIslandModel::Graph m_gim; // FIXME: make const?
const bool m_desync;
// FIXME: Naive executor details are here for now
// but then it should be moved to another place
struct OpDesc
{
std::vector<RcDesc> in_objects;
std::vector<RcDesc> out_objects;
cv::GMetaArgs out_metas;
ade::NodeHandle nh;
cv::GRunArgs in_constants;
std::shared_ptr<GIslandExecutable> isl_exec;
};
std::vector<OpDesc> m_ops;
struct DataDesc
{
ade::NodeHandle slot_nh;
ade::NodeHandle data_nh;
};
std::vector<DataDesc> m_slots;
cv::GRunArgs m_const_vals;
// Order in these vectors follows the GComputaion's protocol
std::vector<ade::NodeHandle> m_emitters;
std::vector<ade::NodeHandle> m_sinks;
class Synchronizer;
std::unique_ptr<Synchronizer> m_sync;
std::vector<std::thread> m_threads;
std::vector<stream::SyncQueue> m_emitter_queues;
// a view over m_emitter_queues
std::vector<stream::SyncQueue*> m_const_emitter_queues;
std::vector<stream::Q*> m_sink_queues;
// desync path tags for outputs. -1 means that output
// doesn't belong to a desync path
std::vector<int> m_sink_sync;
std::unordered_set<stream::Q*> m_internal_queues;
stream::SyncQueue m_out_queue;
// Describes mapping from desync paths to collector threads
struct CollectorThreadInfo {
std::vector<stream::Q*> queues;
std::vector<int> mapping;
};
std::unordered_map<int, CollectorThreadInfo> m_collector_map;
void wait_shutdown();
cv::GTypesInfo out_info;
public:
explicit GStreamingExecutor(std::unique_ptr<ade::Graph> &&g_model,
const cv::GCompileArgs &comp_args);
~GStreamingExecutor();
void setSource(GRunArgs &&args);
void start();
bool pull(cv::GRunArgsP &&outs);
bool pull(cv::GOptRunArgsP &&outs);
std::tuple<bool, cv::util::variant<cv::GRunArgs, cv::GOptRunArgs>> pull();
bool try_pull(cv::GRunArgsP &&outs);
void stop();
bool running() const;
};
} // namespace gimpl
} // namespace cv
#endif // OPENCV_GAPI_GSTREAMING_EXECUTOR_HPP
| 31.853211 | 90 | 0.630904 | [
"vector"
] |
b4ac242a0e8b97fe9864b3086d79dc3cf1dc8173 | 9,801 | cpp | C++ | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipelineResourceLoader.cpp | alinoctavian/ezEngine | 0312c8d777c05ac58911f3fa879e4fd7efcfcb66 | [
"MIT"
] | null | null | null | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipelineResourceLoader.cpp | alinoctavian/ezEngine | 0312c8d777c05ac58911f3fa879e4fd7efcfcb66 | [
"MIT"
] | null | null | null | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipelineResourceLoader.cpp | alinoctavian/ezEngine | 0312c8d777c05ac58911f3fa879e4fd7efcfcb66 | [
"MIT"
] | 1 | 2022-03-28T15:57:46.000Z | 2022-03-28T15:57:46.000Z | #include <RendererCorePCH.h>
#include <Foundation/Serialization/BinarySerializer.h>
#include <RendererCore/Pipeline/Extractor.h>
#include <RendererCore/Pipeline/Implementation/RenderPipelineResourceLoader.h>
#include <RendererCore/Pipeline/RenderPipeline.h>
#include <RendererCore/Pipeline/RenderPipelinePass.h>
#include <RendererCore/Pipeline/RenderPipelineResource.h>
////////////////////////////////////////////////////////////////////////
// ezDocumentNodeManager Internal
////////////////////////////////////////////////////////////////////////
struct RenderPipelineResourceLoaderConnectionInternal
{
RenderPipelineResourceLoaderConnectionInternal() {}
RenderPipelineResourceLoaderConnectionInternal(const char* szPinSource, const ezUuid& target, const char* szPinTarget)
: m_SourcePin(szPinSource)
, m_Target(target)
, m_TargetPin(szPinTarget)
{
}
ezString m_SourcePin;
ezUuid m_Target;
ezString m_TargetPin;
};
EZ_DECLARE_REFLECTABLE_TYPE(EZ_NO_LINKAGE, RenderPipelineResourceLoaderConnectionInternal);
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_TYPE(RenderPipelineResourceLoaderConnectionInternal, ezNoBase, 1, ezRTTIDefaultAllocator<RenderPipelineResourceLoaderConnectionInternal>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("SourcePin", m_SourcePin),
EZ_MEMBER_PROPERTY("Target", m_Target),
EZ_MEMBER_PROPERTY("TargetPin", m_TargetPin),
}
EZ_END_PROPERTIES;
}
EZ_END_STATIC_REFLECTED_TYPE;
// clang-format on
struct RenderPipelineResourceLoaderNodeDataInternal
{
ezVec2 m_NodePos;
ezDynamicArray<RenderPipelineResourceLoaderConnectionInternal> m_Connections;
};
EZ_DECLARE_REFLECTABLE_TYPE(EZ_NO_LINKAGE, RenderPipelineResourceLoaderNodeDataInternal);
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_TYPE(RenderPipelineResourceLoaderNodeDataInternal, ezNoBase, 1, ezRTTIDefaultAllocator<RenderPipelineResourceLoaderNodeDataInternal>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Node::Pos", m_NodePos),
EZ_ARRAY_MEMBER_PROPERTY("Node::Connections", m_Connections),
}
EZ_END_PROPERTIES;
}
EZ_END_STATIC_REFLECTED_TYPE;
// clang-format on
void ezRenderPipelineRttiConverterContext::Clear()
{
ezRttiConverterContext::Clear();
m_pRenderPipeline = nullptr;
}
void* ezRenderPipelineRttiConverterContext::CreateObject(const ezUuid& guid, const ezRTTI* pRtti)
{
EZ_ASSERT_DEBUG(pRtti != nullptr, "Object type is unknown");
if (pRtti->IsDerivedFrom<ezRenderPipelinePass>())
{
if (!pRtti->GetAllocator()->CanAllocate())
{
ezLog::Error("Failed to create ezRenderPipelinePass because '{0}' cannot allocate!", pRtti->GetTypeName());
return nullptr;
}
ezUniquePtr<ezRenderPipelinePass> pass = pRtti->GetAllocator()->Allocate<ezRenderPipelinePass>();
ezRenderPipelinePass* pPass = pass.Borrow();
m_pRenderPipeline->AddPass(std::move(pass));
RegisterObject(guid, pRtti, pPass);
return pPass;
}
else if (pRtti->IsDerivedFrom<ezExtractor>())
{
if (!pRtti->GetAllocator()->CanAllocate())
{
ezLog::Error("Failed to create ezExtractor because '{0}' cannot allocate!", pRtti->GetTypeName());
return nullptr;
}
ezUniquePtr<ezExtractor> extractor = pRtti->GetAllocator()->Allocate<ezExtractor>();
ezExtractor* pExtractor = extractor.Borrow();
m_pRenderPipeline->AddExtractor(std::move(extractor));
RegisterObject(guid, pRtti, pExtractor);
return pExtractor;
}
else
{
return ezRttiConverterContext::CreateObject(guid, pRtti);
}
}
void ezRenderPipelineRttiConverterContext::DeleteObject(const ezUuid& guid)
{
ezRttiConverterObject object = GetObjectByGUID(guid);
const ezRTTI* pRtti = object.m_pType;
EZ_ASSERT_DEBUG(pRtti != nullptr, "Object does not exist!");
if (pRtti->IsDerivedFrom<ezRenderPipelinePass>())
{
ezRenderPipelinePass* pPass = static_cast<ezRenderPipelinePass*>(object.m_pObject);
UnregisterObject(guid);
m_pRenderPipeline->RemovePass(pPass);
}
else if (pRtti->IsDerivedFrom<ezExtractor>())
{
ezExtractor* pExtractor = static_cast<ezExtractor*>(object.m_pObject);
UnregisterObject(guid);
m_pRenderPipeline->RemoveExtractor(pExtractor);
}
else
{
ezRttiConverterContext::DeleteObject(guid);
}
}
// static
ezInternal::NewInstance<ezRenderPipeline> ezRenderPipelineResourceLoader::CreateRenderPipeline(const ezRenderPipelineResourceDescriptor& desc)
{
auto pPipeline = EZ_DEFAULT_NEW(ezRenderPipeline);
ezRenderPipelineRttiConverterContext context;
context.m_pRenderPipeline = pPipeline;
ezRawMemoryStreamReader memoryReader(desc.m_SerializedPipeline);
ezAbstractObjectGraph graph;
ezAbstractGraphBinarySerializer::Read(memoryReader, &graph);
ezRttiConverterReader rttiConverter(&graph, &context);
auto& nodes = graph.GetAllNodes();
for (auto it = nodes.GetIterator(); it.IsValid(); ++it)
{
auto pNode = it.Value();
ezRTTI* pType = ezRTTI::FindTypeByName(pNode->GetType());
if (pType && pType->IsDerivedFrom<ezRenderPipelinePass>())
{
auto pPass = rttiConverter.CreateObjectFromNode(pNode);
if (!pPass)
{
ezLog::Error("Failed to deserialize ezRenderPipelinePass!");
}
}
else if (pType && pType->IsDerivedFrom<ezExtractor>())
{
auto pExtractor = rttiConverter.CreateObjectFromNode(pNode);
if (!pExtractor)
{
ezLog::Error("Failed to deserialize ezExtractor!");
}
}
}
auto pType = ezGetStaticRTTI<RenderPipelineResourceLoaderNodeDataInternal>();
RenderPipelineResourceLoaderNodeDataInternal data;
ezStringBuilder tmp;
for (auto it = nodes.GetIterator(); it.IsValid(); ++it)
{
auto* pNode = it.Value();
const ezUuid& guid = pNode->GetGuid();
auto objectSoure = context.GetObjectByGUID(guid);
if (!objectSoure.m_pObject || !objectSoure.m_pType->IsDerivedFrom<ezRenderPipelinePass>())
{
continue;
}
ezRenderPipelinePass* pSource = static_cast<ezRenderPipelinePass*>(objectSoure.m_pObject);
data.m_Connections.Clear();
rttiConverter.ApplyPropertiesToObject(pNode, pType, &data);
for (const auto& con : data.m_Connections)
{
auto objectTarget = context.GetObjectByGUID(con.m_Target);
if (!objectTarget.m_pObject || !objectTarget.m_pType->IsDerivedFrom<ezRenderPipelinePass>())
{
ezLog::Error("Failed to retrieve connection target '{0}' with pin '{1}'", ezConversionUtils::ToString(guid, tmp), con.m_TargetPin);
continue;
}
ezRenderPipelinePass* pTarget = static_cast<ezRenderPipelinePass*>(objectTarget.m_pObject);
if (!pPipeline->Connect(pSource, con.m_SourcePin, pTarget, con.m_TargetPin))
{
ezLog::Error("Failed to connect '{0}'::'{1}' to '{2}'::'{3}'!", pSource->GetName(), con.m_SourcePin, pTarget->GetName(), con.m_TargetPin);
}
}
}
return pPipeline;
}
// static
void ezRenderPipelineResourceLoader::CreateRenderPipelineResourceDescriptor(const ezRenderPipeline* pPipeline, ezRenderPipelineResourceDescriptor& desc)
{
ezRenderPipelineRttiConverterContext context;
ezAbstractObjectGraph graph;
ezRttiConverterWriter rttiConverter(&graph, &context, false, true);
ezHybridArray<const ezRenderPipelinePass*, 16> passes;
pPipeline->GetPasses(passes);
// Need to serialize all passes first so we have guids for each to be referenced in the connections.
for (auto pPass : passes)
{
ezUuid guid;
guid.CreateNewUuid();
context.RegisterObject(guid, pPass->GetDynamicRTTI(), const_cast<ezRenderPipelinePass*>(pPass));
rttiConverter.AddObjectToGraph(const_cast<ezRenderPipelinePass*>(pPass));
}
ezHybridArray<const ezExtractor*, 16> extractors;
pPipeline->GetExtractors(extractors);
for (auto pExtractor : extractors)
{
ezUuid guid;
guid.CreateNewUuid();
context.RegisterObject(guid, pExtractor->GetDynamicRTTI(), const_cast<ezExtractor*>(pExtractor));
rttiConverter.AddObjectToGraph(const_cast<ezExtractor*>(pExtractor));
}
auto pType = ezGetStaticRTTI<RenderPipelineResourceLoaderNodeDataInternal>();
RenderPipelineResourceLoaderNodeDataInternal data;
auto& nodes = graph.GetAllNodes();
for (auto it = nodes.GetIterator(); it.IsValid(); ++it)
{
auto* pNode = it.Value();
const ezUuid& guid = pNode->GetGuid();
auto objectSoure = context.GetObjectByGUID(guid);
if (!objectSoure.m_pObject || !objectSoure.m_pType->IsDerivedFrom<ezRenderPipelinePass>())
{
continue;
}
ezRenderPipelinePass* pSource = static_cast<ezRenderPipelinePass*>(objectSoure.m_pObject);
data.m_Connections.Clear();
auto outputs = pSource->GetOutputPins();
for (const ezRenderPipelineNodePin* pPinSource : outputs)
{
const ezRenderPipelinePassConnection* pConnection = pPipeline->GetOutputConnection(pSource, pSource->GetPinName(pPinSource));
if (!pConnection)
continue;
for (const ezRenderPipelineNodePin* pPinTarget : pConnection->m_Inputs)
{
const ezUuid targetGuid = context.GetObjectGUID(pPinTarget->m_pParent->GetDynamicRTTI(), pPinTarget->m_pParent);
EZ_ASSERT_DEBUG(targetGuid.IsValid(), "Connection target was not serialized in previous step!");
data.m_Connections.PushBack(RenderPipelineResourceLoaderConnectionInternal(pSource->GetPinName(pPinSource).GetData(), targetGuid, pPinTarget->m_pParent->GetPinName(pPinTarget).GetData()));
}
}
rttiConverter.AddProperties(pNode, pType, &data);
}
ezMemoryStreamContainerWrapperStorage<ezDynamicArray<ezUInt8>> storage(&desc.m_SerializedPipeline);
ezMemoryStreamWriter memoryWriter(&storage);
ezAbstractGraphBinarySerializer::Write(memoryWriter, &graph);
}
EZ_STATICLINK_FILE(RendererCore, RendererCore_Pipeline_Implementation_RenderPipelineResourceLoader);
| 34.03125 | 196 | 0.738394 | [
"object"
] |
b4ac5368b6448e56084c2a91fa9d20374bb7fc2a | 8,456 | cpp | C++ | sycl/test/abi/layout_buffer.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | 653 | 2018-12-27T15:00:01.000Z | 2022-03-30T11:52:23.000Z | sycl/test/abi/layout_buffer.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | sycl/test/abi/layout_buffer.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clangxx -fsycl -c -fno-color-diagnostics -Xclang -fdump-record-layouts %s | FileCheck %s
// REQUIRES: linux
// UNSUPPORTED: libcxx
// clang-format off
#include <CL/sycl/buffer.hpp>
void foo(sycl::buffer<int, 2>) {}
// CHECK: 0 | class sycl::detail::buffer_impl
// CHECK-NEXT: 0 | class sycl::detail::SYCLMemObjT (primary base)
// CHECK-NEXT: 0 | class sycl::detail::SYCLMemObjI (primary base)
// CHECK-NEXT: 0 | (SYCLMemObjI vtable pointer)
// CHECK-NEXT: 8 | class std::shared_ptr<struct sycl::detail::MemObjRecord> MRecord
// CHECK-NEXT: 8 | class std::__shared_ptr<struct sycl::detail::MemObjRecord, __gnu_cxx::_S_atomic> (base)
// CHECK-NEXT: 8 | class std::__shared_ptr_access<struct sycl::detail::MemObjRecord, __gnu_cxx::_S_atomic, false, false> (base) (empty)
// CHECK-NEXT: 8 | std::__shared_ptr<struct sycl::detail::MemObjRecord, __gnu_cxx::_S_atomic>::element_type * _M_ptr
// CHECK-NEXT: 16 | class std::__shared_count<__gnu_cxx::_S_atomic> _M_refcount
// CHECK-NEXT: 16 | _Sp_counted_base<(enum __gnu_cxx::_Lock_policy)2U> * _M_pi
// CHECK-NEXT: 24 | class std::unique_ptr<class sycl::detail::SYCLMemObjAllocator> MAllocator
// CHECK: 24 | class std::__uniq_ptr_impl<class sycl::detail::SYCLMemObjAllocator, struct std::default_delete<class sycl::detail::SYCLMemObjAllocator> >
// CHECK-NEXT: 24 | class std::tuple<class sycl::detail::SYCLMemObjAllocator *, struct std::default_delete<class sycl::detail::SYCLMemObjAllocator> > _M_t
// CHECK-NEXT: 24 | struct std::_Tuple_impl<0, class sycl::detail::SYCLMemObjAllocator *, struct std::default_delete<class sycl::detail::SYCLMemObjAllocator> > (base)
// CHECK-NEXT: 24 | struct std::_Tuple_impl<1, struct std::default_delete<class sycl::detail::SYCLMemObjAllocator> > (base) (empty)
// CHECK-NEXT: 24 | struct std::_Head_base<1, struct std::default_delete<class sycl::detail::SYCLMemObjAllocator>, true> (base) (empty)
// CHECK-NEXT: 24 | struct std::default_delete<class sycl::detail::SYCLMemObjAllocator>
// CHECK-NEXT: 24 | struct std::_Head_base<0, class sycl::detail::SYCLMemObjAllocator *, false> (base)
// CHECK-NEXT: 24 | class sycl::detail::SYCLMemObjAllocator * _M_head_impl
// CHECK-NEXT: 32 | class sycl::property_list MProps
// CHECK-NEXT: 32 | class sycl::detail::PropertyListBase (base)
// CHECK-NEXT: 32 | class std::bitset<32> MDataLessProps
// CHECK-NEXT: 32 | struct std::_Base_bitset<1> (base)
// CHECK-NEXT: 32 | std::_Base_bitset<1>::_WordT _M_w
// CHECK-NEXT: 40 | class std::vector<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > MPropsWithData
// CHECK-NEXT: 40 | struct std::_Vector_base<class std::shared_ptr<class sycl::detail::PropertyWithDataBase>, class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > > (base)
// CHECK-NEXT: 40 | struct std::_Vector_base<class std::shared_ptr<class sycl::detail::PropertyWithDataBase>, class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > >::_Vector_impl _M_impl
// CHECK-NEXT: 40 | class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > (base) (empty)
// CHECK-NEXT: 40 | class __gnu_cxx::new_allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > (base) (empty)
// CHECK: 40 | std::_Vector_base<class std::shared_ptr<class sycl::detail::PropertyWithDataBase>, class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > >::pointer _M_start
// CHECK-NEXT: 48 | std::_Vector_base<class std::shared_ptr<class sycl::detail::PropertyWithDataBase>, class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > >::pointer _M_finish
// CHECK-NEXT: 56 | std::_Vector_base<class std::shared_ptr<class sycl::detail::PropertyWithDataBase>, class std::allocator<class std::shared_ptr<class sycl::detail::PropertyWithDataBase> > >::pointer _M_end_of_storage
// CHECK-NEXT: 64 | class std::shared_ptr<class sycl::detail::event_impl> MInteropEvent
// CHECK-NEXT: 64 | class std::__shared_ptr<class sycl::detail::event_impl, __gnu_cxx::_S_atomic> (base)
// CHECK-NEXT: 64 | class std::__shared_ptr_access<class sycl::detail::event_impl, __gnu_cxx::_S_atomic, false, false> (base) (empty)
// CHECK-NEXT: 64 | std::__shared_ptr<class sycl::detail::event_impl, __gnu_cxx::_S_atomic>::element_type * _M_ptr
// CHECK-NEXT: 72 | class std::__shared_count<__gnu_cxx::_S_atomic> _M_refcount
// CHECK-NEXT: 72 | _Sp_counted_base<(enum __gnu_cxx::_Lock_policy)2U> * _M_pi
// CHECK-NEXT: 80 | class std::shared_ptr<class sycl::detail::context_impl> MInteropContext
// CHECK-NEXT: 80 | class std::__shared_ptr<class sycl::detail::context_impl, __gnu_cxx::_S_atomic> (base)
// CHECK-NEXT: 80 | class std::__shared_ptr_access<class sycl::detail::context_impl, __gnu_cxx::_S_atomic, false, false> (base) (empty)
// CHECK-NEXT: 80 | std::__shared_ptr<class sycl::detail::context_impl, __gnu_cxx::_S_atomic>::element_type * _M_ptr
// CHECK-NEXT: 88 | class std::__shared_count<__gnu_cxx::_S_atomic> _M_refcount
// CHECK-NEXT: 88 | _Sp_counted_base<(enum __gnu_cxx::_Lock_policy)2U> * _M_pi
// CHECK-NEXT: 96 | cl_mem MInteropMemObject
// CHECK-NEXT: 104 | _Bool MOpenCLInterop
// CHECK-NEXT: 105 | _Bool MHostPtrReadOnly
// CHECK-NEXT: 106 | _Bool MNeedWriteBack
// CHECK-NEXT: 112 | size_t MSizeInBytes
// CHECK-NEXT: 120 | void * MUserPtr
// CHECK-NEXT: 128 | void * MShadowCopy
// CHECK-NEXT: 136 | class std::function<void (void)> MUploadDataFunctor
// CHECK-NEXT: 136 | struct std::_Maybe_unary_or_binary_function<void> (base) (empty)
// CHECK-NEXT: 136 | class std::_Function_base (base)
// CHECK-NEXT: 136 | union std::_Any_data _M_functor
// CHECK-NEXT: 136 | union std::_Nocopy_types _M_unused
// CHECK-NEXT: 136 | void * _M_object
// CHECK-NEXT: 136 | const void * _M_const_object
// CHECK-NEXT: 136 | void (*)(void) _M_function_pointer
// CHECK-NEXT: 136 | void (class std::_Undefined_class::*)(void) _M_member_pointer
// CHECK-NEXT: 136 | char [16] _M_pod_data
// CHECK-NEXT: 152 | std::_Function_base::_Manager_type _M_manager
// CHECK-NEXT: 160 | std::function<void (void)>::_Invoker_type _M_invoker
// CHECK-NEXT: 168 | class std::shared_ptr<const void> MSharedPtrStorage
// CHECK-NEXT: 168 | class std::__shared_ptr<const void, __gnu_cxx::_S_atomic> (base)
// CHECK-NEXT: 168 | class std::__shared_ptr_access<const void, __gnu_cxx::_S_atomic, false, true> (base) (empty)
// CHECK-NEXT: 168 | std::__shared_ptr<const void, __gnu_cxx::_S_atomic>::element_type * _M_ptr
// CHECK-NEXT: 176 | class std::__shared_count<__gnu_cxx::_S_atomic> _M_refcount
// CHECK-NEXT: 176 | _Sp_counted_base<(enum __gnu_cxx::_Lock_policy)2U> * _M_pi
// CHECK-NEXT: | [sizeof=184, dsize=184, align=8,
// CHECK-NEXT: | nvsize=184, nvalign=8]
// CHECK: 0 | class sycl::buffer<int, 2, class sycl::detail::aligned_allocator<char>, void>
// CHECK-NEXT: 0 | class std::shared_ptr<class sycl::detail::buffer_impl> impl
// CHECK-NEXT: 0 | class std::__shared_ptr<class sycl::detail::buffer_impl, __gnu_cxx::_S_atomic> (base)
// CHECK-NEXT: 0 | class std::__shared_ptr_access<class sycl::detail::buffer_impl, __gnu_cxx::_S_atomic, false, false> (base) (empty)
// CHECK-NEXT: 0 | std::__shared_ptr<class sycl::detail::buffer_impl, __gnu_cxx::_S_atomic>::element_type * _M_ptr
// CHECK-NEXT: 8 | class std::__shared_count<__gnu_cxx::_S_atomic> _M_refcount
// CHECK-NEXT: 8 | _Sp_counted_base<(enum __gnu_cxx::_Lock_policy)2U> * _M_pi
// CHECK-NEXT: 16 | class sycl::range<2> Range
// CHECK-NEXT: 16 | class sycl::detail::array<2> (base)
// CHECK-NEXT: 16 | size_t [2] common_array
// CHECK-NEXT: 32 | size_t OffsetInBytes
// CHECK-NEXT: 40 | _Bool IsSubBuffer
// CHECK-NEXT: | [sizeof=48, dsize=41, align=8,
// CHECK-NEXT: | nvsize=41, nvalign=8]
| 88.083333 | 235 | 0.680582 | [
"vector"
] |
b4ad6399bdced508b2e1812f2950b0cdea536cb2 | 34,950 | cpp | C++ | NetDb.cpp | sviceman/i2pd | 29cc1cf3904833b2d84824e8f6aacb87e5d479d9 | [
"BSD-3-Clause"
] | 1 | 2017-03-13T11:28:03.000Z | 2017-03-13T11:28:03.000Z | NetDb.cpp | sviceman/i2pd | 29cc1cf3904833b2d84824e8f6aacb87e5d479d9 | [
"BSD-3-Clause"
] | null | null | null | NetDb.cpp | sviceman/i2pd | 29cc1cf3904833b2d84824e8f6aacb87e5d479d9 | [
"BSD-3-Clause"
] | null | null | null | #include <string.h>
#include <fstream>
#include <vector>
#include <boost/asio.hpp>
#include "I2PEndian.h"
#include "Base.h"
#include "Crypto.h"
#include "Log.h"
#include "Timestamp.h"
#include "I2NPProtocol.h"
#include "Tunnel.h"
#include "Transports.h"
#include "RouterContext.h"
#include "Garlic.h"
#include "NetDb.h"
#include "Config.h"
using namespace i2p::transport;
namespace i2p
{
namespace data
{
NetDb netdb;
NetDb::NetDb (): m_IsRunning (false), m_Thread (nullptr), m_Reseeder (nullptr), m_Storage("netDb", "r", "routerInfo-", "dat"), m_FloodfillBootstrap(nullptr), m_HiddenMode(false)
{
}
NetDb::~NetDb ()
{
Stop ();
delete m_Reseeder;
}
void NetDb::Start ()
{
m_Storage.SetPlace(i2p::fs::GetDataDir());
m_Storage.Init(i2p::data::GetBase64SubstitutionTable(), 64);
InitProfilesStorage ();
m_Families.LoadCertificates ();
Load ();
uint16_t threshold; i2p::config::GetOption("reseed.threshold", threshold);
if (m_RouterInfos.size () < threshold) // reseed if # of router less than threshold
Reseed ();
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&NetDb::Run, this));
}
void NetDb::Stop ()
{
if (m_IsRunning)
{
for (auto& it: m_RouterInfos)
it.second->SaveProfile ();
DeleteObsoleteProfiles ();
m_RouterInfos.clear ();
m_Floodfills.clear ();
if (m_Thread)
{
m_IsRunning = false;
m_Queue.WakeUp ();
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
m_LeaseSets.clear();
m_Requests.Stop ();
}
}
void NetDb::Run ()
{
uint32_t lastSave = 0, lastPublish = 0, lastExploratory = 0, lastManageRequest = 0, lastDestinationCleanup = 0;
while (m_IsRunning)
{
try
{
auto msg = m_Queue.GetNextWithTimeout (15000); // 15 sec
if (msg)
{
int numMsgs = 0;
while (msg)
{
LogPrint(eLogDebug, "NetDb: got request with type ", (int) msg->GetTypeID ());
switch (msg->GetTypeID ())
{
case eI2NPDatabaseStore:
HandleDatabaseStoreMsg (msg);
break;
case eI2NPDatabaseSearchReply:
HandleDatabaseSearchReplyMsg (msg);
break;
case eI2NPDatabaseLookup:
HandleDatabaseLookupMsg (msg);
break;
default: // WTF?
LogPrint (eLogError, "NetDb: unexpected message type ", (int) msg->GetTypeID ());
//i2p::HandleI2NPMessage (msg);
}
if (numMsgs > 100) break;
msg = m_Queue.Get ();
numMsgs++;
}
}
if (!m_IsRunning) break;
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
if (ts - lastManageRequest >= 15) // manage requests every 15 seconds
{
m_Requests.ManageRequests ();
lastManageRequest = ts;
}
if (ts - lastSave >= 60) // save routers, manage leasesets and validate subscriptions every minute
{
if (lastSave)
{
SaveUpdated ();
ManageLeaseSets ();
}
lastSave = ts;
}
if (ts - lastDestinationCleanup >= i2p::garlic::INCOMING_TAGS_EXPIRATION_TIMEOUT)
{
i2p::context.CleanupDestination ();
lastDestinationCleanup = ts;
}
if (ts - lastPublish >= NETDB_PUBLISH_INTERVAL && !m_HiddenMode) // publish
{
Publish ();
lastPublish = ts;
}
if (ts - lastExploratory >= 30) // exploratory every 30 seconds
{
auto numRouters = m_RouterInfos.size ();
if (numRouters == 0)
{
LogPrint(eLogError, "NetDb: no known routers, reseed seems to be totally failed");
break;
}
else // we have peers now
m_FloodfillBootstrap = nullptr;
if (numRouters < 2500 || ts - lastExploratory >= 90)
{
numRouters = 800/numRouters;
if (numRouters < 1) numRouters = 1;
if (numRouters > 9) numRouters = 9;
m_Requests.ManageRequests ();
if(!m_HiddenMode)
Explore (numRouters);
lastExploratory = ts;
}
}
}
catch (std::exception& ex)
{
LogPrint (eLogError, "NetDb: runtime exception: ", ex.what ());
}
}
}
bool NetDb::AddRouterInfo (const uint8_t * buf, int len)
{
IdentityEx identity;
if (identity.FromBuffer (buf, len))
return AddRouterInfo (identity.GetIdentHash (), buf, len);
return false;
}
void NetDb::SetHidden(bool hide) {
// TODO: remove reachable addresses from router info
m_HiddenMode = hide;
}
bool NetDb::AddRouterInfo (const IdentHash& ident, const uint8_t * buf, int len)
{
bool updated = true;
auto r = FindRouter (ident);
if (r)
{
if (r->IsNewer (buf, len))
{
r->Update (buf, len);
LogPrint (eLogInfo, "NetDb: RouterInfo updated: ", ident.ToBase64());
// TODO: check if floodfill has been changed
}
else
{
LogPrint (eLogDebug, "NetDb: RouterInfo is older: ", ident.ToBase64());
updated = false;
}
}
else
{
r = std::make_shared<RouterInfo> (buf, len);
if (!r->IsUnreachable ())
{
bool inserted = false;
{
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
inserted = m_RouterInfos.insert ({r->GetIdentHash (), r}).second;
}
if (inserted)
{
LogPrint (eLogInfo, "NetDb: RouterInfo added: ", ident.ToBase64());
if (r->IsFloodfill () && r->IsReachable ()) // floodfill must be reachable
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
m_Floodfills.push_back (r);
}
}
else
{
LogPrint (eLogWarning, "NetDb: Duplicated RouterInfo ", ident.ToBase64());
updated = false;
}
}
else
updated = false;
}
// take care about requested destination
m_Requests.RequestComplete (ident, r);
return updated;
}
bool NetDb::AddLeaseSet (const IdentHash& ident, const uint8_t * buf, int len,
std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
bool updated = false;
if (!from) // unsolicited LS must be received directly
{
auto it = m_LeaseSets.find(ident);
if (it != m_LeaseSets.end ())
{
if (it->second->IsNewer (buf, len))
{
it->second->Update (buf, len);
if (it->second->IsValid ())
{
LogPrint (eLogInfo, "NetDb: LeaseSet updated: ", ident.ToBase32());
updated = true;
}
else
{
LogPrint (eLogWarning, "NetDb: LeaseSet update failed: ", ident.ToBase32());
m_LeaseSets.erase (it);
}
}
else
LogPrint (eLogDebug, "NetDb: LeaseSet is older: ", ident.ToBase32());
}
else
{
auto leaseSet = std::make_shared<LeaseSet> (buf, len, false); // we don't need leases in netdb
if (leaseSet->IsValid ())
{
LogPrint (eLogInfo, "NetDb: LeaseSet added: ", ident.ToBase32());
m_LeaseSets[ident] = leaseSet;
updated = true;
}
else
LogPrint (eLogError, "NetDb: new LeaseSet validation failed: ", ident.ToBase32());
}
}
return updated;
}
std::shared_ptr<RouterInfo> NetDb::FindRouter (const IdentHash& ident) const
{
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
auto it = m_RouterInfos.find (ident);
if (it != m_RouterInfos.end ())
return it->second;
else
return nullptr;
}
std::shared_ptr<LeaseSet> NetDb::FindLeaseSet (const IdentHash& destination) const
{
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
auto it = m_LeaseSets.find (destination);
if (it != m_LeaseSets.end ())
return it->second;
else
return nullptr;
}
std::shared_ptr<RouterProfile> NetDb::FindRouterProfile (const IdentHash& ident) const
{
auto router = FindRouter (ident);
return router ? router->GetProfile () : nullptr;
}
void NetDb::SetUnreachable (const IdentHash& ident, bool unreachable)
{
auto it = m_RouterInfos.find (ident);
if (it != m_RouterInfos.end ())
return it->second->SetUnreachable (unreachable);
}
void NetDb::Reseed ()
{
if (!m_Reseeder)
{
m_Reseeder = new Reseeder ();
m_Reseeder->LoadCertificates (); // we need certificates for SU3 verification
}
// try reseeding from floodfill first if specified
std::string riPath;
if(i2p::config::GetOption("reseed.floodfill", riPath)) {
auto ri = std::make_shared<RouterInfo>(riPath);
if (ri->IsFloodfill()) {
const uint8_t * riData = ri->GetBuffer();
int riLen = ri->GetBufferLen();
if(!i2p::data::netdb.AddRouterInfo(riData, riLen)) {
// bad router info
LogPrint(eLogError, "NetDb: bad router info");
return;
}
m_FloodfillBootstrap = ri;
ReseedFromFloodfill(*ri);
// don't try reseed servers if trying to boostrap from floodfill
return;
}
}
m_Reseeder->Bootstrap ();
}
void NetDb::ReseedFromFloodfill(const RouterInfo & ri, int numRouters, int numFloodfills)
{
LogPrint(eLogInfo, "NetDB: reseeding from floodfill ", ri.GetIdentHashBase64());
std::vector<std::shared_ptr<i2p::I2NPMessage> > requests;
i2p::data::IdentHash ourIdent = i2p::context.GetIdentHash();
i2p::data::IdentHash ih = ri.GetIdentHash();
i2p::data::IdentHash randomIdent;
// make floodfill lookups
while(numFloodfills > 0) {
randomIdent.Randomize();
auto msg = i2p::CreateRouterInfoDatabaseLookupMsg(randomIdent, ourIdent, 0, false);
requests.push_back(msg);
numFloodfills --;
}
// make regular router lookups
while(numRouters > 0) {
randomIdent.Randomize();
auto msg = i2p::CreateRouterInfoDatabaseLookupMsg(randomIdent, ourIdent, 0, true);
requests.push_back(msg);
numRouters --;
}
// send them off
i2p::transport::transports.SendMessages(ih, requests);
}
bool NetDb::LoadRouterInfo (const std::string & path)
{
auto r = std::make_shared<RouterInfo>(path);
if (r->GetRouterIdentity () && !r->IsUnreachable () &&
(!r->UsesIntroducer () || m_LastLoad < r->GetTimestamp () + NETDB_INTRODUCEE_EXPIRATION_TIMEOUT*1000LL)) // 1 hour
{
r->DeleteBuffer ();
r->ClearProperties (); // properties are not used for regular routers
m_RouterInfos[r->GetIdentHash ()] = r;
if (r->IsFloodfill () && r->IsReachable ()) // floodfill must be reachable
m_Floodfills.push_back (r);
}
else
{
LogPrint(eLogWarning, "NetDb: RI from ", path, " is invalid. Delete");
i2p::fs::Remove(path);
}
return true;
}
void NetDb::VisitLeaseSets(LeaseSetVisitor v)
{
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
for ( auto & entry : m_LeaseSets)
v(entry.first, entry.second);
}
void NetDb::VisitStoredRouterInfos(RouterInfoVisitor v)
{
m_Storage.Iterate([v] (const std::string & filename) {
auto ri = std::make_shared<i2p::data::RouterInfo>(filename);
v(ri);
});
}
void NetDb::VisitRouterInfos(RouterInfoVisitor v)
{
std::unique_lock<std::mutex> lock(m_RouterInfosMutex);
for ( const auto & item : m_RouterInfos )
v(item.second);
}
size_t NetDb::VisitRandomRouterInfos(RouterInfoFilter filter, RouterInfoVisitor v, size_t n)
{
std::vector<std::shared_ptr<const RouterInfo> > found;
const size_t max_iters_per_cyle = 3;
size_t iters = max_iters_per_cyle;
while(n > 0)
{
std::unique_lock<std::mutex> lock(m_RouterInfosMutex);
uint32_t idx = rand () % m_RouterInfos.size ();
uint32_t i = 0;
for (const auto & it : m_RouterInfos) {
if(i >= idx) // are we at the random start point?
{
// yes, check if we want this one
if(filter(it.second))
{
// we have a match
--n;
found.push_back(it.second);
// reset max iterations per cycle
iters = max_iters_per_cyle;
break;
}
}
else // not there yet
++i;
}
// we have enough
if(n == 0) break;
--iters;
// have we tried enough this cycle ?
if(!iters) {
// yes let's try the next cycle
--n;
iters = max_iters_per_cyle;
}
}
// visit the ones we found
size_t visited = 0;
for(const auto & ri : found ) {
v(ri);
++visited;
}
return visited;
}
void NetDb::Load ()
{
// make sure we cleanup netDb from previous attempts
m_RouterInfos.clear ();
m_Floodfills.clear ();
m_LastLoad = i2p::util::GetSecondsSinceEpoch();
std::vector<std::string> files;
m_Storage.Traverse(files);
for (const auto& path : files)
LoadRouterInfo(path);
LogPrint (eLogInfo, "NetDb: ", m_RouterInfos.size(), " routers loaded (", m_Floodfills.size (), " floodfils)");
}
void NetDb::SaveUpdated ()
{
int updatedCount = 0, deletedCount = 0;
auto total = m_RouterInfos.size ();
uint64_t expirationTimeout = NETDB_MAX_EXPIRATION_TIMEOUT*1000LL;
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch();
// routers don't expire if less than 90 or uptime is less than 1 hour
bool checkForExpiration = total > NETDB_MIN_ROUTERS && ts > (i2p::context.GetStartupTime () + 600)*1000LL; // 10 minutes
if (checkForExpiration && ts > (i2p::context.GetStartupTime () + 3600)*1000LL) // 1 hour
expirationTimeout = i2p::context.IsFloodfill () ? NETDB_FLOODFILL_EXPIRATION_TIMEOUT*1000LL :
NETDB_MIN_EXPIRATION_TIMEOUT*1000LL + (NETDB_MAX_EXPIRATION_TIMEOUT - NETDB_MIN_EXPIRATION_TIMEOUT)*1000LL*NETDB_MIN_ROUTERS/total;
for (auto& it: m_RouterInfos)
{
std::string ident = it.second->GetIdentHashBase64();
std::string path = m_Storage.Path(ident);
if (it.second->IsUpdated ())
{
it.second->SaveToFile (path);
it.second->SetUpdated (false);
it.second->SetUnreachable (false);
it.second->DeleteBuffer ();
updatedCount++;
continue;
}
// find & mark expired routers
if (it.second->UsesIntroducer ())
{
if (ts > it.second->GetTimestamp () + NETDB_INTRODUCEE_EXPIRATION_TIMEOUT*1000LL)
// RouterInfo expires after 1 hour if uses introducer
it.second->SetUnreachable (true);
}
else if (checkForExpiration && ts > it.second->GetTimestamp () + expirationTimeout)
it.second->SetUnreachable (true);
if (it.second->IsUnreachable ())
{
// delete RI file
m_Storage.Remove(ident);
deletedCount++;
if (total - deletedCount < NETDB_MIN_ROUTERS) checkForExpiration = false;
}
} // m_RouterInfos iteration
if (updatedCount > 0)
LogPrint (eLogInfo, "NetDb: saved ", updatedCount, " new/updated routers");
if (deletedCount > 0)
{
LogPrint (eLogInfo, "NetDb: deleting ", deletedCount, " unreachable routers");
// clean up RouterInfos table
{
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
for (auto it = m_RouterInfos.begin (); it != m_RouterInfos.end ();)
{
if (it->second->IsUnreachable ())
{
it->second->SaveProfile ();
it = m_RouterInfos.erase (it);
continue;
}
++it;
}
}
// clean up expired floodfiils
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
for (auto it = m_Floodfills.begin (); it != m_Floodfills.end ();)
if ((*it)->IsUnreachable ())
it = m_Floodfills.erase (it);
else
++it;
}
}
}
void NetDb::RequestDestination (const IdentHash& destination, RequestedDestination::RequestComplete requestComplete)
{
auto dest = m_Requests.CreateRequest (destination, false, requestComplete); // non-exploratory
if (!dest)
{
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already");
return;
}
auto floodfill = GetClosestFloodfill (destination, dest->GetExcludedPeers ());
if (floodfill)
transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
else
{
LogPrint (eLogError, "NetDb: ", destination.ToBase64(), " destination requested, but no floodfills found");
m_Requests.RequestComplete (destination, nullptr);
}
}
void NetDb::RequestDestinationFrom (const IdentHash& destination, const IdentHash & from, bool exploritory, RequestedDestination::RequestComplete requestComplete)
{
auto dest = m_Requests.CreateRequest (destination, exploritory, requestComplete); // non-exploratory
if (!dest)
{
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already");
return;
}
LogPrint(eLogInfo, "NetDb: destination ", destination.ToBase64(), " being requested directly from ", from.ToBase64());
// direct
transports.SendMessage (from, dest->CreateRequestMessage (nullptr, nullptr));
}
void NetDb::HandleDatabaseStoreMsg (std::shared_ptr<const I2NPMessage> m)
{
const uint8_t * buf = m->GetPayload ();
size_t len = m->GetSize ();
IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET);
if (ident.IsZero ())
{
LogPrint (eLogDebug, "NetDb: database store with zero ident, dropped");
return;
}
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
size_t offset = DATABASE_STORE_HEADER_SIZE;
if (replyToken)
{
auto deliveryStatus = CreateDeliveryStatusMsg (replyToken);
uint32_t tunnelID = bufbe32toh (buf + offset);
offset += 4;
if (!tunnelID) // send response directly
transports.SendMessage (buf + offset, deliveryStatus);
else
{
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = pool ? pool->GetNextOutboundTunnel () : nullptr;
if (outbound)
outbound->SendTunnelDataMsg (buf + offset, tunnelID, deliveryStatus);
else
LogPrint (eLogWarning, "NetDb: no outbound tunnels for DatabaseStore reply found");
}
offset += 32;
}
// we must send reply back before this check
if (ident == i2p::context.GetIdentHash ())
{
LogPrint (eLogDebug, "NetDb: database store with own RouterInfo received, dropped");
return;
}
size_t payloadOffset = offset;
bool updated = false;
if (buf[DATABASE_STORE_TYPE_OFFSET]) // type
{
LogPrint (eLogDebug, "NetDb: store request: LeaseSet for ", ident.ToBase32());
updated = AddLeaseSet (ident, buf + offset, len - offset, m->from);
}
else
{
LogPrint (eLogDebug, "NetDb: store request: RouterInfo");
size_t size = bufbe16toh (buf + offset);
offset += 2;
if (size > 2048 || size > len - offset)
{
LogPrint (eLogError, "NetDb: invalid RouterInfo length ", (int)size);
return;
}
uint8_t uncompressed[2048];
size_t uncompressedSize = m_Inflator.Inflate (buf + offset, size, uncompressed, 2048);
if (uncompressedSize && uncompressedSize < 2048)
updated = AddRouterInfo (ident, uncompressed, uncompressedSize);
else
{
LogPrint (eLogInfo, "NetDb: decompression failed ", uncompressedSize);
return;
}
}
if (replyToken && context.IsFloodfill () && updated)
{
// flood updated
auto floodMsg = NewI2NPShortMessage ();
uint8_t * payload = floodMsg->GetPayload ();
memcpy (payload, buf, 33); // key + type
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0); // zero reply token
size_t msgLen = len - payloadOffset;
floodMsg->len += DATABASE_STORE_HEADER_SIZE + msgLen;
if (floodMsg->len < floodMsg->maxLen)
{
memcpy (payload + DATABASE_STORE_HEADER_SIZE, buf + payloadOffset, msgLen);
floodMsg->FillI2NPMessageHeader (eI2NPDatabaseStore);
std::set<IdentHash> excluded;
excluded.insert (i2p::context.GetIdentHash ()); // don't flood to itself
excluded.insert (ident); // don't flood back
for (int i = 0; i < 3; i++)
{
auto floodfill = GetClosestFloodfill (ident, excluded);
if (floodfill)
{
auto h = floodfill->GetIdentHash();
LogPrint(eLogDebug, "NetDb: Flood lease set for ", ident.ToBase32(), " to ", h.ToBase64());
transports.SendMessage (h, CopyI2NPMessage(floodMsg));
excluded.insert (h);
}
else
break;
}
}
else
LogPrint (eLogError, "NetDb: Database store message is too long ", floodMsg->len);
}
}
void NetDb::HandleDatabaseSearchReplyMsg (std::shared_ptr<const I2NPMessage> msg)
{
const uint8_t * buf = msg->GetPayload ();
char key[48];
int l = i2p::data::ByteStreamToBase64 (buf, 32, key, 48);
key[l] = 0;
int num = buf[32]; // num
LogPrint (eLogDebug, "NetDb: DatabaseSearchReply for ", key, " num=", num);
IdentHash ident (buf);
auto dest = m_Requests.FindRequest (ident);
if (dest)
{
bool deleteDest = true;
if (num > 0)
{
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = pool ? pool->GetNextOutboundTunnel () : nullptr;
auto inbound = pool ? pool->GetNextInboundTunnel () : nullptr;
if (!dest->IsExploratory ())
{
// reply to our destination. Try other floodfills
if (outbound && inbound)
{
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
auto count = dest->GetExcludedPeers ().size ();
if (count < 7)
{
auto nextFloodfill = GetClosestFloodfill (dest->GetDestination (), dest->GetExcludedPeers ());
if (nextFloodfill)
{
// tell floodfill about us
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
nextFloodfill->GetIdentHash (), 0,
CreateDatabaseStoreMsg ()
});
// request destination
LogPrint (eLogDebug, "NetDb: Try ", key, " at ", count, " floodfill ", nextFloodfill->GetIdentHash ().ToBase64 ());
auto msg = dest->CreateRequestMessage (nextFloodfill, inbound);
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
nextFloodfill->GetIdentHash (), 0, msg
});
deleteDest = false;
}
}
else
LogPrint (eLogWarning, "NetDb: ", key, " was not found on ", count, " floodfills");
if (msgs.size () > 0)
outbound->SendTunnelDataMsg (msgs);
}
}
if (deleteDest)
// no more requests for the destinationation. delete it
m_Requests.RequestComplete (ident, nullptr);
}
else
// no more requests for detination possible. delete it
m_Requests.RequestComplete (ident, nullptr);
}
else if(!m_FloodfillBootstrap)
LogPrint (eLogWarning, "NetDb: requested destination for ", key, " not found");
// try responses
for (int i = 0; i < num; i++)
{
const uint8_t * router = buf + 33 + i*32;
char peerHash[48];
int l1 = i2p::data::ByteStreamToBase64 (router, 32, peerHash, 48);
peerHash[l1] = 0;
LogPrint (eLogDebug, "NetDb: ", i, ": ", peerHash);
auto r = FindRouter (router);
if (!r || i2p::util::GetMillisecondsSinceEpoch () > r->GetTimestamp () + 3600*1000LL)
{
// router with ident not found or too old (1 hour)
LogPrint (eLogDebug, "NetDb: found new/outdated router. Requesting RouterInfo ...");
if(m_FloodfillBootstrap)
RequestDestinationFrom(router, m_FloodfillBootstrap->GetIdentHash(), true);
else
RequestDestination (router);
}
else
LogPrint (eLogDebug, "NetDb: [:|||:]");
}
}
void NetDb::HandleDatabaseLookupMsg (std::shared_ptr<const I2NPMessage> msg)
{
const uint8_t * buf = msg->GetPayload ();
IdentHash ident (buf);
if (ident.IsZero ())
{
LogPrint (eLogError, "NetDb: DatabaseLookup for zero ident. Ignored");
return;
}
char key[48];
int l = i2p::data::ByteStreamToBase64 (buf, 32, key, 48);
key[l] = 0;
IdentHash replyIdent(buf + 32);
uint8_t flag = buf[64];
LogPrint (eLogDebug, "NetDb: DatabaseLookup for ", key, " recieved flags=", (int)flag);
uint8_t lookupType = flag & DATABASE_LOOKUP_TYPE_FLAGS_MASK;
const uint8_t * excluded = buf + 65;
uint32_t replyTunnelID = 0;
if (flag & DATABASE_LOOKUP_DELIVERY_FLAG) //reply to tunnel
{
replyTunnelID = bufbe32toh (excluded);
excluded += 4;
}
uint16_t numExcluded = bufbe16toh (excluded);
excluded += 2;
if (numExcluded > 512)
{
LogPrint (eLogWarning, "NetDb: number of excluded peers", numExcluded, " exceeds 512");
return;
}
std::shared_ptr<I2NPMessage> replyMsg;
if (lookupType == DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP)
{
LogPrint (eLogInfo, "NetDb: exploratory close to ", key, " ", numExcluded, " excluded");
std::set<IdentHash> excludedRouters;
for (int i = 0; i < numExcluded; i++)
{
excludedRouters.insert (excluded);
excluded += 32;
}
std::vector<IdentHash> routers;
for (int i = 0; i < 3; i++)
{
auto r = GetClosestNonFloodfill (ident, excludedRouters);
if (r)
{
routers.push_back (r->GetIdentHash ());
excludedRouters.insert (r->GetIdentHash ());
}
}
replyMsg = CreateDatabaseSearchReply (ident, routers);
}
else
{
if (lookupType == DATABASE_LOOKUP_TYPE_ROUTERINFO_LOOKUP ||
lookupType == DATABASE_LOOKUP_TYPE_NORMAL_LOOKUP)
{
auto router = FindRouter (ident);
if (router)
{
LogPrint (eLogDebug, "NetDb: requested RouterInfo ", key, " found");
router->LoadBuffer ();
if (router->GetBuffer ())
replyMsg = CreateDatabaseStoreMsg (router);
}
}
if (!replyMsg && (lookupType == DATABASE_LOOKUP_TYPE_LEASESET_LOOKUP ||
lookupType == DATABASE_LOOKUP_TYPE_NORMAL_LOOKUP))
{
auto leaseSet = FindLeaseSet (ident);
if (!leaseSet)
{
// no lease set found
LogPrint(eLogDebug, "NetDb: requested LeaseSet not found for ", ident.ToBase32());
}
else if (!leaseSet->IsExpired ()) // we don't send back our LeaseSets
{
LogPrint (eLogDebug, "NetDb: requested LeaseSet ", key, " found");
replyMsg = CreateDatabaseStoreMsg (leaseSet);
}
}
if (!replyMsg)
{
std::set<IdentHash> excludedRouters;
const uint8_t * exclude_ident = excluded;
for (int i = 0; i < numExcluded; i++)
{
excludedRouters.insert (exclude_ident);
exclude_ident += 32;
}
auto closestFloodfills = GetClosestFloodfills (ident, 3, excludedRouters, true);
if (closestFloodfills.empty ())
LogPrint (eLogWarning, "NetDb: Requested ", key, " not found, ", numExcluded, " peers excluded");
replyMsg = CreateDatabaseSearchReply (ident, closestFloodfills);
}
}
excluded += numExcluded * 32;
if (replyMsg)
{
if (replyTunnelID)
{
// encryption might be used though tunnel only
if (flag & DATABASE_LOOKUP_ENCRYPTION_FLAG) // encrypted reply requested
{
const uint8_t * sessionKey = excluded;
const uint8_t numTags = excluded[32];
if (numTags)
{
const i2p::garlic::SessionTag sessionTag(excluded + 33); // take first tag
i2p::garlic::GarlicRoutingSession garlic (sessionKey, sessionTag);
replyMsg = garlic.WrapSingleMessage (replyMsg);
if(replyMsg == nullptr) LogPrint(eLogError, "NetDb: failed to wrap message");
}
else
LogPrint(eLogWarning, "NetDb: encrypted reply requested but no tags provided");
}
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr;
if (outbound)
outbound->SendTunnelDataMsg (replyIdent, replyTunnelID, replyMsg);
else
transports.SendMessage (replyIdent, i2p::CreateTunnelGatewayMsg (replyTunnelID, replyMsg));
}
else
transports.SendMessage (replyIdent, replyMsg);
}
}
void NetDb::Explore (int numDestinations)
{
// new requests
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr;
auto inbound = exploratoryPool ? exploratoryPool->GetNextInboundTunnel () : nullptr;
bool throughTunnels = outbound && inbound;
uint8_t randomHash[32];
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
LogPrint (eLogInfo, "NetDb: exploring new ", numDestinations, " routers ...");
for (int i = 0; i < numDestinations; i++)
{
RAND_bytes (randomHash, 32);
auto dest = m_Requests.CreateRequest (randomHash, true); // exploratory
if (!dest)
{
LogPrint (eLogWarning, "NetDb: exploratory destination is requested already");
return;
}
auto floodfill = GetClosestFloodfill (randomHash, dest->GetExcludedPeers ());
if (floodfill)
{
if (i2p::transport::transports.IsConnected (floodfill->GetIdentHash ()))
throughTunnels = false;
if (throughTunnels)
{
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
floodfill->GetIdentHash (), 0,
CreateDatabaseStoreMsg () // tell floodfill about us
});
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
floodfill->GetIdentHash (), 0,
dest->CreateRequestMessage (floodfill, inbound) // explore
});
}
else
i2p::transport::transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
}
else
m_Requests.RequestComplete (randomHash, nullptr);
}
if (throughTunnels && msgs.size () > 0)
outbound->SendTunnelDataMsg (msgs);
}
void NetDb::Publish ()
{
i2p::context.UpdateStats (); // for floodfill
std::set<IdentHash> excluded; // TODO: fill up later
for (int i = 0; i < 2; i++)
{
auto floodfill = GetClosestFloodfill (i2p::context.GetRouterInfo ().GetIdentHash (), excluded);
if (floodfill)
{
uint32_t replyToken;
RAND_bytes ((uint8_t *)&replyToken, 4);
LogPrint (eLogInfo, "NetDb: Publishing our RouterInfo to ", i2p::data::GetIdentHashAbbreviation(floodfill->GetIdentHash ()), ". reply token=", replyToken);
transports.SendMessage (floodfill->GetIdentHash (), CreateDatabaseStoreMsg (i2p::context.GetSharedRouterInfo (), replyToken));
excluded.insert (floodfill->GetIdentHash ());
}
}
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter () const
{
return GetRandomRouter (
[](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden ();
});
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const
{
return GetRandomRouter (
[compatibleWith](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router != compatibleWith &&
router->IsCompatible (*compatibleWith);
});
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomPeerTestRouter (bool v4only) const
{
return GetRandomRouter (
[v4only](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router->IsPeerTesting () && router->IsSSU (v4only);
});
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomIntroducer () const
{
return GetRandomRouter (
[](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router->IsIntroducer ();
});
}
std::shared_ptr<const RouterInfo> NetDb::GetHighBandwidthRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const
{
return GetRandomRouter (
[compatibleWith](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router != compatibleWith &&
router->IsCompatible (*compatibleWith) &&
(router->GetCaps () & RouterInfo::eHighBandwidth);
});
}
template<typename Filter>
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter (Filter filter) const
{
if (m_RouterInfos.empty())
return 0;
uint32_t ind = rand () % m_RouterInfos.size ();
for (int j = 0; j < 2; j++)
{
uint32_t i = 0;
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
for (const auto& it: m_RouterInfos)
{
if (i >= ind)
{
if (!it.second->IsUnreachable () && filter (it.second))
return it.second;
}
else
i++;
}
// we couldn't find anything, try second pass
ind = 0;
}
return nullptr; // seems we have too few routers
}
void NetDb::PostI2NPMsg (std::shared_ptr<const I2NPMessage> msg)
{
if (msg) m_Queue.Put (msg);
}
std::shared_ptr<const RouterInfo> NetDb::GetClosestFloodfill (const IdentHash& destination,
const std::set<IdentHash>& excluded, bool closeThanUsOnly) const
{
std::shared_ptr<const RouterInfo> r;
XORMetric minMetric;
IdentHash destKey = CreateRoutingKey (destination);
if (closeThanUsOnly)
minMetric = destKey ^ i2p::context.GetIdentHash ();
else
minMetric.SetMax ();
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
for (const auto& it: m_Floodfills)
{
if (!it->IsUnreachable ())
{
XORMetric m = destKey ^ it->GetIdentHash ();
if (m < minMetric && !excluded.count (it->GetIdentHash ()))
{
minMetric = m;
r = it;
}
}
}
return r;
}
std::vector<IdentHash> NetDb::GetClosestFloodfills (const IdentHash& destination, size_t num,
std::set<IdentHash>& excluded, bool closeThanUsOnly) const
{
struct Sorted
{
std::shared_ptr<const RouterInfo> r;
XORMetric metric;
bool operator< (const Sorted& other) const { return metric < other.metric; };
};
std::set<Sorted> sorted;
IdentHash destKey = CreateRoutingKey (destination);
XORMetric ourMetric;
if (closeThanUsOnly) ourMetric = destKey ^ i2p::context.GetIdentHash ();
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
for (const auto& it: m_Floodfills)
{
if (!it->IsUnreachable ())
{
XORMetric m = destKey ^ it->GetIdentHash ();
if (closeThanUsOnly && ourMetric < m) continue;
if (sorted.size () < num)
sorted.insert ({it, m});
else if (m < sorted.rbegin ()->metric)
{
sorted.insert ({it, m});
sorted.erase (std::prev (sorted.end ()));
}
}
}
}
std::vector<IdentHash> res;
size_t i = 0;
for (const auto& it: sorted)
{
if (i < num)
{
const auto& ident = it.r->GetIdentHash ();
if (!excluded.count (ident))
{
res.push_back (ident);
i++;
}
}
else
break;
}
return res;
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouterInFamily(const std::string & fam) const {
return GetRandomRouter(
[fam](std::shared_ptr<const RouterInfo> router)->bool
{
return router->IsFamily(fam);
});
}
std::shared_ptr<const RouterInfo> NetDb::GetClosestNonFloodfill (const IdentHash& destination,
const std::set<IdentHash>& excluded) const
{
std::shared_ptr<const RouterInfo> r;
XORMetric minMetric;
IdentHash destKey = CreateRoutingKey (destination);
minMetric.SetMax ();
// must be called from NetDb thread only
for (const auto& it: m_RouterInfos)
{
if (!it.second->IsFloodfill ())
{
XORMetric m = destKey ^ it.first;
if (m < minMetric && !excluded.count (it.first))
{
minMetric = m;
r = it.second;
}
}
}
return r;
}
void NetDb::ManageLeaseSets ()
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
for (auto it = m_LeaseSets.begin (); it != m_LeaseSets.end ();)
{
if (ts > it->second->GetExpirationTime () - LEASE_ENDDATE_THRESHOLD)
{
LogPrint (eLogInfo, "NetDb: LeaseSet ", it->second->GetIdentHash ().ToBase64 (), " expired");
it = m_LeaseSets.erase (it);
}
else
++it;
}
}
}
}
| 29.744681 | 178 | 0.649413 | [
"vector"
] |
b4af17aebe1e8a58902892436d8b581f789b7992 | 1,856 | hpp | C++ | rest_rpc/iguana/iguana/detail/traits.hpp | emogua/CGAssistant | f3ded85a8336bcc03fd1a3d370880cdeedaa570f | [
"MIT"
] | 39 | 2019-03-26T08:03:44.000Z | 2022-02-13T09:06:48.000Z | rest_rpc/iguana/iguana/detail/traits.hpp | emogua/CGAssistant | f3ded85a8336bcc03fd1a3d370880cdeedaa570f | [
"MIT"
] | 10 | 2019-04-08T22:18:10.000Z | 2021-10-04T04:11:00.000Z | rest_rpc/iguana/iguana/detail/traits.hpp | emogua/CGAssistant | f3ded85a8336bcc03fd1a3d370880cdeedaa570f | [
"MIT"
] | 26 | 2019-03-26T08:13:42.000Z | 2022-03-15T04:51:39.000Z | //
// Created by QY on 2017-01-05.
//
#ifndef SERIALIZE_TRAITS_HPP
#define SERIALIZE_TRAITS_HPP
#include <type_traits>
#include <vector>
#include <map>
#include <unordered_map>
#include <deque>
#include <queue>
#include <list>
namespace iguana
{
template< class T >
struct is_signed_intergral_like : std::integral_constant < bool,
(std::is_integral<T>::value) &&
std::is_signed<T>::value
> {};
template< class T >
struct is_unsigned_intergral_like : std::integral_constant < bool,
(std::is_integral<T>::value) &&
std::is_unsigned<T>::value
> {};
template < template <typename...> class U, typename T >
struct is_template_instant_of : std::false_type {};
template < template <typename...> class U, typename... args >
struct is_template_instant_of< U, U<args...> > : std::true_type {};
template<typename T>
struct is_stdstring : is_template_instant_of < std::basic_string, T >
{};
template< class T >
struct is_sequence_container : std::integral_constant < bool,
is_template_instant_of<std::deque, T>::value ||
is_template_instant_of<std::list, T>::value ||
is_template_instant_of<std::vector, T>::value ||
is_template_instant_of<std::queue, T>::value
> {};
template< class T >
struct is_associat_container : std::integral_constant < bool,
is_template_instant_of<std::map, T>::value ||
is_template_instant_of<std::unordered_map, T>::value
> {};
template< class T >
struct is_emplace_back_able : std::integral_constant < bool,
is_template_instant_of<std::deque, T>::value ||
is_template_instant_of<std::list, T>::value ||
is_template_instant_of<std::vector, T>::value
> {};
}
#endif //SERIALIZE_TRAITS_HPP
| 30.42623 | 73 | 0.641164 | [
"vector"
] |
b4b0f0f77087b6cf3ce915258d0d6908ec4af166 | 15,082 | cpp | C++ | tests/testwrite.cpp | Perchik71/mINI | f53feb4c36b1f49570aa8f6761b0ca14da0eeaa8 | [
"MIT"
] | 169 | 2018-05-21T20:55:13.000Z | 2022-03-16T21:40:42.000Z | tests/testwrite.cpp | Perchik71/mINI | f53feb4c36b1f49570aa8f6761b0ca14da0eeaa8 | [
"MIT"
] | 33 | 2021-07-03T18:55:29.000Z | 2022-03-28T17:25:53.000Z | tests/testwrite.cpp | Perchik71/mINI | f53feb4c36b1f49570aa8f6761b0ca14da0eeaa8 | [
"MIT"
] | 72 | 2018-05-21T06:34:31.000Z | 2022-03-25T02:44:17.000Z | #include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include <fstream>
#include "lest.hpp"
#include "mini/ini.h"
using T_LineData = std::vector<std::string>;
using T_INIFileData = std::tuple<std::string, T_LineData, T_LineData>;
//
// helper functions
//
bool writeTestFile(T_INIFileData const& testData)
{
std::string const& filename = std::get<0>(testData);
T_LineData const& lines = std::get<1>(testData);
std::ofstream fileWriteStream(filename);
if (fileWriteStream.is_open())
{
if (lines.size())
{
auto it = lines.begin();
for (;;)
{
fileWriteStream << *it;
if (++it == lines.end())
{
break;
}
fileWriteStream << std::endl;
}
}
return true;
}
return false;
}
bool verifyData(T_INIFileData const& testData)
{
// compares file contents to expected data
std::string line;
std::string const& filename = std::get<0>(testData);
T_LineData const& linesExpected = std::get<2>(testData);
size_t lineCount = 0;
size_t lineCountExpected = linesExpected.size();
std::ifstream fileReadStream(filename);
if (fileReadStream.is_open())
{
while (std::getline(fileReadStream, line))
{
if (fileReadStream.bad())
{
return false;
}
if (lineCount >= lineCountExpected)
{
std::cout << "Line count exceeds expected!" << std::endl;
return false;
}
std::string const& lineExpected = linesExpected[lineCount++];
if (line != lineExpected)
{
std::cout << "Line " << lineCount << " does not match expected!" << std::endl;
std::cout << "Expected: " << lineExpected << std::endl;
std::cout << "Is: " << line << std::endl;
return false;
}
}
if (lineCount < lineCountExpected)
{
std::cout << "Line count falls behind expected!" << std::endl;
}
return lineCount == lineCountExpected;
}
return false;
}
void outputData(mINI::INIStructure const& ini)
{
for (auto const& it : ini)
{
auto const& section = it.first;
auto const& collection = it.second;
std::cout << "[" << section << "]" << std::endl;
for (auto const& it2 : collection)
{
auto const& key = it2.first;
auto const& value = it2.second;
std::cout << key << "=" << value << std::endl;
}
std::cout << std::endl;
}
}
//
// test data
//
const T_INIFileData testDataBasic {
// filename
"data01.ini",
// original data
{
";some comment",
"[some section]",
"some key=1",
"other key=2"
},
// expected result
{
";some comment",
"[some section]",
"some key=2",
"other key=2",
"yet another key=3"
}
};
const T_INIFileData testDataWithGarbage {
// filename
"data02.ini",
// original data
{
"",
" GARBAGE ; ALSO GARBAGE ",
";;;;;;;;;;;;;;;comment comment",
";;;;",
";;;; ",
" ;",
" ;; ;;xxxx ",
"ignored key = ignored value",
"ignored=ignored",
"GARBAGE",
"",
"ignored key2=ignored key2",
"GARBAGE ;;;;;;;;;;;;;;;;;;;;;",
"[section] ; trailing comment",
"",
"GARBAGE",
";;",
"a=1",
"b = 2",
"c =3",
"d= 4",
"e = 5",
"f =6",
"",
"@#%$@(*(!@*@GARBAGE#!@GARBAGE%$@#GARBAGE%@&*%@$",
"GARBAGE",
"[other section] ;also a comment",
"GARBAGE",
"dinosaurs= 16",
"GARBAGE",
"birds= 123456",
"giraffes= 22",
"GARBAGE",
"[extra section];also a comment",
" aaa = 1",
" bbb=2",
" ccc = 3",
"GARBAGE",
"",
""
},
// expected result
{
"",
";;;;;;;;;;;;;;;comment comment",
";;;;",
";;;; ",
" ;",
" ;; ;;xxxx ",
"",
"[section] ; trailing comment",
"",
";;",
"a=2",
"b = 3",
"c =4",
"d= 5",
"e = 6",
"f =7",
"g=8",
"",
"[other section] ;also a comment",
"birds= 123456",
"giraffes= 22",
"[extra section];also a comment",
" aaa = 2",
" bbb=3",
" ccc = 4",
"ddd=5",
"",
"",
"[new section]",
"test=something"
}
};
const T_INIFileData testDataRemEntry {
// filename
"data04.ini",
// original data
{
"[section]",
"data1=A",
"data2=B"
},
// expected result
{
"[section]",
"data2=B"
}
};
const T_INIFileData testDataRemSection {
// filename
"data05.ini",
// original data
{
"[section]",
"data1=A",
"data2=B"
},
// expected result
{
}
};
const T_INIFileData testDataDuplicateKeys {
// filename
"data06.ini",
// original data
{
"[section]",
"data=A",
"data=B",
"[section]",
"data=C"
},
// expected result
{
"[section]",
"data=D",
"data=D",
"[section]",
"data=D"
}
};
const T_INIFileData testDataDuplicateSections {
// filename
"data07.ini",
// original data
{
"[section]",
"[section]",
"[section]"
},
// expected result
{
"[section]",
"data=A",
"[section]",
"data=A",
"[section]",
"data=A"
}
};
const T_INIFileData testDataPrettyPrint {
// filename
"data08.ini",
// oiriginal data
{
"[section1]",
"value1=A",
"value2=B",
"[section2]",
"value1=A"
},
// expected result
{
"[section1]",
"value1=A",
"value2=B",
"value3 = C",
"[section2]",
"value1=A",
"value2 = B",
"",
"[section3]",
"value1 = A",
"value2 = B"
}
};
const T_INIFileData testDataEmptyFile {
// filename
"data09.ini",
// original data
{},
// expected results
{
"[section]",
"key=value"
}
};
const T_INIFileData testDataEmptySection {
// filename
"data10.ini",
// original data
{
"[section]"
},
// expected result
{
"[section]",
"key=value"
}
};
const T_INIFileData testDataManyEmptySections {
// filename
"data11.ini",
// original data
{
"[section1]",
"[section2]",
"[section3]",
"[section4]",
"[section5]"
},
// expected result
{
"[section1]",
"[section2]",
"[section3]",
"key=value",
"[section4]",
"[section5]"
}
};
const T_INIFileData testDataEmptyNames {
// filename
"data12.ini",
// original data
{
"[]",
"key=value",
"key2=value2",
"[section]",
"=value"
},
// expected result
{
"[]",
"key=",
"=value3",
"[section]",
"=value2",
"[section2]",
"="
}
};
const T_INIFileData testDataMalformed1 {
// filename
"data13.ini",
// original data
{
"[[name1]",
"key=value",
"[name2]]",
"key=value",
"[[name3]]",
"key=value"
},
// expected result
{
"[[name1]",
"key=value1",
"[name2]]",
"key=value2",
"[[name3]]",
"key=value3"
}
};
const T_INIFileData testDataMalformed2 {
// filename
"data14.ini",
// original data
{
"[name]",
"\\===", // key: "=" value: "="
"a\\= \\===b", // key: "a= =" value: "=b"
"c\\= \\===d" // key: "c= =" value: "=d"
},
// expected result
{
"[name]",
"\\====", // key: "=" value: "=="
"a\\= \\===bb", // key: "a= =" value: "=bb"
"e\\===f=", // key: "e=" value: "=f=",
"[other]",
"\\==="
}
};
const T_INIFileData testDataConsecutiveWrites {
// filename
"data15.ini",
// original data
{
"[ Food ]",
"Cheese = 32",
"Ice Cream = 64",
"Bananas = 128",
"",
"[ Things ]",
"Scissors = AAA",
"Wooden Box = BBB",
"Speakers = CCC"
},
// expected result
{
"[ Food ]",
"Cheese = AAA",
"Ice Cream = BBB",
"Bananas = CCC",
"soup=DDD",
"",
"[ Things ]",
"Scissors = 32",
"Wooden Box = 64",
"Speakers = 128",
"book=256"
}
};
const T_INIFileData testDataEmptyValues {
// filename
"data16.ini",
// original data
{
"[section]",
"key=value"
},
// expected result
{
"[section]",
"key="
}
};
//
// test cases
//
const lest::test mINI_tests[] = {
CASE("TEST: Basic write")
{
// do some basic modifications to an INI file
// then compare resulting file to expected data
std::string const& filename = std::get<0>(testDataBasic);
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
ini["some section"]["some key"] = "2";
ini["some section"]["yet another key"] = "3";
EXPECT(file.write(ini) == true);
EXPECT(verifyData(testDataBasic));
},
CASE("TEST: Garbage data")
{
auto const& filename = std::get<0>(testDataWithGarbage);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"].set({
{"a", "2"},
{"b", "3"},
{"c", "4"},
{"d", "5"},
{"e", "6"},
{"f", "7"},
{"g", "8"}
});
ini["other section"].remove("dinosaurs"); // sorry, dinosaurs
ini["extra section"].set({
{"aaa", "2"},
{"bbb", "3"},
{"ccc", "4"},
{"ddd", "5"}
});
ini["new section"]["test"] = "something";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataWithGarbage));
},
CASE("Test: Remove entry")
{
auto const& filename = std::get<0>(testDataRemEntry);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"].remove("data1");
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataRemEntry));
},
CASE("Test: Remove section")
{
auto const& filename = std::get<0>(testDataRemSection);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini.remove("section");
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataRemSection));
},
CASE("Test: Duplicate keys")
{
auto const& filename = std::get<0>(testDataDuplicateKeys);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"]["data"] = "D";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataDuplicateKeys));
},
CASE("Test: Duplicate sections")
{
auto const& filename = std::get<0>(testDataDuplicateSections);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"]["data"] = "A";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataDuplicateSections));
},
CASE("Test: Pretty print")
{
auto const& filename = std::get<0>(testDataPrettyPrint);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section1"]["value3"] = "C";
ini["section2"]["value2"] = "B";
ini["section3"].set({
{"value1", "A"},
{"value2", "B"}
});
// write to file
EXPECT(file.write(ini, true) == true);
// verify data
EXPECT(verifyData(testDataPrettyPrint));
},
CASE("Test: Write to empty file")
{
auto const& filename = std::get<0>(testDataEmptyFile);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"]["key"] = "value";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataEmptyFile));
},
CASE("Test: Write to empty section")
{
auto const& filename = std::get<0>(testDataEmptySection);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"]["key"] = "value";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataEmptySection));
},
CASE("Test: Write to a single empty section among many")
{
auto const& filename = std::get<0>(testDataManyEmptySections);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section3"]["key"] = "value";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataManyEmptySections));
},
CASE("Test: Write with empty section and key names")
{
auto const& filename = std::get<0>(testDataEmptyNames);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini[""]["key"] = "";
EXPECT(ini[""].remove("key2") == true);
ini[""][""] = "value3";
ini["section"][""] = "value2";
ini["section2"][""] = "";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataEmptyNames));
},
CASE("Test: Write malformed section names")
{
auto const& filename = std::get<0>(testDataMalformed1);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["[name1"]["key"] = "value1";
ini["name2]"]["key"] = "value2";
ini["[name3]"]["key"] = "value3";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataMalformed1));
},
CASE("Test: Write malformed key names")
{
auto const& filename = std::get<0>(testDataMalformed2);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["name"].set({
{"=", " == "},
{"a= =", "=bb"},
{"e=", " =f= "}
});
ini["name"].remove("c= =");
ini["other"]["="] = "=";
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataMalformed2));
},
CASE("Test: Consecutive writes")
{
auto const& filename = std::get<0>(testDataConsecutiveWrites);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["food"].set({
{"cheese", "AAA"},
{"ice cream", "BBB"},
{"bananas", "CCC"},
{"soup", "DDD"}
});
ini["things"].set({
{"scissors", "32"},
{"wooden box", "64"},
{" speakers ", " 128 "},
{" book ", " 256 "}
});
// write to file multiple times
for (unsigned int i = 0; i < 10; ++i)
{
EXPECT(file.write(ini) == true);
}
// verify data
EXPECT(verifyData(testDataConsecutiveWrites));
},
CASE("Test: Empty values")
{
auto const& filename = std::get<0>(testDataEmptyValues);
// read from file
mINI::INIFile file(filename);
mINI::INIStructure ini;
EXPECT(file.read(ini) == true);
// update data
ini["section"]["key"].clear();
// write to file
EXPECT(file.write(ini) == true);
// verify data
EXPECT(verifyData(testDataEmptyValues));
}
};
int main(int argc, char** argv)
{
// write test files
writeTestFile(testDataBasic);
writeTestFile(testDataWithGarbage);
writeTestFile(testDataRemEntry);
writeTestFile(testDataRemSection);
writeTestFile(testDataDuplicateKeys);
writeTestFile(testDataDuplicateSections);
writeTestFile(testDataPrettyPrint);
writeTestFile(testDataEmptyFile);
writeTestFile(testDataEmptySection);
writeTestFile(testDataManyEmptySections);
writeTestFile(testDataEmptyNames);
writeTestFile(testDataMalformed1);
writeTestFile(testDataMalformed2);
writeTestFile(testDataConsecutiveWrites);
writeTestFile(testDataEmptyValues);
// run tests
if (int failures = lest::run(mINI_tests, argc, argv))
{
return failures;
}
return std::cout << std::endl << "All tests passed!" << std::endl, EXIT_SUCCESS;
}
| 20.163102 | 82 | 0.586859 | [
"vector"
] |
b4b496758cf06805e443c3173a7b50afe0fc8c7d | 18,374 | cpp | C++ | apps/exampleViewer/widgets/transferFunction.cpp | burlen/ospray | e041b985dc53a2339a90a5735a22d0489b730df0 | [
"Apache-2.0"
] | null | null | null | apps/exampleViewer/widgets/transferFunction.cpp | burlen/ospray | e041b985dc53a2339a90a5735a22d0489b730df0 | [
"Apache-2.0"
] | null | null | null | apps/exampleViewer/widgets/transferFunction.cpp | burlen/ospray | e041b985dc53a2339a90a5735a22d0489b730df0 | [
"Apache-2.0"
] | null | null | null | // ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <cmath>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <imgui.h>
#include <imconfig.h>
#include "ospcommon/ospmath.h"
#include "ospray/ospray_cpp/Data.h"
#include "ospray/ospray_cpp/TransferFunction.h"
#include "tfn_lib/tfn_lib.h"
#include "transferFunction.h"
#include "sg/common/Data.h"
using namespace ospcommon;
static float lerp(const float a, const float b, const float t)
{
return (1.0 - t) * a + t * b;
}
namespace ospray {
namespace imgui3D {
TransferFunction::Line::Line() :
line({vec2f(0, 0),
vec2f(1, 1)}),
color(0xffffffff)
{
}
void TransferFunction::Line::movePoint(const float &startX, const vec2f &end)
{
// Find the closest point to where the user clicked
auto fnd = std::min_element(line.begin(), line.end(),
[&startX](const vec2f &a, const vec2f &b){
return std::abs(startX - a.x) < std::abs(startX - b.x);
});
// If there's no nearby point we need to insert a new one
// TODO: How much fudge to allow for here?
if (std::abs(startX - fnd->x) >= 0.01){
std::vector<vec2f>::iterator split = line.begin();
for (; split != line.end(); ++split){
if (split->x < startX && startX < (split + 1)->x){
break;
}
}
assert(split != line.end());
line.insert(split + 1, end);
} else {
*fnd = end;
// Keep the start and end points clamped to the left/right side
if (fnd == line.begin()){
fnd->x = 0;
} else if (fnd == line.end() - 1){
fnd->x = 1;
} else {
// If it's a point in the middle keep it from going past its neighbors
fnd->x = clamp(fnd->x, (fnd - 1)->x, (fnd + 1)->x);
}
}
}
void TransferFunction::Line::removePoint(const float &x)
{
if (line.size() == 2)
return;
// See if we have a segment starting near that point
auto fnd = std::min_element(line.begin(), line.end(),
[&x](const vec2f &a, const vec2f &b){
return std::abs(x - a.x) < std::abs(x - b.x);
});
// Don't allow erasure of the start and end points of the line
if (fnd != line.end() && fnd + 1 != line.end() && fnd != line.begin())
line.erase(fnd);
}
TransferFunction::TransferFunction(std::shared_ptr<sg::TransferFunction> tfn) :
transferFcn(tfn),
activeLine(3),
tfcnSelection(JET),
customizing(false),
fcnChanged(true),
paletteTex(0),
textBuffer(512, '\0')
{
// TODO: Use the transfer function passed to use to configure the initial widget lines
rgbaLines[0].color = 0xff0000ff;
rgbaLines[1].color = 0xff00ff00;
rgbaLines[2].color = 0xffff0000;
rgbaLines[3].color = 0xffffffff;
setColorMap(false);
}
TransferFunction::~TransferFunction()
{
if (paletteTex)
glDeleteTextures(1, &paletteTex);
}
TransferFunction::TransferFunction(const TransferFunction &t) :
transferFcn(t.transferFcn),
rgbaLines(t.rgbaLines),
activeLine(t.activeLine),
tfcnSelection(t.tfcnSelection),
customizing(t.customizing),
transferFunctions(t.transferFunctions),
fcnChanged(true),
paletteTex(0),
textBuffer(512, '\0')
{
setColorMap(false);
}
TransferFunction& TransferFunction::operator=(const TransferFunction &t)
{
if (this == &t)
return *this;
transferFcn = t.transferFcn;
rgbaLines = t.rgbaLines;
activeLine = t.activeLine;
tfcnSelection = t.tfcnSelection;
customizing = t.customizing;
transferFunctions = t.transferFunctions;
fcnChanged = true;
setColorMap(false);
return *this;
}
void TransferFunction::setColorMapByName(std::string name, bool useOpacities)
{
for (int i =0; i < transferFunctions.size(); i++)
{
if (name == transferFunctions[i].name)
{
tfcnSelection = i;
setColorMap(useOpacities);
return;
}
}
}
void TransferFunction::drawUi()
{
ImGui::Text("Left click and drag to add/move points\nRight click to remove\n");
ImGui::InputText("filename", textBuffer.data(), textBuffer.size() - 1);
if (ImGui::Button("Save")){
save(textBuffer.data());
}
ImGui::SameLine();
if (ImGui::Button("Load")){
load(textBuffer.data());
}
std::vector<const char*> colorMaps(transferFunctions.size(), nullptr);
std::transform(transferFunctions.begin(), transferFunctions.end(), colorMaps.begin(),
[](const tfn::TransferFunction &t) { return t.name.c_str(); });
if (ImGui::Combo("ColorMap", &tfcnSelection, colorMaps.data(), colorMaps.size())) {
setColorMap(false);
}
ImGui::Checkbox("Customize", &customizing);
if (customizing) {
ImGui::SameLine();
ImGui::RadioButton("Red", &activeLine, 0); ImGui::SameLine();
ImGui::SameLine();
ImGui::RadioButton("Green", &activeLine, 1); ImGui::SameLine();
ImGui::SameLine();
ImGui::RadioButton("Blue", &activeLine, 2); ImGui::SameLine();
ImGui::SameLine();
ImGui::RadioButton("Alpha", &activeLine, 3);
} else {
activeLine = 3;
}
vec2f canvasPos(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y);
vec2f canvasSize(ImGui::GetContentRegionAvail().x, std::min(ImGui::GetContentRegionAvail().y, 255.0f));
// Force some min size of the editor
if (canvasSize.x < 50.f){
canvasSize.x = 50.f;
}
if (canvasSize.y < 50.f){
canvasSize.y = 50.f;
}
if (paletteTex){
ImGui::Image(reinterpret_cast<void*>(paletteTex), ImVec2(canvasSize.x, 16));
canvasPos.y += 20;
canvasSize.y -= 20;
}
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(canvasPos, canvasPos + canvasSize, IM_COL32_WHITE);
const vec2f viewScale(canvasSize.x, -canvasSize.y + 10);
const vec2f viewOffset(canvasPos.x, canvasPos.y + canvasSize.y - 10);
ImGui::InvisibleButton("canvas", canvasSize);
if (ImGui::IsItemHovered()){
vec2f mousePos = vec2f(ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y);
mousePos = (mousePos - viewOffset) / viewScale;
// Need to somehow find which line of RGBA the mouse is closest too
if (ImGui::GetIO().MouseDown[0]){
rgbaLines[activeLine].movePoint(mousePos.x, mousePos);
fcnChanged = true;
} else if (ImGui::IsMouseClicked(1)){
rgbaLines[activeLine].removePoint(mousePos.x);
fcnChanged = true;
}
}
draw_list->PushClipRect(canvasPos, canvasPos + canvasSize);
if (customizing) {
for (int i = 0; i < static_cast<int>(rgbaLines.size()); ++i){
if (i == activeLine){
continue;
}
for (size_t j = 0; j < rgbaLines[i].line.size() - 1; ++j){
const vec2f &a = rgbaLines[i].line[j];
const vec2f &b = rgbaLines[i].line[j + 1];
draw_list->AddLine(viewOffset + viewScale * a, viewOffset + viewScale * b,
rgbaLines[i].color, 2.0f);
}
}
}
// Draw the active line on top
for (size_t j = 0; j < rgbaLines[activeLine].line.size() - 1; ++j){
const vec2f &a = rgbaLines[activeLine].line[j];
const vec2f &b = rgbaLines[activeLine].line[j + 1];
draw_list->AddLine(viewOffset + viewScale * a, viewOffset + viewScale * b,
rgbaLines[activeLine].color, 2.0f);
draw_list->AddCircleFilled(viewOffset + viewScale * a, 4.f, rgbaLines[activeLine].color);
// If we're last draw the list Circle as well
if (j == rgbaLines[activeLine].line.size() - 2) {
draw_list->AddCircleFilled(viewOffset + viewScale * b, 4.f, rgbaLines[activeLine].color);
}
}
draw_list->PopClipRect();
}
void TransferFunction::render()
{
if (!transferFcn)
return;
const int samples = transferFcn->child("numSamples").valueAs<int>();
// Upload to GL if the transfer function has changed
if (!paletteTex) {
GLint prevBinding = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &prevBinding);
glGenTextures(1, &paletteTex);
glBindTexture(GL_TEXTURE_2D, paletteTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, samples, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
if (prevBinding)
glBindTexture(GL_TEXTURE_2D, prevBinding);
}
if (fcnChanged) {
GLint prevBinding = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &prevBinding);
// Sample the palette then upload the data
std::vector<uint8_t> palette(samples * 4, 0);
// Step along the alpha line and sample it
std::array<std::vector<vec2f>::const_iterator, 4> lit = {
rgbaLines[0].line.begin(), rgbaLines[1].line.begin(),
rgbaLines[2].line.begin(), rgbaLines[3].line.begin()
};
const float step = 1.0 / samples;
for (size_t i = 0; i < samples; ++i){
const float x = step * i;
std::array<float, 4> sampleColor;
for (size_t j = 0; j < 4; ++j){
if (x > (lit[j] + 1)->x) {
++lit[j];
}
assert(lit[j] != rgbaLines[j].line.end());
const float t = (x - lit[j]->x) / ((lit[j] + 1)->x - lit[j]->x);
// It's hard to click down at exactly 0, so offset a little bit
sampleColor[j] = clamp(lerp(lit[j]->y - 0.001, (lit[j] + 1)->y - 0.001, t));
}
for (size_t j = 0; j < 3; ++j) {
palette[i * 4 + j] = clamp(sampleColor[j] * 255.0, 0.0, 255.0);
}
palette[i * 4 + 3] = 255;
}
glBindTexture(GL_TEXTURE_2D, paletteTex);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, samples, 1, GL_RGBA,
GL_UNSIGNED_BYTE, static_cast<const void*>(palette.data()));
auto &colorCP = *transferFcn->child("colorControlPoints").nodeAs<sg::DataVector4f>();
auto &opacityCP = *transferFcn->child("opacityControlPoints").nodeAs<sg::DataVector2f>();
opacityCP.clear();
colorCP.clear();
for (auto line : rgbaLines[3].line)
opacityCP.push_back(line);
int i = 0;
for (auto line : rgbaLines[0].line) {
colorCP.push_back(vec4f(line.x, line.y, 0.f, 0.f));
colorCP.v.back()[2] = rgbaLines[1].line[i].y;
colorCP.v.back()[3] = rgbaLines[2].line[i].y;
i++;
}
// NOTE(jda) - HACK! colors array isn't updating, so we have to forcefully
// say "make sure you update yourself"...???
opacityCP.markAsModified();
colorCP.markAsModified();
// NOTE(jda) - MORE HACKS! (ugh)
auto &colors = *transferFcn->child("colors").nodeAs<sg::DataBuffer>();
auto &opacities = *transferFcn->child("opacities").nodeAs<sg::DataBuffer>();
colors.markAsModified();
opacities.markAsModified();
transferFcn->updateChildDataValues();
if (prevBinding)
glBindTexture(GL_TEXTURE_2D, prevBinding);
fcnChanged = false;
}
}
void TransferFunction::load(const ospcommon::FileName &fileName)
{
try {
tfn::TransferFunction loaded(fileName);
transferFunctions.emplace_back(fileName);
tfcnSelection = transferFunctions.size() - 1;
setColorMap(true);
} catch (const std::runtime_error &e) {
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
void TransferFunction::save(const ospcommon::FileName &fileName) const
{
// For opacity we can store the associated data value and only have 1 line,
// so just save it out directly
tfn::TransferFunction output(transferFunctions[tfcnSelection].name,
std::vector<vec3f>(), rgbaLines[3].line, 0, 1, 1);
// Pull the RGB line values to compute the transfer function and save it out
// here we may need to do some interpolation, if the RGB lines have differing numbers
// of control points
// Find which x values we need to sample to get all the control points for the tfcn.
std::vector<float> controlPoints;
for (size_t i = 0; i < 3; ++i) {
for (const auto &x : rgbaLines[i].line)
controlPoints.push_back(x.x);
}
// Filter out same or within epsilon control points to get unique list
std::sort(controlPoints.begin(), controlPoints.end());
auto uniqueEnd = std::unique(controlPoints.begin(), controlPoints.end(),
[](const float &a, const float &b) { return std::abs(a - b) < 0.0001; });
controlPoints.erase(uniqueEnd, controlPoints.end());
// Step along the lines and sample them
std::array<std::vector<vec2f>::const_iterator, 3> lit = {
rgbaLines[0].line.begin(), rgbaLines[1].line.begin(),
rgbaLines[2].line.begin()
};
for (const auto &x : controlPoints) {
std::array<float, 3> sampleColor;
for (size_t j = 0; j < 3; ++j) {
if (x > (lit[j] + 1)->x)
++lit[j];
assert(lit[j] != rgbaLines[j].line.end());
const float t = (x - lit[j]->x) / ((lit[j] + 1)->x - lit[j]->x);
// It's hard to click down at exactly 0, so offset a little bit
sampleColor[j] = clamp(lerp(lit[j]->y - 0.001, (lit[j] + 1)->y - 0.001, t));
}
output.rgbValues.push_back(vec3f(sampleColor[0], sampleColor[1], sampleColor[2]));
}
try {
output.save(fileName);
} catch (const std::runtime_error &e) {
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
void TransferFunction::setColorMap(const bool useOpacity)
{
if (transferFunctions.size() < 1)
return;
const auto &colors = transferFunctions[tfcnSelection].rgbValues;
const auto &opacities = transferFunctions[tfcnSelection].opacityValues;
for (size_t i = 0; i < 3; ++i)
rgbaLines[i].line.clear();
const float nColors = static_cast<float>(colors.size()) - 1;
for (size_t i = 0; i < colors.size(); ++i) {
for (size_t j = 0; j < 3; ++j)
rgbaLines[j].line.push_back(vec2f(i / nColors, colors[i][j]));
}
if (useOpacity && !opacities.empty()) {
rgbaLines[3].line.clear();
const double valMin = transferFunctions[tfcnSelection].dataValueMin;
const double valMax = transferFunctions[tfcnSelection].dataValueMax;
// Setup opacity if the colormap has it
for (size_t i = 0; i < opacities.size(); ++i) {
const float x = (opacities[i].x - valMin) / (valMax - valMin);
rgbaLines[3].line.push_back(vec2f(x, opacities[i].y));
}
}
fcnChanged = true;
}
void TransferFunction::loadColorMapPresets(std::shared_ptr<sg::Node> tfPresets)
{
for (auto preset : tfPresets->children())
{
std::vector<vec3f> colors;
std::vector<vec2f> opacities;
auto& tfPreset = *preset.second->nodeAs<sg::TransferFunction>();
auto& colorsDV = tfPreset["colors"].nodeAs<sg::DataVector3f>()->v;
for (auto color : colorsDV)
colors.push_back(color);
auto& opacitiesDV = tfPreset["opacityControlPoints"].nodeAs<sg::DataVector2f>()->v;
for (auto opacity : opacitiesDV)
opacities.push_back(opacity);
transferFunctions.emplace_back(tfPreset.name(), colors, opacities, 0, 1, 1);
}
}
void TransferFunction::loadColorMapPresets()
{
std::vector<vec3f> colors;
// The presets have no existing opacity value
const std::vector<vec2f> opacity;
// From the old volume viewer, these are based on ParaView
// Jet transfer function
colors.push_back(vec3f(0 , 0, 0.562493));
colors.push_back(vec3f(0 , 0, 1 ));
colors.push_back(vec3f(0 , 1, 1 ));
colors.push_back(vec3f(0.500008, 1, 0.500008));
colors.push_back(vec3f(1 , 1, 0 ));
colors.push_back(vec3f(1 , 0, 0 ));
colors.push_back(vec3f(0.500008, 0, 0 ));
transferFunctions.emplace_back("Jet", colors, opacity, 0, 1, 1);
colors.clear();
colors.push_back(vec3f(0 , 0 , 0 ));
colors.push_back(vec3f(0 , 0.120394 , 0.302678 ));
colors.push_back(vec3f(0 , 0.216587 , 0.524575 ));
colors.push_back(vec3f(0.0552529, 0.345022 , 0.659495 ));
colors.push_back(vec3f(0.128054 , 0.492592 , 0.720287 ));
colors.push_back(vec3f(0.188952 , 0.641306 , 0.792096 ));
colors.push_back(vec3f(0.327672 , 0.784939 , 0.873426 ));
colors.push_back(vec3f(0.60824 , 0.892164 , 0.935546 ));
colors.push_back(vec3f(0.881376 , 0.912184 , 0.818097 ));
colors.push_back(vec3f(0.9514 , 0.835615 , 0.449271 ));
colors.push_back(vec3f(0.904479 , 0.690486 , 0 ));
colors.push_back(vec3f(0.854063 , 0.510857 , 0 ));
colors.push_back(vec3f(0.777096 , 0.330175 , 0.000885023));
colors.push_back(vec3f(0.672862 , 0.139086 , 0.00270085 ));
colors.push_back(vec3f(0.508812 , 0 , 0 ));
colors.push_back(vec3f(0.299413 , 0.000366217, 0.000549325));
colors.push_back(vec3f(0.0157473, 0.00332647 , 0 ));
transferFunctions.emplace_back("Ice Fire", colors, opacity, 0, 1, 1);
colors.clear();
colors.push_back(vec3f(0.231373, 0.298039 , 0.752941));
colors.push_back(vec3f(0.865003, 0.865003 , 0.865003));
colors.push_back(vec3f(0.705882, 0.0156863, 0.14902));
transferFunctions.emplace_back("Cool Warm", colors, opacity, 0, 1, 1);
colors.clear();
colors.push_back(vec3f(0, 0, 1));
colors.push_back(vec3f(1, 0, 0));
transferFunctions.emplace_back("Blue Red", colors, opacity, 0, 1, 1);
colors.clear();
colors.push_back(vec3f(0));
colors.push_back(vec3f(1));
transferFunctions.emplace_back("Grayscale", colors, opacity, 0, 1, 1);
colors.clear();
}
}// ::imgui3D
}// ::ospray
| 35.402697 | 107 | 0.620605 | [
"render",
"vector",
"transform"
] |
b4b51333c23d8715d32465fe967ef41446d3396a | 29,635 | cxx | C++ | vigranumpy/src/core/segmentation.cxx | ilastik/vigra-ilastik-05 | bc3daec5a71016363baebc27ad3a45fb6056579f | [
"MIT"
] | 1 | 2017-01-23T11:27:56.000Z | 2017-01-23T11:27:56.000Z | vigranumpy/src/core/segmentation.cxx | ilastik/vigra-ilastik-05 | bc3daec5a71016363baebc27ad3a45fb6056579f | [
"MIT"
] | null | null | null | vigranumpy/src/core/segmentation.cxx | ilastik/vigra-ilastik-05 | bc3daec5a71016363baebc27ad3a45fb6056579f | [
"MIT"
] | 3 | 2015-12-09T13:47:13.000Z | 2019-04-06T21:28:59.000Z | /************************************************************************/
/* */
/* Copyright 2009 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyanalysis_PyArray_API
//#define NO_IMPORT_ARRAY
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <vigra/localminmax.hxx>
#include <vigra/labelimage.hxx>
#include <vigra/watersheds.hxx>
#include <vigra/seededregiongrowing.hxx>
#include <vigra/labelvolume.hxx>
#include <vigra/watersheds3d.hxx>
#include <vigra/seededregiongrowing3d.hxx>
#include <string>
#include <cmath>
#include <ctype.h> // tolower()
namespace python = boost::python;
namespace vigra
{
template < class PixelType >
NumpyAnyArray
pythonLabelImage(NumpyArray<2, Singleband<PixelType> > image,
int neighborhood = 4,
NumpyArray<2, Singleband<npy_uint32> > res = NumpyArray<2, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"labelImage(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "labelImage(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
labelImage(srcImageRange(image), destImage(res), false);
break;
}
case 8:
{
labelImage(srcImageRange(image), destImage(res), true);
break;
}
}
return res;
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pyLabelImage, pythonLabelImage)
template < class PixelType >
NumpyAnyArray
pythonLabelImageWithBackground(NumpyArray<2, Singleband<PixelType> > image,
int neighborhood = 4,
PixelType background_value = 0,
NumpyArray<2, Singleband<npy_uint32> > res = NumpyArray<2, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"labelImageWithBackground(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "labelImageWithBackground(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
labelImageWithBackground(srcImageRange(image),
destImage(res), false, background_value);
break;
}
case 8:
{
labelImageWithBackground(srcImageRange(image),
destImage(res), true, background_value);
break;
}
}
return res;
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pyLabelImageWithBackground, pythonLabelImageWithBackground)
template < class VoxelType >
NumpyAnyArray
pythonLabelVolume(NumpyArray<3, Singleband<VoxelType> > volume,
int neighborhood=6,
NumpyArray<3, Singleband<npy_uint32> > res=NumpyArray<3, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 6 || neighborhood == 26,
"labelVolume(): neighborhood must be 6 or 26.");
res.reshapeIfEmpty(volume.shape(), "labelVolume(): Output array has wrong shape.");
switch (neighborhood)
{
case 6:
{
labelVolume(srcMultiArrayRange(volume),
destMultiArray(res), NeighborCode3DSix());
break;
}
case 26:
{
labelVolume(srcMultiArrayRange(volume),
destMultiArray(res), NeighborCode3DTwentySix());
break;
}
}
return res;
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pyLabelVolume, pythonLabelVolume)
template < class VoxelType >
NumpyAnyArray
pythonLabelVolumeWithBackground(NumpyArray<3, Singleband<VoxelType> > volume,
int neighborhood=6,
VoxelType background_value = 0,
NumpyArray<3, Singleband<npy_uint32> > res=NumpyArray<3, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 6 || neighborhood == 26,
"labelVolumeWithBackground(): neighborhood must be 6 or 26.");
res.reshapeIfEmpty(volume.shape(), "labelVolumeWithBackground(): Output array has wrong shape.");
switch (neighborhood)
{
case 6:
{
labelVolumeWithBackground(srcMultiArrayRange(volume),
destMultiArray(res), NeighborCode3DSix(),
background_value);
break;
}
case 26:
{
labelVolumeWithBackground(srcMultiArrayRange(volume),
destMultiArray(res), NeighborCode3DTwentySix(),
background_value);
break;
}
}
return res;
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pyLabelVolumeWithBackground, pythonLabelVolumeWithBackground)
/*********************************************************************************/
template < class PixelType >
NumpyAnyArray
pythonLocalMinima2D(NumpyArray<2, Singleband<PixelType> > image,
PixelType marker = NumericTraits<PixelType>::one(),
int neighborhood = 8,
NumpyArray<2, Singleband<PixelType> > res = python::object())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"localMinima(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "localMinima(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
localMinima(srcImageRange(image), destImage(res), marker,
FourNeighborCode());
break;
}
case 8:
{
localMinima(srcImageRange(image), destImage(res), marker,
EightNeighborCode());
break;
}
}
return res;
}
template < class PixelType >
NumpyAnyArray
pythonExtendedLocalMinima2D(NumpyArray<2, Singleband<PixelType> > image,
PixelType marker = NumericTraits<PixelType>::one(),
int neighborhood = 8,
NumpyArray<2, Singleband<PixelType> > res = python::object())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"extendedLocalMinima(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "extendedLocalMinima(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
extendedLocalMinima(srcImageRange(image), destImage(res),
marker, FourNeighborCode());
break;
}
case 8:
{
extendedLocalMinima(srcImageRange(image), destImage(res),
marker, EightNeighborCode());
break;
}
}
return res;
}
template < class PixelType >
NumpyAnyArray
pythonLocalMaxima2D(NumpyArray<2, Singleband<PixelType> > image,
PixelType marker = NumericTraits<PixelType>::one(),
int neighborhood = 8,
NumpyArray<2, Singleband<PixelType> > res = python::object())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"localMaxima(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "localMaxima(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
localMaxima(srcImageRange(image), destImage(res), marker,
FourNeighborCode());
break;
}
case 8:
{
localMaxima(srcImageRange(image), destImage(res), marker,
EightNeighborCode());
break;
}
}
return res;
}
template < class PixelType >
NumpyAnyArray
pythonExtendedLocalMaxima2D(NumpyArray<2, Singleband<PixelType> > image,
PixelType marker = NumericTraits<PixelType>::one(),
int neighborhood = 8,
NumpyArray<2, Singleband<PixelType> > res = python::object())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"extendedLocalMaxima(): neighborhood must be 4 or 8.");
res.reshapeIfEmpty(image.shape(), "extendedLocalMaxima(): Output array has wrong shape.");
switch (neighborhood)
{
case 4:
{
extendedLocalMaxima(srcImageRange(image), destImage(res),
marker, FourNeighborCode());
break;
}
case 8:
{
extendedLocalMaxima(srcImageRange(image), destImage(res),
marker, EightNeighborCode());
break;
}
}
return res;
}
/*************************************************************************/
#if 0
template < class PixelType >
python::tuple
pythonWatersheds2DOld(NumpyArray<2, Singleband<PixelType> > image,
int neighborhood = 4,
NumpyArray<2, Singleband<npy_uint32> > seeds = python::object(),
std::string method = "RegionGrowing",
SRGType srgType = CompleteGrow,
PixelType max_cost = 0.0,
NumpyArray<2, Singleband<npy_uint32> > res = python::object())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"watersheds2D(): neighborhood must be 4 or 8.");
for(unsigned int k=0; k<method.size(); ++k)
method[k] = (std::string::value_type)tolower(method[k]);
bool haveSeeds = seeds.hasData();
unsigned int maxRegionLabel = 0;
if(method == "")
method = "regiongrowing";
if(method == "regiongrowing")
{
seeds.reshapeIfEmpty(image.shape(), "watersheds(): Seed array has wrong shape.");
if(!haveSeeds)
{
MultiArray<2, UInt8> minima(image.shape());
localMinima(srcImageRange(image), destImage(minima), 1, EightNeighborCode());
maxRegionLabel = labelImageWithBackground(srcImageRange(minima), destImage(seeds), true, 0);
}
else
{
FindMinMax< npy_uint32 > minmax;
inspectImage(srcImageRange(seeds), minmax);
maxRegionLabel = minmax.max;
}
res.reshapeIfEmpty(image.shape(), "watersheds(): Output array has wrong shape.");
ArrayOfRegionStatistics< SeedRgDirectValueFunctor< PixelType > > stats(maxRegionLabel);
if(neighborhood == 4)
{
seededRegionGrowing(srcImageRange(image), srcImage(seeds), destImage(res),
stats, srgType, FourNeighborCode(), max_cost);
}
else
{
seededRegionGrowing(srcImageRange(image), srcImage(seeds), destImage(res),
stats, srgType, EightNeighborCode(), max_cost);
}
}
else if(method == "unionfind")
{
vigra_precondition(!haveSeeds,
"watersheds(): UnionFind does not support seed images.");
vigra_precondition(srgType == CompleteGrow,
"watersheds(): UnionFind only supports 'CompleteGrow' mode.");
res.reshapeIfEmpty(image.shape(), "watersheds(): Output array has wrong shape.");
if(neighborhood == 4)
{
maxRegionLabel = watershedsUnionFind(srcImageRange(image), destImage(res),
FourNeighborCode());
}
else
{
maxRegionLabel = watershedsUnionFind(srcImageRange(image), destImage(res),
EightNeighborCode());
}
}
else
{
vigra_precondition(false, "watersheds(): Unknown watershed method requested.");
}
return python::make_tuple(res, maxRegionLabel);
}
#endif
template < class PixelType >
python::tuple
pythonWatersheds2D(NumpyArray<2, Singleband<PixelType> > image,
int neighborhood = 4,
NumpyArray<2, Singleband<npy_uint32> > seeds = NumpyArray<2, Singleband<npy_uint32> >(),
std::string method = "RegionGrowing",
SRGType srgType = CompleteGrow,
PixelType max_cost = 0.0,
NumpyArray<2, Singleband<npy_uint32> > res = NumpyArray<2, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 4 || neighborhood == 8,
"watersheds2D(): neighborhood must be 4 or 8.");
for(unsigned int k=0; k<method.size(); ++k)
method[k] = (std::string::value_type)tolower(method[k]);
if(method == "")
method = "regiongrowing";
res.reshapeIfEmpty(image.shape(), "watersheds(): Output array has wrong shape.");
WatershedOptions options;
options.srgType(srgType);
if(max_cost > 0.0)
{
vigra_precondition(method != "unionfind",
"watersheds(): UnionFind does not support a cost threshold.");
options.stopAtThreshold(max_cost);
}
if(seeds.hasData())
{
vigra_precondition(method != "unionfind",
"watersheds(): UnionFind does not support seed images.");
res = seeds;
}
else
{
options.seedOptions(SeedOptions().minima());
}
npy_uint32 maxRegionLabel = 0;
if(method == "regiongrowing")
{
if(neighborhood == 4)
{
maxRegionLabel = watershedsRegionGrowing(srcImageRange(image), destImage(res),
FourNeighborCode(), options);
}
else
{
maxRegionLabel = watershedsRegionGrowing(srcImageRange(image), destImage(res),
EightNeighborCode(), options);
}
}
else if(method == "unionfind")
{
vigra_precondition(srgType == CompleteGrow,
"watersheds(): UnionFind only supports 'CompleteGrow' mode.");
if(neighborhood == 4)
{
maxRegionLabel = watershedsUnionFind(srcImageRange(image), destImage(res),
FourNeighborCode());
}
else
{
maxRegionLabel = watershedsUnionFind(srcImageRange(image), destImage(res),
EightNeighborCode());
}
}
else
{
vigra_precondition(false, "watersheds(): Unknown watershed method requested.");
}
return python::make_tuple(res, maxRegionLabel);
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pywatersheds2D, pythonWatersheds2D)
template < class PixelType >
python::tuple
pythonWatersheds3D(NumpyArray<3, Singleband<PixelType> > image,
int neighborhood = 6,
NumpyArray<3, Singleband<npy_uint32> > seeds = NumpyArray<3, Singleband<npy_uint32> >(),
std::string method = "RegionGrowing",
SRGType srgType = CompleteGrow,
PixelType max_cost = 0.0,
NumpyArray<3, Singleband<npy_uint32> > res = NumpyArray<3, Singleband<npy_uint32> >())
{
vigra_precondition(neighborhood == 6 || neighborhood == 26,
"watersheds3D(): neighborhood must be 6 or 26.");
for(unsigned int k=0; k<method.size(); ++k)
method[k] = (std::string::value_type)tolower(method[k]);
bool haveSeeds = seeds.hasData();
unsigned int maxRegionLabel;
if(method == "")
method = "regiongrowing";
if(method == "regiongrowing")
{
seeds.reshapeIfEmpty(image.shape(), "watersheds(): Seed array has wrong shape.");
if(!haveSeeds)
{
maxRegionLabel = 0;
// determine seeds
// FIXME: implement localMinima() for volumes
typedef NeighborCode3DTwentySix Neighborhood;
typedef Neighborhood::Direction Direction;
MultiArrayShape<3>::type p(0,0,0);
for(p[2]=0; p[2]<image.shape(2); ++p[2])
{
for(p[1]=0; p[1]<image.shape(1); ++p[1])
{
for(p[0]=0; p[0]<image.shape(0); ++p[0])
{
AtVolumeBorder atBorder = isAtVolumeBorder(p, image.shape());
int totalCount = Neighborhood::nearBorderDirectionCount(atBorder),
minimumCount = 0;
if(atBorder == NotAtBorder)
{
for(int k=0; k<totalCount; ++k)
{
if(image[p] < image[p+Neighborhood::diff((Direction)k)])
++minimumCount;
}
}
else
{
for(int k=0; k<totalCount; ++k)
{
if(image[p] < image[p+Neighborhood::diff(
Neighborhood::nearBorderDirections(atBorder, k))])
++minimumCount;
}
}
if(minimumCount == totalCount)
{
seeds[p] = ++maxRegionLabel;
}
else
{
seeds[p] = 0;
}
}
}
}
}
else
{
FindMinMax< npy_uint32 > minmax;
inspectMultiArray(srcMultiArrayRange(seeds), minmax);
maxRegionLabel = minmax.max;
}
res.reshapeIfEmpty(image.shape(), "watersheds(): Output array has wrong shape.");
ArrayOfRegionStatistics< SeedRgDirectValueFunctor< PixelType > > stats(maxRegionLabel);
if(neighborhood == 6)
{
seededRegionGrowing3D(srcMultiArrayRange(image), srcMultiArray(seeds), destMultiArray(res),
stats, srgType, NeighborCode3DSix(), max_cost);
}
else
{
seededRegionGrowing3D(srcMultiArrayRange(image), srcMultiArray(seeds), destMultiArray(res),
stats, srgType, NeighborCode3DTwentySix(), max_cost);
}
}
else if(method == "unionfind")
{
vigra_precondition(!haveSeeds,
"watersheds(): UnionFind does not support seed images.");
vigra_precondition(srgType == CompleteGrow,
"watersheds(): UnionFind only supports 'CompleteGrow' mode.");
res.reshapeIfEmpty(image.shape(), "watersheds(): Output array has wrong shape.");
if(neighborhood == 6)
{
maxRegionLabel = watersheds3DSix(srcMultiArrayRange(image), destMultiArray(res));
}
else
{
maxRegionLabel = watersheds3DTwentySix(srcMultiArrayRange(image), destMultiArray(res));
}
}
else
{
vigra_precondition(false, "watersheds(): Unknown watershed method requested.");
}
return python::make_tuple(res, maxRegionLabel);
}
VIGRA_PYTHON_MULTITYPE_FUNCTOR(pywatersheds3D, pythonWatersheds3D)
void defineSegmentation()
{
using namespace python;
docstring_options doc_options(true, true, false);
multidef("labelImage", pyLabelImage<npy_uint8, float>(),
(arg("image"),
arg("neighborhood") = 4,
arg("out")=python::object()),
"Find the connected components of a segmented image. Parameter 'neighborhood' specifies "
"the pixel neighborhood to be used and can be 4 (default) or 8.\n\n"
"For details see labelImage_ in the vigra C++ documentation.\n");
multidef("labelImageWithBackground", pyLabelImageWithBackground<npy_uint8, float>(),
(arg("image"),
arg("neighborhood") = 4,
arg("background_value") = 0,
arg("out")=python::object()),
"Find the connected components of a segmented image, excluding the "
"background from labeling, where the background is the set of all pixels with "
"the given 'background_value'. Parameter 'neighborhood' specifies "
"the pixel neighborhood to be used and can be 4 (default) or 8.\n\n"
"For details see labelImageWithBackground_ in the vigra C++ documentation.\n");
multidef("labelVolume", pyLabelVolume<npy_uint8, float>(),
(arg("volume"),
arg("neighborhood")=6,
arg("out")=python::object()),
"Find the connected components of a segmented volume. Parameter 'neighborhood' specifies "
"the pixel neighborhood to be used and can be 6 (default) or 26.\n"
"\n"
"For details see labelVolume_ in the vigra C++ documentation.\n");
multidef("labelVolumeWithBackground", pyLabelVolumeWithBackground<npy_uint8, float>(),
(arg("volume"),
arg("neighborhood")=6,
arg("background_value")=0,
arg("out")=python::object()),
"Find the connected components of a segmented volume, excluding the "
"background from labeling, where the background is the set of all pixels with "
"the given 'background_value'. Parameter 'neighborhood' specifies "
"the pixel neighborhood to be used and can be 6 (default) or 26.\n"
"\n"
"For details see labelVolumeWithBackground_ in the vigra C++ documentation.\n");
/******************************************************************************/
def("localMinima",
registerConverters(&pythonLocalMinima2D<float>),
(arg("image"),
arg("marker")=1.0,
arg("neighborhood") = 8,
arg("out")=python::object()),
"Find local minima in an image and mark them with the given 'marker'. Parameter "
"'neighborhood' specifies the pixel neighborhood to be used and can be "
"4 or 8 (default).\n\n"
"For details see localMinima_ in the vigra C++ documentation.\n");
def("extendedLocalMinima",
registerConverters(&pythonExtendedLocalMinima2D<float>),
(arg("image"),
arg("marker")=1.0,
arg("neighborhood") = 8,
arg("out")=python::object()),
"Find local minima and minimal plateaus in an image and mark them with "
"the given 'marker'. Parameter 'neighborhood' specifies the pixel "
"neighborhood to be used and can be 4 or 8 (default).\n\n"
"For details see extendedLocalMinima_ in the vigra C++ documentation.\n"
);
def("localMaxima",
registerConverters(&pythonLocalMaxima2D<float>),
(arg("image"),
arg("marker")=1.0,
arg("neighborhood") = 8,
arg("out")=python::object()),
"Find local maxima in an image and mark them with the given 'marker'. Parameter "
"'neighborhood' specifies the pixel neighborhood to be used and can be "
"4 or 8 (default).\n\n"
"For details see localMaxima_ in the vigra C++ documentation.\n");
def("extendedLocalMaxima",
registerConverters(&pythonExtendedLocalMaxima2D<float>),
(arg("image"),
arg("marker")=1.0,
arg("neighborhood") = 8,
arg("out")=python::object()),
"Find local maxima and maximal plateaus in an image and mark them with "
"the given 'marker'. Parameter 'neighborhood' specifies the pixel "
"neighborhood to be used and can be 4 or 8 (default).\n\n"
"For details see localMinima_ in the vigra C++ documentation.\n");
/*************************************************************************/
enum_<vigra::SRGType>("SRGType")
.value("CompleteGrow", vigra::CompleteGrow)
.value("KeepContours", vigra::KeepContours)
.value("StopAtThreshold", vigra::StopAtThreshold)
;
/* FIXME: int64 is unsupported by the C++ code (hard-coded int) */
multidef("watersheds", pywatersheds2D< npy_uint8, float >(),
(arg("image"),
arg("neighborhood") = 4,
arg("seeds")=python::object(),
arg("method")="RegionGrowing",
arg("terminate")=CompleteGrow,
arg("max_cost")=0.0,
arg("out")=python::object()),
"Compute the watersheds of a 2D image.\n"
"\n"
" watersheds(image, neighborhood=4, seeds = None, methods = 'RegionGrowing', \n"
" terminate=CompleteGrow, threshold=0, out = None) -> (labelimage, max_ragion_label)\n"
"\n"
"Parameters:\n\n"
" image:\n"
" the image or volume containing the boundary indicator values "
" (high values = high edgeness, dtype=numpy.uint8 or numpy.float32).\n"
" neighborhood:\n"
" the pixel neighborhood to be used. Feasible values depend on the "
" dimension and method:\n\n"
" 2-dimensional data:\n"
" 4 (default) or 8.\n"
" 3-dimensional data:\n"
" 6 (default) or 26\n\n"
" seeds:\n"
" a label image specifying region seeds, only supported by method 'RegionGrowing' "
" (with dtype=numpy.uint32).\n"
" method:\n"
" the algorithm to be used for watershed computation. Possible values:\n\n"
" 'RegionGrowing':\n"
" (default) use seededRegionGrowing_ or seededRegionGrowing3D_ respectively\n"
" 'UnionFind:\n"
" use watersheds_ or watersheds3D_ respectively\n\n"
" terminate:\n"
" when to stop growing. Possible values:\n\n"
" CompleteGrow:\n"
" (default) grow until all pixels are assigned to a region\n"
" KeepCountours:\n"
" keep a 1-pixel wide contour between all regions, only supported "
" by method 'RegionGrowing'\n"
" StopAtThreshold:\n"
" stop when the boundary indicator values exceed the threshold given by "
" parameter 'max_cost', only supported by method 'RegionGrowing'\n"
" KeepCountours | StopAtThreshold:\n"
" keep 1-pixel wide contour and stop at given 'max_cost', only "
" supported by method 'RegionGrowing'\n\n"
" max_cost:\n"
" terminate growing when boundary indicator exceeds this value (ignored when "
" 'terminate' is not StopAtThreshold or method is not 'RegionGrowing')\n"
" out:\n"
" the label image (with dtype=numpy.uint32) to be filled by the algorithm. "
" It will be allocated by the watershed function if not provided)\n\n"
"The function returns a Python tuple (labelImage, maxRegionLabel)\n\n"
);
multidef("watersheds", pywatersheds3D< npy_uint8, float >(),
(arg("volume"),
arg("neighborhood") = 6,
arg("seeds")=python::object(),
arg("method")="RegionGrowing",
arg("terminate")=CompleteGrow,
arg("max_cost")=0.0,
arg("out")=python::object()),
"Likewise, compute watersheds of a volume.\n");
}
void defineEdgedetection();
void defineInterestpoints();
} // namespace vigra
using namespace vigra;
using namespace boost::python;
BOOST_PYTHON_MODULE_INIT(analysis)
{
import_vigranumpy();
defineSegmentation();
defineEdgedetection();
defineInterestpoints();
}
| 38.140283 | 117 | 0.555154 | [
"object",
"shape"
] |
b4bc77de7c79ddf9cc09bd417a8d7d1b93798bf5 | 528 | hpp | C++ | console/State.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | 4 | 2019-10-17T20:26:09.000Z | 2019-11-14T12:01:57.000Z | console/State.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | console/State.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | #pragma once
#include "controller/Controllers.hpp"
#include <raylib.h>
enum class StateChange {
None,
Menu,
Starship,
Tetris,
Pong,
};
class State {
public:
State() = default;
State(const State&) = delete;
State& operator=(const State&) = delete;
State(State&&) = delete;
State& operator=(State&&) = delete;
virtual ~State() = default;
virtual void update(const std::vector<ControllerState>&) = 0;
virtual void draw() = 0;
virtual StateChange state_change() = 0;
};
| 18.206897 | 65 | 0.628788 | [
"vector"
] |
b4bd657850e559df05d0d43eb1cd7b8f51290dcf | 2,197 | cpp | C++ | seg_tree/abc185_f.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | seg_tree/abc185_f.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | seg_tree/abc185_f.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
// xorに関する区間更新・区間取得
/*
参考リンク
ABC 185 F - Range Xor Query
https://atcoder.jp/contests/abc185/tasks/abc185_f
*/
template <class Monoid>
class SegTree {
int n; // 葉の数
vector<Monoid> data; // データを格納するvector
Monoid def; // 初期値かつ単位元
function<Monoid(Monoid, Monoid)> operation; // 区間クエリで使う処理
function<Monoid(Monoid, Monoid)> update; // 点更新で使う処理
// 区間[a,b)の総和。ノードk=[l,r)に着目している。
Monoid _query(int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return def; // 交差しない
if (a <= l && r <= b)
return data[k]; // a,l,r,bの順で完全に含まれる
else {
Monoid c1 = _query(a, b, 2 * k + 1, l, (l + r) / 2); // 左の子
Monoid c2 = _query(a, b, 2 * k + 2, (l + r) / 2, r); // 右の子
return operation(c1, c2);
}
}
public:
// _n:必要サイズ, _def:初期値かつ単位元, _operation:クエリ関数,
// _update:更新関数
SegTree(size_t _n, Monoid _def, function<Monoid(Monoid, Monoid)> _operation,
function<Monoid(Monoid, Monoid)> _update)
: def(_def), operation(_operation), update(_update) {
n = 1;
while (n < _n) {
n *= 2;
}
data = vector<Monoid>(2 * n - 1, def);
}
// 場所i(0-indexed)の値をxで更新
void change(int i, Monoid x) {
i += n - 1;
data[i] = update(data[i], x);
while (i > 0) {
i = (i - 1) / 2;
data[i] = operation(data[i * 2 + 1], data[i * 2 + 2]);
}
}
// [a, b)の区間クエリを実行
Monoid query(int a, int b) { return _query(a, b, 0, 0, n); }
// 添字でアクセス
Monoid operator[](int i) { return data[i + n - 1]; }
};
int main() {
int n, q;
cin >> n >> q;
vector<int> a(n);
rep(i, n) cin >> a[i];
SegTree<int> st(
n, 0, [](int a, int b) { return a ^ b; }, [](int a, int b) { return b; });
rep(i, n) st.change(i, a[i]);
rep(i, q) {
int t, x, y;
cin >> t >> x >> y;
x--;
if (t == 1) {
int v = st.query(x, x + 1);
v ^= y;
st.change(x, v);
} else {
cout << st.query(x, y) << endl;
}
}
return 0;
} | 25.252874 | 80 | 0.496586 | [
"vector"
] |
b4be725371fc7ba7b5ffbc692e6c5f2f4a70a2ae | 13,454 | cpp | C++ | src/compiler.cpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 2 | 2018-03-19T20:19:01.000Z | 2018-10-22T23:41:12.000Z | src/compiler.cpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 1 | 2017-01-18T20:45:33.000Z | 2017-01-21T20:57:37.000Z | src/compiler.cpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | null | null | null | /// Copyright 2017 Lucas Saldyt
#include "compiler.hpp"
/**
* Demonstration of very high-level compiler usage
*/
int main(int argc, char* argv[])
{
using namespace compiler;
vector<string> args;
for (int i = 1; i < argc; i++)
{
args.push_back(argv[i]);
}
assert(args.size() > 3);
int verbosity = std::stoi(args[0]);
string from = args[1];
string to = args[2];
vector<string> files = slice(args, 3);
compileFiles(files, "input", from, "output", to, verbosity);
print("Compilation finished");
}
/**
* Collection of high level functions for compilation
*/
namespace compiler
{
/**
* Read in simple symbol conversions from a file
* i.e. append -> push_back
* @param filename File defining symbol conversions
* @return Dictionary defining symbol conversions
*/
unordered_map<string, string> readSymbolTable(string filename)
{
unordered_map<string, string> symbol_table;
for (auto line : readFile(filename))
{
auto terms = lex::seperate(line, {make_tuple(" ", false)});
assert(terms.size() == 3);
symbol_table[terms[0]] = terms[2];
}
return symbol_table;
}
/**
* High level function for creating a Grammar object from a set of grammar files
* @param language Language to load
* @return Grammar for parsing the given language
*/
Grammar loadGrammar(string language)
{
print("Loading grammar for " + language);
string directory = "languages/" + language + "/";
string lex_dir = directory + "lex/";
auto grammar = Grammar(directory);
print("Done loading grammar file");
return grammar;
}
/**
* High level function for loading a code generator for a language
* @param language Language for code generator to be loaded for
* @return Generator which can construct source code for the given language
*/
Generator loadGenerator(string language)
{
print("Loading constructors for " + language);
auto constructor_files = readFile("languages/" + language + "/constructors/core");
auto generator = Generator(constructor_files, "languages/" + language + "/constructors/");
print("Done");
return generator;
}
/**
* High level function for loading a code transformer for a language
* @param language Language for code generator to be loaded for
* @return Transformer which can transformer AST for the given language
*/
Transformer loadTransformer(string language, string prefix)
{
print("Loading transformers for " + language);
auto transformer_files = readFile("languages/" + language + "/" + prefix + "transformers/core");
auto transformer = Transformer(transformer_files, "languages/" + language + "/" + prefix + "transformers/");
print("Done");
return transformer;
}
/**
* High level function for transpilation
* Converts source files of one language to source files of another, copying them into a new directory
* @param filenames List of files to transpile
* @param input_dir Input directory containing files in input language
* @param input_lang String name of input langauge
* @param output_dir Output directory that will contain files in output language
* @param output_lang String name of output language
* @param verbosity Verbosity level of output
*/
void compileFiles(vector<string> filenames, string input_dir, string input_lang, string output_dir, string output_lang, int verbosity)
{
auto grammar = loadGrammar(input_lang);
auto generator = loadGenerator(output_lang);
auto lexmap = buildLexMap("languages/" + input_lang + "/lex/", grammar.keywords);
auto pre_transformer = loadTransformer(input_lang, "pre_");
auto post_transformer = loadTransformer(output_lang, "post_");
auto symbol_table = readSymbolTable("languages/symboltables/" + input_lang + output_lang);
OutputManager logger(verbosity);
for (auto& file : filenames)
{
try
{
compile(file, grammar, generator, lexmap, pre_transformer, post_transformer, symbol_table, input_dir, output_dir, logger);
}
catch(...)
{
logger.log("In file: " + file);
logger.log("In directory: " + input_dir);
throw;
}
}
}
/**
* Function for compilation of an individual file given a grammar, generator, symbol_table, input directory, and output directory
* @param filename File to be compiled
* @param grammar Grammar of input language
* @param generator Generator for output language
* @param symbol_table Dictionary of symbol conversions
* @param input_directory String of input directory
* @param output_directory String name of output directory
* @param logger OutputManager class for managing verbose output. Use instead of print() calls
*/
void compile(string filename, Grammar& grammar, Generator& generator, LexMap& lexmap,
Transformer& pre_transformer,
Transformer& post_transformer,
unordered_map<string, string>& symbol_table, string input_directory,
string output_directory, OutputManager logger)
{
logger.log("Reading file " + filename);
auto content = readFile (input_directory + "/" + filename);
logger.log("Lexing terms");
auto tokens = tokenPass (content, lexmap, symbol_table, logger);
logger.log("Creating symbols");
auto symbolic_tokens = symbolicPass (tokens, logger);
logger.log("Joining symbolic tokens");
auto joined_tokens = join (symbolic_tokens, lexmap.newline);
for(auto& jt : joined_tokens)
{
logger.log("Joined Token: " + jt.type + ", " + jt.sub_type + ", \"" + jt.text + "\" " + std::to_string(jt.line));
}
logger.log("Identifying tokens from grammar:");
auto identified_groups = grammar.identifyGroups(joined_tokens, logger);
logger.log("Initial AST:");
showAST(identified_groups, logger);
logger.log("Universal AST:");
pre_transformer(identified_groups);
showAST(identified_groups, logger);
logger.log("Specialized AST:");
post_transformer(identified_groups);
showAST(identified_groups, logger);
logger.log("Compiling identified groups");
auto files = compileGroups(identified_groups, filename, generator, logger);
logger.log("Initial file");
for (auto line : content)
{
logger.log(line);
}
for (auto kv : files)
{
logger.log("Generated " + kv.first + " file:");
auto body = get<0>(kv.second);
auto path = get<1>(kv.second);
for (auto line : body)
{
logger.log(line);
}
writeFile(body, output_directory + "/" + path);
}
}
/**
* Converts lines of source code to a list of tokens, provided a grammar
* @param content Lines of source
* @param grammar Grammar of input language
* @param symbol_table Dictionary of symbol conversions
* @return Vector of unsymbolized tokens (annotated terms)
*/
std::vector<Tokens> tokenPass(std::vector<std::string> content, LexMap& lexmap, unordered_map<string, string>& symbol_table, OutputManager logger)
{
int line_num = 0;
std::vector<Tokens> tokens;
string unseperated_content;
for (auto line : content)
{
unseperated_content += line + "\n";
}
bool in_multiline_string = false;
auto groups = lex::seperate(unseperated_content, {make_tuple(lexmap.multiline_comment_delimiter, true)}, {}, "");
for (auto group : groups)
{
if (group == lexmap.multiline_comment_delimiter)
{
in_multiline_string = !in_multiline_string;
}
else if (in_multiline_string)
{
tokens.push_back(Tokens(1, Token(vector<string>(1, group), "comment", "comment", line_num)));
// Count newlines in mulitline comment
size_t nPos = group.find("\n", 0);
while (nPos != string::npos)
{
line_num++;
nPos = group.find("\n", nPos+1);
}
line_num++;
}
else
{
auto lines = lex::seperate(group, {make_tuple("\n", false)}, {}, "");
for (auto it = lines.begin(); it != lines.end(); it++)
{
line_num++;
auto token_group = lexWith(*it, lexmap, lexmap.string_delimiters, lexmap.comment_delimiter);
for (auto& token : token_group)
{
token.line = line_num;
}
tokens.push_back(token_group);
}
}
}
for (auto& token_group : tokens)
{
for (auto& token : token_group)
{
for (auto& value : token.values)
{
logger.log("Token Value: " + value, 2);
if (contains(symbol_table, value))
{
value = symbol_table[value];
}
}
}
}
return tokens;
}
/**
* Converts a vector of non-symbolic tokens to symbolic ones
* @param tokens Non symbolized tokens
* @return 2D array of Symbolized tokens
*/
std::vector<vector<SymbolicToken>> symbolicPass(std::vector<Tokens> tokens, OutputManager logger)
{
std::vector<vector<SymbolicToken>> symbolic_tokens;
for (auto token_group : tokens)
{
symbolic_tokens.push_back(toSymbolic(generatorMap, token_group, logger));
}
return symbolic_tokens;
}
/**
* Converts a 2D matrix of tokens to a vector
* @param token_groups 2D matrix of tokens
* @param newline option to insert newlines between groups of tokens
* @return Vector of symbolic tokens
*/
vector<SymbolicToken> join(std::vector<vector<SymbolicToken>> token_groups, bool newline)
{
auto tokens = vector<SymbolicToken>();
for (auto token_group : token_groups)
{
for (auto t : token_group)
{
tokens.push_back(t);
}
if (newline)
{
tokens.push_back(SymbolicToken(make_shared<Symbol>(Newline("\n")), "newline", "newline", "\n"));
}
}
return tokens;
}
unordered_map<string, tuple<vector<string>, string>> compileGroups(IdentifiedGroups identified_groups,
string filename,
Generator &generator,
OutputManager logger)
{
unordered_map<string, tuple<vector<string>, string>> files;
for (auto identified_group : identified_groups)
{
logger.log("Compiling groups (Identified as " + get<0>(identified_group) + ")");
string gen_with = "none";
if (files.empty())
{
gen_with = filename;
}
unordered_set<string> names;
logger.log("Generating code for " + get<0>(identified_group));
auto a = getTime();
auto generated = generator(names, get<1>(identified_group), get<0>(identified_group), gen_with, 1, logger);
auto b = getTime();
logger.log("Generation step took " + std::to_string((double)(b - a) / 1000000.) + "s");
logger.log("Adding generated code to file content");
for (auto fileinfo : generated)
{
string type = get<0>(fileinfo);
string path = get<1>(fileinfo);
vector<string> body = get<2>(fileinfo);
if (contains(files, type))
{
logger.log("Adding to " + type + " file");
concat(get<0>(files[type]), body);
}
else
{
logger.log("Creating initial " + type + " file");
files[type] = make_tuple(body, path);
}
}
}
return files;
}
void showAST(const IdentifiedGroups& identified_groups, OutputManager logger)
{
for (const auto& identified_group : identified_groups)
{
auto ms_table = get<1>(identified_group);
for (auto kv : ms_table)
{
for (auto symbol : kv.second)
{
auto abstract = symbol->abstract();
logger.log(abstract);
}
}
}
}
}
| 37.476323 | 150 | 0.559908 | [
"object",
"vector"
] |
b4c155ed0e6345d7be1c437f026553010ecb1919 | 24,549 | cc | C++ | Modules/Image/src/ImageAttributes.cc | SVRTK/MIRTK | 6bbe1a76881ac2aaa1baed132be89cf5bdcbb92b | [
"Apache-2.0"
] | null | null | null | Modules/Image/src/ImageAttributes.cc | SVRTK/MIRTK | 6bbe1a76881ac2aaa1baed132be89cf5bdcbb92b | [
"Apache-2.0"
] | null | null | null | Modules/Image/src/ImageAttributes.cc | SVRTK/MIRTK | 6bbe1a76881ac2aaa1baed132be89cf5bdcbb92b | [
"Apache-2.0"
] | null | null | null | /*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/ImageAttributes.h"
#include "mirtk/Math.h"
#include "mirtk/Array.h"
#include "mirtk/Memory.h"
#include "mirtk/Stream.h"
#include "mirtk/Indent.h"
#include "mirtk/Vector.h"
#include "mirtk/Vector3.h"
#include "mirtk/Matrix.h"
#include "mirtk/Matrix3x3.h"
namespace mirtk {
// -----------------------------------------------------------------------------
ImageAttributes::ImageAttributes()
{
// Default image size
_x = 0;
_y = 0;
_z = 1;
_t = 1;
// Default voxel size
_dx = 1;
_dy = 1;
_dz = 1;
_dt = 1;
// Default origin
_xorigin = 0;
_yorigin = 0;
_zorigin = 0;
_torigin = 0;
// Default x-axis
_xaxis[0] = 1;
_xaxis[1] = 0;
_xaxis[2] = 0;
// Default y-axis
_yaxis[0] = 0;
_yaxis[1] = 1;
_yaxis[2] = 0;
// Default z-axis
_zaxis[0] = 0;
_zaxis[1] = 0;
_zaxis[2] = 1;
// Default affine transformation
_smat.Initialize(4, 4);
_smat.Ident();
_i2w = nullptr;
_w2i = nullptr;
}
// -----------------------------------------------------------------------------
ImageAttributes::ImageAttributes(int x, int y, double dx, double dy)
{
// Default image size
_x = x;
_y = y;
_z = 1;
_t = 1;
// Default voxel size
_dx = dx;
_dy = dy;
_dz = 1;
_dt = 1;
// Default origin
_xorigin = 0;
_yorigin = 0;
_zorigin = 0;
_torigin = 0;
// Default x-axis
_xaxis[0] = 1;
_xaxis[1] = 0;
_xaxis[2] = 0;
// Default y-axis
_yaxis[0] = 0;
_yaxis[1] = 1;
_yaxis[2] = 0;
// Default z-axis
_zaxis[0] = 0;
_zaxis[1] = 0;
_zaxis[2] = 1;
// Default affine transformation
_smat.Initialize(4, 4);
_smat.Ident();
_i2w = nullptr;
_w2i = nullptr;
}
// -----------------------------------------------------------------------------
ImageAttributes::ImageAttributes(int x, int y, int z, double dx, double dy, double dz)
{
_x = x;
_y = y;
_z = z;
_t = 1;
_dx = dx;
_dy = dy;
_dz = dz;
_dt = 1;
_xorigin = 0;
_yorigin = 0;
_zorigin = 0;
_torigin = 0;
_xaxis[0] = 1;
_xaxis[1] = 0;
_xaxis[2] = 0;
_yaxis[0] = 0;
_yaxis[1] = 1;
_yaxis[2] = 0;
_zaxis[0] = 0;
_zaxis[1] = 0;
_zaxis[2] = 1;
_smat.Initialize(4, 4);
_smat.Ident();
_i2w = nullptr;
_w2i = nullptr;
}
// -----------------------------------------------------------------------------
ImageAttributes::ImageAttributes(int x, int y, int z, int t, double dx, double dy, double dz, double dt)
{
_x = x;
_y = y;
_z = z;
_t = t;
_dx = dx;
_dy = dy;
_dz = dz;
_dt = dt;
_xorigin = 0;
_yorigin = 0;
_zorigin = 0;
_torigin = 0;
_xaxis[0] = 1;
_xaxis[1] = 0;
_xaxis[2] = 0;
_yaxis[0] = 0;
_yaxis[1] = 1;
_yaxis[2] = 0;
_zaxis[0] = 0;
_zaxis[1] = 0;
_zaxis[2] = 1;
_smat.Initialize(4, 4);
_smat.Ident();
_i2w = nullptr;
_w2i = nullptr;
}
// -----------------------------------------------------------------------------
ImageAttributes::ImageAttributes(const ImageAttributes &attr)
{
_x = attr._x;
_y = attr._y;
_z = attr._z;
_t = attr._t;
_dx = attr._dx;
_dy = attr._dy;
_dz = attr._dz;
_dt = attr._dt;
_xorigin = attr._xorigin;
_yorigin = attr._yorigin;
_zorigin = attr._zorigin;
_torigin = attr._torigin;
_xaxis[0] = attr._xaxis[0];
_xaxis[1] = attr._xaxis[1];
_xaxis[2] = attr._xaxis[2];
_yaxis[0] = attr._yaxis[0];
_yaxis[1] = attr._yaxis[1];
_yaxis[2] = attr._yaxis[2];
_zaxis[0] = attr._zaxis[0];
_zaxis[1] = attr._zaxis[1];
_zaxis[2] = attr._zaxis[2];
_smat = attr._smat;
// Do not copy pointers to pre-computed matrices as we don't know how
// long the objects pointed to by the other attributes will be valid
_i2w = nullptr;
_w2i = nullptr;
}
// -----------------------------------------------------------------------------
ImageAttributes &ImageAttributes::operator =(const ImageAttributes &attr)
{
if (this != &attr) {
_x = attr._x;
_y = attr._y;
_z = attr._z;
_t = attr._t;
_dx = attr._dx;
_dy = attr._dy;
_dz = attr._dz;
_dt = attr._dt;
_xorigin = attr._xorigin;
_yorigin = attr._yorigin;
_zorigin = attr._zorigin;
_torigin = attr._torigin;
_xaxis[0] = attr._xaxis[0];
_xaxis[1] = attr._xaxis[1];
_xaxis[2] = attr._xaxis[2];
_yaxis[0] = attr._yaxis[0];
_yaxis[1] = attr._yaxis[1];
_yaxis[2] = attr._yaxis[2];
_zaxis[0] = attr._zaxis[0];
_zaxis[1] = attr._zaxis[1];
_zaxis[2] = attr._zaxis[2];
_smat = attr._smat;
}
// Do not copy pointers to pre-computed matrices as we don't know how
// long the objects pointed to by the other attributes will be valid
//
// Reset pointers even when assigning to itself such that behavior is
// the same as when assigning from another instance
_i2w = nullptr;
_w2i = nullptr;
return *this;
}
// -----------------------------------------------------------------------------
void ImageAttributes::LatticeToWorld(double *x, double *y, double *z) const
{
int idx = 0;
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i, ++idx) {
x[idx] = i, y[idx] = j, z[idx] = k;
LatticeToWorld(x[idx], y[idx], z[idx]);
}
}
// -----------------------------------------------------------------------------
void ImageAttributes::LatticeToWorld(double *x, double *y, double *z, double *t) const
{
const int xyz = _x * _y * _z;
LatticeToWorld(x, y, z);
if (_dt == .0) {
double tl = LatticeToTime(0);
for (int idx = 0; idx < xyz; ++idx) {
(*t++) = tl;
}
} else {
int idx = xyz;
for (int l = 1; l < _t; ++l) {
memcpy(x + idx, x, xyz * sizeof(double));
memcpy(y + idx, y, xyz * sizeof(double));
memcpy(z + idx, z, xyz * sizeof(double));
idx += xyz;
}
for (int l = 0; l < _t; ++l) {
double tl = LatticeToTime(l);
for (int idx = 0; idx < xyz; ++idx) {
(*t++) = tl;
}
}
}
}
// -----------------------------------------------------------------------------
bool ImageAttributes::ContainsInSpace(const ImageAttributes &attr) const
{
double x = 0, y = 0, z = 0;
attr.LatticeToWorld(x, y, z);
this->WorldToLattice(x, y, z);
if (x <= -.5 || x >= _x - .5 || y <= -.5 || y >= _y - .5 || z <= -.5 || z >= _z - .5) return false;
x = attr._x - 1, y = attr._y - 1, z = attr._z - 1;
attr.LatticeToWorld(x, y, z);
this->WorldToLattice(x, y, z);
if (x <= -.5 || x >= _x - .5 || y <= -.5 || y >= _y - .5 || z <= -.5 || z >= _z - .5) return false;
return true;
}
// -----------------------------------------------------------------------------
bool ImageAttributes::EqualInSpace(const ImageAttributes &attr) const
{
constexpr double tol = 1e-3;
// Spatial dimensions
if (_x != attr._x || _y != attr._y || _z != attr._z) return false;
// Spatial resolution
if (!AreEqual(_dx, attr._dx, tol) || !AreEqual(_dy, attr._dy, tol) || !AreEqual(_dz, attr._dz, tol)) return false;
// Spatial orientation
for (int i = 0; i < 3; ++i) if (!AreEqual(_xaxis[i], attr._xaxis[i])) return false;
for (int i = 0; i < 3; ++i) if (!AreEqual(_yaxis[i], attr._yaxis[i])) return false;
for (int i = 0; i < 3; ++i) if (!AreEqual(_zaxis[i], attr._zaxis[i])) return false;
// Spatial origin
if (!AreEqual(_xorigin, attr._xorigin, tol) || !AreEqual(_yorigin, attr._yorigin, tol) || !AreEqual(_zorigin, attr._zorigin, tol)) return false;
// Spatial transformation
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
if (!AreEqual(_smat(r, c), attr._smat(r, c))) return false;
}
}
return true;
}
// -----------------------------------------------------------------------------
bool ImageAttributes::EqualInTime(const ImageAttributes &attr) const
{
constexpr double tol = 1e-3;
return (_t == attr._t) && AreEqual(_dt, attr._dt, tol) && AreEqual(_torigin, attr._torigin, tol);
}
// -----------------------------------------------------------------------------
double ImageAttributes::Area() const
{
return _x * _dx * _y * _dy;
}
// -----------------------------------------------------------------------------
double ImageAttributes::Volume() const
{
return _x * _dx * _y * _dy * _z * _dz;
}
// -----------------------------------------------------------------------------
double ImageAttributes::Space() const
{
if (static_cast<bool>(*this)) {
if (_dz > 0.) return Volume();
else return Area();
} else {
return 0.;
}
}
// -----------------------------------------------------------------------------
void ImageAttributes::Print(ostream &os, Indent indent) const
{
// Change output stream settings
const streamsize w = os.width (0);
const streamsize p = os.precision(5);
const ios::fmtflags f = os.flags ();
// Print attributes of lattice
bool sz = (_z > 1 && _dz);
bool st = (_t > 1 && _dt);
bool dz = (_dz && (_dz != 1.0 || _z > 1));
bool dt = (_dt && (_dt != 1.0 || _t > 1));
if (_t > 1 && !_dt) os << indent << "Channels: " << setw(10) << _t << "\n";
os << indent << "Size: " << setw(10) << _x
<< " x " << setw(10) << _y;
if (sz || st) os << " x " << setw(10) << _z;
if ( st) os << " x " << setw(10) << _t;
os << "\n";
os << indent << "Spacing: " << fixed << setw(10) << _dx
<< " x " << fixed << setw(10) << _dy;
if (dz || dt) os << " x " << fixed << setw(10) << _dz;
if ( dt) os << " x " << fixed << setw(10) << _dt;
os << "\n";
os << indent << "Origin: [" << fixed << setw(10) << _xorigin
<< " , " << fixed << setw(10) << _yorigin
<< " , " << fixed << setw(10) << _zorigin
<< " , " << fixed << setw(10) << _torigin
<< "]\n";
os << indent << "X-axis: [" << fixed << setw(10) << _xaxis[0]
<< " , " << fixed << setw(10) << _xaxis[1]
<< " , " << fixed << setw(10) << _xaxis[2]
<< "]\n";
os << indent << "Y-axis: [" << fixed << setw(10) << _yaxis[0]
<< " , " << fixed << setw(10) << _yaxis[1]
<< " , " << fixed << setw(10) << _yaxis[2]
<< "]\n";
os << indent << "Z-axis: [" << fixed << setw(10) << _zaxis[0]
<< " , " << fixed << setw(10) << _zaxis[1]
<< " , " << fixed << setw(10) << _zaxis[2]
<< "]\n";
if (!_smat.IsIdentity()) {
os << indent << "Affine";
_smat.Print(os, indent);
}
// Restore output stream settings
os.width (w);
os.precision(p);
os.flags (f);
}
// -----------------------------------------------------------------------------
void ImageAttributes::Print(Indent indent) const
{
Print(cout, indent);
}
// -----------------------------------------------------------------------------
Matrix ImageAttributes::GetLatticeToWorldMatrix() const
{
// Final mat = A * T * R * S * T0
Matrix mat(4, 4), tmp(4, 4);
// T0: Translate image origin
mat.Ident();
mat(0, 3) = - (_x - 1) / 2.0;
mat(1, 3) = - (_y - 1) / 2.0;
mat(2, 3) = - (_z - 1) / 2.0;
// S: Convert to world units
tmp.Ident();
tmp(0, 0) = _dx;
tmp(1, 1) = _dy;
tmp(2, 2) = _dz;
mat = tmp * mat;
// R: Orientation
tmp(0, 0) = _xaxis[0];
tmp(1, 0) = _xaxis[1];
tmp(2, 0) = _xaxis[2];
tmp(0, 1) = _yaxis[0];
tmp(1, 1) = _yaxis[1];
tmp(2, 1) = _yaxis[2];
tmp(0, 2) = _zaxis[0];
tmp(1, 2) = _zaxis[1];
tmp(2, 2) = _zaxis[2];
mat = tmp * mat;
// T: Translate world origin
tmp.Ident();
tmp(0, 3) = _xorigin;
tmp(1, 3) = _yorigin;
tmp(2, 3) = _zorigin;
mat = tmp * mat;
// A: Transform world coordinate by optional affine transformation
// to align (scanner) coordinates with another anatomy
mat = _smat * mat;
return mat;
}
// -----------------------------------------------------------------------------
Matrix ImageAttributes::GetWorldToLatticeMatrix() const
{
// Final mat = inv(A * T * R * S * T0)
// = inv(T0) * inv(S) * inv(R) * inv(T) * inv(A),
Matrix mat(4, 4), tmp(4, 4);
// inv(A): Transform world coordinate by optional inverse of the affine
// transformation which aligns (scanner) coordinates with another anatomy
if (_smat.IsIdentity()) {
mat.Ident(); // avoid numerical imprecisions caused by Matrix::Invert
} else {
mat = _smat.Inverse();
}
// inv(T): Translate world origin
tmp.Ident();
tmp(0, 3) = - _xorigin;
tmp(1, 3) = - _yorigin;
tmp(2, 3) = - _zorigin;
mat = tmp * mat;
// inv(R): Orientation
tmp(0, 0) = _xaxis[0];
tmp(0, 1) = _xaxis[1];
tmp(0, 2) = _xaxis[2];
tmp(0, 3) = .0;
tmp(1, 0) = _yaxis[0];
tmp(1, 1) = _yaxis[1];
tmp(1, 2) = _yaxis[2];
tmp(1, 3) = .0;
tmp(2, 0) = _zaxis[0];
tmp(2, 1) = _zaxis[1];
tmp(2, 2) = _zaxis[2];
tmp(2, 3) = .0;
mat = tmp * mat;
// inv(S): Convert to voxel units
tmp.Ident();
if (_dx) tmp(0, 0) = 1.0 / _dx;
if (_dy) tmp(1, 1) = 1.0 / _dy;
if (_dz) tmp(2, 2) = 1.0 / _dz;
mat = tmp * mat;
// inv(T0): Translate image origin
tmp(0, 0) = tmp(1, 1) = tmp(2, 2) = 1.0;
tmp(0, 3) = (_x - 1) / 2.0;
tmp(1, 3) = (_y - 1) / 2.0;
tmp(2, 3) = (_z - 1) / 2.0;
mat = tmp * mat;
return mat;
}
// -----------------------------------------------------------------------------
void ImageAttributes::PutAffineMatrix(const Matrix &m, bool apply)
{
if (m.IsIdentity()) {
_smat.Ident();
} else if (apply) {
// Lattice to world matrix is: A * T * R * S * T0
const Matrix B = GetLatticeToWorldMatrix();
// T0: Translate image origin
Matrix T0(4, 4);
T0.Ident();
T0(0, 3) = - (_x - 1) / 2.;
T0(1, 3) = - (_y - 1) / 2.;
T0(2, 3) = - (_z - 1) / 2.;
// Get new lattice to world matrix, excluding T0
Matrix C = m * B * T0.Inverse();
// Decompose C into T * R * S * K components
// (K: shear, S: scale, R: rotation, T: translation)
double tx, ty, tz, rx, ry, rz, sx, sy, sz, sxy, sxz, syz;
MatrixToAffineParameters(C, tx, ty, tz, rx, ry, rz, sx, sy, sz, sxy, sxz, syz);
// Remove shearing part
const Matrix K = AffineParametersToMatrix(0., 0., 0., 0., 0., 0., 1., 1., 1, sxy, sxz, syz);
const bool has_shearing = !K.IsIdentity();
if (has_shearing) {
C = C * K.Inverse();
}
// Decompose again, this time without shearing
MatrixToAffineParameters(C, tx, ty, tz, rx, ry, rz, sx, sy, sz, sxy, sxz, syz);
// Voxel size must be positive
Matrix flip(4, 4);
flip.Ident();
if (sx < 0.) {
flip(0, 0) = -1.;
sx = -sx;
}
if (sy < 0.) {
flip(1, 1) = -1.;
sy = -sy;
}
if (sz < 0.) {
flip(2, 2) = -1.;
sz = -sz;
}
// Set new lattice attributes
_dx = sx;
_dy = sy;
_dz = sz;
// R: Orientation
const Matrix R = RigidParametersToMatrix(0., 0., 0., rx, ry, rz) * flip;
_xaxis[0] = R(0, 0);
_xaxis[1] = R(1, 0);
_xaxis[2] = R(2, 0);
_yaxis[0] = R(0, 1);
_yaxis[1] = R(1, 1);
_yaxis[2] = R(2, 1);
_zaxis[0] = R(0, 2);
_zaxis[1] = R(1, 2);
_zaxis[2] = R(2, 2);
// T: Translate world origin
_xorigin = tx;
_yorigin = ty;
_zorigin = tz;
// Set remaining difference due to shearing as post-image to world mapping
if (has_shearing) {
_smat = C * K * T0 * GetWorldToLatticeMatrix();
}
} else {
_smat = m;
}
}
// =============================================================================
// Image domain helpers
// =============================================================================
// -----------------------------------------------------------------------------
/// Adjust size of output domain if necessary such that all corners of the
/// input image domain are within the bounds of the output image domain
///
/// \param[in] in Image grid that should fit into \p out domain.
/// \param[in,out] out Image grid which should fully contain \p in without
/// changing its orientation nor voxel size.
void AdjustFieldOfView(const ImageAttributes &in, ImageAttributes &out)
{
const Matrix i2w = in .GetImageToWorldMatrix();
Matrix w2i = out.GetWorldToImageMatrix();
const int di = (in._x > 1 ? in._x - 1 : 1);
const int dj = (in._y > 1 ? in._y - 1 : 1);
const int dk = (in._z > 1 ? in._z - 1 : 1);
for (int k1 = 0; k1 < in._z; k1 += dk)
for (int j1 = 0; j1 < in._y; j1 += dj)
for (int i1 = 0; i1 < in._x; i1 += di) {
// Convert corner voxel indices of input domain to world coordinates
double x = i2w(0, 0) * i1 + i2w(0, 1) * j1 + i2w(0, 2) * k1 + i2w(0, 3);
double y = i2w(1, 0) * i1 + i2w(1, 1) * j1 + i2w(1, 2) * k1 + i2w(1, 3);
double z = i2w(2, 0) * i1 + i2w(2, 1) * j1 + i2w(2, 2) * k1 + i2w(2, 3);
// Convert world coordinates to voxel index w.r.t output domain
double i2 = w2i(0, 0) * x + w2i(0, 1) * y + w2i(0, 2) * z + w2i(0, 3);
double j2 = w2i(1, 0) * x + w2i(1, 1) * y + w2i(1, 2) * z + w2i(1, 3);
double k2 = w2i(2, 0) * x + w2i(2, 1) * y + w2i(2, 2) * z + w2i(2, 3);
// If point is outside the output domain...
if (i2 < 0 || i2 > out._x-1 || j2 < 0 || j2 > out._y-1 || k2 < 0 || k2 > out._z-1) {
// Increase output domain by difference along the axes directions
if (i2 < 0) {
int dv = iceil(abs(i2));
out._x += dv;
out._xorigin -= out._xaxis[0] * out._dx * dv / 2.0;
out._yorigin -= out._xaxis[1] * out._dx * dv / 2.0;
out._zorigin -= out._xaxis[2] * out._dx * dv / 2.0;
} else if (i2 > out._x - 1) {
int dv = iceil(i2 - out._x + 1);
out._x += dv;
out._xorigin += out._xaxis[0] * out._dx * dv / 2.0;
out._yorigin += out._xaxis[1] * out._dx * dv / 2.0;
out._zorigin += out._xaxis[2] * out._dx * dv / 2.0;
}
if (j2 < 0) {
int dv = iceil(abs(j2));
out._y += dv;
out._xorigin -= out._yaxis[0] * out._dy * dv / 2.0;
out._yorigin -= out._yaxis[1] * out._dy * dv / 2.0;
out._zorigin -= out._yaxis[2] * out._dy * dv / 2.0;
} else if (j2 > out._y - 1) {
int dv = iceil(j2 - out._y + 1);
out._y += dv;
out._xorigin += out._yaxis[0] * out._dy * dv / 2.0;
out._yorigin += out._yaxis[1] * out._dy * dv / 2.0;
out._zorigin += out._yaxis[2] * out._dy * dv / 2.0;
}
if (k2 < 0) {
int dv = iceil(abs(k2));
out._z += dv;
out._xorigin -= out._zaxis[0] * out._dz * dv / 2.0;
out._yorigin -= out._zaxis[1] * out._dz * dv / 2.0;
out._zorigin -= out._zaxis[2] * out._dz * dv / 2.0;
} else if (k2 > out._z - 1) {
int dv = iceil(k2 - out._z + 1);
out._z += dv;
out._xorigin += out._zaxis[0] * out._dz * dv / 2.0;
out._yorigin += out._zaxis[1] * out._dz * dv / 2.0;
out._zorigin += out._zaxis[2] * out._dz * dv / 2.0;
}
// Update transformation matrix
w2i = out.GetWorldToImageMatrix();
}
}
}
// -----------------------------------------------------------------------------
void GetCorners(const ImageAttributes &attr, double *corners[3])
{
int idx = 0;
for (int k = 0; k <= 1; ++k)
for (int j = 0; j <= 1; ++j)
for (int i = 0; i <= 1; ++i, ++idx) {
corners[idx][0] = i * (attr._x - 1);
corners[idx][1] = j * (attr._y - 1);
corners[idx][2] = k * (attr._z - 1);
attr.LatticeToWorld(corners[idx][0], corners[idx][1], corners[idx][2]);
}
}
// -----------------------------------------------------------------------------
void GetCorners(const ImageAttributes &attr, double corners[][3])
{
int idx = 0;
for (int k = 0; k <= 1; ++k)
for (int j = 0; j <= 1; ++j)
for (int i = 0; i <= 1; ++i, ++idx) {
corners[idx][0] = i * (attr._x - 1);
corners[idx][1] = j * (attr._y - 1);
corners[idx][2] = k * (attr._z - 1);
attr.LatticeToWorld(corners[idx][0], corners[idx][1], corners[idx][2]);
}
}
// -----------------------------------------------------------------------------
ImageAttributes OrthogonalFieldOfView(const ImageAttributes &attr)
{
ImageAttributes out = attr;
// Apply any additional affine transformation to the attributes of the image domain
if (!attr._smat.IsIdentity()) {
// Reset affine transformation of output attributes
out._smat.Ident();
// Get corners of transformed image lattice
double corners[8][3];
GetCorners(attr, corners);
// Set output origin
out._xorigin = out._yorigin = out._zorigin = .0;
for (int i = 0; i < 8; ++i) {
out._xorigin += corners[i][0];
out._yorigin += corners[i][1];
out._zorigin += corners[i][2];
}
out._xorigin /= 8, out._yorigin /= 8, out._zorigin /= 8;
// Set output orientation
Matrix3x3 covar(.0);
for (int i = 0; i < 8; ++i) {
corners[i][0] -= out._xorigin;
corners[i][1] -= out._yorigin;
corners[i][2] -= out._zorigin;
for (int r = 0; r < 3; ++r)
for (int c = 0; c < 3; ++c) {
covar[r][c] += corners[i][r] * corners[i][c];
}
}
double eigen[3];
Vector3 axis [3];
covar.EigenSolveSymmetric(eigen, axis);
Vector3::GenerateOrthonormalBasis(axis[0], axis[1], axis[2]);
for (int d = 0; d < 3; ++d) {
out._xaxis[d] = axis[0][d];
out._yaxis[d] = axis[1][d];
out._zaxis[d] = axis[2][d];
}
// Set output size
out._x = out._y = out._z = 1;
AdjustFieldOfView(attr, out);
}
return out;
}
// -----------------------------------------------------------------------------
ImageAttributes OverallFieldOfView(const Array<ImageAttributes> &attr)
{
ImageAttributes out;
const int N = static_cast<int>(attr.size());
if (N == 0) return out;
if (N == 1) return attr[0];
// Set output resolution
out._dx = out._dy = out._dz = .0;
for (int n = 0; n < N; ++n) {
out._dx += attr[n]._dx;
out._dy += attr[n]._dy;
out._dz += attr[n]._dz;
}
out._dx /= N, out._dy /= N, out._dz /= N;
// Set output origin
out._xorigin = out._yorigin = out._zorigin = .0;
for (int n = 0; n < N; ++n) {
out._xorigin += attr[n]._xorigin;
out._yorigin += attr[n]._yorigin;
out._zorigin += attr[n]._zorigin;
}
out._xorigin /= N, out._yorigin /= N, out._zorigin /= N;
// Set output orientation
bool have_same_orientation = true;
const Matrix R = attr[0].GetLatticeToWorldOrientation();
for (int n = 1; n < N; ++n) {
if (attr[n].GetLatticeToWorldOrientation() != R) {
have_same_orientation = false;
break;
}
}
if (have_same_orientation) {
for (int d = 0; d < 3; ++d) {
out._xaxis[d] = attr[0]._xaxis[d];
out._yaxis[d] = attr[0]._yaxis[d];
out._zaxis[d] = attr[0]._zaxis[d];
}
} else {
const int ncorners = 8 * N;
double **corners = Allocate<double>(3, ncorners);
for (int n = 0; n < N; ++n) {
GetCorners(attr[n], corners + 8 * n);
}
Matrix3x3 covar(.0);
for (int i = 0; i < ncorners; ++i) {
corners[i][0] -= out._xorigin;
corners[i][1] -= out._yorigin;
corners[i][2] -= out._zorigin;
for (int r = 0; r < 3; ++r)
for (int c = 0; c < 3; ++c) {
covar[r][c] += corners[i][r] * corners[i][c];
}
}
Deallocate(corners);
double eigen[3];
Vector3 axis [3];
covar.EigenSolveSymmetric(eigen, axis);
Vector3::GenerateOrthonormalBasis(axis[0], axis[1], axis[2]);
for (int d = 0; d < 3; ++d) {
out._xaxis[d] = axis[0][d];
out._yaxis[d] = axis[1][d];
out._zaxis[d] = axis[2][d];
}
}
// Set output size
out._x = out._y = out._z = 1;
for (int n = 0; n < N; ++n) {
AdjustFieldOfView(attr[n], out);
}
return out;
}
} // namespace mirtk
| 28.779601 | 146 | 0.494888 | [
"vector",
"transform"
] |
b4c1773d3f2f24530a20e432e7137771b7f8bd2a | 23,775 | cc | C++ | gearbox/job/JobManager.cc | coryb/gearbox | 88027f2f101c2d1fab16093928963052b9d3294d | [
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | 3 | 2015-06-26T15:37:40.000Z | 2016-05-22T07:42:39.000Z | gearbox/job/JobManager.cc | coryb/gearbox | 88027f2f101c2d1fab16093928963052b9d3294d | [
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null | gearbox/job/JobManager.cc | coryb/gearbox | 88027f2f101c2d1fab16093928963052b9d3294d | [
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012, Yahoo! Inc. All rights reserved.
// Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
#include "config.h"
#include <gearbox/job/JobManager.h>
#include <gearbox/core/logger.h>
#include <gearbox/core/Errors.h>
#include <gearbox/job/GearmanJobImpl.h>
#include <gearbox/job/RestJobImpl.h>
#include <gearbox/core/util.h> // uuid_b32c urand
#include <unistd.h> // usleep
#include <glob.h>
#include <stdexcept>
#include <queue>
#include <gearbox/core/JsonSchema.h>
#include <sys/stat.h> // stat
#include <limits>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem/operations.hpp>
namespace bfs=boost::filesystem;
namespace Gearbox {
typedef std::map< std::string, boost::shared_ptr<JsonSchema> > SchemaMap;
static SchemaMap schemas;
static JsonSchema * getSchema(const std::string & schemaName, const ConfigFile & cfg) {
static std::string schemadir = cfg.get_string_default("schemadir", DATADIR "/gearbox/schemas");
std::string schema = schemadir + "/" + schemaName + ".js";
if( schemas.find(schema) == schemas.end() ) {
struct stat buf;
if( stat(schema.c_str(), &buf) == 0 ) {
_TRACE("Using Schema " << schema);
schemas.insert( SchemaMap::value_type(schema, boost::shared_ptr<JsonSchema>(new JsonSchema())) );
schemas[schema]->parseFile( schema );
}
else {
_DEBUG("Schema " << schema << " not found, using NULL schema");
schemas.insert( SchemaMap::value_type(schema, boost::shared_ptr<JsonSchema>()) );
}
}
return schemas[schema].get();
}
JsonSchema * JobManager::getSchema(const JobImpl * ji, const ConfigFile & cfg ) {
std::string schema = ji->operation()
+ "-" + ji->component()
+ "-" + ji->resource_type()
+ "-" + ji->api_version();
JsonSchema * s = Gearbox::getSchema(schema, cfg);
if( !s ) {
schema = ji->operation()
+ "-global"
+ "-" + ji->resource_type()
+ "-" + ji->api_version();
s = Gearbox::getSchema(schema, cfg);
}
if( !s ) {
int needed = cfg.get_int_default("require_schemas", -1);
bool fail = false;
// if not explicitly enabled/disabled in the worker
// config file then check the global static setting
if( needed == -1 ) {
if( JobManager::require_schemas ) {
fail = true;
}
}
if( needed == 1 ) {
fail = true;
}
if( fail ) {
gbTHROW( std::runtime_error("Required schema for job " + ji->name() + " not found!") );
}
}
return s;
}
bool JobManager::require_schemas(false);
struct JobManager::Private {
ConfigFile cfg;
std::string parent_uri;
std::string base_uri;
static std::map<std::string, int> runnable_jobs;
Private(const Private & copy)
: cfg(copy.cfg),
parent_uri(copy.parent_uri),
base_uri(copy.base_uri) {}
Private & operator=(const Private & copy) {
this->cfg = copy.cfg;
this->parent_uri = copy.parent_uri;
this->base_uri = copy.base_uri;
return *this;
}
Private(const ConfigFile & c) : cfg(c) {
if( runnable_jobs.empty() ) {
std::string job_file = cfg.get_string("handlers_file" );
if ( ! job_file.empty() ) {
_DEBUG( "Enabling jobs from file '" << job_file << "'..." );
Json hcfg;
hcfg.parseFile( job_file );
for ( int i=0; i < hcfg["handlers"].length(); i++ ) {
std::string job = hcfg["handlers"][i].as<std::string>();
_TRACE( "-> " << job );
this->runnable_jobs[job] = 1;
}
}
std::string confdir = cfg.get_string_default("gearbox", "conf", SYSCONFDIR "/gearbox");
glob_t globbuf;
glob( std::string(confdir + "/*handlers[._]d").c_str(), 0, NULL, &globbuf);
std::vector<std::string> job_dirs;
for( unsigned int i=0; i < globbuf.gl_pathc; i++ ) {
if( bfs::is_directory(bfs::path(globbuf.gl_pathv[i])) ) {
job_dirs.push_back( globbuf.gl_pathv[i] );
}
}
globfree(&globbuf);
for( unsigned int i=0; i < job_dirs.size(); ++i ) {
_DEBUG( "Enabling jobs from dir '" << job_dirs[i] << "'..." );
bfs::directory_iterator end;
for ( bfs::directory_iterator itr( job_dirs[i] );
itr != end;
++itr ) {
std::string job = itr->path().filename().string();
size_t s = job.find( "do_", 0 );
if ( s < std::string::npos ) {
s = job.find("_", s);
if( s < std::string::npos ) {
_TRACE( "-> " << job );
this->runnable_jobs[job] = 1;
}
else {
_DEBUG( "Ignoring '" << job << "' (does not start with do_)" );
}
}
else {
_DEBUG( "Ignoring '" << job << "' (bad prefix)" );
}
}
}
}
}
};
std::map<std::string, int> JobManager::Private::runnable_jobs;
JobManager::JobManager(const ConfigFile & cfg) : impl( new Private(cfg) ) {}
JobManager::JobManager(const JobImpl * job) : impl( new Private( job->cfg() ) ) {
this->base_uri( job->base_uri() );
this->parent_uri( job->parent_uri() );
}
JobManager::JobManager(const JobManager & copy) : impl(new Private(*copy.impl)) {}
JobManager & JobManager::operator=(const JobManager & copy ) {
if( this == © ) return *this;
*(this->impl) = *(copy.impl);
return *this;
}
JobManager::~JobManager() {
if( impl ) delete impl;
}
void
JobManager::parent_uri( const std::string & parent_uri_uri ) {
impl->parent_uri = parent_uri_uri;
}
void
JobManager::base_uri( const std::string & base_uri ) {
impl->base_uri = base_uri;
}
void
JobManager::cfg( const ConfigFile & c ) {
impl->cfg = c;
}
bool JobManager::known_job_name( const std::string & name ) const {
if ( impl->cfg.get_int_default( "allow_unknown_jobs", 0 ) ) {
return true;
}
return impl->runnable_jobs[name];
}
JobPtr
JobManager::job(const std::string & job_name) const {
if ( ! this->known_job_name(job_name) ) {
gbTHROW( std::invalid_argument("No such job '" + job_name + "' enabled in config.") );
}
std::auto_ptr<JobImpl> ji(new GearmanJobImpl(impl->cfg));
ji->base_uri( impl->base_uri );
ji->parent_uri( impl->parent_uri );
ji->name(job_name);
return JobPtr( new Job( ji.release() ) );
}
JobPtr
JobManager::job(HttpClient::method_t method, const Uri & job_uri) const {
std::auto_ptr<JobImpl> ji(new RestJobImpl(impl->cfg));
ji->base_uri( impl->base_uri );
ji->parent_uri( impl->parent_uri );
ji->method(method);
ji->name(job_uri.canonical());
return JobPtr( new Job(ji.release()) );
}
JobPtr
JobManager::job(const std::string & job_name, const std::string & envelope) const {
Json job_envelope;
job_envelope.setSchema( Gearbox::getSchema("job-envelope", impl->cfg) );
job_envelope.parse(envelope);
return this->job(job_name, job_envelope);
}
JobPtr
JobManager::job(const std::string & job_name, const Json & job_envelope ) const {
if ( ! this->known_job_name(job_name) ) {
_WARN("No such job '" + job_name + "' enabled in config.");
}
std::auto_ptr<JobImpl> ji(new GearmanJobImpl(impl->cfg));
ji->name(job_name);
if ( job_envelope.hasKey("job_type") ) {
std::string type = job_envelope["job_type"].as<std::string>();
if( type == "sync" ) {
ji->type(Job::JOB_SYNC);
}
else if ( type == "async" ) {
ji->type(Job::JOB_ASYNC);
}
else {
gbTHROW( std::invalid_argument(
"job envelope does not contain a valid job_type"
) );
}
}
// this must be done before status and base_uri are parsed
// so that they dont taint the currently running job manager
// which should have the base_uri/parent_uri set by the "current"
// jobs, not the on-event jobs
if( job_envelope.hasKey("on") ) {
const Json::Object & obj = job_envelope["on"].as<Json::Object>();
Json::Object::const_iterator it = obj.begin();
Json::Object::const_iterator end = obj.end();
for( ; it != end; ++it ) {
JobPtr j = this->job(
it->second->get("name").as<std::string>(),
it->second->get("envelope")
);
ji->on( Job::str2event(it->first), *j );
}
}
if ( job_envelope.hasKey("version") )
ji->api_version( job_envelope["version"].as<std::string>() );
if ( job_envelope.hasKey("operation") )
ji->operation( job_envelope["operation"].as<std::string>() );
if ( job_envelope.hasKey("component") )
ji->component( job_envelope["component"].as<std::string>() );
if ( job_envelope.hasKey("resource") ) {
if ( job_envelope["resource"].hasKey("type") )
ji->resource_type( job_envelope["resource"]["type"].as<std::string>() );
if ( job_envelope["resource"].hasKey("name") )
ji->resource_name( job_envelope["resource"]["name"].as<std::string>() );
}
if( job_envelope.hasKey("parent_uri") )
ji->parent_uri( job_envelope["parent_uri"].as<std::string>() );
if( job_envelope.hasKey("base_uri") ) {
ji->base_uri( job_envelope["base_uri"].as<std::string>() );
impl->base_uri = job_envelope["base_uri"].as<std::string>();
}
if( job_envelope.hasKey("status") ) {
ji->status( job_envelope["status"].as<std::string>() );
}
// this throws when no schema available and requireSchema is set
this->getSchema(ji.get(), impl->cfg);
if( job_envelope.hasKey("content") ) {
ji->content( job_envelope["content"].as<std::string>() );
}
if( job_envelope.hasKey("headers") ) {
const Json::Object & obj = job_envelope["headers"].as<Json::Object>();
Json::Object::const_iterator it = obj.begin();
for( ; it != obj.end(); ++it ) {
// if this was a remote http call then
// y-staus-parent-uri header will be set
if( it->first == "y-status-parent-uri" ) {
ji->parent_uri( it->second->as<std::string>() );
}
else {
ji->add_header(it->first, it->second->as<std::string>());
}
}
}
if( job_envelope.hasKey("matrix_arguments") ) {
const Json::Object & obj = job_envelope["matrix_arguments"].as<Json::Object>();
Json::Object::const_iterator it = obj.begin();
for( ; it != obj.end(); ++it ) {
ji->add_matrix_argument(it->first, it->second->as<std::string>());
}
}
if( job_envelope.hasKey("environ") ) {
const Json::Object & obj = job_envelope["environ"].as<Json::Object>();
Json::Object::const_iterator it = obj.begin();
for( ; it != obj.end(); ++it ) {
ji->add_environ(it->first, it->second->as<std::string>());
}
}
if( job_envelope.hasKey("query_params") ) {
const Json::Object & obj = job_envelope["query_params"].as<Json::Object>();
Json::Object::const_iterator it = obj.begin();
for( ; it != obj.end(); ++it ) {
ji->add_query_param(it->first, it->second->as<std::string>());
}
}
if( job_envelope.hasKey("arguments") ) {
const Json::Array & arr = job_envelope["arguments"].as<Json::Array>();
Json::Array::const_iterator it = arr.begin();
for( ; it != arr.end(); ++it ) {
ji->add_argument((*it)->as<std::string>());
}
}
if( job_envelope.hasKey("event_status") ) {
StatusManager sm(impl->cfg);
ji->event_status( *(sm.fetch(job_envelope["event_status"])) );
}
return JobPtr( new Job(ji.release()) );
}
void
JobManager::delay(const Job & job, int seconds ) const {
_DEBUG("delaying job " << job.name() << " for " << seconds << " seconds.");
JobPtr dj = this->job("do_put_delay_job_v1");
dj->type(Job::JOB_SYNC);
Json delay;
time_t when = time(NULL) + seconds;
delay["name"] = job.name();
delay["envelope"].parse(job.serialize());
delay["time"] = when;
if( ! job.status().empty() ) {
StatusManager sm(impl->cfg);
StatusPtr s = sm.fetch(job.status());
s->ytime( when );
delay["status_name"] = s->name();
}
dj->content(delay.serialize());
while( true ) {
try {
JobResponse resp = dj->run();
if( resp.status()->has_completed() && !resp.status()->is_success() ) {
_WARN("Failed to put delay job " << dj->name() << ": " << resp.status()->messages().back());
sleep(1);
continue;
}
break;
}
catch(const std::exception & err) {
_WARN("Failed to run delay job: " << err.what());
sleep(1);
}
}
}
void
JobManager::retry( const Job & job, int max_delay, int max_jitter ) {
// keep track of how many times this job has been retried
int retry = 1;
if( ! job.status().empty() ) {
StatusManager sm(impl->cfg);
StatusPtr s = sm.fetch(job.status());
retry = s->failures() + 1;
s->failures( retry );
}
_DEBUG("retrying job " << job.name() << " for the " << retry << " attempt");
// fib(35) = 9220695 seconds =~ 106 days
// that's excessive and we want to avoid an overflow
if ( max_delay > 9220695 ) {
_WARN("maximum max_delay is 9220695 seconds (which is fib(35))");
max_delay = 9220695;
}
int delay = max_delay;
// formula for the nth fibonicci number
float phi = 1.618;
if ( retry < 35 )
delay = (int)(ceil( ( pow( phi, retry ) - pow( 1 - phi, retry ) ) / sqrt( 5 ) ) );
if ( delay > max_delay )
delay = max_delay;
if ( delay > max_jitter )
delay += (int) (max_jitter * (urand() / (std::numeric_limits<uint32_t>::max() + 1.0)));
this->delay( job, delay );
}
std::string
JobManager::gen_id(const std::string & prefix) {
std::string id = prefix + "-";
std::string uuid;
uuid_b32c( uuid, false );
id += uuid;
return id;
}
JobQueue
JobManager::job_queue( const Json & job_config ) const {
_TRACE("Agent configuration:" << job_config.serialize() );
// define graph types
typedef std::vector<JobPtr> Nodes;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS> Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
typedef std::list<Vertex> Order;
JobQueue jq;
// parse the JSON agent configuration into a set of nodes
if ( job_config.empty() ) return jq;
Nodes nodes;
Json::Object & sa = job_config.as<Json::Object>();
Json::Object::iterator it = sa.begin();
for (; it != sa.end(); ++it ) {
Job::JobType type = Job::JOB_ASYNC;
Json & value = *(it->second);
if( value.hasKey("type") ) {
if( value["type"].as<std::string>() == "SYNC" ) {
type = Job::JOB_SYNC;
}
}
JobPtr j;
if( value.hasKey("method") ) {
std::string mval = value["method"].as<std::string>();
HttpClient::method_t method =
mval == "PUT" ? HttpClient::METHOD_PUT :
mval == "POST" ? HttpClient::METHOD_POST :
mval == "DELETE" ? HttpClient::METHOD_DELETE :
HttpClient::METHOD_GET;
j = this->job(method, it->first);
j->type(Job::JOB_UNKNOWN);
}
else {
j = this->job(it->first);
j->type(type);
}
j->impl->base_uri( impl->base_uri );
j->impl->parent_uri( impl->parent_uri );
// 0 timeout means we shouldn't timeout
int timeout = value.hasKey("timeout") ? value["timeout"].as<int>() : 0;
j->timeout(timeout);
nodes.push_back(j);
}
// allocate a graph of N nodes.
Graph graph( nodes.size() );
int i;
for ( i=0; i<=(int)nodes.size()-1; i++ ) {
std::string node = nodes.at(i)->name();
if ( !sa[node]->hasKey("require") ) continue;
for ( int j=0; j<=(*sa[node])["require"].length()-1; j++ ) {
std::string req = (*sa[node])["require"][j].as<std::string>();
int k = 0;
bool found = false;
Nodes::iterator it = nodes.begin();
for( ; it != nodes.end(); it++ ) {
if ( req == (*it)->name() ) { found=true; break; }
k++;
}
if ( !found ) {
gbTHROW( ERR_INTERNAL_SERVER_ERROR(
"Agent: '" + node + "' has undefined dependency '" +
req + "'" ) );
}
else if ( i == k ) {
gbTHROW( ERR_INTERNAL_SERVER_ERROR(
"Agent: '" + node + "' defines a cyclic dependency!" ) );
}
boost::add_edge(k, i, graph);
}
}
// topologically sort the graph, providing dependency ordering -- will throw "not a dag"
// if cycles are discovered.
Order order;
try {
boost::topological_sort(graph, std::front_inserter(order));
}
catch ( std::exception & e ) {
gbTHROW( ERR_INTERNAL_SERVER_ERROR( "Cycle detected in configuration: " + std::string(e.what()) ) );
}
// for nodes that have dependencies (in_degree() > 0) iterate through the edges and count them,
// this provides grouping of nodes which are orthogonal to one another and can run in parallel
std::vector<int> edge_count( nodes.size(), 0 );
std::map<int, std::vector<JobPtr> > group;
for (Order::iterator it = order.begin(); it != order.end(); ++it ) {
if ( ! in_degree( *it, graph ) ) {
group[0].push_back( nodes.at( *it ) );
_TRACE("-> " << *it << " - " << edge_count[*it] << " - " << nodes.at(*it)->name() );
}
else {
Graph::in_edge_iterator j, j_end;
int maxdist = 0;
for( tie( j, j_end ) = in_edges( *it, graph ); j != j_end; ++j ) {
maxdist = std::max( edge_count[source(*j, graph)], maxdist);
edge_count[*it] = maxdist + 1;
}
group[edge_count.at( *it )].push_back( nodes.at( *it ) );
_TRACE("-> " << *it << " - " << edge_count[*it] << " - " << nodes.at(*it)->name() );
}
}
// populate runorder queue
std::map<int, std::vector<JobPtr> >::iterator mit=group.begin();
for ( ; mit != group.end(); mit++ )
jq.push_back( mit->second );
return jq;
}
void
JobManager::job_queue_run( JobQueue & jobs ) {
std::map<JobPtr, std::pair<time_t, int> > timer;
// process agents in batches run in parallel
for( unsigned int i=0; i < jobs.size(); i++ ) {
std::queue<JobResponse> jq;
std::vector<JobPtr> batch = jobs[i];
// dispatch agent tasks asychronously
for( unsigned int j=0; j < batch.size(); j++ ) {
JobPtr job = batch[j];
// determine timeout value for this job
int timeout = job->timeout();
if ( timeout ) {
timer[job] = std::pair<time_t, int>(time(NULL), timeout );
}
jq.push( job->run() );
}
// poll async tasks until all have completed, or there is
// a failure, timeout, etc.
while ( ! jq.empty() ) {
JobResponse & resp = jq.front();
_DEBUG("Polling '" << resp.job()->name() << "' ... ");
resp.status()->sync();
_DEBUG("Progress: " << resp.status()->progress());
if ( resp.status()->progress() != 100 ) {
// if this job has a timeout, check it
if ( timer.count( resp.job() ) ) {
int runtime = time(NULL) - timer[resp.job()].first;
if ( timer[resp.job()].second && runtime >= timer[resp.job()].second ) {
gbTHROW( ERR_INTERNAL_SERVER_ERROR(
"Agent '" + resp.job()->name() + "' exceeded timeout!"
) );
}
}
usleep(10000); // sleep .1 seconds
}
else if ( resp.status()->code() != 0 ) {
gbTHROW( ERR_INTERNAL_SERVER_ERROR(
"Agent '" + resp.job()->name() + "' returned status code " +
boost::lexical_cast<std::string>(resp.status()->code())
) );
}
else {
_DEBUG("Agent '" << resp.job()->name() << "' completed successfully.");
jq.pop();
}
}
}
}
void JobManager::requireSchemas(bool b) {
JobManager::require_schemas = b;
}
}
| 38.97541 | 113 | 0.48408 | [
"object",
"vector"
] |
b4c4fa06371cd2810b51190d3c0cd7d020d3fef3 | 10,332 | hpp | C++ | src/database/database.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | src/database/database.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | src/database/database.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | #pragma once
#include <biboumi.h>
#ifdef USE_DATABASE
#include <database/table.hpp>
#include <database/column.hpp>
#include <database/count_query.hpp>
#include <database/engine.hpp>
#include <utils/optional_bool.hpp>
#include <utils/datetime.hpp>
#include <chrono>
#include <string>
#include <memory>
#include <map>
class Database
{
public:
struct RecordNotFound: public std::exception {};
enum class Paging { first, last };
struct Uuid: Column<std::string> { static constexpr auto name = "uuid_"; };
struct Owner: Column<std::string> { static constexpr auto name = "owner_"; };
struct IrcChanName: Column<std::string> { static constexpr auto name = "ircchanname_"; };
struct Channel: Column<std::string> { static constexpr auto name = "channel_"; };
struct IrcServerName: Column<std::string> { static constexpr auto name = "ircservername_"; };
struct Server: Column<std::string> { static constexpr auto name = "server_"; };
struct OldDate: Column<std::chrono::system_clock::time_point::rep> { static constexpr auto name = "date_"; };
struct Date: Column<DateTime> { static constexpr auto name = "date_"; };
struct Body: Column<std::string> { static constexpr auto name = "body_"; };
struct Nick: Column<std::string> { static constexpr auto name = "nick_"; };
struct Pass: Column<std::string> { static constexpr auto name = "pass_"; };
struct Ports: Column<std::string> { static constexpr auto name = "ports_";
Ports(): Column<std::string>("6667") {} };
struct TlsPorts: Column<std::string> { static constexpr auto name = "tlsports_";
TlsPorts(): Column<std::string>("6697;6670") {} };
struct Username: Column<std::string> { static constexpr auto name = "username_"; };
struct Realname: Column<std::string> { static constexpr auto name = "realname_"; };
struct AfterConnectionCommand: Column<std::string> { static constexpr auto name = "afterconnectioncommand_"; };
struct TrustedFingerprint: Column<std::string> { static constexpr auto name = "trustedfingerprint_"; };
struct EncodingOut: Column<std::string> { static constexpr auto name = "encodingout_"; };
struct EncodingIn: Column<std::string> { static constexpr auto name = "encodingin_"; };
struct MaxHistoryLength: Column<int> { static constexpr auto name = "maxhistorylength_";
MaxHistoryLength(): Column<int>(20) {} };
struct RecordHistory: Column<bool> { static constexpr auto name = "recordhistory_";
RecordHistory(): Column<bool>(true) {}};
struct RecordHistoryOptional: Column<OptionalBool> { static constexpr auto name = "recordhistory_"; };
struct VerifyCert: Column<bool> { static constexpr auto name = "verifycert_";
VerifyCert(): Column<bool>(true) {} };
struct Persistent: Column<bool> { static constexpr auto name = "persistent_";
Persistent(): Column<bool>(false) {} };
struct GlobalPersistent: Column<bool> { static constexpr auto name = "persistent_";
GlobalPersistent(); };
struct LocalJid: Column<std::string> { static constexpr auto name = "local"; };
struct RemoteJid: Column<std::string> { static constexpr auto name = "remote"; };
struct Address: Column<std::string> { static constexpr auto name = "address_"; };
using MucLogLineTable = Table<Id, Uuid, Owner, IrcChanName, IrcServerName, Date, Body, Nick>;
using MucLogLine = MucLogLineTable::RowType;
using OldMucLogLineTable = Table<Id, Uuid, Owner, IrcChanName, IrcServerName, OldDate, Body, Nick>;
using OldMucLogLine = OldMucLogLineTable::RowType;
using GlobalOptionsTable = Table<Id, Owner, MaxHistoryLength, RecordHistory, GlobalPersistent>;
using GlobalOptions = GlobalOptionsTable::RowType;
using IrcServerOptionsTable = Table<Id, Owner, Server, Pass, TlsPorts, Ports, Username, Realname, VerifyCert, TrustedFingerprint, EncodingOut, EncodingIn, MaxHistoryLength, Address, Nick>;
using IrcServerOptions = IrcServerOptionsTable::RowType;
using IrcChannelOptionsTable = Table<Id, Owner, Server, Channel, EncodingOut, EncodingIn, MaxHistoryLength, Persistent, RecordHistoryOptional>;
using IrcChannelOptions = IrcChannelOptionsTable::RowType;
using RosterTable = Table<LocalJid, RemoteJid>;
using RosterItem = RosterTable::RowType;
using AfterConnectionCommandsTable = Table<Id, ForeignKey, AfterConnectionCommand>;
using AfterConnectionCommands = std::vector<AfterConnectionCommandsTable::RowType>;
Database() = default;
~Database() = default;
Database(const Database&) = delete;
Database(Database&&) = delete;
Database& operator=(const Database&) = delete;
Database& operator=(Database&&) = delete;
static GlobalOptions get_global_options(const std::string& owner);
static IrcServerOptions get_irc_server_options(const std::string& owner,
const std::string& server);
static IrcChannelOptions get_irc_channel_options(const std::string& owner,
const std::string& server,
const std::string& channel);
static IrcChannelOptions get_irc_channel_options_with_server_default(const std::string& owner,
const std::string& server,
const std::string& channel);
static IrcChannelOptions get_irc_channel_options_with_server_and_global_default(const std::string& owner,
const std::string& server,
const std::string& channel);
static AfterConnectionCommands get_after_connection_commands(const IrcServerOptions& server_options);
static void set_after_connection_commands(const IrcServerOptions& server_options, AfterConnectionCommands& commands);
/**
* Get all the lines between (optional) start and end dates, with a (optional) limit.
* If after_id is set, only the records after it will be returned.
*/
static std::vector<MucLogLine> get_muc_logs(const std::string& owner, const std::string& chan_name, const std::string& server,
int limit=-1, const std::string& start="", const std::string& end="",
const std::string& reference_record_id={}, Paging=Paging::first);
/**
* Get just one single record matching the given uuid, between (optional) end and start.
* If it does not exist (or is not between end and start), throw a RecordNotFound exception.
*/
static MucLogLine get_muc_log(const std::string& owner, const std::string& chan_name, const std::string& server, const std::string& uuid, const std::string& start="", const std::string& end="");
static std::string store_muc_message(const std::string& owner, const std::string& chan_name, const std::string& server_name,
DateTime::time_point date, const std::string& body, const std::string& nick);
static void add_roster_item(const std::string& local, const std::string& remote);
static bool has_roster_item(const std::string& local, const std::string& remote);
static void delete_roster_item(const std::string& local, const std::string& remote);
static std::vector<Database::RosterItem> get_contact_list(const std::string& local);
static std::vector<Database::RosterItem> get_full_roster();
static void close();
static void open(const std::string& filename);
template <typename TableType>
static int64_t count(const TableType& table)
{
CountQuery query{table.get_name()};
return query.execute(*Database::db);
}
static MucLogLineTable muc_log_lines;
static GlobalOptionsTable global_options;
static IrcServerOptionsTable irc_server_options;
static IrcChannelOptionsTable irc_channel_options;
static RosterTable roster;
static AfterConnectionCommandsTable after_connection_commands;
static std::unique_ptr<DatabaseEngine> db;
static DatabaseEngine::EngineType engine_type()
{
if (Database::db)
return Database::db->engine_type();
return DatabaseEngine::EngineType::None;
}
/**
* Some caches, to avoid doing very frequent query requests for a few options.
*/
using CacheKey = std::tuple<std::string, std::string, std::string>;
static EncodingIn::real_type get_encoding_in(const std::string& owner,
const std::string& server,
const std::string& channel)
{
CacheKey channel_key{owner, server, channel};
auto it = Database::encoding_in_cache.find(channel_key);
if (it == Database::encoding_in_cache.end())
{
auto options = Database::get_irc_channel_options_with_server_default(owner, server, channel);
EncodingIn::real_type result = options.col<Database::EncodingIn>();
if (result.empty())
result = "ISO-8859-1";
it = Database::encoding_in_cache.insert(std::make_pair(channel_key, result)).first;
}
return it->second;
}
static void invalidate_encoding_in_cache(const std::string& owner,
const std::string& server,
const std::string& channel)
{
CacheKey channel_key{owner, server, channel};
Database::encoding_in_cache.erase(channel_key);
}
static void invalidate_encoding_in_cache()
{
Database::encoding_in_cache.clear();
}
static auto raw_exec(const std::string& query)
{
return Database::db->raw_exec(query);
}
private:
static std::string gen_uuid();
static std::map<CacheKey, EncodingIn::real_type> encoding_in_cache;
};
class Transaction
{
public:
Transaction();
~Transaction();
void rollback();
bool success{false};
};
template <typename... T>
void convert_date_format(DatabaseEngine& db, Table<T...> table)
{
const auto existing_columns = db.get_all_columns_from_table(table.get_name());
const auto date_pair = existing_columns.find(Database::Date::name);
if (date_pair != existing_columns.end() && date_pair->second == "integer")
{
log_info("Converting Date_ format to the new one.");
db.convert_date_format(db);
}
}
#endif /* USE_DATABASE */
| 42.171429 | 196 | 0.680798 | [
"vector"
] |
b4c51ba13630a7b15443943f65b25243ff49d07e | 6,400 | cpp | C++ | console/src/boost_1_78_0/libs/histogram/test/axis_variable_test.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | console/src/boost_1_78_0/libs/histogram/test/axis_variable_test.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | Libs/boost_1_76_0/libs/histogram/test/axis_variable_test.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 41 | 2015-07-08T19:18:35.000Z | 2021-01-14T16:39:56.000Z | // Copyright 2015-2017 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/axis/ostream.hpp>
#include <boost/histogram/axis/variable.hpp>
#include <limits>
#include <sstream>
#include <type_traits>
#include <vector>
#include "is_close.hpp"
#include "std_ostream.hpp"
#include "throw_exception.hpp"
#include "utility_axis.hpp"
#include "utility_str.hpp"
using namespace boost::histogram;
int main() {
constexpr auto inf = std::numeric_limits<double>::infinity();
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
BOOST_TEST(std::is_nothrow_move_assignable<axis::variable<>>::value);
BOOST_TEST(std::is_nothrow_move_constructible<axis::variable<>>::value);
// bad_ctors
{
BOOST_TEST_THROWS(axis::variable<>(std::vector<double>{}), std::invalid_argument);
BOOST_TEST_THROWS(axis::variable<>({1.0}), std::invalid_argument);
BOOST_TEST_THROWS(axis::variable<>({1.0, 1.0}), std::invalid_argument);
BOOST_TEST_THROWS(axis::variable<>({1.0, -1.0}), std::invalid_argument);
BOOST_TEST_THROWS((axis::variable<>{{1.0, 2.0, nan}}), std::invalid_argument);
BOOST_TEST_THROWS((axis::variable<>{{1.0, nan, 2.0}}), std::invalid_argument);
BOOST_TEST_THROWS((axis::variable<>{{nan, 1.0, 2.0}}), std::invalid_argument);
BOOST_TEST_THROWS((axis::variable<>{{inf, inf}}), std::invalid_argument);
}
// axis::variable
{
axis::variable<> a{{-1, 0, 1}, "foo"};
BOOST_TEST_EQ(a.size(), 2);
BOOST_TEST_EQ(a.metadata(), "foo");
BOOST_TEST_EQ(static_cast<const axis::variable<>&>(a).metadata(), "foo");
a.metadata() = "bar";
BOOST_TEST_EQ(static_cast<const axis::variable<>&>(a).metadata(), "bar");
BOOST_TEST_EQ(a.bin(-1).lower(), -inf);
BOOST_TEST_EQ(a.bin(a.size()).upper(), inf);
BOOST_TEST_EQ(a.value(0), -1);
BOOST_TEST_EQ(a.value(0.5), -0.5);
BOOST_TEST_EQ(a.value(1), 0);
BOOST_TEST_EQ(a.value(1.5), 0.5);
BOOST_TEST_EQ(a.value(2), 1);
BOOST_TEST_EQ(a.index(-10), -1);
BOOST_TEST_EQ(a.index(-1), 0);
BOOST_TEST_EQ(a.index(0), 1);
BOOST_TEST_EQ(a.index(1), 2);
BOOST_TEST_EQ(a.index(10), 2);
BOOST_TEST_EQ(a.index(-inf), -1);
BOOST_TEST_EQ(a.index(inf), 2);
BOOST_TEST_EQ(a.index(nan), 2);
BOOST_TEST_EQ(str(a),
"variable(-1, 0, 1, metadata=\"bar\", options=underflow | overflow)");
axis::variable<> b;
BOOST_TEST_NE(a, b);
b = a;
BOOST_TEST_EQ(a, b);
axis::variable<> c = std::move(b);
BOOST_TEST_EQ(c, a);
axis::variable<> d;
BOOST_TEST_NE(c, d);
d = std::move(c);
BOOST_TEST_EQ(d, a);
axis::variable<> e{-2, 0, 2};
BOOST_TEST_NE(a, e);
}
// infinity values in constructor
{
axis::variable<> a{{-inf, 1.0, 2.0, inf}};
BOOST_TEST_EQ(a.index(-inf), 0);
BOOST_TEST_EQ(a.index(0.0), 0);
BOOST_TEST_EQ(a.index(1.0), 1);
BOOST_TEST_EQ(a.index(2.0), 2);
BOOST_TEST_EQ(a.index(inf), 3);
BOOST_TEST_EQ(a.value(-1), -inf);
BOOST_TEST_EQ(a.value(-0.5), -inf);
BOOST_TEST_EQ(a.value(0), -inf);
BOOST_TEST_EQ(a.value(0.5), -inf);
BOOST_TEST_EQ(a.value(1), 1.0);
BOOST_TEST_EQ(a.value(1.5), 1.5);
BOOST_TEST_EQ(a.value(2), 2.0);
BOOST_TEST_EQ(a.value(2.5), inf);
BOOST_TEST_EQ(a.value(3), inf);
BOOST_TEST_EQ(a.value(4), inf);
BOOST_TEST_EQ(str(a), "variable(-inf, 1, 2, inf, options=underflow | overflow)");
}
// axis::variable circular
{
axis::variable<double, axis::null_type, axis::option::circular_t> a{-1, 1, 2};
BOOST_TEST_EQ(a.value(-2), -4);
BOOST_TEST_EQ(a.value(-1), -2);
BOOST_TEST_EQ(a.value(0), -1);
BOOST_TEST_EQ(a.value(1), 1);
BOOST_TEST_EQ(a.value(2), 2);
BOOST_TEST_EQ(a.value(3), 4);
BOOST_TEST_EQ(a.value(4), 5);
BOOST_TEST_EQ(a.index(-3), 0); // -3 + 3 = 0
BOOST_TEST_EQ(a.index(-2), 1); // -2 + 3 = 1
BOOST_TEST_EQ(a.index(-1), 0);
BOOST_TEST_EQ(a.index(0), 0);
BOOST_TEST_EQ(a.index(1), 1);
BOOST_TEST_EQ(a.index(2), 0);
BOOST_TEST_EQ(a.index(3), 0); // 3 - 3 = 0
BOOST_TEST_EQ(a.index(4), 1); // 4 - 3 = 1
}
// axis::regular with growth
{
using pii_t = std::pair<axis::index_type, axis::index_type>;
axis::variable<double, axis::null_type, axis::option::growth_t> a{0, 1};
BOOST_TEST_EQ(a.size(), 1);
BOOST_TEST_EQ(a.update(0), pii_t(0, 0));
BOOST_TEST_EQ(a.size(), 1);
BOOST_TEST_EQ(a.update(1.1), pii_t(1, -1));
BOOST_TEST_EQ(a.size(), 2);
BOOST_TEST_EQ(a.value(0), 0);
BOOST_TEST_EQ(a.value(1), 1);
BOOST_TEST_EQ(a.value(2), 1.5);
BOOST_TEST_EQ(a.update(-0.1), pii_t(0, 1));
BOOST_TEST_EQ(a.value(0), -0.5);
BOOST_TEST_EQ(a.size(), 3);
BOOST_TEST_EQ(a.update(10), pii_t(3, -1));
BOOST_TEST_EQ(a.size(), 4);
BOOST_TEST_IS_CLOSE(a.value(4), 10, 1e-9);
BOOST_TEST_EQ(a.update(-10), pii_t(0, 1));
BOOST_TEST_EQ(a.size(), 5);
BOOST_TEST_IS_CLOSE(a.value(0), -10, 1e-9);
BOOST_TEST_EQ(a.update(-inf), pii_t(-1, 0));
BOOST_TEST_EQ(a.update(inf), pii_t(a.size(), 0));
BOOST_TEST_EQ(a.update(nan), pii_t(a.size(), 0));
}
// iterators
{
test_axis_iterator(axis::variable<>{1, 2, 3}, 0, 2);
test_axis_iterator(
axis::variable<double, axis::null_type, axis::option::circular_t>{1, 2, 3}, 0, 2);
}
// shrink and rebin
{
using A = axis::variable<>;
auto a = A({0, 1, 2, 3, 4, 5});
auto b = A(a, 1, 4, 1);
BOOST_TEST_EQ(b.size(), 3);
BOOST_TEST_EQ(b.value(0), 1);
BOOST_TEST_EQ(b.value(3), 4);
auto c = A(a, 0, 4, 2);
BOOST_TEST_EQ(c.size(), 2);
BOOST_TEST_EQ(c.value(0), 0);
BOOST_TEST_EQ(c.value(2), 4);
auto e = A(a, 1, 5, 2);
BOOST_TEST_EQ(e.size(), 2);
BOOST_TEST_EQ(e.value(0), 1);
BOOST_TEST_EQ(e.value(2), 5);
}
// shrink and rebin with circular option
{
using A = axis::variable<double, axis::null_type, axis::option::circular_t>;
auto a = A({1, 2, 3, 4, 5});
BOOST_TEST_THROWS(A(a, 1, 4, 1), std::invalid_argument);
BOOST_TEST_THROWS(A(a, 0, 3, 1), std::invalid_argument);
auto b = A(a, 0, 4, 2);
BOOST_TEST_EQ(b.size(), 2);
BOOST_TEST_EQ(b.value(0), 1);
BOOST_TEST_EQ(b.value(2), 5);
}
return boost::report_errors();
}
| 33.507853 | 90 | 0.624375 | [
"vector"
] |
b4c5596b8f4417ab4ae924ff2da874090e027adc | 13,195 | cpp | C++ | PROCY/System/Map/Map.cpp | mflottDesign/DAT220 | fcff0e599fba0216d2107a7c28e21783a8c87e9c | [
"MIT"
] | null | null | null | PROCY/System/Map/Map.cpp | mflottDesign/DAT220 | fcff0e599fba0216d2107a7c28e21783a8c87e9c | [
"MIT"
] | null | null | null | PROCY/System/Map/Map.cpp | mflottDesign/DAT220 | fcff0e599fba0216d2107a7c28e21783a8c87e9c | [
"MIT"
] | null | null | null | //
// Created by Chrim14 on 10.10.2017.
//
#include "Map.h"
#include "MapStaticFunctions.h"
///From: Game::Game
///Function: create map and update map changes in views
void Map::mapHandler(sf::Shader &shader, Player &player,Timer &gameTimer,std::vector<Tower> &towersPlaced,std::string &towerSelected, sf::VertexArray &mapTiles, sf::VertexArray &bitTiles, StateMachine &state, sf::RenderWindow &window, Settings &json,sf::VertexArray &miniMapSquare, tgui::Gui &gui, Sound &sound,Paths& path, WaveManager &waveManager) {
if (state.getState() == List_State::MapEditor || state.getState() == List_State::Game ||
state.getState() == List_State::Pause) {
if (!json.mapLoaded) {
if (state.getState() == List_State::MapEditor) {
json.view["map"].setViewport(sf::FloatRect(0.80f, 0.74f, 0.18f, 0.22f));
lInfo("Starting MapEditor");
if (json.editor["name"] == "new") CreateNewMap(json);
} else if (state.getState() == List_State::Game) {
//json.view["map"].setViewport(sf::FloatRect(0.01f, 0.72f, 0.25f, 0.25f));
json.view["map"].setViewport(sf::FloatRect(0.01f, 0.68f, 0.23f, 0.30f));
lInfo("Starting Game");
}
setView(json.view["main"], json);
window.setView(json.view["main"]);
getMap(mapTiles, bitTiles, json);
setMiniMapView(window, json, miniMapSquare);
towersPlaced.clear();
if (state.getState() == List_State::Game) {
mf::setBitMapHighlightPanel(bitTiles, json);
Paths new_path;
new_path.setPaths(json);
path = new_path;
waveManager.mapStart(json, path);
}
json.mapLoaded = true;
}
window.setView(json.view["main"]);
window.draw(mapTiles, &json.texture["tiles"]);
if (!towerSelected.empty()) json.highlight = true;
if (json.highlight) window.draw(bitTiles);
if (state.getState() == List_State::Pause) getMiniMapView(gui, window, json, mapTiles, miniMapSquare);
if (state.getState() != List_State::MapEditor) gui.draw();
if (state.getState() != List_State::Pause) getMiniMapView(gui, window, json, mapTiles, miniMapSquare);
if (state.getState() == List_State::MapEditor) gui.draw();
window.setView(json.view["main"]);
}
else if (state.getState() == List_State::New_Game && json.mapSelected) {
if (!json.mapPreview) {
getMap(mapTiles, bitTiles, json);
setMiniMapView(window, json, miniMapSquare);
json.mapPreview = true;
}
else {
gui.draw();
getMiniMapView(gui, window, json, mapTiles, miniMapSquare);
}
}
else {
gui.draw();
json.mapLoaded = false;
}
}
/** ##################################### PROTECTED ##################################################################### */
///From: Map::clickEvent
///Function: Return a INT value after which view clicked on
int Map::getViewFocused(std::vector<tgui::Panel::Ptr> &panels,bool dynamical_focus, sf::Vector2i &pixelPosition, Settings &json, StateMachine &state, sf::RenderWindow &window, tgui::Gui &gui) {
//IF the view excist in both states, like mini map
if(state.getState() == List_State::MapEditor || state.getState() == List_State::Game) {
//Checking if MiniMap is focused
if(
pixelPosition.y >= json.view["map"].getViewport().top*window.getSize().y &&
pixelPosition.x >= json.view["map"].getViewport().left*window.getSize().x &&
pixelPosition.y <= (json.view["map"].getViewport().top+json.view["map"].getViewport().height)*window.getSize().y &&
pixelPosition.x <= (json.view["map"].getViewport().left+json.view["map"].getViewport().width)*window.getSize().x
){
return 2;
}
// Check if the mouse is inside the hudView
if(state.getState() == List_State::Game){
for (auto &panel : panels) {
tgui::Panel* temp = panel.get();
if(pixelPosition.x >= temp->getAbsolutePosition().x &&
pixelPosition.x <= (temp->getSize().x + temp->getAbsolutePosition().x)&&
pixelPosition.y >= temp->getAbsolutePosition().y &&
pixelPosition.y <= (temp->getSize().y + temp->getAbsolutePosition().y)){
return 4;
}
}
}
//If the view only excist in Map editor, like child windows
if(state.getState() == List_State::MapEditor){
try{
tgui::MenuBar::Ptr toolbar = gui.get<tgui::MenuBar>("menu");
if (toolbar != nullptr) {
if(!dynamical_focus && toolbar->isFocused()) return 3;
if( pixelPosition.y < toolbar->getSize().y){
return 3;
}
}
} catch (...) {
lError("Tried to check if TGUI focused, failed");
}
std::vector<std::string> list = {"tileChildMenu", "saveChildMenu", "loadChildMenu", "pmChildMenu", "changeTileChildMenu", "selectedTileChildWindow", "description"};
for (const auto& temp : list) {
try {
tgui::ChildWindow::Ptr menu = gui.get<tgui::ChildWindow>(temp);
if (menu != nullptr) {
//if (!dynamical_focus && menu->isFocused()) return 3;
if (pixelPosition.x >= menu->getPosition().x &&
pixelPosition.x <= menu->getPosition().x + menu->getSize().x &&
pixelPosition.y >= menu->getPosition().y &&
pixelPosition.y <= menu->getPosition().y + menu->getSize().y+30) {
return 3;
}
}
}
catch (...) {
lError("Tried to check if TGUI child window was focused, failed on: "+temp);
}
}
}
}
return 1;
}
/** ################################### PRIVATE ##################################################################### */
///From: Map::mapHandler
///Function: Setting the start view, max view and view center
void Map::setView(sf::View &view, Settings &json) {
float height = json.map["height"];
float width = json.map["width"];
float centerHeight = (height*Tile_Size)/2;
float centerWidth = (width*Tile_Size)/2;
float minSize = 10.0f;
if(height <= minSize || width <= minSize){
view.setSize(sf::Vector2f((minSize*Tile_Size)*(16.f/9.f),(minSize*Tile_Size)));
view.setCenter(centerWidth,centerHeight);
}
else{
float temp = json.setting["startView"];
//error handling if someone alter the "startView" number in file
if(temp < minSize) temp = minSize;
else if(temp > Layer_One_Size) temp = Layer_One_Size;
view.setSize(sf::Vector2f((temp*Tile_Size)*(16.f/9.f),(temp*Tile_Size)));
//TODO: Add player center position here
view.setCenter(centerWidth,centerHeight);
}
}
///From: Map::mapHandler
///Function: initialize the MiniMap view
void Map::setMiniMapView(sf::RenderWindow &window, Settings &json,sf::VertexArray &miniMapSquare) {
float height = json.map["height"];
float width = json.map["width"];
float max;
if(height > width)
max = height;
else
max = width;
float length = max * Tile_Size;
json.view["map"].setSize(sf::Vector2f(length,length));
json.view["map"].setCenter(sf::Vector2f(length/2.0f,length/2.0f));
if(height > width){
max = height-width;
max = max / 2.0f;
length = max * Tile_Size;
json.view["map"].move(-length, 0);
} else{
max = width-height;
max = max / 2.0f;
length = max * Tile_Size;
json.view["map"].move(0,-length);
}
sf::Vector2f viewMin = json.view["main"].getCenter() - (json.view["main"].getSize() / 2.0f);
sf::Vector2f viewMax = viewMin + json.view["main"].getSize();
if(json.mapLoaded) {
miniMapSquare[0].position = sf::Vector2f(viewMin.x + 1, viewMin.y + 1);
miniMapSquare[1].position = sf::Vector2f(viewMax.x, viewMin.y + 1);
miniMapSquare[2].position = sf::Vector2f(viewMax.x, viewMax.y - 1);
miniMapSquare[3].position = sf::Vector2f(viewMin.x + 1, viewMax.y - 1);
miniMapSquare[4].position = sf::Vector2f(viewMin.x + 1, viewMin.y + 1);
for (int i = 0; i <= 4; ++i) {
miniMapSquare[i].color = sf::Color::Yellow;
}
}
}
///From: Map::mapHandler
///Function: Drawing the MiniMap view
void Map::getMiniMapView(tgui::Gui &gui,sf::RenderWindow &window, Settings &json, sf::VertexArray &mapTiles,sf::VertexArray &miniMapSquare) {
sf::RectangleShape rectangle(sf::Vector2f(Layer_One_Size*Tile_Size*2,Layer_One_Size*Tile_Size*2));
rectangle.setPosition(-(signed)(Layer_One_Size*Tile_Size),-(signed)(Layer_One_Size*Tile_Size));
rectangle.setFillColor(sf::Color(0, 0, 0));
sf::Vector2f viewMin = json.view["main"].getCenter() - (json.view["main"].getSize() / 2.0f);
sf::Vector2f viewMax = viewMin + json.view["main"].getSize();
if(json.mapLoaded) {
miniMapSquare[0].position = sf::Vector2f(viewMin.x + 1, viewMin.y + 1);
miniMapSquare[1].position = sf::Vector2f(viewMax.x, viewMin.y + 1);
miniMapSquare[2].position = sf::Vector2f(viewMax.x, viewMax.y - 1);
miniMapSquare[3].position = sf::Vector2f(viewMin.x + 1, viewMax.y - 1);
miniMapSquare[4].position = sf::Vector2f(viewMin.x + 1, viewMin.y + 1);
}
float height = json.view["hud"].getSize().y;
float width = json.view["hud"].getSize().x;
//0.01f,0.72f,0.25f,0.25f
sf::RectangleShape frame(sf::Vector2f(json.view["map"].getViewport().width*width,json.view["map"].getViewport().height*height));
frame.setPosition(sf::Vector2f(json.view["map"].getViewport().left*width,json.view["map"].getViewport().top*height));
frame.setTexture(&json.texture["miniMapFrame"]);
if(!json.mapImage || json.mapLoaded) {
window.setView(json.view["map"]);
window.draw(rectangle);
window.draw(mapTiles, &json.texture["tiles"]);
}
if(json.mapLoaded) window.draw(miniMapSquare);
window.setView(json.view["hud"]);
window.draw(frame);
}
///From: Map::mapHandler
///Function: Drawing up all map tiles
void Map::getMap(sf::VertexArray &mapTiles, sf::VertexArray &bitTiles, Settings &json) {
const size_t width = json.map["width"];
const size_t height = json.map["height"];
//clearing VerexArrays to prevent old data
mapTiles.clear();
mapTiles.resize(width*height*4);
bitTiles.clear();
bitTiles.resize(width*Bits_To_Tiles*height*Bits_To_Tiles*4);
sf::Vector2i tileStart, tileSize;
int counter = 0;
int tempY = 0;
for (int y = 0; y < height; ++y) {
int tempX = 0;
for (int x = 0; x < width; ++x) {
unsigned int tile = json.tileValue[x][y];
getTileCoordinates(tile, tileStart, tileSize, json);
mapTiles[counter].position = sf::Vector2f(tempX, tempY);
mapTiles[counter + 1].position = sf::Vector2f(tempX + Tile_Size, tempY);
mapTiles[counter + 2].position = sf::Vector2f(tempX + Tile_Size, tempY + Tile_Size);
mapTiles[counter + 3].position = sf::Vector2f(tempX, tempY + Tile_Size);
if((((tile >> 31) & 1) && ((tile >> 30) & 1)) || (!((tile >> 31) & 1) && !((tile >> 30) & 1))) {
mapTiles[counter].texCoords = sf::Vector2f(tileStart.x, tileStart.y);
mapTiles[counter + 1].texCoords = sf::Vector2f(tileStart.x + tileSize.x, tileStart.y);
mapTiles[counter + 2].texCoords = sf::Vector2f(tileStart.x + tileSize.x, tileStart.y + tileSize.y);
mapTiles[counter + 3].texCoords = sf::Vector2f(tileStart.x, tileStart.y + tileSize.y);
}
else {
mapTiles[counter].texCoords = sf::Vector2f(tileStart.x, tileStart.y);
mapTiles[counter + 1].texCoords = sf::Vector2f(tileStart.x, tileStart.y + tileSize.y);
mapTiles[counter + 2].texCoords = sf::Vector2f(tileStart.x + tileSize.x, tileStart.y + tileSize.y);
mapTiles[counter + 3].texCoords = sf::Vector2f(tileStart.x + tileSize.x, tileStart.y);
}
counter += 4;
tempX += Tile_Size;
}
tempY += Tile_Size;
}
}
///From: Map::mapHandler
///Function: Fills a 2D array with information about what tile is there
void Map::CreateNewMap(Settings &json) {
size_t startTile = json.editor["tile"];
memset(json.bitTileValue,0, sizeof(json.bitTileValue));
for (auto &i : json.tileValue) {
for (unsigned int &j : i) {
j = (unsigned int) startTile;
}
}
}
| 38.581871 | 351 | 0.570292 | [
"vector"
] |
b4c5c5b28c9ad710a7849307f3d11f18abca7c99 | 2,521 | hpp | C++ | src/usher_graph.hpp | lgozasht/usher | 4afe8e59a5d60ee9516a52111c1852b2d6fb53df | [
"MIT"
] | null | null | null | src/usher_graph.hpp | lgozasht/usher | 4afe8e59a5d60ee9516a52111c1852b2d6fb53df | [
"MIT"
] | null | null | null | src/usher_graph.hpp | lgozasht/usher | 4afe8e59a5d60ee9516a52111c1852b2d6fb53df | [
"MIT"
] | null | null | null | //#include "tree.hpp"
#include "mutation_annotated_tree.hpp"
#include <set>
#include <cassert>
#include <unordered_set>
#include <mutex>
#include <sys/time.h>
#include <tbb/mutex.h>
#pragma once
//extern std::mutex data_lock;
namespace MAT = Mutation_Annotated_Tree;
class Timer {
private:
struct timeval m_StartTime, m_EndTime;
public:
void Start() {
gettimeofday(&m_StartTime, NULL);
}
long Stop() {
long useconds, seconds, mseconds;
gettimeofday(&m_EndTime, NULL);
useconds = m_EndTime.tv_usec - m_StartTime.tv_usec;
seconds = m_EndTime.tv_sec - m_StartTime.tv_sec;
mseconds = ((seconds) * 1000 + useconds/1000.0 + 0.5);
return mseconds;
}
};
struct Missing_Sample {
std::string name;
std::vector<MAT::Mutation> mutations;
size_t num_ambiguous;
Missing_Sample (std::string sample_name) {
name = sample_name;
mutations.clear();
num_ambiguous = 0;
}
bool operator==(const Missing_Sample& other) const
{
return (*this).name == other.name;
}
bool operator<(const Missing_Sample& other) const
{
return (*this).num_ambiguous < other.num_ambiguous;
}
};
struct mapper_input {
MAT::Tree* T;
std::string chrom;
int8_t ref_nuc;
int variant_pos;
std::vector<MAT::Node*>* bfs;
std::unordered_map<std::string, size_t>* bfs_idx;
std::vector<std::tuple<size_t, int8_t>> variants;
std::vector<std::string>* variant_ids;
std::vector<Missing_Sample>* missing_samples;
//std::vector<std::vector<MAT::Mutation>>* missing_sample_mutations;
};
struct mapper_body {
int operator()(mapper_input input);
};
struct mapper2_input {
std::string missing_sample;
MAT::Tree* T;
MAT::Node* node;
std::vector<MAT::Mutation>* missing_sample_mutations;
int* best_set_difference;
int* set_difference;
size_t* best_node_num_leaves;
size_t j;
size_t* best_j;
size_t distance;
size_t* best_distance;
size_t* num_best;
MAT::Node** best_node;
std::vector<bool>* node_has_unique;
std::vector<size_t>* best_j_vec;
bool* has_unique;
std::vector<MAT::Mutation>* excess_mutations;
std::vector<MAT::Mutation>* imputed_mutations;
mapper2_input () {
distance = 0;
best_distance = &distance;
}
};
void mapper2_body(mapper2_input& inp, bool compute_parsimony_scores);
| 24.475728 | 72 | 0.637842 | [
"vector"
] |
b4c7c181f2746868d07bedaa7488a28e6c2f9fdd | 2,651 | cpp | C++ | rapidlib_old_version/src/seriesClassification.cpp | carlotes247/Rapidlib-dll | e498477a3a3b3e198c9f9de5c7a8cf43aaa9ba92 | [
"MIT"
] | null | null | null | rapidlib_old_version/src/seriesClassification.cpp | carlotes247/Rapidlib-dll | e498477a3a3b3e198c9f9de5c7a8cf43aaa9ba92 | [
"MIT"
] | null | null | null | rapidlib_old_version/src/seriesClassification.cpp | carlotes247/Rapidlib-dll | e498477a3a3b3e198c9f9de5c7a8cf43aaa9ba92 | [
"MIT"
] | null | null | null | //
// seriesClassification.cpp
// RapidAPI
//
// Created by mzed on 08/06/2017.
// Copyright © 2017 Goldsmiths. All rights reserved.
//
#include <vector>
#include "seriesClassification.h"
#ifdef EMSCRIPTEN
#include "emscripten/seriesClassificationEmbindings.h"
#endif
seriesClassification::seriesClassification() {};
seriesClassification::~seriesClassification() {};
bool seriesClassification::addSeries(const std::vector<std::vector<double>> &newSeries) {
dtw newDTW;
newDTW.setSeries(newSeries);
dtwClassifiers.push_back(newDTW);
return true;
}
bool seriesClassification::addTrainingSet(const std::vector<trainingExample> &trainingSet) {
std::vector<std::vector<double>> newSeries;
for (int i = 0; i < trainingSet.size(); ++i) {
newSeries.push_back(trainingSet[i].input);
}
return addSeries(newSeries);
};
bool seriesClassification::train(const std::vector<std::vector<std::vector<double> > > &newSeriesSet) {
bool trained = true;
reset();
for (int i = 0; i < newSeriesSet.size(); ++i) {
if (!addSeries(newSeriesSet[i])) {
trained = false;
};
}
return trained;
}
bool seriesClassification::trainTrainingSet(const std::vector<std::vector<trainingExample> > &seriesSet) {
bool trained = true;
reset();
for (int i = 0; i < seriesSet.size(); ++i) {
if (!addTrainingSet(seriesSet[i])) {
trained = false;
};
}
return trained;
}
void seriesClassification::reset() {
dtwClassifiers.clear();
}
int seriesClassification::run(const std::vector<std::vector<double>> &inputSeries) {
//TODO: check vector sizes and reject bad data
int closestSeries = 0;
allCosts.clear();
double lowestCost = dtwClassifiers[0].run(inputSeries);
allCosts.push_back(lowestCost);
for (int i = 1; i < dtwClassifiers.size(); ++i) {
double currentCost = dtwClassifiers[i].run(inputSeries);
allCosts.push_back(currentCost);
if (currentCost < lowestCost) {
lowestCost = currentCost;
closestSeries = i;
}
}
return closestSeries;
};
int seriesClassification::runTrainingSet(const std::vector<trainingExample> &trainingSet) {
std::vector<std::vector<double>> newSeries;
for (int i = 0; i < trainingSet.size(); ++i) {
newSeries.push_back(trainingSet[i].input);
}
return run(newSeries);
};
std::vector<double> seriesClassification::getCosts() {
return allCosts;
}
std::vector<double> seriesClassification::getCosts(const std::vector<trainingExample> &trainingSet) {
runTrainingSet(trainingSet);
return allCosts;
} | 28.815217 | 106 | 0.669181 | [
"vector"
] |
b4c9e623811087cbaa545591112a4ca35867fa4a | 2,492 | cpp | C++ | internal/oboe/oboe_opensles_OutputMixerOpenSLES_android.cpp | CxZMoE/oto | 0466d3057c853eae27a3d73306f25ec8741a7dc3 | [
"Apache-2.0"
] | 1,022 | 2017-05-04T12:18:25.000Z | 2022-03-29T06:57:02.000Z | internal/oboe/oboe_opensles_OutputMixerOpenSLES_android.cpp | CxZMoE/oto | 0466d3057c853eae27a3d73306f25ec8741a7dc3 | [
"Apache-2.0"
] | 146 | 2017-05-04T19:02:03.000Z | 2022-03-24T17:37:10.000Z | internal/oboe/oboe_opensles_OutputMixerOpenSLES_android.cpp | CxZMoE/oto | 0466d3057c853eae27a3d73306f25ec8741a7dc3 | [
"Apache-2.0"
] | 120 | 2017-05-04T22:59:35.000Z | 2022-03-23T11:04:20.000Z | /*
* Copyright 2017 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 "oboe_common_OboeDebug_android.h"
#include "oboe_opensles_EngineOpenSLES_android.h"
#include "oboe_opensles_OpenSLESUtilities_android.h"
#include "oboe_opensles_OutputMixerOpenSLES_android.h"
using namespace oboe;
OutputMixerOpenSL &OutputMixerOpenSL::getInstance() {
static OutputMixerOpenSL sInstance;
return sInstance;
}
SLresult OutputMixerOpenSL::open() {
std::lock_guard<std::mutex> lock(mLock);
SLresult result = SL_RESULT_SUCCESS;
if (mOpenCount++ == 0) {
// get the output mixer
result = EngineOpenSLES::getInstance().createOutputMix(&mOutputMixObject);
if (SL_RESULT_SUCCESS != result) {
LOGE("OutputMixerOpenSL() - createOutputMix() result:%s", getSLErrStr(result));
goto error;
}
// realize the output mix
result = (*mOutputMixObject)->Realize(mOutputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
LOGE("OutputMixerOpenSL() - Realize() mOutputMixObject result:%s", getSLErrStr(result));
goto error;
}
}
return result;
error:
close();
return result;
}
void OutputMixerOpenSL::close() {
std::lock_guard<std::mutex> lock(mLock);
if (--mOpenCount == 0) {
// destroy output mix object, and invalidate all associated interfaces
if (mOutputMixObject != nullptr) {
(*mOutputMixObject)->Destroy(mOutputMixObject);
mOutputMixObject = nullptr;
}
}
}
SLresult OutputMixerOpenSL::createAudioPlayer(SLObjectItf *objectItf,
SLDataSource *audioSource) {
SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, mOutputMixObject};
SLDataSink audioSink = {&loc_outmix, NULL};
return EngineOpenSLES::getInstance().createAudioPlayer(objectItf, audioSource, &audioSink);
}
| 33.226667 | 100 | 0.689005 | [
"object"
] |
b4cfe0400398dbde63b307020cd05f8a069be93e | 731 | hpp | C++ | lib/libcppy/Tools/armatopy.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcppy/Tools/armatopy.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcppy/Tools/armatopy.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #include "Solvers/solver.hpp"
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include "Alat/armadillo.hpp"
namespace bp = boost::python;
namespace np = boost::python::numpy;
/*---------------------------------------------------------------------------*/
namespace simfem
{
struct ArmavecToNumpyConverter{
static PyObject* convert(const alat::armavec& avec);
};
struct ErrorsMapToDictConverter{
static PyObject* convert(const solvers::ErrorsMap& map);
};
alat::armavec numpy_to_armavec(const np::ndarray& y);
boost::python::object armavec_to_numpy(const alat::armavec& v);
arma::mat numpy_to_armamat(const np::ndarray& y);
boost::python::object armamat_to_numpy(const arma::mat& v);
}
| 29.24 | 79 | 0.653899 | [
"object"
] |
b4d2c2ff8ec5ebaec9d811afbe3d548f9847fb00 | 3,285 | cpp | C++ | src/CalibrationSolver.cpp | syntheticmagus/webpiled-opencv-calibration | 329f0090d548e053490cc8050e776b718dea2980 | [
"MIT"
] | 1 | 2021-01-26T13:27:14.000Z | 2021-01-26T13:27:14.000Z | src/CalibrationSolver.cpp | syntheticmagus/webpiled-opencv-calibration | 329f0090d548e053490cc8050e776b718dea2980 | [
"MIT"
] | null | null | null | src/CalibrationSolver.cpp | syntheticmagus/webpiled-opencv-calibration | 329f0090d548e053490cc8050e776b718dea2980 | [
"MIT"
] | null | null | null | #include "CalibrationSolver.h"
#include <opencv2/opencv.hpp>
#include <vector>
namespace
{
struct ChessboardMeasurements
{
float SquareWidthMeters{ 0.005f };
cv::Size BoardDimensionsSquares{ 6, 9 };
};
std::vector<cv::Point3f> getCornerPositions(const ChessboardMeasurements& measurements)
{
std::vector<cv::Point3f> corners{};
corners.reserve(measurements.BoardDimensionsSquares.area());
for (int j = 0; j < measurements.BoardDimensionsSquares.height; j++)
{
for (int i = 0; i < measurements.BoardDimensionsSquares.width; i++)
{
corners.emplace_back(i * measurements.SquareWidthMeters, j * measurements.SquareWidthMeters, 0.f);
}
}
return std::move(corners);
}
}
struct CalibrationSolver::Impl
{
bool AddImage(size_t width, size_t height, void *data);
CalibrationSolver::Calibration SolveForCalibration() const;
private:
ChessboardMeasurements m_measurements{};
std::vector<std::vector<cv::Point2f>> m_foundPoints{};
cv::Size m_frameSize;
};
bool CalibrationSolver::Impl::AddImage(size_t width, size_t height, void *data)
{
cv::Mat image{};
cv::Mat(height, width, CV_8U, data).copyTo(image);
m_foundPoints.emplace_back();
auto& points = m_foundPoints.back();
if (cv::findChessboardCorners(image, m_measurements.BoardDimensionsSquares, points))
{
m_frameSize = image.size();
return true;
}
else
{
m_foundPoints.pop_back();
return false;
}
}
CalibrationSolver::Calibration CalibrationSolver::Impl::SolveForCalibration() const
{
cv::Mat cameraMatrix{ cv::Mat::eye(3, 3, CV_64F) };
cv::Mat distortionCoefficients{};
std::vector<std::vector<cv::Point3f>> worldSpaceCornerPoints;
worldSpaceCornerPoints.resize(m_foundPoints.size(), getCornerPositions(m_measurements));
std::vector<cv::Mat> rVectors;
std::vector<cv::Mat> tVectors;
distortionCoefficients = cv::Mat::zeros(8, 1, CV_64F);
Calibration calibration{};
calibration.FrameWidth = m_frameSize.width;
calibration.FrameHeight = m_frameSize.height;
calibration.AverageReprojectionError = cv::calibrateCamera(worldSpaceCornerPoints, m_foundPoints, m_frameSize, cameraMatrix, distortionCoefficients, rVectors, tVectors);
calibration.Fx = cameraMatrix.at<double>(0, 0);
calibration.Fy = cameraMatrix.at<double>(1, 1);
calibration.Cx = cameraMatrix.at<double>(0, 2);
calibration.Cy = cameraMatrix.at<double>(1, 2);
calibration.K1 = distortionCoefficients.at<double>(0, 0);
calibration.K2 = distortionCoefficients.at<double>(1, 0);
calibration.P1 = distortionCoefficients.at<double>(2, 0);
calibration.P2 = distortionCoefficients.at<double>(3, 0);
calibration.K3 = distortionCoefficients.at<double>(4, 0);
return calibration;
}
CalibrationSolver::CalibrationSolver()
: m_impl{ std::make_unique<Impl>() }
{}
CalibrationSolver::~CalibrationSolver()
{}
bool CalibrationSolver::AddImage(size_t width, size_t height, void *data)
{
return m_impl->AddImage(width, height, data);
}
CalibrationSolver::Calibration CalibrationSolver::SolveForCalibration() const
{
return m_impl->SolveForCalibration();
} | 30.700935 | 173 | 0.696195 | [
"vector"
] |
b4d5051fe092d8e104ddc2bddf618d890dbf37de | 1,661 | cpp | C++ | implementations/LCA_EulerTour.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | 1 | 2019-12-15T22:23:20.000Z | 2019-12-15T22:23:20.000Z | implementations/LCA_EulerTour.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | null | null | null | implementations/LCA_EulerTour.cpp | LeoRiether/Competicao-Programativa | ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 100005; // MaxN = 100005 runs out of stack space :(
const int MaxLog = 18;
vector<vector<int>> adj;
vector<pair<int, int>> et; // Euler tour array
int F[2*MaxN]; // first ocurrence of node i
void eulerDfs(int n, int p, int depth) {
if (!F[n]) F[n] = et.size();
et.emplace_back(depth, n);
for (const auto e : adj[n]) {
if (e == p) continue;
eulerDfs(e, n, depth+1);
et.emplace_back(depth, n);
}
}
int logt[MaxN];
pair<int,int> st[MaxN][MaxLog];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
// Read tree
int n; cin >> n;
adj.resize(n+1);
for (int i = 0; i < n-1; i++) {
int a, b; cin >> a >> b;
adj[a].emplace_back(b);
adj[b].emplace_back(a);
}
// Construct euler tour (assuming 1 as root)
et.reserve(2*n);
eulerDfs(1, 0, 0);
// Preprocess logs
logt[1] = 0;
for (int i = 2; i < MaxN; i++)
logt[i] = logt[i/2] + 1;
// Build sparse table
memset(st, 0, sizeof(st));
for (int i = 0; i < int(et.size()); i++)
st[i][0] = et[i];
for (int k = 1; k < MaxLog; k++) {
for (int i = 0; i < int(et.size()); i++) {
if (i + (1<<(k-1)) < int(et.size()))
st[i][k] = min(st[i][k-1], st[i + (1<<(k-1))][k-1]);
else
st[i][k] = st[i][k-1];
}
}
int x, y;
int l, r;
while (cin >> x >> y) {
if (x < 0 || y < 0) break;
l = F[x]; r = F[y];
int k = logt[r-l+1];
cout << "LCA(" << x << ", " << y << ") = ";
cout << min(st[l][k], st[r - (1<<k) +1][k]).second << endl;
}
return 0;
} | 23.728571 | 69 | 0.482842 | [
"vector"
] |
b4de34c1fd3953f6699f334912fc34254a6f9357 | 6,942 | cpp | C++ | src/compositor/qt/qtwaylandsurfacenode.cpp | thegreatpissant/motorcar | bb12319d37420d4bd2daffddfba68282293af114 | [
"BSD-2-Clause"
] | 1 | 2015-08-25T19:01:17.000Z | 2015-08-25T19:01:17.000Z | src/compositor/qt/qtwaylandsurfacenode.cpp | thegreatpissant/motorcar | bb12319d37420d4bd2daffddfba68282293af114 | [
"BSD-2-Clause"
] | null | null | null | src/compositor/qt/qtwaylandsurfacenode.cpp | thegreatpissant/motorcar | bb12319d37420d4bd2daffddfba68282293af114 | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************
**This file is part of the MotorCar QtWayland Compositor
**
**
**Copyright (C) 2013 Forrest Reiling
**
**
** You may use this file under the terms of the BSD license as follows:
**
** "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
** 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 "qtwaylandsurfacenode.h"
QtwaylandSurfaceNode::QtwaylandSurfaceNode(QObject *parent, QWaylandSurface *surface, glm::mat4 transform):
SceneGraphNode(parent, transform)
{
this->setSurface(surface);
}
QtwaylandSurfaceNode::~QtwaylandSurfaceNode(){}
QWaylandSurface *QtwaylandSurfaceNode::surface() const
{
return m_surface;
}
void QtwaylandSurfaceNode::setSurface(QWaylandSurface *surface)
{
m_surface = surface;
}
bool QtwaylandSurfaceNode::draw(DisplayNode *display)
{
if (m_surface->visible()){
return display->drawSurfaceNode(this);
}else{
return false;
}
}
GLuint QtwaylandSurfaceNode::composeSurface(QWaylandSurface *surface, OpenGLData *glData)
{
glData->m_textureBlitter->bind();
GLuint texture = 0;
QOpenGLFunctions *functions = QOpenGLContext::currentContext()->functions();
functions->glBindFramebuffer(GL_FRAMEBUFFER, glData->m_surface_fbo);
if (surface->type() == QWaylandSurface::Shm) {
texture = glData->m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
} else if (surface->type() == QWaylandSurface::Texture) {
texture = surface->texture(QOpenGLContext::currentContext());
}
functions->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texture, 0);
paintChildren(surface,surface, glData);
functions->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,0, 0);
functions->glBindFramebuffer(GL_FRAMEBUFFER, 0);
glData->m_textureBlitter->release();
return texture;
}
void QtwaylandSurfaceNode::paintChildren(QWaylandSurface *surface, QWaylandSurface *window, OpenGLData *glData) {
if (surface->subSurfaces().size() == 0)
return;
QLinkedListIterator<QWaylandSurface *> i(surface->subSurfaces());
while (i.hasNext()) {
QWaylandSurface *subSurface = i.next();
QPointF p = subSurface->mapTo(window,QPointF(0,0));
if (subSurface->size().isValid()) {
GLuint texture = 0;
if (subSurface->type() == QWaylandSurface::Texture) {
texture = subSurface->texture(QOpenGLContext::currentContext());
} else if (surface->type() == QWaylandSurface::Shm ) {
texture = glData->m_textureCache->bindTexture(QOpenGLContext::currentContext(),surface->image());
}
QRect geo(p.toPoint(),subSurface->size());
glData->m_textureBlitter->drawTexture(texture,geo,window->size(),0,window->isYInverted(),subSurface->isYInverted());
}
paintChildren(subSurface,window, glData);
}
}
void QtwaylandSurfaceNode::computeSurfaceTransform(float ppcm)
{
if(ppcm > 0.0f){
float ppm = ppcm * 100.f;
glm::mat4 surfaceRotation = glm::rotate(glm::mat4(1), 180.0f ,glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 surfaceScale = glm::scale(glm::mat4(1), glm::vec3( m_surface->size().width() / ppm, m_surface->size().height() / ppm, 1.0f));
glm::mat4 surfaceOffset = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f, -0.5f, 0.0f));
m_surfaceTransform = surfaceRotation * surfaceScale * surfaceOffset ;
}
}
QtwaylandSurfaceNode *QtwaylandSurfaceNode::getSurfaceNode(const QWaylandSurface *surface)
{
if(surface == NULL || surface == this->m_surface) {
return this;
}else{
return SceneGraphNode::getSurfaceNode(surface);
}
}
bool QtwaylandSurfaceNode::computeLocalSurfaceIntersection(const Geometry::Ray &localRay, QPointF &localIntersection, float &t) const
{
Geometry::Plane surfacePlane = Geometry::Plane(glm::vec3(0.0f), glm::vec3(0.0f,0.0f,1.0f));
if(glm::dot(localRay.d, surfacePlane.n) == 0) return false;
Geometry::Ray transformedRay = localRay.transform(glm::inverse(surfaceTransform()));
t = surfacePlane.intersect(transformedRay);
glm::vec3 intersection = transformedRay.solve(t);
glm::vec3 coords= intersection * glm::vec3(m_surface->size().width(), m_surface->size().height(), 0);
localIntersection = QPointF(coords.x, coords.y);
return true;
}
SceneGraphNode::RaySurfaceIntersection *QtwaylandSurfaceNode::intersectWithSurfaces(const Geometry::Ray &ray)
{
SceneGraphNode::RaySurfaceIntersection *closestSubtreeIntersection = SceneGraphNode::intersectWithSurfaces(ray);
Geometry::Ray localRay = ray.transform(glm::inverse(transform()));
float t;
QPointF localIntersection;
bool isIntersected = computeLocalSurfaceIntersection(localRay, localIntersection, t);
//qDebug() << "intersection: " << localIntersection ;
if(isIntersected && (closestSubtreeIntersection == NULL || t < closestSubtreeIntersection-> t)){
if(localIntersection.x() >= 0 && localIntersection.x() <= m_surface->size().width() && localIntersection.y() >= 0 && localIntersection.y() <= m_surface->size().height()){
return new SceneGraphNode::RaySurfaceIntersection(this, localIntersection, ray, t);
}else{
return NULL;
}
}else{
return closestSubtreeIntersection;
}
}
glm::mat4 QtwaylandSurfaceNode::surfaceTransform() const
{
return m_surfaceTransform;
}
| 36.15625 | 178 | 0.68064 | [
"geometry",
"transform"
] |
b4e1c0a814508f317091b4999c34ebba7dba116e | 26,137 | cc | C++ | src/ui/scenic/lib/input/input_command_dispatcher.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | src/ui/scenic/lib/input/input_command_dispatcher.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | src/ui/scenic/lib/input/input_command_dispatcher.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/scenic/lib/input/input_command_dispatcher.h"
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <lib/fidl/cpp/clone.h>
#include <lib/fostr/fidl/fuchsia/ui/input/formatting.h>
#include <memory>
#include <vector>
#include <trace/event.h>
#include "src/lib/fxl/logging.h"
#include "src/ui/lib/escher/geometry/types.h"
#include "src/ui/scenic/lib/gfx/engine/hit_accumulator.h"
#include "src/ui/scenic/lib/gfx/resources/compositor/layer_stack.h"
#include "src/ui/scenic/lib/input/helper.h"
#include "src/ui/scenic/lib/input/input_system.h"
#include "src/ui/scenic/lib/scenic/event_reporter.h"
namespace scenic_impl {
namespace input {
using AccessibilityPointerEvent = fuchsia::ui::input::accessibility::PointerEvent;
using FocusChangeStatus = scenic_impl::gfx::ViewTree::FocusChangeStatus;
using InputCommand = fuchsia::ui::input::Command;
using Phase = fuchsia::ui::input::PointerEventPhase;
using ScenicCommand = fuchsia::ui::scenic::Command;
using fuchsia::ui::input::InputEvent;
using fuchsia::ui::input::PointerEvent;
using fuchsia::ui::input::PointerEventType;
using fuchsia::ui::input::SendPointerInputCmd;
namespace {
// TODO(SCN-1278): Remove this.
// Turn two floats (high bits, low bits) into a 64-bit uint.
trace_flow_id_t PointerTraceHACK(float fa, float fb) {
uint32_t ia, ib;
memcpy(&ia, &fa, sizeof(uint32_t));
memcpy(&ib, &fb, sizeof(uint32_t));
return (((uint64_t)ia) << 32) | ib;
}
gfx::LayerStackPtr GetLayerStack(gfx::Engine* engine, GlobalId compositor_id) {
FXL_DCHECK(engine);
gfx::CompositorWeakPtr compositor = engine->scene_graph()->GetCompositor(compositor_id);
FXL_DCHECK(compositor) << "No compositor, violated invariant.";
gfx::LayerStackPtr layer_stack = compositor->layer_stack();
FXL_DCHECK(layer_stack) << "No layer stack, violated invariant.";
return layer_stack;
}
// The x and y values are in device (screen) coordinates.
// The initial dispatch logic guarantees a valid compositor and layer stack.
// NOTE: The accumulated hit structs contain resources that callers should let go of as soon as
// possible.
//
// Only the root presenter creates compositors and sends input commands.
// This invariant means this dispatcher context's session, handling an input
// command, also originally created the compositor.
//
void PerformGlobalHitTest(const gfx::LayerStackPtr& layer_stack, const escher::vec2& pointer,
gfx::HitAccumulator<gfx::ViewHit>* accumulator) {
escher::ray4 ray = CreateScreenPerpendicularRay(pointer.x, pointer.y);
FXL_VLOG(1) << "HitTest: device point (" << ray.origin.x << ", " << ray.origin.y << ")";
layer_stack->HitTest(ray, accumulator);
}
// Helper function to build an AccessibilityPointerEvent when there is a
// registered accessibility listener.
AccessibilityPointerEvent BuildAccessibilityPointerEvent(const PointerEvent& original,
const escher::vec2& ndc_point,
const escher::vec2& local_point,
uint64_t viewref_koid) {
AccessibilityPointerEvent event;
event.set_event_time(original.event_time);
event.set_device_id(original.device_id);
event.set_pointer_id(original.pointer_id);
event.set_type(original.type);
event.set_phase(original.phase);
event.set_ndc_point({ndc_point.x, ndc_point.y});
event.set_viewref_koid(viewref_koid);
if (viewref_koid != ZX_KOID_INVALID) {
event.set_local_point({local_point.x, local_point.y});
}
return event;
}
} // namespace
InputCommandDispatcher::InputCommandDispatcher(scheduling::SessionId session_id,
std::shared_ptr<EventReporter> event_reporter,
gfx::Engine* engine, InputSystem* input_system)
: session_id_(session_id),
event_reporter_(std::move(event_reporter)),
engine_(engine),
input_system_(input_system) {
FXL_CHECK(engine_);
FXL_CHECK(input_system_);
}
void InputCommandDispatcher::DispatchCommand(ScenicCommand command,
scheduling::PresentId present_id) {
TRACE_DURATION("input", "dispatch_command", "command", "ScenicCmd");
FXL_DCHECK(command.Which() == ScenicCommand::Tag::kInput);
InputCommand& input = command.input();
if (input.is_send_keyboard_input()) {
DispatchCommand(input.send_keyboard_input());
} else if (input.is_send_pointer_input()) {
// Compositor and layer stack required for dispatch.
GlobalId compositor_id(session_id_, input.send_pointer_input().compositor_id);
gfx::CompositorWeakPtr compositor = engine_->scene_graph()->GetCompositor(compositor_id);
if (!compositor)
return; // It's legal to race against GFX's compositor setup.
gfx::LayerStackPtr layer_stack = compositor->layer_stack();
if (!layer_stack)
return; // It's legal to race against GFX's layer stack setup.
DispatchCommand(input.send_pointer_input());
} else if (input.is_set_hard_keyboard_delivery()) {
DispatchCommand(input.set_hard_keyboard_delivery());
} else if (input.is_set_parallel_dispatch()) {
DispatchCommand(input.set_parallel_dispatch());
}
}
void InputCommandDispatcher::DispatchCommand(const SendPointerInputCmd& command) {
TRACE_DURATION("input", "dispatch_command", "command", "PointerCmd");
switch (command.pointer_event.type) {
case PointerEventType::TOUCH:
DispatchTouchCommand(command);
break;
case PointerEventType::MOUSE:
DispatchMouseCommand(command);
break;
default:
// TODO(SCN-940), TODO(SCN-164): Stylus support needs to account for HOVER
// events, which need to trigger an additional hit test on the DOWN event
// and send CANCEL events to disassociated clients.
FXL_LOG(INFO) << "Add stylus support.";
break;
}
}
// The touch state machine comprises ADD/DOWN/MOVE*/UP/REMOVE. Some notes:
// - We assume one touchscreen device, and use the device-assigned finger ID.
// - Touch ADD associates the following ADD/DOWN/MOVE*/UP/REMOVE event sequence
// with the set of clients available at that time. To enable gesture
// disambiguation, we perform parallel dispatch to all clients.
// - Touch DOWN triggers a focus change, honoring the "may receive focus" property.
// - Touch REMOVE drops the association between event stream and client.
void InputCommandDispatcher::DispatchTouchCommand(const SendPointerInputCmd& command) {
TRACE_DURATION("input", "dispatch_command", "command", "TouchCmd");
trace_flow_id_t trace_id =
PointerTraceHACK(command.pointer_event.radius_major, command.pointer_event.radius_minor);
TRACE_FLOW_END("input", "dispatch_event_to_scenic", trace_id);
const uint32_t pointer_id = command.pointer_event.pointer_id;
const Phase pointer_phase = command.pointer_event.phase;
const escher::vec2 pointer = PointerCoords(command.pointer_event);
const bool a11y_enabled = ShouldForwardAccessibilityPointerEvents();
FXL_DCHECK(command.pointer_event.type == PointerEventType::TOUCH);
FXL_DCHECK(pointer_phase != Phase::HOVER) << "Oops, touch device had unexpected HOVER event.";
if (pointer_phase == Phase::ADD) {
GlobalId compositor_id(session_id_, command.compositor_id);
gfx::SessionHitAccumulator accumulator;
PerformGlobalHitTest(GetLayerStack(engine_, compositor_id), pointer, &accumulator);
const auto& hits = accumulator.hits();
// Find input targets. Honor the "input masking" view property.
ViewStack hit_views;
{
// Find the transform (input -> view coordinates) for each hit and fill out hit_views.
for (const gfx::ViewHit& hit : hits) {
hit_views.stack.push_back({
hit.view->view_ref_koid(),
hit.view->event_reporter()->GetWeakPtr(),
hit.transform,
});
if (/*TODO(SCN-919): view_id may mask input */ false) {
break;
}
}
}
FXL_VLOG(1) << "View stack of hits: " << hit_views;
// Save targets for consistent delivery of touch events.
touch_targets_[pointer_id] = hit_views;
// If there is an accessibility pointer event listener enabled, an ADD event means that a new
// pointer id stream started. Perform it unconditionally, even if the view stack is empty.
if (a11y_enabled) {
pointer_event_buffer_->AddStream(pointer_id);
}
} else if (pointer_phase == Phase::DOWN) {
// If accessibility listener is on, focus change events must be sent only if
// the stream is rejected. This way, this operation is deferred.
if (!a11y_enabled) {
if (!touch_targets_[pointer_id].stack.empty()) {
// Request that focus be transferred to the top view.
RequestFocusChange(touch_targets_[pointer_id].stack[0].view_ref_koid);
} else if (focus_chain_root() != ZX_KOID_INVALID) {
// The touch event stream has no designated receiver.
// Request that focus be transferred to the root view, so that (1) the currently focused
// view becomes unfocused, and (2) the focus chain remains under control of the root view.
RequestFocusChange(focus_chain_root());
}
}
}
// Input delivery must be parallel; needed for gesture disambiguation.
std::vector<ViewStack::Entry> deferred_event_receivers;
for (const auto& entry : touch_targets_[pointer_id].stack) {
if (a11y_enabled) {
deferred_event_receivers.emplace_back(entry);
} else {
ReportPointerEvent(entry, command.pointer_event);
}
if (!parallel_dispatch_) {
break; // TODO(SCN-1047): Remove when gesture disambiguation is ready.
}
}
FXL_DCHECK(a11y_enabled || deferred_event_receivers.empty())
<< "When a11y pointer forwarding is off, never defer events.";
if (a11y_enabled) {
// We handle both latched (!deferred_event_receivers.empty()) and unlatched
// (deferred_event_receivers.empty()) touch events, for two reasons. (1) We must notify
// accessibility about events regardless of latch, so that it has full
// information about a gesture stream. E.g., the gesture could start traversal in empty
// space before MOVE-ing onto a rect; accessibility needs both the gesture and the rect.
// (2) We must trigger a potential focus change request, even if no view receives the triggering
// DOWN event, so that (a) the focused view receives an unfocus event, and (b) the focus
// chain gets updated and dispatched accordingly.
//
// NOTE: Do not rely on the latched view stack for "top hit" information; elevation can change
// dynamically (it's only guaranteed correct for DOWN). Instead, perform an independent query
// for "top hit".
glm::mat4 view_transform(1.f);
zx_koid_t view_ref_koid = ZX_KOID_INVALID;
GlobalId compositor_id(session_id_, command.compositor_id);
gfx::LayerStackPtr layer_stack = GetLayerStack(engine_, compositor_id);
{
// Find top-hit target and send it to accessibility.
// NOTE: We may hit various mouse cursors (owned by root presenter), but |TopHitAccumulator|
// will keep going until we find a hit with a valid owning View.
gfx::TopHitAccumulator top_hit;
PerformGlobalHitTest(layer_stack, pointer, &top_hit);
if (top_hit.hit()) {
const gfx::ViewHit& hit = *top_hit.hit();
view_transform = hit.transform;
view_ref_koid = hit.view->view_ref_koid();
}
}
const auto ndc = NormalizePointerCoords(pointer, layer_stack);
const auto top_hit_view_local = TransformPointerCoords(pointer, view_transform);
AccessibilityPointerEvent packet = BuildAccessibilityPointerEvent(
command.pointer_event, ndc, top_hit_view_local, view_ref_koid);
pointer_event_buffer_->AddEvent(
pointer_id,
{.event = std::move(command.pointer_event),
.parallel_event_receivers = std::move(deferred_event_receivers)},
std::move(packet));
} else {
input_system_->ReportPointerEventToPointerCaptureListener(command.pointer_event);
}
if (pointer_phase == Phase::REMOVE || pointer_phase == Phase::CANCEL) {
touch_targets_.erase(pointer_id);
}
}
// The mouse state machine is simpler, comprising MOVE*-DOWN/MOVE*/UP-MOVE*. Its
// behavior is similar to touch events, but with some differences.
// - There can be multiple mouse devices, so we track each device individually.
// - Mouse DOWN associates the following DOWN/MOVE*/UP event sequence with one
// particular client: the top-hit View. Mouse events aren't associated with
// gestures, so there is no parallel dispatch.
// - Mouse DOWN triggers a focus change, honoring the "may receive focus" property.
// - Mouse UP drops the association between event stream and client.
// - For an unlatched MOVE event, we perform a hit test, and send the
// top-most client this MOVE event. Focus does not change for unlatched
// MOVEs.
// - The hit test must account for the mouse cursor itself, which today is
// owned by the root presenter. The nodes associated with visible mouse
// cursors(!) do not roll up to any View (as expected), but may appear in the
// hit test; our dispatch needs to account for such behavior.
// TODO(SCN-1078): Enhance trackpad support.
void InputCommandDispatcher::DispatchMouseCommand(const SendPointerInputCmd& command) {
TRACE_DURATION("input", "dispatch_command", "command", "MouseCmd");
const uint32_t device_id = command.pointer_event.device_id;
const Phase pointer_phase = command.pointer_event.phase;
const escher::vec2 pointer = PointerCoords(command.pointer_event);
FXL_DCHECK(command.pointer_event.type == PointerEventType::MOUSE);
FXL_DCHECK(pointer_phase != Phase::ADD && pointer_phase != Phase::REMOVE &&
pointer_phase != Phase::HOVER)
<< "Oops, mouse device (id=" << device_id << ") had an unexpected event: " << pointer_phase;
if (pointer_phase == Phase::DOWN) {
GlobalId compositor_id(session_id_, command.compositor_id);
// Find top-hit target and associated properties.
// NOTE: We may hit various mouse cursors (owned by root presenter), but |TopHitAccumulator|
// will keep going until we find a hit with a valid owning View.
gfx::TopHitAccumulator top_hit;
PerformGlobalHitTest(GetLayerStack(engine_, compositor_id), pointer, &top_hit);
ViewStack hit_view;
if (top_hit.hit()) {
const gfx::ViewHit& hit = *top_hit.hit();
hit_view.stack.push_back({
hit.view->view_ref_koid(),
hit.view->event_reporter()->GetWeakPtr(),
hit.transform,
});
}
FXL_VLOG(1) << "View hit: " << hit_view;
if (!hit_view.stack.empty()) {
// Request that focus be transferred to the top view.
RequestFocusChange(hit_view.stack[0].view_ref_koid);
} else if (focus_chain_root() != ZX_KOID_INVALID) {
// The mouse event stream has no designated receiver.
// Request that focus be transferred to the root view, so that (1) the currently focused view
// becomes unfocused, and (2) the focus chain remains under control of the root view.
RequestFocusChange(focus_chain_root());
}
// Save target for consistent delivery of mouse events.
mouse_targets_[device_id] = hit_view;
}
if (mouse_targets_.count(device_id) > 0 && // Tracking this device, and
mouse_targets_[device_id].stack.size() > 0) { // target view exists.
const auto& entry = mouse_targets_[device_id].stack[0];
PointerEvent clone;
fidl::Clone(command.pointer_event, &clone);
ReportPointerEvent(entry, std::move(clone));
}
if (pointer_phase == Phase::UP || pointer_phase == Phase::CANCEL) {
mouse_targets_.erase(device_id);
}
// Deal with unlatched MOVE events.
if (pointer_phase == Phase::MOVE && mouse_targets_.count(device_id) == 0) {
GlobalId compositor_id(session_id_, command.compositor_id);
// Find top-hit target and send it this move event.
// NOTE: We may hit various mouse cursors (owned by root presenter), but |TopHitAccumulator|
// will keep going until we find a hit with a valid owning View.
gfx::TopHitAccumulator top_hit;
PerformGlobalHitTest(GetLayerStack(engine_, compositor_id), pointer, &top_hit);
if (top_hit.hit()) {
const gfx::ViewHit& hit = *top_hit.hit();
ViewStack::Entry view_info;
view_info.reporter = hit.view->event_reporter()->GetWeakPtr();
view_info.transform = hit.transform;
PointerEvent clone;
fidl::Clone(command.pointer_event, &clone);
ReportPointerEvent(view_info, std::move(clone));
}
}
}
void InputCommandDispatcher::DispatchCommand(
const fuchsia::ui::input::SendKeyboardInputCmd& command) {
TRACE_DURATION("input", "dispatch_command", "command", "SendKeyboardInputCmd");
// Expected (but soon to be deprecated) event flow.
ReportToImeService(input_system_->ime_service(), command.keyboard_event);
// Unusual: Clients may have requested direct delivery when focused.
const zx_koid_t focused_view = focus();
if (focused_view == ZX_KOID_INVALID)
return; // No receiver.
const scenic_impl::gfx::ViewTree& view_tree = engine_->scene_graph()->view_tree();
EventReporterWeakPtr reporter = view_tree.EventReporterOf(focused_view);
scheduling::SessionId session_id = view_tree.SessionIdOf(focused_view);
if (reporter && input_system_->hard_keyboard_requested().count(session_id) > 0) {
ReportKeyboardEvent(reporter.get(), command.keyboard_event);
}
}
void InputCommandDispatcher::DispatchCommand(
const fuchsia::ui::input::SetHardKeyboardDeliveryCmd& command) {
// Can't easily retrieve owning view's ViewRef KOID from just the Session or SessionId.
FXL_VLOG(2) << "Hard keyboard events, session_id=" << session_id_
<< ", delivery_request=" << (command.delivery_request ? "on" : "off");
if (command.delivery_request) {
// Take this opportunity to remove dead sessions.
std::vector<scheduling::SessionId> dead_sessions;
for (auto& reporter : input_system_->hard_keyboard_requested()) {
if (!reporter.second) {
dead_sessions.push_back(reporter.first);
}
}
for (auto session_ids : dead_sessions) {
input_system_->hard_keyboard_requested().erase(session_id_);
}
// This code assumes one event reporter per session id.
FXL_DCHECK(input_system_->hard_keyboard_requested().count(session_id_) == 0);
if (event_reporter_)
input_system_->hard_keyboard_requested().insert({session_id_, event_reporter_->GetWeakPtr()});
} else {
input_system_->hard_keyboard_requested().erase(session_id_);
}
}
void InputCommandDispatcher::DispatchCommand(
const fuchsia::ui::input::SetParallelDispatchCmd& command) {
TRACE_DURATION("input", "dispatch_command", "command", "SetParallelDispatchCmd");
FXL_LOG(INFO) << "Scenic: Parallel dispatch is turned "
<< (command.parallel_dispatch ? "ON" : "OFF");
parallel_dispatch_ = command.parallel_dispatch;
}
void InputCommandDispatcher::DispatchDeferredPointerEvent(
PointerEventBuffer::DeferredPointerEvent views_and_event) {
// If this parallel dispatch of events corresponds to a DOWN event, this
// triggers a possible deferred focus change event.
if (views_and_event.event.phase == fuchsia::ui::input::PointerEventPhase::DOWN) {
if (!views_and_event.parallel_event_receivers.empty()) {
// Request that focus be transferred to the top view.
const zx_koid_t view_koid = views_and_event.parallel_event_receivers[0].view_ref_koid;
FXL_DCHECK(view_koid != ZX_KOID_INVALID) << "invariant";
RequestFocusChange(view_koid);
} else if (focus_chain_root() != ZX_KOID_INVALID) {
// The touch event stream has no designated receiver.
// Request that focus be transferred to the root view, so that (1) the currently focused
// view becomes unfocused, and (2) the focus chain remains under control of the root view.
RequestFocusChange(focus_chain_root());
}
}
input_system_->ReportPointerEventToPointerCaptureListener(views_and_event.event);
for (auto& view : views_and_event.parallel_event_receivers) {
ReportPointerEvent(view, views_and_event.event);
}
}
void InputCommandDispatcher::ReportPointerEvent(const ViewStack::Entry& view_info,
const PointerEvent& pointer) {
if (!view_info.reporter)
return; // Session's event reporter no longer available. Bail quietly.
TRACE_DURATION("input", "dispatch_event_to_client", "event_type", "pointer");
trace_flow_id_t trace_id = PointerTraceHACK(pointer.radius_major, pointer.radius_minor);
TRACE_FLOW_BEGIN("input", "dispatch_event_to_client", trace_id);
InputEvent event;
event.set_pointer(BuildLocalPointerEvent(pointer, view_info.transform));
view_info.reporter->EnqueueEvent(std::move(event));
}
void InputCommandDispatcher::ReportKeyboardEvent(EventReporter* reporter,
fuchsia::ui::input::KeyboardEvent keyboard) {
FXL_DCHECK(reporter) << "precondition";
InputEvent event;
event.set_keyboard(std::move(keyboard));
reporter->EnqueueEvent(std::move(event));
}
void InputCommandDispatcher::ReportToImeService(
const fuchsia::ui::input::ImeServicePtr& ime_service,
fuchsia::ui::input::KeyboardEvent keyboard) {
TRACE_DURATION("input", "dispatch_event_to_client", "event_type", "ime_keyboard_event");
if (ime_service && ime_service.is_bound()) {
InputEvent event;
event.set_keyboard(std::move(keyboard));
ime_service->InjectInput(std::move(event));
}
}
zx_koid_t InputCommandDispatcher::focus() const {
if (!engine_->scene_graph())
return ZX_KOID_INVALID; // No scene graph, no view tree, no focus chain.
const auto& chain = engine_->scene_graph()->view_tree().focus_chain();
if (chain.empty())
return ZX_KOID_INVALID; // Scene not present, or scene not connected to compositor.
const zx_koid_t focused_view = chain.back();
FXL_DCHECK(focused_view != ZX_KOID_INVALID) << "invariant";
return focused_view;
}
zx_koid_t InputCommandDispatcher::focus_chain_root() const {
if (!engine_->scene_graph())
return ZX_KOID_INVALID; // No scene graph, no view tree, no focus chain.
const auto& chain = engine_->scene_graph()->view_tree().focus_chain();
if (chain.empty())
return ZX_KOID_INVALID; // Scene not present, or scene not connected to compositor.
const zx_koid_t root_view = chain.front();
FXL_DCHECK(root_view != ZX_KOID_INVALID) << "invariant";
return root_view;
}
bool InputCommandDispatcher::ShouldForwardAccessibilityPointerEvents() {
if (input_system_->IsAccessibilityPointerEventForwardingEnabled()) {
// If the buffer was not initialized yet, perform the following sanity
// check: make sure to send active pointer event streams to their final
// location and do not send them to the a11y listener.
if (!pointer_event_buffer_) {
pointer_event_buffer_ = std::make_unique<PointerEventBuffer>(
/* DispatchEventFunction */
[this](PointerEventBuffer::DeferredPointerEvent views_and_event) {
DispatchDeferredPointerEvent(std::move(views_and_event));
},
/* ReportAccessibilityEventFunction */
[input_system = input_system_](fuchsia::ui::input::accessibility::PointerEvent pointer) {
input_system->accessibility_pointer_event_listener()->OnEvent(std::move(pointer));
});
for (const auto& kv : touch_targets_) {
// Force a reject in all active pointer IDs. When a new stream arrives,
// they will automatically be sent for the a11y listener decide
// what to do with them as the status will change to WAITING_RESPONSE.
pointer_event_buffer_->SetActiveStreamInfo(
/*pointer_id=*/kv.first, PointerEventBuffer::PointerIdStreamStatus::REJECTED);
}
// Registers an event handler for this listener. This callback captures a pointer to the event
// buffer that we own, so we need to clear it before we destroy it (see below).
input_system_->accessibility_pointer_event_listener().events().OnStreamHandled =
[buffer = pointer_event_buffer_.get()](
uint32_t device_id, uint32_t pointer_id,
fuchsia::ui::input::accessibility::EventHandling handled) {
buffer->UpdateStream(pointer_id, handled);
};
}
return true;
} else if (pointer_event_buffer_) {
// The listener disconnected. Release held events, delete the buffer.
input_system_->accessibility_pointer_event_listener().events().OnStreamHandled = nullptr;
pointer_event_buffer_.reset();
}
return false;
}
void InputCommandDispatcher::RequestFocusChange(zx_koid_t view) {
FXL_DCHECK(view != ZX_KOID_INVALID) << "precondition";
if (!engine_->scene_graph())
return; // No scene graph, no view tree, no focus chain.
if (engine_->scene_graph()->view_tree().focus_chain().empty())
return; // Scene not present, or scene not connected to compositor.
// Input system acts on authority of top-most view.
const zx_koid_t requestor = engine_->scene_graph()->view_tree().focus_chain()[0];
auto status = engine_->scene_graph()->RequestFocusChange(requestor, view);
FXL_VLOG(1) << "Scenic RequestFocusChange. Authority: " << requestor << ", request: " << view
<< ", status: " << static_cast<int>(status);
FXL_DCHECK(status == FocusChangeStatus::kAccept ||
status == FocusChangeStatus::kErrorRequestCannotReceiveFocus)
<< "User has authority to request focus change, but the only valid rejection is when the "
"requested view may not receive focus. Error code: "
<< static_cast<int>(status);
}
} // namespace input
} // namespace scenic_impl
| 43.78057 | 100 | 0.709798 | [
"geometry",
"vector",
"transform"
] |
b4e326619c3f86b642b9285d313972b9a84a2262 | 4,767 | cpp | C++ | elfreader.cpp | NMSU-PLEASE-Lab/ELFReader | f4fbb76ad7269451e75e21a5c1212a6b440d3ba5 | [
"MIT"
] | null | null | null | elfreader.cpp | NMSU-PLEASE-Lab/ELFReader | f4fbb76ad7269451e75e21a5c1212a6b440d3ba5 | [
"MIT"
] | null | null | null | elfreader.cpp | NMSU-PLEASE-Lab/ELFReader | f4fbb76ad7269451e75e21a5c1212a6b440d3ba5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <elf.h>
#include <dlfcn.h>
#include <ElfProgram.h>
//
// Get all definitions and uses of a program symbol, and
// print their information. A symbol can have multiple
// definitions, as long as one is regular and others are
// weak (or if some libs have been PRELOADed or dynamically
// loaded).
//
void printSymbolDU(ProgramInfo* pInfo, char* symbol)
{
ElfSymbol *sym, **defs, **uses;
int i, dcount, ucount;
defs = pInfo->findSymbolDefinitions(symbol,&dcount);
uses = pInfo->findSymbolUses(symbol,&ucount);
printf("(%s) has %u defs and %u uses\n",symbol, dcount,ucount);
for (i=0; i<dcount; i++)
{
sym = defs[i];
printf(" D:(%s) Raw=%8.8x PLT=%p GOT=%p (%p) in (%s)\n",
sym->getName(), sym->getRawValue(),
sym->getPLTEntryAddress(), sym->getGOTEntryAddress(),
sym->getSymbolAddress(),
sym->getLoadObject()->getName());
printf(" Bind=%2.2d Type=%2.2d I=%2.2d Size=%d Other=%d\n",
sym->getBind(), sym->getType(),
(sym->getSHIndex()==65521)?99:sym->getSHIndex(),
sym->getSize(), sym->getOther());
}
for (i=0; i<ucount; i++)
{
sym = uses[i];
printf(" U:(%s) Raw=%8.8x PLT=%p GOT=%p (%p) in (%s)\n",
sym->getName(), sym->getRawValue(),
sym->getPLTEntryAddress(), sym->getGOTEntryAddress(),
sym->getSymbolAddress(),
sym->getLoadObject()->getName());
printf(" Bind=%2.2d Type=%2.2d I=%2.2d Size=%d Other=%d\n",
sym->getBind(), sym->getType(),
(sym->getSHIndex()==65521)?99:sym->getSHIndex(),
sym->getSize(), sym->getOther());
}
}
//
// Main
//
int main(int argc, char **argv)
{
ProgramInfo *pInfo;
LoadObject *lo;
ElfSymbol *sym;
unsigned int iter;
//int i;
void *p1;
void *p2;
//
// get some sample function pointers and print values
//
//p1 = (void*) &printf; // will point to PLT entry, not actual function
p1 = 0;
p2 = (void*) &fopen;
printf("(printf)=%p, fopen=%p\n",p1,p2);
//
// because of statements above, getting printf through dlsym will
// also return PLT entry. If statements above are missing, dlsym will
// return the actual function address.
p1 = (void*) dlsym(0,"printf");
printf("(printf)-dl=%p\n",p1);
//
// Create new ProgramInfo object -- this triggers and entire reading
// of the ELF info for all loaded objects
//
pInfo = new ProgramInfo();
//pInfo->debugPrintInfo();
//
// iterate over all loaded objects and print out all
// dynamic symbols (currently disabled by while (0))
//
lo = pInfo->loadedObjects;
while (0) //(lo)
{
printf("Loaded Object: %s\n", lo->getName());
sym = lo->startDynamicSymbolIter(&iter);
while (sym)
{
// uncomment to just get code symbols
//(sym->isDataObject() || sym->isCodeObject())
{
printf(" (%s) Raw=%8.8x PLT=%p GOT=%p\n",
sym->getName(), sym->getRawValue(),
sym->getPLTEntryAddress(), sym->getGOTEntryAddress());
printf(" Bind=%2.2d Type=%2.2d I=%2.2d Size=%d Other=%d\n",
sym->getBind(), sym->getType(),
(sym->getSHIndex()==65521)?99:sym->getSHIndex(),
sym->getSize(), sym->getOther());
}
sym = lo->nextDynamicSymbolIter(&iter);
}
lo = lo->next;
}
//
// iterate over all loaded objects and print out all
// static symbols NOT(currently disabled by while (0))
//
lo = pInfo->loadedObjects;
while (lo)
{
printf("Loaded Object: %s\n", lo->getName());
sym = lo->startStaticSymbolIter(&iter);
while (sym)
{
// uncomment to just get code symbols
//(sym->isDataObject() || sym->isCodeObject())
{
printf(" (%s) Raw=%8.8x PLT=%p GOT=%p\n",
sym->getName(), sym->getRawValue(),
sym->getPLTEntryAddress(), sym->getGOTEntryAddress());
printf(" Bind=%2.2d Type=%2.2d I=%2.2d Size=%d Other=%d\n",
sym->getBind(), sym->getType(),
(sym->getSHIndex()==65521)?99:sym->getSHIndex(),
sym->getSize(), sym->getOther());
}
sym = lo->nextStaticSymbolIter(&iter);
}
lo = lo->next;
}
//
// See function definition above main()
//
printSymbolDU(pInfo, "printf");
printSymbolDU(pInfo, "malloc");
printSymbolDU(pInfo, "fopen");
printSymbolDU(pInfo, "stdout");
printSymbolDU(pInfo, "__gmon_start__");
delete pInfo;
return 0;
}
| 31.569536 | 75 | 0.552129 | [
"object"
] |
b4e8c77e5e36e16d8fc10951c4a816c669e3c226 | 4,035 | cpp | C++ | tests/core_tests/ta_apply_delta_record_8u.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | tests/core_tests/ta_apply_delta_record_8u.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | tests/core_tests/ta_apply_delta_record_8u.cpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | 1 | 2022-03-28T07:52:21.000Z | 2022-03-28T07:52:21.000Z | /*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
/**
* @brief Contain test to check @ref dmlc_apply_delta_record_8u
* @details Test list:
* - @ref ta_apply_delta_record_format
* - @ref ta_apply_delta_record_large_offset
* - @ref ta_apply_delta_record_cross
*
* @date 2/25/2020
*/
#include "t_delta_record_feature_defines.hpp"
#include "t_random_generator.hpp"
#include <optimization_dispatcher.hpp>
/**
* @brief Tests what delta record apply is a works correctly in accordance with format
*/
auto ta_apply_delta_record_format() -> void
{
// Seed
const auto seed = test_system::get_seed();
// Randomizers
dml::test::random_t<uint8_t> random_byte(seed);
// Constants
constexpr auto vector_size = DELTA_DATA_FIELD_SIZE;
constexpr auto delta_record_size = DELTA_NOTE_BYTE_SIZE;
// Variables
std::vector<uint8_t> base_array(vector_size);
std::vector<uint8_t> mismatched_array(vector_size);
std::vector<uint8_t> delta_record(delta_record_size);
// Vectors init
std::generate(base_array.begin(), base_array.end(), random_byte);
for (std::size_t i = 0u; i < DELTA_DATA_FIELD_SIZE; i++)
{
const auto pattern = base_array[i];
const auto anti_pattern = ~pattern;
mismatched_array[i] = anti_pattern;
}
// Create Delta note.
// 1. Zero Offset set.
delta_record[0] = 0u;
delta_record[1] = 0u;
// 2. Write deltas.
for (std::size_t j = 0u; j < DELTA_DATA_FIELD_SIZE; j++)
{
delta_record[j + sizeof(offset_t)] = base_array[j];
}
// Apply delta record
dml::core::dispatch::apply_delta(delta_record.data(), mismatched_array.data(), delta_record_size);
ASSERT_EQ(base_array, mismatched_array);
}
CORE_TEST_REGISTER(apply_delta_record_8u, ta_apply_delta_record_format);
/**
* @brief Tests what delta record functions works correctly in pair
*/
auto ta_apply_delta_record_cross() -> void
{
// Seed
const auto seed = test_system::get_seed();
const auto pattern_count_range = REGIONS_COUNT;
// Randomizers
dml::test::random_t<uint8_t> random_byte(seed);
dml::test::random_t<uint32_t> random_pattern_count(pattern_count_range, seed);
// Constants
const auto data_regions_count = random_pattern_count.get_next();
const auto vector_size = DELTA_DATA_FIELD_SIZE * data_regions_count;
const auto delta_record_max_size = DELTA_NOTE_BYTE_SIZE * data_regions_count;
// Variables
std::vector<uint8_t> base_vector(vector_size);
std::vector<uint8_t> mismatched_vector(base_vector);
std::vector<uint8_t> delta_record_vector(delta_record_max_size);
// Vectors init
std::generate(base_vector.begin(), base_vector.end(), random_byte);
for (std::size_t i = 0u; i < base_vector.size(); i++)
{
const auto pattern = base_vector[i];
const auto anti_pattern = ~pattern;
mismatched_vector[i] = anti_pattern;
}
// Create delta record
const auto [delta_record_size, result] = dml::core::dispatch::create_delta(mismatched_vector.data(),
base_vector.data(),
vector_size,
delta_record_vector.data(),
delta_record_max_size);
ASSERT_EQ(result, 1);
ASSERT_EQ(delta_record_max_size, delta_record_size);
// Apply delta record
dml::core::dispatch::apply_delta(delta_record_vector.data(), mismatched_vector.data(), delta_record_size);
ASSERT_EQ(base_vector, mismatched_vector);
}
CORE_TEST_REGISTER(apply_delta_record_8u, ta_apply_delta_record_cross);
| 33.907563 | 110 | 0.624535 | [
"vector"
] |
b4e922c3e622f95a7114ab87e9787aa17b0a233d | 1,420 | cc | C++ | vos/gui/sub/gui/histspike/KeyInSpikeInterface.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/gui/sub/gui/histspike/KeyInSpikeInterface.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/gui/sub/gui/histspike/KeyInSpikeInterface.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | //////////////////////////////////////////////////////////////
// KeyInSpikeInterface.C: An KeyIn interface to a Cmd object
///////////////////////////////////////////////////////////////
#include "KeyInSpikeInterface.h"
#include "Cmd.h"
#include "KeyinView.h"
#include "stdlib.h"
#include "stdio.h"
#include <iostream>
#include <stdint.h>
using namespace std;
#include <Xm/RowColumn.h>
KeyInSpikeInterface::KeyInSpikeInterface ( Widget parent,
Cmd *cmd ) : CmdInterface ( cmd )
{
_w = XtCreateManagedWidget(_name, xmRowColumnWidgetClass, parent,
NULL, 0 );
installDestroyHandler();
_spike = addOneSubView(_w, "SpikeValue:");
setValue(_cmd->getValue());
}
KeyInSpikeInterface::~KeyInSpikeInterface ()
{
delete _spike;
}
KeyinView *KeyInSpikeInterface::addOneSubView (Widget parent, const char *name)
{
KeyinView *view = new KeyinView(parent, name);
view->manage();
view->installCallback(&CmdInterface::executeCmdCallback, (XtPointer)this);
return view;
}
void KeyInSpikeInterface::executeCmd(XtPointer)
{
char *_strValue;
int _intValue;
_strValue = _spike->getFieldValue();
_intValue = atoi(_strValue);
XtFree(_strValue);
runCmd((CmdValue) (uintptr_t) _intValue);
}
void KeyInSpikeInterface::setValue(CmdValue value)
{
char _strValue[20];
int _intValue = (int) (uintptr_t)value;
sprintf(_strValue, "%d", _intValue);
_spike->setFieldValue(_strValue);
}
| 23.666667 | 79 | 0.660563 | [
"object"
] |
b4ec332658dc0254e3aaed83de7d9da540546711 | 4,777 | cxx | C++ | src/ttbarReco.cxx | demarley/goldilocks | 97e790a1263fe7952d25c3a7a41bc0ca16f2d558 | [
"MIT"
] | null | null | null | src/ttbarReco.cxx | demarley/goldilocks | 97e790a1263fe7952d25c3a7a41bc0ca16f2d558 | [
"MIT"
] | 5 | 2018-05-28T20:37:34.000Z | 2018-09-21T20:20:12.000Z | src/ttbarReco.cxx | demarley/goldilocks | 97e790a1263fe7952d25c3a7a41bc0ca16f2d558 | [
"MIT"
] | null | null | null | /*
Created: 19 February 2018
Last Updated: 19 May 2018
Dan Marley
daniel.edison.marley@cernSPAMNOT.ch
Texas A&M University
-----
Tool for performing deep learning tasks
*/
#include "Analysis/goldilocks/interface/ttbarReco.h"
ttbarReco::ttbarReco( configuration& cmaConfig ) :
m_config(&cmaConfig){
m_targetMap = m_config->mapOfTargetValues();
}
ttbarReco::~ttbarReco() {}
void ttbarReco::execute(const std::vector<Jet>& jets, const std::vector<Ljet>& ljets){
/* Build top quarks system
Testing semi-resolved tagger; only interested in AK8(QB/W)+AK4
0 :: NONE = QCD (background)
1 :: QB-Q = Signal AK8(QB) + AK4(Q)
2 :: QQ-B = Signal AK8(W) + AK4(B)
3 :: FULL = Signal AK8
4 :: QQ+X/QB+X (Other = pseudo-signal)
-- if (fully contained): top_cand.target = 'full'; no extra AK4 needed
-- if (q/b-only) top_cand.target = 4; need two extra AK4 -> this is effectively the 'fully resolved' case
*/
m_ttbar.clear();
m_jets = jets;
m_ljets = ljets;
// Reconstruct ttbar, define containment
bool isQCD(m_config->isQCD());
bool isTtbar(m_config->isTtbar());
unsigned int target(4);
cma::DEBUG("TTBARRECO : building ttbar with "+std::to_string(m_ljets.size())+" ak8 candidates");
for (const auto& ljet : ljets){
// Overlap Removal (subtract AK4 if matched to AK8 subjet)
std::vector<Jet> ak4candidates;
overlapRemoval(ljet,ak4candidates,isTtbar); // overlap removal of AK4 from AK8
int absLjetCt = std::abs(ljet.containment);
cma::DEBUG("TTBARRECO : Access AK8 jet matched to parton "+std::to_string(ljet.matchId)+"; containment = "+std::to_string(absLjetCt));
for (const auto& jet : ak4candidates){
Top top_cand; // reconstructed top candidates
top_cand.isGood = false;
top_cand.jets.clear();
top_cand.ljet = ljet.index;
if (isTtbar && (absLjetCt==BQ || absLjetCt==W)){
cma::DEBUG("TTBARRECO : -- AK8 that is QB or W");
int total_containment = jet.containment+ljet.containment;
if (total_containment==FULL || total_containment==-FULL){
cma::DEBUG("TTBARRECO : AK8+AK4 top in ttbar");
target = (absLjetCt==BQ) ? m_targetMap.at("BQ") : m_targetMap.at("W");
}
else{
cma::DEBUG("TTBARRECO : AK8+AK4 background combo in ttbar");
target = m_targetMap.at("ttbckg");
}
} // end if ljet is QB or W
else if (isQCD){
// Just assign AK8+AK4 jets as background (target 0)
target = m_targetMap.at("none");
} // end if QCD
else continue; // only want specific ttbar scenarios & qcd
top_cand.jets.push_back(jet.index);
top_cand.p4 = (jet.p4+ljet.p4);
top_cand.target = target;
// Require 'good' candidates to have:
// -- 0.8 < DeltaR(AK4,AK8) < 4
// -- 40 < (AK8+AK4).M() < 400 GeV
// this should reduce the size of output QCD files...
float deltaR = jet.p4.DeltaR(ljet.p4);
float mass = top_cand.p4.M();
if ( deltaR>0.8 && deltaR<4.0 &&
mass >40. && mass < 400. ){
top_cand.isGood = true;
m_ttbar.push_back( top_cand );
}
} // end loop over AK4
} // end loop over ak8 candidates
cma::DEBUG("TTBARRECO : Ttbar built ");
return;
}
void ttbarReco::overlapRemoval(const Ljet& ak8, std::vector<Jet>& new_objects, const bool isTtbar){
/*
Remove AK4 jets that overlap with AK8 candidate
'match_truth' for checking the AK4 and AK8 match the same parton
*/
new_objects.clear();
for (const auto& jet : m_jets){
unsigned int dRmatch(0);
// Don't use an AK4 jet that matches to the same individual parton (q,q,b) as the AK8
unsigned int n_parton_overlaps(0);
if (isTtbar){
for (const auto& tp : jet.truth_partons){
if (std::find(ak8.truth_partons.begin(), ak8.truth_partons.end(), tp) != ak8.truth_partons.end()) n_parton_overlaps++;
}
}
if (n_parton_overlaps>0) continue;
if (ak8.subjets.size()<1) // match directly to AK8 if there are no subjets
dRmatch = cma::deltaRMatch(ak8.p4, jet.p4, ak8.radius);
else{
for (const auto& sj : ak8.subjets)
dRmatch += cma::deltaRMatch(sj.p4, jet.p4, sj.radius);
}
if (dRmatch<1) new_objects.push_back( jet );
}
return;
}
// THE END //
| 33.405594 | 142 | 0.572326 | [
"vector"
] |
b4f8ad03940aace14ed0a2836a5c3999866222bc | 331 | hxx | C++ | src/Tools/Algo/Draw_generator/Event_generator/Event_generator.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | src/Tools/Algo/Draw_generator/Event_generator/Event_generator.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | src/Tools/Algo/Draw_generator/Event_generator/Event_generator.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | #include "Tools/Algo/Draw_generator/Event_generator/Event_generator.hpp"
namespace aff3ct
{
namespace tools
{
template <typename R, typename E>
template <class A>
void Event_generator<R,E>::generate(std::vector<E,A> &draw, const R event_probability)
{
this->generate(draw.data(), (unsigned)draw.size(), event_probability);
}
}
}
| 22.066667 | 86 | 0.761329 | [
"vector"
] |
b4fc0f5d8d82490ce60b167999229556b37d3fe5 | 9,587 | cpp | C++ | rmidevice/rmidevice.cpp | synasnoguchi/rmi4utils | 5932feea90ff953f589a67b31a71e46bb1df42a6 | [
"Apache-2.0"
] | 1 | 2015-04-24T12:56:21.000Z | 2015-04-24T12:56:21.000Z | rmidevice/rmidevice.cpp | synasnoguchi/rmi4utils | 5932feea90ff953f589a67b31a71e46bb1df42a6 | [
"Apache-2.0"
] | null | null | null | rmidevice/rmidevice.cpp | synasnoguchi/rmi4utils | 5932feea90ff953f589a67b31a71e46bb1df42a6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "rmidevice.h"
#define RMI_DEVICE_PDT_ENTRY_SIZE 6
#define RMI_DEVICE_PAGE_SELECT_REGISTER 0xFF
#define RMI_DEVICE_MAX_PAGE 0xFF
#define RMI_DEVICE_PAGE_SIZE 0x100
#define RMI_DEVICE_PAGE_SCAN_START 0x00e9
#define RMI_DEVICE_PAGE_SCAN_END 0x0005
#define RMI_DEVICE_F01_BASIC_QUERY_LEN 11
#define RMI_DEVICE_F01_QRY5_YEAR_MASK 0x1f
#define RMI_DEVICE_F01_QRY6_MONTH_MASK 0x0f
#define RMI_DEVICE_F01_QRY7_DAY_MASK 0x1f
#define RMI_DEVICE_F01_QRY1_HAS_LTS (1 << 2)
#define RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID (1 << 3)
#define RMI_DEVICE_F01_QRY1_HAS_CHARGER_INP (1 << 4)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE (1 << 5)
#define RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF (1 << 6)
#define RMI_DEVICE_F01_QRY1_HAS_PROPS_2 (1 << 7)
#define RMI_DEVICE_F01_LTS_RESERVED_SIZE 19
#define RMI_DEVICE_F01_QRY42_DS4_QUERIES (1 << 0)
#define RMI_DEVICE_F01_QRY42_MULTI_PHYS (1 << 1)
#define RMI_DEVICE_F01_QRY43_01_PACKAGE_ID (1 << 0)
#define RMI_DEVICE_F01_QRY43_01_BUILD_ID (1 << 1)
#define PACKAGE_ID_BYTES 4
#define BUILD_ID_BYTES 3
#define RMI_F01_CMD_DEVICE_RESET 1
#define RMI_F01_DEFAULT_RESET_DELAY_MS 100
int RMIDevice::SetRMIPage(unsigned char page)
{
int rc;
if (m_page == page)
return 0;
m_page = page;
rc = Write(RMI_DEVICE_PAGE_SELECT_REGISTER, &page, 1);
if (rc < 0) {
m_page = -1;
return rc;
}
return 0;
}
int RMIDevice::QueryBasicProperties()
{
int rc;
unsigned char basicQuery[RMI_DEVICE_F01_BASIC_QUERY_LEN];
unsigned short queryAddr;
unsigned char infoBuf[4];
unsigned short prodInfoAddr;
RMIFunction f01;
SetRMIPage(0x00);
if (GetFunction(f01, 1)) {
queryAddr = f01.GetQueryBase();
rc = Read(queryAddr, basicQuery, RMI_DEVICE_F01_BASIC_QUERY_LEN);
if (rc < 0) {
fprintf(stderr, "Failed to read the basic query: %s\n", strerror(errno));
return rc;
}
m_manufacturerID = basicQuery[0];
m_hasLTS = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_LTS;
m_hasSensorID = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_SENSOR_ID;
m_hasAdjustableDoze = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE;
m_hasAdjustableDozeHoldoff = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_ADJ_DOZE_HOFF;
m_hasQuery42 = basicQuery[1] & RMI_DEVICE_F01_QRY1_HAS_PROPS_2;
m_firmwareVersionMajor = basicQuery[2];
m_firmwareVersionMinor = basicQuery[3];
snprintf(m_dom, sizeof(m_dom), "20%02d/%02d/%02d",
basicQuery[5] & RMI_DEVICE_F01_QRY5_YEAR_MASK,
basicQuery[6] & RMI_DEVICE_F01_QRY6_MONTH_MASK,
basicQuery[7] & RMI_DEVICE_F01_QRY7_DAY_MASK);
queryAddr += 11;
rc = Read(queryAddr, m_productID, RMI_PRODUCT_ID_LENGTH);
if (rc < 0) {
fprintf(stderr, "Failed to read the product id: %s\n", strerror(errno));
return rc;
}
m_productID[RMI_PRODUCT_ID_LENGTH] = '\0';
prodInfoAddr = queryAddr + 6;
queryAddr += 10;
if (m_hasLTS)
++queryAddr;
if (m_hasSensorID) {
rc = Read(queryAddr++, &m_sensorID, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read sensor id: %s\n", strerror(errno));
return rc;
}
}
if (m_hasLTS)
queryAddr += RMI_DEVICE_F01_LTS_RESERVED_SIZE;
if (m_hasQuery42) {
rc = Read(queryAddr++, infoBuf, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read query 42: %s\n", strerror(errno));
return rc;
}
m_hasDS4Queries = infoBuf[0] & RMI_DEVICE_F01_QRY42_DS4_QUERIES;
m_hasMultiPhysical = infoBuf[0] & RMI_DEVICE_F01_QRY42_MULTI_PHYS;
}
if (m_hasDS4Queries) {
rc = Read(queryAddr++, &m_ds4QueryLength, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read DS4 query length: %s\n", strerror(errno));
return rc;
}
}
for (int i = 1; i <= m_ds4QueryLength; ++i) {
unsigned char val;
rc = Read(queryAddr++, &val, 1);
if (rc < 0) {
fprintf(stderr, "Failed to read F01 Query43.%02d: %s\n", i, strerror(errno));
continue;
}
switch(i) {
case 1:
m_hasPackageIDQuery = val & RMI_DEVICE_F01_QRY43_01_PACKAGE_ID;
m_hasBuildIDQuery = val & RMI_DEVICE_F01_QRY43_01_BUILD_ID;
break;
case 2:
case 3:
default:
break;
}
}
if (m_hasPackageIDQuery) {
rc = Read(prodInfoAddr++, infoBuf, PACKAGE_ID_BYTES);
if (rc > 0) {
unsigned short *val = (unsigned short *)infoBuf;
m_packageID = *val;
val = (unsigned short *)(infoBuf + 2);
m_packageRev = *val;
}
}
if (m_hasBuildIDQuery) {
rc = Read(prodInfoAddr, infoBuf, BUILD_ID_BYTES);
if (rc > 0) {
unsigned short *val = (unsigned short *)infoBuf;
m_buildID = *val;
m_buildID += infoBuf[2] * 65536;
}
}
}
return 0;
}
void RMIDevice::PrintProperties()
{
fprintf(stdout, "manufacturerID:\t\t%d\n", m_manufacturerID);
fprintf(stdout, "Has LTS?:\t\t%d\n", m_hasLTS);
fprintf(stdout, "Has Sensor ID?:\t\t%d\n", m_hasSensorID);
fprintf(stdout, "Has Adjustable Doze?:\t%d\n", m_hasAdjustableDoze);
fprintf(stdout, "Has Query 42?:\t\t%d\n", m_hasQuery42);
fprintf(stdout, "Date of Manufacturer:\t%s\n", m_dom);
fprintf(stdout, "Product ID:\t\t%s\n", m_productID);
fprintf(stdout, "Firmware Version:\t%d.%d\n", m_firmwareVersionMajor, m_firmwareVersionMinor);
fprintf(stdout, "Package ID:\t\t%d\n", m_packageID);
fprintf(stdout, "Package Rev:\t\t%d\n", m_packageRev);
fprintf(stdout, "Build ID:\t\t%ld\n", m_buildID);
fprintf(stdout, "Sensor ID:\t\t%d\n", m_sensorID);
fprintf(stdout, "Has DS4 Queries?:\t%d\n", m_hasDS4Queries);
fprintf(stdout, "Has Multi Phys?:\t%d\n", m_hasMultiPhysical);
fprintf(stdout, "\n");
}
int RMIDevice::Reset()
{
int rc;
RMIFunction f01;
const unsigned char deviceReset = RMI_F01_CMD_DEVICE_RESET;
if (!GetFunction(f01, 1))
return -1;
fprintf(stdout, "Resetting...\n");
rc = Write(f01.GetCommandBase(), &deviceReset, 1);
if (rc < 0)
return rc;
rc = Sleep(RMI_F01_DEFAULT_RESET_DELAY_MS);
if (rc < 0)
return -1;
fprintf(stdout, "Reset completed.\n");
return 0;
}
bool RMIDevice::GetFunction(RMIFunction &func, int functionNumber)
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter) {
if (funcIter->GetFunctionNumber() == functionNumber) {
func = *funcIter;
return true;
}
}
return false;
}
void RMIDevice::PrintFunctions()
{
std::vector<RMIFunction>::iterator funcIter;
for (funcIter = m_functionList.begin(); funcIter != m_functionList.end(); ++funcIter)
fprintf(stdout, "0x%02x (%d) (%d) (0x%x): 0x%02x 0x%02x 0x%02x 0x%02x\n",
funcIter->GetFunctionNumber(), funcIter->GetFunctionVersion(),
funcIter->GetInterruptSourceCount(),
funcIter->GetInterruptMask(),
funcIter->GetDataBase(),
funcIter->GetControlBase(), funcIter->GetCommandBase(),
funcIter->GetQueryBase());
}
int RMIDevice::ScanPDT(int endFunc, int endPage)
{
int rc;
unsigned int page;
unsigned int maxPage;
unsigned int addr;
unsigned char entry[RMI_DEVICE_PDT_ENTRY_SIZE];
unsigned int interruptCount = 0;
maxPage = (unsigned int)((endPage < 0) ? RMI_DEVICE_MAX_PAGE : endPage);
m_functionList.clear();
for (page = 0; page < maxPage; ++page) {
unsigned int page_start = RMI_DEVICE_PAGE_SIZE * page;
unsigned int pdt_start = page_start + RMI_DEVICE_PAGE_SCAN_START;
unsigned int pdt_end = page_start + RMI_DEVICE_PAGE_SCAN_END;
bool found = false;
SetRMIPage(page);
for (addr = pdt_start; addr >= pdt_end; addr -= RMI_DEVICE_PDT_ENTRY_SIZE) {
rc = Read(addr, entry, RMI_DEVICE_PDT_ENTRY_SIZE);
if (rc < 0) {
fprintf(stderr, "Failed to read PDT entry at address (0x%04x)\n", addr);
return rc;
}
RMIFunction func(entry, page_start, interruptCount);
if (func.GetFunctionNumber() == 0)
break;
m_functionList.push_back(func);
interruptCount += func.GetInterruptSourceCount();
found = true;
if (func.GetFunctionNumber() == endFunc)
return 0;
}
if (!found && (endPage < 0))
break;
}
m_numInterruptRegs = (interruptCount + 7) / 8;
return 0;
}
bool RMIDevice::InBootloader()
{
RMIFunction f01;
if (GetFunction(f01, 0x01)) {
int rc;
unsigned char status;
rc = Read(f01.GetDataBase(), &status, 1);
if (rc < 0)
return true;
return !!(status & 0x40);
}
return true;
}
long long diff_time(struct timespec *start, struct timespec *end)
{
long long diff;
diff = (end->tv_sec - start->tv_sec) * 1000 * 1000;
diff += (end->tv_nsec - start->tv_nsec) / 1000;
return diff;
}
int Sleep(int ms)
{
struct timespec ts;
struct timespec rem;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000 * 1000;
for (;;) {
if (nanosleep(&ts, &rem) == 0) {
break;
} else {
if (errno == EINTR) {
ts = rem;
continue;
}
return -1;
}
}
return 0;
}
void print_buffer(const unsigned char *buf, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i) {
fprintf(stdout, "0x%02X ", buf[i]);
if (i % 8 == 7)
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
} | 26.483425 | 95 | 0.694586 | [
"vector"
] |
b4fe7844707a4025109b4a2f8c9b337e49d701c1 | 2,492 | cpp | C++ | SPQSP_IO/NSCLC/SP_QSP_NSCLC/pde/DiffuseGrid.cpp | popellab/SPQSP_IO | eca3ea55ec2f75b0db5d58da09500ddffabc001d | [
"MIT"
] | null | null | null | SPQSP_IO/NSCLC/SP_QSP_NSCLC/pde/DiffuseGrid.cpp | popellab/SPQSP_IO | eca3ea55ec2f75b0db5d58da09500ddffabc001d | [
"MIT"
] | null | null | null | SPQSP_IO/NSCLC/SP_QSP_NSCLC/pde/DiffuseGrid.cpp | popellab/SPQSP_IO | eca3ea55ec2f75b0db5d58da09500ddffabc001d | [
"MIT"
] | null | null | null | #include "DiffuseGrid.h"
#include "../core/GlobalUtilities.h"
namespace SP_QSP_IO{
namespace SP_QSP_NSCLC{
DiffuseGrid::DiffuseGrid()
:_min_substrate({1E-5})
{
setup_biofvm_grid();
}
DiffuseGrid::~DiffuseGrid()
{
}
/*! initializae tumor microenvironment grid.
This is called during model setup.
No need to serialize variables that remains unchanged
during simulation.
*/
void DiffuseGrid::setup_biofvm_grid(void) {
_tme.name="tumor_pde";
// density unit: amount/cm^3. 'amount' correspond to
// amount/sec in release rate unit.
_tme.set_density(0, "IFNg" , "amount/mL" );
_tme.add_density("IL_2", "amount/mL");
//_tme.add_density("IL_10", "amount/micron^3");
_tme.spatial_units = "cm";
_tme.mesh.units = "cm";
_tme.time_units = "sec";
double minX, minY, minZ, maxX, maxY, maxZ, mesh_resolution;
minX = 0;
minY = 0;
minZ = 0;
// convert from micron to cm
mesh_resolution = params.getVal(PARAM_VOXEL_SIZE_CM);
maxX = params.getVal(PARAM_TUMOR_X) * mesh_resolution;
maxY = params.getVal(PARAM_TUMOR_Y) * mesh_resolution;
maxZ = params.getVal(PARAM_TUMOR_Z) * mesh_resolution;
_tme.resize_space_uniform( minX,maxX,minY,maxY,minZ,maxZ, mesh_resolution );
//_tme.display_information( std::cout );
// register the diffusion solver
_tme.diffusion_decay_solver = BioFVM::diffusion_decay_solver__constant_coefficients_LOD_3D;
// register substrates properties
_tme.diffusion_coefficients[CHEM_IFN] = params.getVal(PARAM_IFN_G_DIFFUSIVITY); // microns^2 / sec
_tme.decay_rates[CHEM_IFN] = params.getVal(PARAM_IFN_G_DECAY_RATE); // 1/sec
_tme.diffusion_coefficients[CHEM_IL_2] = params.getVal(PARAM_IL_2_DIFFUSIVITY); // microns^2 / sec
_tme.decay_rates[CHEM_IL_2] = params.getVal(PARAM_IL_2_DECAY_RATE); // 1/sec
//_tme.diffusion_coefficients[CHEM_IL_10] = params.getVal(PARAM_IL_10_DIFFUSIVITY); // microns^2 / sec
//_tme.decay_rates[CHEM_IL_10] = params.getVal(PARAM_IL_10_DECAY_RATE); // 1/sec
_nrVoxel = _tme.number_of_voxels();
_nrSubstrate = _tme.number_of_densities();
for( int i=0; i < _tme.number_of_voxels() ; i++ )
{
_tme.density_vector(i)[0]= 0.0;
}
return;
}
/*! check if tme can be skipped
Skip time step If:
1. total amount of substrate is smaller than set value
2. No existing source/sink
*/
bool DiffuseGrid::grid_skippable(void) {
bool res = true;
for (size_t i = 0; i < _nrSubstrate; i++)
{
res &= (get_total_amount(i) < _min_substrate[i]);
}
res &= _sink_source.empty();
return res;
}
};
};
| 27.086957 | 104 | 0.729133 | [
"mesh",
"model"
] |
b4fee8a3695e5589cd31c63a1546056b0275a297 | 25,007 | hpp | C++ | Pods/Realm/include/sync/remote_mongo_collection.hpp | taptalk-io/meettalk-ios | 9300303a7ecc8280af6b84ece32a3defe68f841d | [
"MIT"
] | 3 | 2021-08-09T09:30:44.000Z | 2022-01-17T00:35:49.000Z | Pods/Realm/include/sync/remote_mongo_collection.hpp | taptalk-io/meettalk-ios | 9300303a7ecc8280af6b84ece32a3defe68f841d | [
"MIT"
] | 1 | 2020-11-30T08:44:14.000Z | 2020-11-30T08:44:14.000Z | Pods/Realm/include/sync/remote_mongo_collection.hpp | taptalk-io/meettalk-ios | 9300303a7ecc8280af6b84ece32a3defe68f841d | [
"MIT"
] | 6 | 2021-08-29T01:57:47.000Z | 2022-03-25T10:07:59.000Z | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or utilied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REMOTE_MONGO_COLLECTION_HPP
#define REMOTE_MONGO_COLLECTION_HPP
#include "sync/app_service_client.hpp"
#include "sync/generic_network_transport.hpp"
#include "util/bson/bson.hpp"
#include <json.hpp>
#include <realm/util/optional.hpp>
#include <string>
#include <vector>
namespace realm {
class SyncUser;
namespace app {
class MongoCollection {
public:
struct UpdateResult {
/// The number of documents that matched the filter.
int32_t matched_count;
/// The number of documents modified.
int32_t modified_count;
/// The identifier of the inserted document if an upsert took place.
util::Optional<ObjectId> upserted_id;
};
/// Options to use when executing a `find` command on a `RemoteMongoCollection`.
struct FindOptions {
/// The maximum number of documents to return.
util::Optional<int64_t> limit;
/// Limits the fields to return for all matching documents.
util::Optional<bson::BsonDocument> projection_bson;
/// The order in which to return matching documents.
util::Optional<bson::BsonDocument> sort_bson;
};
/// Options to use when executing a `find_one_and_update`, `find_one_and_replace`,
/// or `find_one_and_delete` command on a `remote_mongo_collection`.
struct FindOneAndModifyOptions {
/// Limits the fields to return for all matching documents.
util::Optional<bson::BsonDocument> projection_bson;
/// The order in which to return matching documents.
util::Optional<bson::BsonDocument> sort_bson;
/// Whether or not to perform an upsert, default is false
/// (only available for find_one_and_replace and find_one_and_update)
bool upsert = false;
/// If this is true then the new document is returned,
/// Otherwise the old document is returned (default)
/// (only available for find_one_and_replace and find_one_and_update)
bool return_new_document = false;
void set_bson(bson::BsonDocument &bson)
{
if (upsert) {
bson["upsert"] = true;
}
if (return_new_document) {
bson["returnNewDocument"] = true;
}
if (projection_bson) {
bson["projection"] = *projection_bson;
}
if (sort_bson) {
bson["sort"] = *sort_bson;
}
}
};
~MongoCollection() = default;
MongoCollection(MongoCollection&&) = default;
MongoCollection(const MongoCollection&) = default;
MongoCollection& operator=(const MongoCollection& v) = default;
MongoCollection& operator=(MongoCollection&&) = default;
const std::string& name() const
{
return m_name;
}
const std::string& database_name() const
{
return m_database_name;
}
/// Finds the documents in this collection which match the provided filter.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param options `FindOptions` to use when executing the command.
/// @param completion_block The resulting bson array of documents or error if one occurs
void find(const bson::BsonDocument& filter_bson,
FindOptions options,
std::function<void(util::Optional<bson::BsonArray>, util::Optional<AppError>)> completion_block);
/// Finds the documents in this collection which match the provided filter.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param completion_block The resulting bson array as a string or error if one occurs
void find(const bson::BsonDocument& filter_bson,
std::function<void(util::Optional<bson::BsonArray>, util::Optional<AppError>)> completion_block);
/// Returns one document from a collection or view which matches the
/// provided filter. If multiple documents satisfy the query, this method
/// returns the first document according to the query's sort order or natural
/// order.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param options `FindOptions` to use when executing the command.
/// @param completion_block The resulting bson or error if one occurs
void find_one(const bson::BsonDocument& filter_bson,
FindOptions options,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Returns one document from a collection or view which matches the
/// provided filter. If multiple documents satisfy the query, this method
/// returns the first document according to the query's sort order or natural
/// order.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param completion_block The resulting bson or error if one occurs
void find_one(const bson::BsonDocument& filter_bson,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Runs an aggregation framework pipeline against this collection.
/// @param pipeline A bson array made up of `Documents` containing the pipeline of aggregation operations to perform.
/// @param completion_block The resulting bson array of documents or error if one occurs
void aggregate(const bson::BsonArray& pipeline,
std::function<void(util::Optional<bson::BsonArray>, util::Optional<AppError>)> completion_block);
/// Counts the number of documents in this collection matching the provided filter.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param limit The max amount of documents to count
/// @param completion_block Returns the count of the documents that matched the filter.
void count(const bson::BsonDocument& filter_bson,
int64_t limit,
std::function<void(uint64_t, util::Optional<AppError>)> completion_block);
/// Counts the number of documents in this collection matching the provided filter.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param completion_block Returns the count of the documents that matched the filter.
void count(const bson::BsonDocument& filter_bson,
std::function<void(uint64_t, util::Optional<AppError>)> completion_block);
/// Encodes the provided value to BSON and inserts it. If the value is missing an identifier, one will be
/// generated for it.
/// @param value_bson A `Document` value to insert.
/// @param completion_block The result of attempting to perform the insert. An Id will be returned for the inserted object on sucess
void insert_one(const bson::BsonDocument& value_bson,
std::function<void(util::Optional<bson::Bson>, util::Optional<AppError>)> completion_block);
/// Encodes the provided values to BSON and inserts them. If any values are missing identifiers,
/// they will be generated.
/// @param documents The `Document` values in a bson array to insert.
/// @param completion_block The result of the insert, returns an array inserted document ids in order
void insert_many(bson::BsonArray documents,
std::function<void(std::vector<bson::Bson>, util::Optional<AppError>)> completion_block);
/// Deletes a single matching document from the collection.
/// @param filter_bson A `Document` as bson that should match the query.
/// @param completion_block The result of performing the deletion. Returns the count of deleted objects
void delete_one(const bson::BsonDocument& filter_bson,
std::function<void(uint64_t, util::Optional<AppError>)> completion_block);
/// Deletes multiple documents
/// @param filter_bson Document representing the match criteria
/// @param completion_block The result of performing the deletion. Returns the count of the deletion
void delete_many(const bson::BsonDocument& filter_bson,
std::function<void(uint64_t, util::Optional<AppError>)> completion_block);
/// Updates a single document matching the provided filter in this collection.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param upsert When true, creates a new document if no document matches the query.
/// @param completion_block The result of the attempt to update a document.
void update_one(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
bool upsert,
std::function<void(UpdateResult, util::Optional<AppError>)> completion_block);
/// Updates a single document matching the provided filter in this collection.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param completion_block The result of the attempt to update a document.
void update_one(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
std::function<void(UpdateResult, util::Optional<AppError>)> completion_block);
/// Updates multiple documents matching the provided filter in this collection.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param upsert When true, creates a new document if no document matches the query.
/// @param completion_block The result of the attempt to update a document.
void update_many(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
bool upsert,
std::function<void(UpdateResult, util::Optional<AppError>)> completion_block);
/// Updates multiple documents matching the provided filter in this collection.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param completion_block The result of the attempt to update a document.
void update_many(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
std::function<void(UpdateResult, util::Optional<AppError>)> completion_block);
/// Updates a single document in a collection based on a query filter and
/// returns the document in either its pre-update or post-update form. Unlike
/// `update_one`, this action allows you to atomically find, update, and
/// return a document with the same command. This avoids the risk of other
/// update operations changing the document between separate find and update
/// operations.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param options Optional `FindOneAndModifyOptions` to use when executing the command.
/// @param completion_block The result of the attempt to update a document.
void find_one_and_update(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Updates a single document in a collection based on a query filter and
/// returns the document in either its pre-update or post-update form. Unlike
/// `update_one`, this action allows you to atomically find, update, and
/// return a document with the same command. This avoids the risk of other
/// update operations changing the document between separate find and update
/// operations.
/// @param filter_bson A bson `Document` representing the match criteria.
/// @param update_bson A bson `Document` representing the update to be applied to a matching document.
/// @param completion_block The result of the attempt to update a document.
void find_one_and_update(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Overwrites a single document in a collection based on a query filter and
/// returns the document in either its pre-replacement or post-replacement
/// form. Unlike `update_one`, this action allows you to atomically find,
/// replace, and return a document with the same command. This avoids the
/// risk of other update operations changing the document between separate
/// find and update operations.
/// @param filter_bson A `Document` that should match the query.
/// @param replacement_bson A `Document` describing the update.
/// @param options Optional `FindOneAndModifyOptions` to use when executing the command.
/// @param completion_block The result of the attempt to replace a document.
void find_one_and_replace(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& replacement_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Overwrites a single document in a collection based on a query filter and
/// returns the document in either its pre-replacement or post-replacement
/// form. Unlike `update_one`, this action allows you to atomically find,
/// replace, and return a document with the same command. This avoids the
/// risk of other update operations changing the document between separate
/// find and update operations.
/// @param filter_bson A `Document` that should match the query.
/// @param replacement_bson A `Document` describing the update.
/// @param completion_block The result of the attempt to replace a document.
void find_one_and_replace(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& replacement_bson,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Removes a single document from a collection based on a query filter and
/// returns a document with the same form as the document immediately before
/// it was deleted. Unlike `delete_one`, this action allows you to atomically
/// find and delete a document with the same command. This avoids the risk of
/// other update operations changing the document between separate find and
/// delete operations.
/// @param filter_bson A `Document` that should match the query.
/// @param options Optional `FindOneAndModifyOptions` to use when executing the command.
/// @param completion_block The result of the attempt to delete a document.
void find_one_and_delete(const bson::BsonDocument& filter_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
/// Removes a single document from a collection based on a query filter and
/// returns a document with the same form as the document immediately before
/// it was deleted. Unlike `delete_one`, this action allows you to atomically
/// find and delete a document with the same command. This avoids the risk of
/// other update operations changing the document between separate find and
/// delete operations.
/// @param filter_bson A `Document` that should match the query.
/// @param completion_block The result of the attempt to delete a document.
void find_one_and_delete(const bson::BsonDocument& filter_bson,
std::function<void(util::Optional<bson::BsonDocument>, util::Optional<AppError>)> completion_block);
// The following methods are equivalent to the ones without _bson suffix with the exception
// that they return the raw bson response from the function instead of attempting to parse it.
void find_bson(const bson::BsonDocument& filter_bson,
FindOptions options,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void find_one_bson(const bson::BsonDocument& filter_bson,
FindOptions options,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void aggregate_bson(const bson::BsonArray& pipeline,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void count_bson(const bson::BsonDocument& filter_bson,
int64_t limit,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void insert_one_bson(const bson::BsonDocument& value_bson,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void insert_many_bson(bson::BsonArray documents,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void delete_one_bson(const bson::BsonDocument& filter_bson,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void delete_many_bson(const bson::BsonDocument& filter_bson,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void update_one_bson(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
bool upsert,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void update_many_bson(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
bool upsert,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void find_one_and_update_bson(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& update_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void find_one_and_replace_bson(const bson::BsonDocument& filter_bson,
const bson::BsonDocument& replacement_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
void find_one_and_delete_bson(const bson::BsonDocument& filter_bson,
FindOneAndModifyOptions options,
std::function<void(util::Optional<AppError>, util::Optional<bson::Bson>)> completion_block);
/*
* SDKs should also support a watch method with the following 3 overloads:
* watch()
* watch(ids: List<Bson>)
* watch(filter: BsonDocument)
*
* In all cases, an asynchronous stream should be returned or a multi-shot
* callback should be accepted depending on the idioms in your language.
* The argument to send the server are a single BsonDocument, either empty
* or with a single kv-pair for the argument name and value of the selected
* overload.
*
* See the WatchStream class below for how to implement this stream.
*/
private:
friend class MongoDatabase;
MongoCollection(std::string name, std::string database_name, std::shared_ptr<SyncUser> user,
std::shared_ptr<AppServiceClient> service, std::string service_name)
: m_name(std::move(name))
, m_database_name(std::move(database_name))
, m_base_operation_args({{"database", m_database_name}, {"collection", m_name}})
, m_user(std::move(user))
, m_service(std::move(service))
, m_service_name(std::move(service_name))
{
}
/// The name of this collection.
std::string m_name;
/// The name of the database containing this collection.
std::string m_database_name;
/// Returns a document of database name and collection name
bson::BsonDocument m_base_operation_args;
std::shared_ptr<SyncUser> m_user;
std::shared_ptr<AppServiceClient> m_service;
std::string m_service_name;
};
/**
* Simplifies the handling the stream for collection.watch() API.
*
* General pattern for languages with pull-based async generators (preferred):
* auto request = app.make_streaming_request("watch", ...);
* auto reply = await doHttpRequestUsingNativeLibs(request);
* if (reply.error)
* throw reply.error;
* auto ws = WatchStream();
* for await (chunk : reply.body) {
* ws.feedBuffer(chunk);
* while (ws.state == WatchStream::HAVE_EVENT) {
* yield ws.nextEvent();
* }
* if (ws.state == WatchStream::HAVE_ERROR)
* throw ws.error;
* }
*
* General pattern for languages with only push-based streams:
* auto request = app.make_streaming_request("watch", ...);
* doHttpRequestUsingNativeLibs(request, {
* .onError = [downstream](error) { downstream.onError(error); },
* .onHeadersDone = [downstream](reply) {
* if (reply.error)
* downstream.onError(error);
* },
* .onBodyChunk = [downstream, ws = WatchStream()](chunk) {
* ws.feedBuffer(chunk);
* while (ws.state == WatchStream::HAVE_EVENT) {
* downstream.nextEvent(ws.nextEvent());
* }
* if (ws.state == WatchStream::HAVE_ERROR)
* downstream.onError(ws.error);
* }
* });
*/
struct WatchStream {
// NOTE: this is a fully processed event, not a single "data: foo" line!
struct ServerSentEvent {
std::string_view data;
std::string_view eventType = "message";
};
// Call these when you have data, in whatever shape is easiest for your SDK to get.
// Pick one, mixing and matching on a single instance isn't supported.
// These can only be called in NEED_DATA state, which is the initial state.
void feed_buffer(std::string_view); // May have multiple and/or partial lines.
void feed_line(std::string_view); // May include terminating CR and/or LF (not required).
void feed_sse(ServerSentEvent); // Only interested in "message" and "error" events. Others are ignored.
// Call state() to see what to do next.
enum State {
NEED_DATA, // Need to call one of the feed functions.
HAVE_EVENT, // Call next_event() to consume an event.
HAVE_ERROR, // Call error().
};
State state() const { return m_state; }
// Consumes the returned event. If you used feed_buffer(), there may be another event or error after this one,
// so you need to call state() again to see what to do next.
bson::BsonDocument next_event() {
REALM_ASSERT(m_state == HAVE_EVENT);
auto out = std::move(m_next_event);
m_state = NEED_DATA;
advance_buffer_state();
return out;
}
// Once this enters the error state, it stays that way. You should not feed any more data.
const app::AppError& error() const {
REALM_ASSERT(m_state == HAVE_ERROR);
return *m_error;
}
private:
void advance_buffer_state();
State m_state = NEED_DATA;
util::Optional<app::AppError> m_error;
bson::BsonDocument m_next_event;
// Used by feed_buffer to construct lines
std::string m_buffer;
size_t m_buffer_offset = 0;
// Used by feed_line for building the next SSE
std::string m_event_type;
std::string m_data_buffer;
};
} // namespace app
} // namespace realm
#endif /* remote_mongo_collection_h */
| 49.814741 | 136 | 0.682689 | [
"object",
"shape",
"vector"
] |
37022f5b4c8f92cb58ef57e4b2e88d77d3e0af65 | 9,510 | cpp | C++ | src/PerlServer.cpp | BenBanerjeeRichards/perl-ide-server | 9a4a2d6342219241ef56da8b968688626d3102f3 | [
"MIT"
] | 1 | 2020-02-15T21:33:35.000Z | 2020-02-15T21:33:35.000Z | src/PerlServer.cpp | BenBanerjeeRichards/perl-ide-server | 9a4a2d6342219241ef56da8b968688626d3102f3 | [
"MIT"
] | null | null | null | src/PerlServer.cpp | BenBanerjeeRichards/perl-ide-server | 9a4a2d6342219241ef56da8b968688626d3102f3 | [
"MIT"
] | null | null | null | //
// Created by Ben Banerjee-Richards on 2019-11-24.
//
#include "PerlServer.h"
void sendJson(httplib::Response &res, json &jsonObject, std::string error = "", std::string errorMessage = "") {
json response;
response["body"] = jsonObject;
if (error.empty()) {
response["success"] = true;
} else {
response["success"] = false;
response["error"] = error;
response["errorMessage"] = errorMessage;
res.status = 400;
}
res.set_content(response.dump(), "application/json");
}
void sendJson(httplib::Response &res, std::string error = "", std::string errorMessage = "") {
json null;
sendJson(res, null, std::move(error), std::move(errorMessage));
}
void handleAutocompleteVariable(httplib::Response &res, json params, Cache &cache) {
if (!params.contains("path") || !params.contains("sigil")) {
sendJson(res, "BAD_PARAMS", "Bad parameters");
return;
}
int line, col;
try {
line = params["line"];
col = params["col"];
} catch (json::exception &) {
sendJson(res, "BAD_PARAMS", "Bad Params");
return;
}
std::vector<AutocompleteItem> completeItems;
try {
completeItems = analysis::autocompleteVariables(params["path"], params["context"], FilePos(line, col),
params["projectFiles"], std::string(params["sigil"])[0], cache);
} catch (IOException &) {
sendJson(res, "PATH_NOT_FOUND", "File " + std::string(params["path"]) + " not found");
return;
} catch (TokeniseException &ex) {
sendJson(res, "PARSE_ERROR", "Error occured during tokenization " + ex.reason);
return;
} catch (json::exception &) {
sendJson(res, "BAD_PARAMS", "Bad Params");
return;
}
json response;
std::vector<std::vector<std::string>> jsonFrom;
for (const AutocompleteItem &completeItem : completeItems) {
std::vector<std::string> itemForm{completeItem.name, completeItem.detail};
jsonFrom.emplace_back(itemForm);
}
response = jsonFrom;
sendJson(res, response);
}
void handleAutocompleteSubroutine(httplib::Response &res, json params, Cache &cache) {
std::string path = params["path"];
int line, col;
try {
line = params["line"];
col = params["col"];
} catch (json::exception &) {
sendJson(res, "BAD_PARAMS", "Bad Params 2");
return;
}
std::vector<AutocompleteItem> completeItems;
try {
completeItems = analysis::autocompleteSubs(path, params["context"], FilePos(line, col), params["projectFiles"],
cache);
} catch (IOException &) {
sendJson(res, "PATH_NOT_FOUND", "File " + path + " not found");
return;
} catch (TokeniseException &ex) {
sendJson(res, "PARSE_ERROR", "Error occurred during tokenization " + ex.reason);
return;
} catch (json::exception &) {
sendJson(res, "BAD_PARAMS", "Bad Params");
return;
}
json response;
std::vector<std::vector<std::string>> jsonFrom;
for (const AutocompleteItem &completeItem : completeItems) {
std::vector<std::string> itemForm{completeItem.name, completeItem.detail};
jsonFrom.emplace_back(itemForm);
}
response = jsonFrom;
sendJson(res, response);
}
void handleFindUsages(httplib::Response &res, json params, Cache &cache) {
try {
std::string path = params["path"];
std::string contextPath = params["context"];
int line = params["line"];
int col = params["col"];
std::vector<std::string> projectFiles = params["projectFiles"];
std::map<std::string, std::vector<std::vector<int>>> jsonFrom;
for (const auto &fileWithUsages : analysis::findUsages(path, contextPath, FilePos(line, col),
projectFiles, cache)) {
std::vector<std::vector<int>> fileLocations;
for (const Range &usage : fileWithUsages.second) {
fileLocations.emplace_back(std::vector<int>{usage.from.line, usage.from.col});
}
std::sort(fileLocations.begin(), fileLocations.end());
if (!fileLocations.empty()) jsonFrom[fileWithUsages.first] = fileLocations;
}
json response = jsonFrom;
sendJson(res, response);
} catch (json::exception &) {
sendJson(res, "BAD_PARAMS", "Bad Params");
return;
}
}
void handleFindDeclaration(httplib::Response &res, json params, Cache &cache) {
std::string path = params["path"];
std::string context = params["context"];
std::vector<std::string> projectFiles = params["projectFiles"];
int line = params["line"];
int col = params["col"];
// TODO expand search to multiple files
json response;
auto maybeDecl = analysis::findVariableDeclaration(path, FilePos(line, col));
if (maybeDecl.has_value()) {
response["exists"] = true;
response["file"] = context;
response["line"] = maybeDecl.value().line;
response["col"] = maybeDecl.value().col;
} else {
auto maybeSub = analysis::findSubroutineDeclaration(path, context, FilePos(line, col), projectFiles, cache);
if (maybeSub.has_value()) {
response["exists"] = true;
response["file"] = maybeSub.value().path;
response["line"] = maybeSub.value().pos.line;
response["col"] = maybeSub.value().pos.col;
} else {
response["exists"] = false;
}
}
sendJson(res, response);
}
void handleIndexProject(httplib::Response &res, json params, Cache &cache) {
if (!params.contains("projectFiles")) {
sendJson(res, "BAD_PARAMS", "No project files provided");
return;
}
std::vector<std::string> projectFiles = params["projectFiles"];
analysis::indexProject(projectFiles, cache);
json response;
sendJson(res, response);
}
void handleIsSymbol(httplib::Response &res, json params, Cache &cache) {
int line = params["line"];
int col = params["col"];
std::string path = params["path"];
std::vector<std::string> projectFiles = params["projectFiles"];
json response;
if (auto symbolName = analysis::getSymbolName(path, FilePos(line, col), projectFiles, cache)) {
response["exists"] = true;
response["name"] = symbolName.value();
} else {
response["exists"] = false;
}
sendJson(res, response);
}
void handleRenameSymbol(httplib::Response &res, json params, Cache &cache) {
int line = params["line"];
int col = params["col"];
std::string path = params["path"];
std::vector<std::string> projectFiles = params["projectFiles"];
std::string renameTo = params["renameTo"];
json response;
auto renameRes = analysis::renameSymbol(path, FilePos(line, col), renameTo, projectFiles, cache);
if (renameRes.success) {
sendJson(res, response);
} else {
sendJson(res, "BAD_RENAME", renameRes.error);
}
}
void startAndBlock(int port) {
httplib::Server httpServer;
// Setup cache
Cache cache;
// Mutex to only allow one request at once
std::mutex mutex;
httpServer.Post("/", [&](const httplib::Request &req, httplib::Response &res) {
std::cout << "Waiting for lock..." << std::endl;
std::unique_lock<std::mutex> lock(mutex);
std::cout << "Got lock" << std::endl;
json reqJson;
try {
reqJson = json::parse(req.body);
} catch (json::exception &ex) {
sendJson(res, "BAD_JSON", "Failed to parse json request");
return;
}
if (!reqJson.contains("method")) {
sendJson(res, "NO_METHOD", "No method provided");
return;
}
if (!reqJson.contains("params")) {
sendJson(res, "BAD_PARAMS", "No params provided");
return;
}
try {
json params = reqJson["params"];
if (reqJson["method"] == "autocomplete-var") {
handleAutocompleteVariable(res, params, cache);
} else if (reqJson["method"] == "autocomplete-sub") {
handleAutocompleteSubroutine(res, params, cache);
} else if (reqJson["method"] == "find-usages") {
handleFindUsages(res, params, cache);
} else if (reqJson["method"] == "find-declaration") {
handleFindDeclaration(res, params, cache);
} else if (reqJson["method"] == "index-project") {
handleIndexProject(res, params, cache);
} else if (reqJson["method"] == "is-symbol") {
handleIsSymbol(res, params, cache);
} else if (reqJson["method"] == "rename") {
handleRenameSymbol(res, params, cache);
} else {
sendJson(res, "UNKNOWN_METHOD", "Method " + std::string(reqJson["method"]) + " not supported");
return;
}
} catch (json::exception &e) {
sendJson(res, "BAD_PARAMS", "Bad Params 2");
return;
}
});
httpServer.Get("/ping", [](const httplib::Request &req, httplib::Response &res) {
res.set_content("ok", "text/plain");
});
bool listenOk = httpServer.listen("localhost", port);
std::cout << "DONE! listenOk=" << listenOk << std::endl;
}
| 34.835165 | 120 | 0.584543 | [
"vector"
] |
37079abc008bc2df4daa57dcf3e3a78633f0b29e | 9,692 | cpp | C++ | src/third_party/harfbuzz/test/shaping/data/aots/hb-aots-tester.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 2 | 2021-02-24T07:36:40.000Z | 2021-05-15T12:42:21.000Z | src/third_party/harfbuzz/test/shaping/data/aots/hb-aots-tester.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | null | null | null | src/third_party/harfbuzz/test/shaping/data/aots/hb-aots-tester.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | null | null | null | /*____________________________________________________________________________
Copyright 2000-2016 Adobe Systems Incorporated. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use these files 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 "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "hb.h"
#include "hb-ot.h"
static const bool verbose = true;
hb_feature_t *gFeatures;
int gNbFeatures;
hb_buffer_t *runTest(const char *testName,
const char *fontfileName,
unsigned int *in, int nbIn,
unsigned int *select, int nbSelect)
{
FILE *f = fopen (fontfileName, "rb");
fseek(f, 0, SEEK_END);
long fontsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *fontdata = (char *)malloc (fontsize);
fread(fontdata, fontsize, 1, f);
fclose(f);
if (verbose) {
printf ("------------------------------- %s\n", testName);
}
// setup font
hb_blob_t *blob = hb_blob_create(fontdata, fontsize,
HB_MEMORY_MODE_WRITABLE,
0, 0);
hb_face_t *face = hb_face_create(blob, 0);
hb_font_t *font = hb_font_create(face);
unsigned int upem = hb_face_get_upem (face);
hb_font_set_scale(font, upem, upem);
hb_ot_font_set_funcs (font);
// setup buffer
hb_buffer_t *buffer = hb_buffer_create();
hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
hb_buffer_set_script(buffer, HB_SCRIPT_LATIN);
hb_buffer_set_language(buffer, hb_language_from_string("en", 2));
hb_buffer_add_utf32(buffer, in, nbIn, 0, nbIn);
// setup features
hb_feature_t *features;
int nbFeatures;
if (nbSelect == 0)
{
nbFeatures = 1;
features = (hb_feature_t *) malloc (sizeof (*features));
features[0].tag = HB_TAG('t', 'e', 's', 't');
features[0].value = 1;
features[0].start = HB_FEATURE_GLOBAL_START;
features[0].end = HB_FEATURE_GLOBAL_END;
}
else
{
nbFeatures = 0;
features = (hb_feature_t *) malloc (sizeof (*features) * nbSelect);
for (int i = 0; i < nbSelect; i++) {
if (select[i] != -1) {
features[nbFeatures].tag = HB_TAG('t', 'e', 's', 't');
features[nbFeatures].value = select[i];
features[nbFeatures].start = i;
features[nbFeatures].end = i + 1;
nbFeatures++;
}
}
}
gFeatures = features;
gNbFeatures = nbFeatures;
// shape
hb_shape(font, buffer, features, nbFeatures);
hb_blob_destroy(blob);
hb_font_destroy(font);
hb_face_destroy(face);
//free(features);
return buffer;
}
void printArray (const char* s, int *a, int n)
{
printf ("%s %d : ", s, n);
for (int i = 0; i < n; i++) {
printf (" %d", a[i]);
}
printf ("\n");
}
void printUArray (const char* s, unsigned int *a, int n)
{
printArray (s, (int *) a, n);
}
bool gsub_test(const char *testName,
const char *fontfileName,
int nbIn, unsigned int *in,
int nbSelect, unsigned int *select,
int nbExpected, unsigned int *expected)
{
hb_buffer_t *buffer = runTest(testName,
fontfileName,
in, nbIn,
select, nbSelect);
// verify
hb_glyph_info_t *actual = hb_buffer_get_glyph_infos(buffer, 0);
unsigned int nbActual = hb_buffer_get_length(buffer);
bool ok = true;
if (nbActual != nbExpected)
ok = false;
else {
for (int i = 0; i < nbActual; i++) {
if (actual[i].codepoint != expected [i]) {
ok = false;
break;
}
}
}
char test_name[255];
sprintf (test_name, "../../tests/%.*s.tests", (int) (strrchr (testName, '_') - testName), testName);
FILE *tests_file = fopen (test_name, "a+");
if (!ok) fprintf (tests_file, "#");
fprintf (tests_file, "../fonts/%s:--features=\"", fontfileName + 9);
for (unsigned int i = 0; i < gNbFeatures; i++)
{
if (i != 0) fprintf (tests_file, ",");
char buf[255];
hb_feature_to_string (&gFeatures[i], buf, sizeof (buf));
fprintf (tests_file, "%s", buf);
}
free (gFeatures);
fprintf (tests_file, "\" --no-clusters --no-glyph-names --no-positions:");
for (unsigned int i = 0; i < nbIn; i++)
{
if (i != 0) fprintf (tests_file, ",");
fprintf (tests_file, "U+%04X", in[i]);
}
fprintf (tests_file, ":[");
for (unsigned int i = 0; i < nbActual; i++)
{
if (i != 0) fprintf (tests_file, "|");
fprintf (tests_file, "%d", expected[i]);
}
fprintf (tests_file, "]");
fprintf (tests_file, "\n");
fclose (tests_file);
if (! ok) {
printf ("******* GSUB %s\n", testName);
printf ("expected %d:", nbExpected);
for (int i = 0; i < nbExpected; i++) {
printf (" %d", expected[i]); }
printf ("\n");
printf (" actual %d:", nbActual);
for (int i = 0; i < nbActual; i++) {
printf (" %d", actual[i].codepoint); }
printf ("\n");
}
hb_buffer_destroy(buffer);
return ok;
}
bool gpos_test(const char *testName,
const char *fontfileName,
int nbIn,
unsigned int *in,
int nbOut,
unsigned int *out,
int *x,
int *y)
{
hb_buffer_t *buffer = runTest(testName,
fontfileName,
in, nbIn,
0, 0);
// verify
unsigned int nbActual;
hb_glyph_info_t *actual = hb_buffer_get_glyph_infos(buffer, &nbActual);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (buffer, NULL);
unsigned int *actualG = (unsigned int *) malloc(sizeof(*actualG) * nbActual);
int *actualX = (int *) malloc(sizeof(*actualX) * nbActual);
int *actualY = (int *) malloc(sizeof(*actualY) * nbActual);
int curX = 0;
int curY = 0;
for (int i = 0; i < nbActual; i++) {
actualG[i] = actual[i].codepoint;
actualX[i] = curX + pos[i].x_offset;
actualY[i] = curY + pos[i].y_offset;
actualX[i] -= 1500 * i;
curX += pos[i].x_advance;
curY += pos[i].y_advance;
}
bool nbOk = true;
bool xOk = true;
bool yOk = true;
if (nbActual != nbOut)
nbOk = false;
else {
for (int i = 0; i < nbActual; i++) {
if (actualX[i] != x[i]) {
xOk = false;
}
if (actualY[i] != y[i]) {
yOk = false;
}
}
}
bool ok = (nbOk && xOk && yOk);
if (! ok) {
printf ("******* GPOS %s\n", testName);
if (! (nbOk && xOk)) {
printArray ("expectedX", x, nbOut);
printArray ("actualX ", actualX, nbActual);
printf ("xadv/pos:");
for (int i = 0; i < nbOut; i++) {
printf (" %d/%d", pos[i].x_advance, pos[i].x_offset);
}
printf ("\n");
}
if (! (nbOk && yOk)) {
printArray ("expectedY", y, nbOut);
printArray ("actualY ", actualY, nbActual);
printf ("yadv/pos:");
for (int i = 0; i < nbOut; i++) {
printf (" %d/%d", pos[i].y_advance, pos[i].y_offset);
}
printf ("\n");
}
}
char test_name[255];
sprintf (test_name, "../../tests/%.*s.tests", (int) (strrchr (testName, '_') - testName), testName);
FILE *tests_file = fopen (test_name, "a+");
if (!ok) fprintf (tests_file, "#");
fprintf (tests_file, "../fonts/%s:--features=\"", fontfileName + 9);
for (unsigned int i = 0; i < gNbFeatures; i++)
{
if (i != 0) fprintf (tests_file, ",");
char buf[255];
hb_feature_to_string (&gFeatures[i], buf, sizeof (buf));
fprintf (tests_file, "%s", buf);
}
free (gFeatures);
fprintf (tests_file, "\" --no-clusters --no-glyph-names --ned:");
for (unsigned int i = 0; i < nbIn; i++)
{
if (i != 0) fprintf (tests_file, ",");
fprintf (tests_file, "U+%04X", in[i]);
}
fprintf (tests_file, ":[");
for (unsigned int i = 0; i < nbActual; i++)
{
if (i != 0) fprintf (tests_file, "|");
fprintf (tests_file, "%d", /*it should be "out[i]"*/ actualG[i]);
int expected_x = x[i] + 1500*i;
int expected_y = y[i];
if (expected_x || expected_y) fprintf (tests_file, "@%d,%d", expected_x, expected_y);
}
fprintf (tests_file, "]");
fprintf (tests_file, "\n");
fclose (tests_file);
hb_buffer_destroy(buffer);
free(actualG);
free(actualX);
free(actualY);
return ok;
}
int main(int argc, char **argv)
{
int failures = 0;
int pass = 0;
#include "hb-aots-tester.h"
printf ("%d failures, %d pass\n", failures, pass);
}
| 28.092754 | 104 | 0.53343 | [
"shape"
] |
37093b946609ce1b547c44d4e2a4f44fbd5b27bd | 21,253 | cc | C++ | chrome/browser/profiles/profile_window.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/profiles/profile_window.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/profiles/profile_window.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/profiles/profile_window.h"
#include <stddef.h>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/account_reconcilor_factory.h"
#include "chrome/browser/signin/account_tracker_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/signin_ui_util.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/profile_chooser_constants.h"
#include "chrome/browser/ui/user_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/browser_sync/profile_sync_service.h"
#include "components/flags_ui/pref_service_flags_storage.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/account_reconcilor.h"
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "components/signin/core/common/signin_pref_names.h"
#include "components/signin/core/common/signin_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/features/features.h"
#include "net/base/escape.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/extension_service.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_factory.h"
#include "extensions/browser/extension_system.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#if !defined(OS_ANDROID)
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#endif // !defined (OS_ANDROID)
using base::UserMetricsAction;
using content::BrowserThread;
namespace {
#if BUILDFLAG(ENABLE_EXTENSIONS)
void BlockExtensions(Profile* profile) {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile)->extension_service();
extension_service->BlockAllExtensions();
}
void UnblockExtensions(Profile* profile) {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile)->extension_service();
extension_service->UnblockAllExtensions();
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
// Handles running a callback when a new Browser for the given profile
// has been completely created.
class BrowserAddedForProfileObserver : public chrome::BrowserListObserver {
public:
BrowserAddedForProfileObserver(
Profile* profile,
ProfileManager::CreateCallback callback)
: profile_(profile),
callback_(callback) {
DCHECK(!callback_.is_null());
BrowserList::AddObserver(this);
}
~BrowserAddedForProfileObserver() override {}
private:
// Overridden from BrowserListObserver:
void OnBrowserAdded(Browser* browser) override {
if (browser->profile() == profile_) {
BrowserList::RemoveObserver(this);
// By the time the browser is added a tab (or multiple) are about to be
// added. Post the callback to the message loop so it gets executed after
// the tabs are created.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(callback_, profile_, Profile::CREATE_STATUS_INITIALIZED));
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
}
// Profile for which the browser should be opened.
Profile* profile_;
ProfileManager::CreateCallback callback_;
DISALLOW_COPY_AND_ASSIGN(BrowserAddedForProfileObserver);
};
// Called after a |system_profile| is available to be used by the user manager.
// Based on the value of |tutorial_mode| we determine a url to be displayed
// by the webui and run the |callback|, if it exists. Depending on the value of
// |user_manager_action|, executes an action once the user manager displays or
// after a profile is opened.
void OnUserManagerSystemProfileCreated(
const base::FilePath& profile_path_to_focus,
profiles::UserManagerTutorialMode tutorial_mode,
profiles::UserManagerAction user_manager_action,
const base::Callback<void(Profile*, const std::string&)>& callback,
Profile* system_profile,
Profile::CreateStatus status) {
if (status != Profile::CREATE_STATUS_INITIALIZED || callback.is_null())
return;
// Tell the webui which user should be focused.
std::string page = chrome::kChromeUIMdUserManagerUrl;
if (tutorial_mode == profiles::USER_MANAGER_TUTORIAL_OVERVIEW) {
page += profiles::kUserManagerDisplayTutorial;
} else if (!profile_path_to_focus.empty()) {
// The file path is processed in the same way as base::CreateFilePathValue
// (i.e. convert to std::string with AsUTF8Unsafe()), and then URI encoded.
page += "#";
page += net::EscapeUrlEncodedData(profile_path_to_focus.AsUTF8Unsafe(),
false);
} else if (user_manager_action ==
profiles::USER_MANAGER_OPEN_CREATE_USER_PAGE) {
page += profiles::kUserManagerOpenCreateUserPage;
} else if (user_manager_action ==
profiles::USER_MANAGER_SELECT_PROFILE_TASK_MANAGER) {
page += profiles::kUserManagerSelectProfileTaskManager;
} else if (user_manager_action ==
profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME) {
page += profiles::kUserManagerSelectProfileAboutChrome;
} else if (user_manager_action ==
profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS) {
page += profiles::kUserManagerSelectProfileChromeSettings;
} else if (user_manager_action ==
profiles::USER_MANAGER_SELECT_PROFILE_APP_LAUNCHER) {
page += profiles::kUserManagerSelectProfileAppLauncher;
}
callback.Run(system_profile, page);
}
// Called in profiles::LoadProfileAsync once profile is loaded. It runs
// |callback| if it isn't null.
void ProfileLoadedCallback(ProfileManager::CreateCallback callback,
Profile* profile,
Profile::CreateStatus status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != Profile::CREATE_STATUS_INITIALIZED)
return;
if (!callback.is_null())
callback.Run(profile, Profile::CREATE_STATUS_INITIALIZED);
}
} // namespace
namespace profiles {
// User Manager parameters are prefixed with hash.
const char kUserManagerDisplayTutorial[] = "#tutorial";
const char kUserManagerOpenCreateUserPage[] = "#create-user";
const char kUserManagerSelectProfileTaskManager[] = "#task-manager";
const char kUserManagerSelectProfileAboutChrome[] = "#about-chrome";
const char kUserManagerSelectProfileChromeSettings[] = "#chrome-settings";
const char kUserManagerSelectProfileAppLauncher[] = "#app-launcher";
base::FilePath GetPathOfProfileWithEmail(ProfileManager* profile_manager,
const std::string& email) {
base::string16 profile_email = base::UTF8ToUTF16(email);
std::vector<ProfileAttributesEntry*> entries =
profile_manager->GetProfileAttributesStorage().GetAllProfilesAttributes();
for (ProfileAttributesEntry* entry : entries) {
if (entry->GetUserName() == profile_email)
return entry->GetPath();
}
return base::FilePath();
}
void FindOrCreateNewWindowForProfile(
Profile* profile,
chrome::startup::IsProcessStartup process_startup,
chrome::startup::IsFirstRun is_first_run,
bool always_create) {
DCHECK(profile);
if (!always_create) {
Browser* browser = chrome::FindTabbedBrowser(profile, false);
if (browser) {
browser->window()->Activate();
return;
}
}
content::RecordAction(UserMetricsAction("NewWindow"));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
browser_creator.LaunchBrowser(
command_line, profile, base::FilePath(), process_startup, is_first_run);
}
void OpenBrowserWindowForProfile(
ProfileManager::CreateCallback callback,
bool always_create,
bool is_new_profile,
Profile* profile,
Profile::CreateStatus status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != Profile::CREATE_STATUS_INITIALIZED)
return;
chrome::startup::IsProcessStartup is_process_startup =
chrome::startup::IS_NOT_PROCESS_STARTUP;
chrome::startup::IsFirstRun is_first_run = chrome::startup::IS_NOT_FIRST_RUN;
// If this is a brand new profile, then start a first run window.
if (is_new_profile) {
is_process_startup = chrome::startup::IS_PROCESS_STARTUP;
is_first_run = chrome::startup::IS_FIRST_RUN;
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
// The signin bit will still be set if the profile is being unlocked and the
// browser window for it is opening. As part of this unlock process, unblock
// all the extensions.
if (!profile->IsGuestSession()) {
ProfileAttributesEntry* entry;
if (g_browser_process->profile_manager()->GetProfileAttributesStorage().
GetProfileAttributesWithPath(profile->GetPath(), &entry) &&
entry->IsSigninRequired()) {
UnblockExtensions(profile);
}
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
// If |always_create| is false, and we have a |callback| to run, check
// whether a browser already exists so that we can run the callback. We don't
// want to rely on the observer listening to OnBrowserSetLastActive in this
// case, as you could manually activate an incorrect browser and trigger
// a false positive.
if (!always_create) {
Browser* browser = chrome::FindTabbedBrowser(profile, false);
if (browser) {
browser->window()->Activate();
if (!callback.is_null())
callback.Run(profile, Profile::CREATE_STATUS_INITIALIZED);
return;
}
}
// If there is a callback, create an observer to make sure it is only
// run when the browser has been completely created. This observer will
// delete itself once that happens. This should not leak, because we are
// passing |always_create| = true to FindOrCreateNewWindow below, which ends
// up calling LaunchBrowser and opens a new window. If for whatever reason
// that fails, either something has crashed, or the observer will be cleaned
// up when a different browser for this profile is opened.
if (!callback.is_null())
new BrowserAddedForProfileObserver(profile, callback);
// We already dealt with the case when |always_create| was false and a browser
// existed, which means that here a browser definitely needs to be created.
// Passing true for |always_create| means we won't duplicate the code that
// tries to find a browser.
profiles::FindOrCreateNewWindowForProfile(profile, is_process_startup,
is_first_run, true);
}
#if !defined(OS_ANDROID)
void LoadProfileAsync(const base::FilePath& path,
ProfileManager::CreateCallback callback) {
g_browser_process->profile_manager()->CreateProfileAsync(
path, base::Bind(&ProfileLoadedCallback, callback), base::string16(),
std::string(), std::string());
}
void SwitchToProfile(const base::FilePath& path,
bool always_create,
ProfileManager::CreateCallback callback,
ProfileMetrics::ProfileOpen metric) {
ProfileMetrics::LogProfileSwitch(metric,
g_browser_process->profile_manager(),
path);
g_browser_process->profile_manager()->CreateProfileAsync(
path,
base::Bind(&profiles::OpenBrowserWindowForProfile,
callback,
always_create,
false),
base::string16(), std::string(), std::string());
}
void SwitchToGuestProfile(ProfileManager::CreateCallback callback) {
const base::FilePath& path = ProfileManager::GetGuestProfilePath();
ProfileMetrics::LogProfileSwitch(ProfileMetrics::SWITCH_PROFILE_GUEST,
g_browser_process->profile_manager(),
path);
g_browser_process->profile_manager()->CreateProfileAsync(
path, base::Bind(&profiles::OpenBrowserWindowForProfile,
callback,
false,
false),
base::string16(), std::string(), std::string());
}
#endif
bool HasProfileSwitchTargets(Profile* profile) {
size_t min_profiles = profile->IsGuestSession() ? 1 : 2;
size_t number_of_profiles =
g_browser_process->profile_manager()->GetNumberOfProfiles();
return number_of_profiles >= min_profiles;
}
void CreateAndSwitchToNewProfile(ProfileManager::CreateCallback callback,
ProfileMetrics::ProfileAdd metric) {
ProfileAttributesStorage& storage =
g_browser_process->profile_manager()->GetProfileAttributesStorage();
int placeholder_avatar_index = profiles::GetPlaceholderAvatarIndex();
ProfileManager::CreateMultiProfileAsync(
storage.ChooseNameForNewProfile(placeholder_avatar_index),
profiles::GetDefaultAvatarIconUrl(placeholder_avatar_index),
base::Bind(&profiles::OpenBrowserWindowForProfile,
callback,
true,
true),
std::string());
ProfileMetrics::LogProfileAddNewUser(metric);
}
void ProfileBrowserCloseSuccess(const base::FilePath& profile_path) {
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
}
void CloseGuestProfileWindows() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = profile_manager->GetProfileByPath(
ProfileManager::GetGuestProfilePath());
if (profile) {
BrowserList::CloseAllBrowsersWithProfile(
profile, base::Bind(&ProfileBrowserCloseSuccess),
BrowserList::CloseCallback());
}
}
void LockBrowserCloseSuccess(const base::FilePath& profile_path) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
ProfileAttributesEntry* entry;
bool has_entry = profile_manager->GetProfileAttributesStorage().
GetProfileAttributesWithPath(profile_path, &entry);
DCHECK(has_entry);
entry->SetIsSigninRequired(true);
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Profile guaranteed to exist for it to have been locked.
BlockExtensions(profile_manager->GetProfileByPath(profile_path));
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
chrome::HideTaskManager();
UserManager::Show(profile_path,
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
}
void LockProfile(Profile* profile) {
DCHECK(profile);
if (profile) {
BrowserList::CloseAllBrowsersWithProfile(
profile, base::Bind(&LockBrowserCloseSuccess),
BrowserList::CloseCallback());
}
}
bool IsLockAvailable(Profile* profile) {
DCHECK(profile);
if (!switches::IsNewProfileManagement())
return false;
if (profile->IsGuestSession() || profile->IsSystemProfile())
return false;
std::string hosted_domain = profile->GetPrefs()->
GetString(prefs::kGoogleServicesHostedDomain);
// TODO(mlerman): After one release remove any hosted_domain reference to the
// pref, since all users will have this in the AccountTrackerService.
if (hosted_domain.empty()) {
AccountTrackerService* account_tracker =
AccountTrackerServiceFactory::GetForProfile(profile);
std::string account_id =
SigninManagerFactory::GetForProfile(profile)->GetAuthenticatedAccountId();
hosted_domain = account_tracker->GetAccountInfo(account_id).hosted_domain;
}
// TODO(mlerman): Prohibit only users who authenticate using SAML. Until then,
// prohibited users who use hosted domains (aside from google.com).
if (hosted_domain != Profile::kNoHostedDomainFound &&
hosted_domain != "google.com") {
return false;
}
// Lock only when there is at least one supervised user on the machine.
std::vector<ProfileAttributesEntry*> entries =
g_browser_process->profile_manager()->GetProfileAttributesStorage().
GetAllProfilesAttributes();
for (ProfileAttributesEntry* entry : entries) {
if (entry->IsSupervised())
return true;
}
return false;
}
void CloseProfileWindows(Profile* profile) {
DCHECK(profile);
BrowserList::CloseAllBrowsersWithProfile(
profile, base::Bind(&ProfileBrowserCloseSuccess),
BrowserList::CloseCallback());
}
void CreateSystemProfileForUserManager(
const base::FilePath& profile_path_to_focus,
profiles::UserManagerTutorialMode tutorial_mode,
profiles::UserManagerAction user_manager_action,
const base::Callback<void(Profile*, const std::string&)>& callback) {
// Create the system profile, if necessary, and open the User Manager
// from the system profile.
g_browser_process->profile_manager()->CreateProfileAsync(
ProfileManager::GetSystemProfilePath(),
base::Bind(&OnUserManagerSystemProfileCreated,
profile_path_to_focus,
tutorial_mode,
user_manager_action,
callback),
base::string16(),
std::string(),
std::string());
}
void ShowUserManagerMaybeWithTutorial(Profile* profile) {
// Guest users cannot appear in the User Manager, nor display a tutorial.
if (!profile || profile->IsGuestSession()) {
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_NO_TUTORIAL,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
return;
}
UserManager::Show(base::FilePath(),
profiles::USER_MANAGER_TUTORIAL_OVERVIEW,
profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
}
void BubbleViewModeFromAvatarBubbleMode(
BrowserWindow::AvatarBubbleMode mode,
BubbleViewMode* bubble_view_mode,
TutorialMode* tutorial_mode) {
*tutorial_mode = TUTORIAL_MODE_NONE;
switch (mode) {
case BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT:
*bubble_view_mode = BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN:
*bubble_view_mode = BUBBLE_VIEW_MODE_GAIA_SIGNIN;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_ADD_ACCOUNT:
*bubble_view_mode = BUBBLE_VIEW_MODE_GAIA_ADD_ACCOUNT;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH:
*bubble_view_mode = BUBBLE_VIEW_MODE_GAIA_REAUTH;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN:
*bubble_view_mode = BUBBLE_VIEW_MODE_PROFILE_CHOOSER;
*tutorial_mode = TUTORIAL_MODE_CONFIRM_SIGNIN;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_SHOW_ERROR:
*bubble_view_mode = BUBBLE_VIEW_MODE_PROFILE_CHOOSER;
*tutorial_mode = TUTORIAL_MODE_SHOW_ERROR;
return;
case BrowserWindow::AVATAR_BUBBLE_MODE_FAST_USER_SWITCH:
*bubble_view_mode = profiles::BUBBLE_VIEW_MODE_FAST_PROFILE_CHOOSER;
return;
default:
*bubble_view_mode = profiles::BUBBLE_VIEW_MODE_PROFILE_CHOOSER;
}
}
bool ShouldShowWelcomeUpgradeTutorial(
Profile* profile, TutorialMode tutorial_mode) {
const int show_count = profile->GetPrefs()->GetInteger(
prefs::kProfileAvatarTutorialShown);
// Do not show the tutorial if user has dismissed it.
if (show_count > signin_ui_util::kUpgradeWelcomeTutorialShowMax)
return false;
return tutorial_mode == TUTORIAL_MODE_WELCOME_UPGRADE ||
show_count != signin_ui_util::kUpgradeWelcomeTutorialShowMax;
}
bool ShouldShowRightClickTutorial(Profile* profile) {
PrefService* local_state = g_browser_process->local_state();
const bool dismissed = local_state->GetBoolean(
prefs::kProfileAvatarRightClickTutorialDismissed);
// Don't show the tutorial if it's already been dismissed or if right-clicking
// wouldn't show any targets.
return !dismissed && HasProfileSwitchTargets(profile);
}
} // namespace profiles
| 39.284658 | 80 | 0.731144 | [
"vector"
] |
370c2e0d9b7784700e04e4a5be03f18dbe3682a2 | 3,377 | cpp | C++ | Source/Model/Reader/NMR_ModelReader.cpp | qmuntal/lib3mf | ad82d2f17bd37b942635c9cc7a33e4ea060b7adf | [
"BSD-2-Clause"
] | 1 | 2021-11-26T13:23:39.000Z | 2021-11-26T13:23:39.000Z | Source/Model/Reader/NMR_ModelReader.cpp | qmuntal/lib3mf | ad82d2f17bd37b942635c9cc7a33e4ea060b7adf | [
"BSD-2-Clause"
] | null | null | null | Source/Model/Reader/NMR_ModelReader.cpp | qmuntal/lib3mf | ad82d2f17bd37b942635c9cc7a33e4ea060b7adf | [
"BSD-2-Clause"
] | null | null | null | /*++
Copyright (C) 2018 3MF Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Abstract:
NMR_ModelReader.cpp implements the Model Reader Class.
A model reader reads in a model file and generates an in-memory representation of it.
--*/
#include "Model/Reader/NMR_ModelReader.h"
#include "Common/NMR_Exception.h"
#include "Common/NMR_Exception_Windows.h"
#include "Common/Platform/NMR_ImportStream.h"
#include "Model/Classes/NMR_ModelObject.h"
#include "Model/Classes/NMR_ModelMeshObject.h"
#include "Model/Classes/NMR_ModelBuildItem.h"
namespace NMR {
CModelReader::CModelReader(_In_ PModel pModel)
{
if (!pModel.get())
throw CNMRException(NMR_ERROR_INVALIDPARAM);
m_pModel = pModel;
m_pWarnings = std::make_shared<CModelReaderWarnings>();
m_pProgressMonitor = std::make_shared<CProgressMonitor>();
// Clear all legacy settings
m_pModel->clearAll();
}
void CModelReader::readFromMeshImporter(_In_ CMeshImporter * pImporter)
{
__NMRASSERT(pImporter);
// Create Empty Mesh
PMesh pMesh = std::make_shared<CMesh>();
// Import Mesh
pImporter->loadMesh(pMesh.get(), nullptr);
// Add Single Mesh to Model
PModelMeshObject pMeshObject = std::make_shared<CModelMeshObject>(m_pModel->generateResourceID(), m_pModel.get(), pMesh);
m_pModel->addResource(pMeshObject);
// Add Build Item to Model
PModelBuildItem pBuildItem = std::make_shared<CModelBuildItem>(pMeshObject.get(), m_pModel->createHandle());
m_pModel->addBuildItem(pBuildItem);
}
PImportStream CModelReader::retrievePrintTicket(_Out_ std::string & sContentType)
{
sContentType = m_sPrintTicketContentType;
return m_pPrintTicketStream;
}
PModelReaderWarnings CModelReader::getWarnings()
{
return m_pWarnings;
}
void CModelReader::addRelationToRead(_In_ std::string sRelationShipType)
{
m_RelationsToRead.insert(sRelationShipType);
}
void CModelReader::removeRelationToRead(_In_ std::string sRelationShipType)
{
m_RelationsToRead.erase(sRelationShipType);
}
void CModelReader::SetProgressCallback(Lib3MFProgressCallback callback, void* userData)
{
m_pProgressMonitor->SetProgressCallback(callback, userData);
}
}
| 32.786408 | 123 | 0.787385 | [
"mesh",
"model"
] |
37152a7e8609cd527a26d4933d5ea57ef2bc7257 | 6,582 | cc | C++ | JetMETCorrections/Type1MET/plugins/MultShiftMETcorrDBInputProducer.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2020-01-21T11:23:39.000Z | 2020-01-21T11:23:42.000Z | JetMETCorrections/Type1MET/plugins/MultShiftMETcorrDBInputProducer.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 8 | 2020-03-20T23:18:36.000Z | 2020-05-27T11:00:06.000Z | JetMETCorrections/Type1MET/plugins/MultShiftMETcorrDBInputProducer.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | #include "JetMETCorrections/Type1MET/plugins/MultShiftMETcorrDBInputProducer.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "CondFormats/JetMETObjects/interface/MEtXYcorrectParameters.h"
#include "CondFormats/JetMETObjects/interface/Utilities.h"
#include "JetMETCorrections/Objects/interface/MEtXYcorrectRecord.h"
#include "DataFormats/METReco/interface/CorrMETData.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/Common/interface/View.h"
#include <TString.h>
int MultShiftMETcorrDBInputProducer::translateTypeToAbsPdgId(reco::PFCandidate::ParticleType type) {
switch (type) {
case reco::PFCandidate::ParticleType::h:
return 211; // pi+
case reco::PFCandidate::ParticleType::e:
return 11;
case reco::PFCandidate::ParticleType::mu:
return 13;
case reco::PFCandidate::ParticleType::gamma:
return 22;
case reco::PFCandidate::ParticleType::h0:
return 130; // K_L0
case reco::PFCandidate::ParticleType::h_HF:
return 1; // dummy pdg code
case reco::PFCandidate::ParticleType::egamma_HF:
return 2; // dummy pdg code
case reco::PFCandidate::ParticleType::X:
default:
return 0;
}
}
MultShiftMETcorrDBInputProducer::MultShiftMETcorrDBInputProducer(const edm::ParameterSet& cfg)
: moduleLabel_(cfg.getParameter<std::string>("@module_label")) {
mPayloadName = cfg.getParameter<std::string>("payloadName");
mSampleType = (cfg.exists("sampleType")) ? cfg.getParameter<std::string>("sampleType") : "MC";
mIsData = cfg.getParameter<bool>("isData");
pflow_ = consumes<edm::View<reco::Candidate> >(cfg.getParameter<edm::InputTag>("srcPFlow"));
vertices_ = consumes<edm::View<reco::Vertex> >(cfg.getParameter<edm::InputTag>("vertexCollection"));
etaMin_.clear();
etaMax_.clear();
produces<CorrMETData>();
}
MultShiftMETcorrDBInputProducer::~MultShiftMETcorrDBInputProducer() {}
void MultShiftMETcorrDBInputProducer::produce(edm::Event& evt, const edm::EventSetup& es) {
// Get para.s from DB
edm::ESHandle<MEtXYcorrectParametersCollection> MEtXYcorParaColl;
es.get<MEtXYcorrectRecord>().get(mPayloadName, MEtXYcorParaColl);
// get the sections from Collection (pair of section and METCorr.Par class)
std::vector<MEtXYcorrectParametersCollection::key_type> keys;
// save level to keys for each METParameter in METParameter collection
MEtXYcorParaColl->validKeys(keys);
//get primary vertices
edm::Handle<edm::View<reco::Vertex> > hpv;
evt.getByToken(vertices_, hpv);
if (!hpv.isValid()) {
edm::LogError("MultShiftMETcorrDBInputProducer::produce") << "could not find vertex collection ";
}
std::vector<reco::Vertex> goodVertices;
for (unsigned i = 0; i < hpv->size(); i++) {
if ((*hpv)[i].ndof() > 4 && (fabs((*hpv)[i].z()) <= 24.) && (fabs((*hpv)[i].position().rho()) <= 2.0))
goodVertices.push_back((*hpv)[i]);
}
int ngoodVertices = goodVertices.size();
edm::Handle<edm::View<reco::Candidate> > particleFlow;
evt.getByToken(pflow_, particleFlow);
//loop over all constituent types and sum each correction
//std::unique_ptr<CorrMETData> metCorr(new CorrMETData());
std::unique_ptr<CorrMETData> metCorr(new CorrMETData());
double corx = 0.;
double cory = 0.;
// check DB
for (std::vector<MEtXYcorrectParametersCollection::key_type>::const_iterator ikey = keys.begin(); ikey != keys.end();
++ikey) {
if (mIsData) {
if (!MEtXYcorParaColl->isShiftData(*ikey))
throw cms::Exception("MultShiftMETcorrDBInputProducer::produce")
<< "DB is not for Data. Set proper option: \"corrPfMetXYMultDB.isData\" !!\n";
} else {
if (MEtXYcorParaColl->isShiftData(*ikey))
throw cms::Exception("MultShiftMETcorrDBInputProducer::produce")
<< "DB is for Data. Set proper option: \"corrPfMetXYMultDB.isData\" !!\n";
}
}
for (std::vector<MEtXYcorrectParametersCollection::key_type>::const_iterator ikey = keys.begin(); ikey != keys.end();
++ikey) {
if (!mIsData) {
if (mSampleType == "MC") {
if (!MEtXYcorParaColl->isShiftMC(*ikey))
continue;
} else if (mSampleType == "DY") {
if (!MEtXYcorParaColl->isShiftDY(*ikey))
continue;
} else if (mSampleType == "TTJets") {
if (!MEtXYcorParaColl->isShiftTTJets(*ikey))
continue;
} else if (mSampleType == "WJets") {
if (!MEtXYcorParaColl->isShiftWJets(*ikey))
continue;
} else
throw cms::Exception("MultShiftMETcorrDBInputProducer::produce")
<< "SampleType: " << mSampleType << " is not reserved !!!\n";
}
std::string sectionName = MEtXYcorParaColl->findLabel(*ikey);
MEtXYcorrectParameters const& MEtXYcorParams = (*MEtXYcorParaColl)[*ikey];
counts_ = 0;
sumPt_ = 0;
for (unsigned i = 0; i < particleFlow->size(); ++i) {
const reco::Candidate& c = particleFlow->at(i);
if (abs(c.pdgId()) ==
translateTypeToAbsPdgId(reco::PFCandidate::ParticleType(MEtXYcorParams.definitions().PtclType()))) {
if ((c.eta() > MEtXYcorParams.record(0).xMin(0)) and (c.eta() < MEtXYcorParams.record(0).xMax(0))) {
counts_ += 1;
sumPt_ += c.pt();
continue;
}
}
}
double val(0.);
unsigned parVar = MEtXYcorParams.definitions().parVar(0);
if (parVar == 0) {
val = counts_;
} else if (parVar == 1) {
val = ngoodVertices;
} else if (parVar == 2) {
val = sumPt_;
} else {
throw cms::Exception("MultShiftMETcorrDBInputProducer::produce")
<< "parVar: " << parVar << " is not reserved !!!\n";
}
formula_x_.reset(new TF1("corrPx", MEtXYcorParams.definitions().formula().c_str()));
formula_y_.reset(new TF1("corrPy", MEtXYcorParams.definitions().formula().c_str()));
for (unsigned i(0); i < MEtXYcorParams.record(0).nParameters(); i++) {
formula_x_->SetParameter(i, MEtXYcorParams.record(0).parameter(i));
}
for (unsigned i(0); i < MEtXYcorParams.record(1).nParameters(); i++) {
formula_y_->SetParameter(i, MEtXYcorParams.record(1).parameter(i));
}
corx -= formula_x_->Eval(val);
cory -= formula_y_->Eval(val);
} //end loop over corrections
metCorr->mex = corx;
metCorr->mey = cory;
evt.put(std::move(metCorr), "");
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(MultShiftMETcorrDBInputProducer);
| 36.77095 | 119 | 0.671376 | [
"vector"
] |
3719c5a15f09bf53dbd9864a5c6d15ee6060e38e | 2,109 | cpp | C++ | src/CommandLineParser.cpp | grahambrooks/jak | 14e6c195807b797471b11499f2ffe6cde898321c | [
"MIT"
] | null | null | null | src/CommandLineParser.cpp | grahambrooks/jak | 14e6c195807b797471b11499f2ffe6cde898321c | [
"MIT"
] | null | null | null | src/CommandLineParser.cpp | grahambrooks/jak | 14e6c195807b797471b11499f2ffe6cde898321c | [
"MIT"
] | null | null | null | #include <iostream>
#include "CommandLineParser.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
CommandLineParser::RuntimeConfiguration CommandLineParser::parse(int argc, char *argv[]) {
const char* commands_key = "commands";
try {
std::string appName = boost::filesystem::basename(argv[0]);
std::vector<std::string> sentence;
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print help messages")
("token,t", po::value<std::string>(), "Access token for account access")
(commands_key, po::value<std::vector<std::string> >(), commands_key);
po::positional_options_description positionalOptions;
positionalOptions.add(commands_key, -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(positionalOptions).run(), vm);
if (vm.count("help")) {
std::cout << desc;
return RuntimeConfiguration(ParserStatus::SUCCESS);
}
po::notify(vm);
if (vm.count(commands_key)) {
auto commands = vm[commands_key].as<std::vector<std::string>>();
return RuntimeConfiguration(ParserStatus::SUCCESS, "", commands);
}
}
catch (boost::program_options::required_option &e) {
return RuntimeConfiguration(ParserStatus::ERROR_IN_COMMAND_LINE, e.what());
}
catch (boost::program_options::error &e) {
return RuntimeConfiguration(ParserStatus::ERROR_IN_COMMAND_LINE, e.what());
}
}
catch (std::exception &e) {
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return RuntimeConfiguration(ParserStatus::ERROR_UNHANDLED_EXCEPTION);
}
return RuntimeConfiguration(ParserStatus::SUCCESS);
}
| 36.362069 | 90 | 0.59412 | [
"vector"
] |
371b0cac4165027061348b3ed819c4250f0f6347 | 8,441 | cpp | C++ | src/llvm/analysis/PointsTo/Structure.cpp | tum-i4/dg | 287f5fe9a0e7fd01ab57a3480bf2f51d0b6e0f9a | [
"MIT"
] | 1 | 2019-12-16T01:48:08.000Z | 2019-12-16T01:48:08.000Z | src/llvm/analysis/PointsTo/Structure.cpp | tum-i4/dg | 287f5fe9a0e7fd01ab57a3480bf2f51d0b6e0f9a | [
"MIT"
] | 1 | 2018-07-02T19:42:04.000Z | 2018-07-02T19:42:04.000Z | src/llvm/analysis/PointsTo/Structure.cpp | ManSoSec/dg | 4bd115f8cf26d3584f009c92c0f7c21b1fb57307 | [
"MIT"
] | 1 | 2021-02-10T02:14:31.000Z | 2021-02-10T02:14:31.000Z | #include <cassert>
#include <set>
// ignore unused parameters in LLVM libraries
#if (__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <llvm/Config/llvm-config.h>
#if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 5))
#include <llvm/Support/CFG.h>
#else
#include <llvm/IR/CFG.h>
#endif
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Constant.h>
#include <llvm/Support/raw_os_ostream.h>
#if (__clang__)
#pragma clang diagnostic pop // ignore -Wunused-parameter
#else
#pragma GCC diagnostic pop
#endif
#include "analysis/PointsTo/PointerSubgraph.h"
#include "PointerSubgraph.h"
namespace dg {
namespace analysis {
namespace pta {
static size_t blockAddSuccessors(std::map<const llvm::BasicBlock *,
PSNodesSeq>& built_blocks,
std::set<const llvm::BasicBlock *>& found_blocks,
PSNodesSeq& ptan,
const llvm::BasicBlock& block)
{
size_t num = 0;
for (llvm::succ_const_iterator
S = llvm::succ_begin(&block), SE = llvm::succ_end(&block); S != SE; ++S) {
// we already processed this block? Then don't try to add the edges again
if (!found_blocks.insert(*S).second)
continue;
PSNodesSeq& succ = built_blocks[*S];
assert((succ.first && succ.second) || (!succ.first && !succ.second));
if (!succ.first) {
// if we don't have this block built (there was no points-to
// relevant instruction), we must pretend to be there for
// control flow information. Thus instead of adding it as
// successor, add its successors as successors
num += blockAddSuccessors(built_blocks, found_blocks, ptan, *(*S));
} else {
// add successor to the last nodes
ptan.second->addSuccessor(succ.first);
++num;
}
// assert that we didn't corrupt the block
assert((succ.first && succ.second) || (!succ.first && !succ.second));
}
return num;
}
PSNodesSeq
LLVMPointerSubgraphBuilder::buildArguments(const llvm::Function& F)
{
PSNodesSeq seq;
PSNode *last = nullptr;
int idx = 0;
for (auto A = F.arg_begin(), E = F.arg_end(); A != E; ++A, ++idx) {
auto it = nodes_map.find(&*A);
if (it == nodes_map.end())
continue;
PSNodesSeq& cur = it->second;
assert(cur.first == cur.second);
if (!seq.first) {
assert(!last);
seq.first = cur.first;
} else {
assert(last);
last->addSuccessor(cur.first);
}
last = cur.second;
}
seq.second = last;
assert((seq.first && seq.second) || (!seq.first && !seq.second));
return seq;
}
PSNodesSeq LLVMPointerSubgraphBuilder::buildBlockStructure(const llvm::BasicBlock& block)
{
PSNodesSeq seq = PSNodesSeq(nullptr, nullptr);
PSNode *last = nullptr;
for (const llvm::Instruction& Inst : block) {
auto it = nodes_map.find(&Inst);
if (it == nodes_map.end()) {
assert(!isRelevantInstruction(Inst));
continue;
}
PSNodesSeq& cur = it->second;
if (!seq.first) {
assert(!last);
seq.first = cur.first;
} else {
assert(last);
last->addSuccessor(cur.first);
}
// We store only the call node
// in the nodes_map, so there is not valid (call, return)
// sequence but only one node (actually, for call that may not
// be a sequence). We need to "insert" whole call here,
// so set the return node as the last node
if (llvm::isa<llvm::CallInst>(&Inst) &&
// undeclared funcs do not have paired nodes
cur.first->getPairedNode()) {
last = cur.first->getPairedNode();
} else
last = cur.second;
}
seq.second = last;
assert((seq.first && seq.second) || (!seq.first && !seq.second));
if (seq.first)
built_blocks[&block] = seq;
return seq;
}
void LLVMPointerSubgraphBuilder::addProgramStructure(const llvm::Function *F,
Subgraph& subg)
{
assert(subg.root && "Subgraph has no root");
assert(subg.ret && "Subgraph has no ret");
// with function pointer calls it may happen that we try
// to add structure more times, so bail out in that case
if (subg.has_structure)
return;
PSNodesSeq args = buildArguments(*F);
PSNode *lastNode = nullptr;
// make arguments the entry block of the subgraphs (if there
// are any arguments)
if (args.first) {
assert(args.second && "BUG: Have only first argument");
subg.root->addSuccessor(args.first);
// inset the variadic arg node into the graph if needed
if (F->isVarArg()) {
assert(subg.vararg);
args.second->addSuccessor(subg.vararg);
lastNode = subg.vararg;
} else
lastNode = args.second;
} else if (subg.vararg) {
// this function has only ... argument
assert(F->isVarArg());
assert(!args.second && "BUG: Have only last argument");
subg.root->addSuccessor(subg.vararg);
lastNode = subg.vararg;
} else {
assert(!args.second && "BUG: Have only last argument");
lastNode = subg.root;
}
assert(lastNode);
// add successors in one basic block
for (const llvm::BasicBlock* block : subg.llvmBlocks)
buildBlockStructure(*block);
// check whether we create the entry block. If not, we would
// have a problem while adding successors, so fake that
// the entry block is the root or the last argument
const llvm::BasicBlock *entry = &F->getBasicBlockList().front();
PSNodesSeq& enblk = built_blocks[entry];
if (!enblk.first) {
assert(!enblk.second);
enblk.first = subg.root;
enblk.second = lastNode;
} else {
// if we have the entry block, just make it the successor
// of the root or the last argument
lastNode->addSuccessor(enblk.first);
}
std::vector<PSNode *> rets;
for (const llvm::BasicBlock& block : *F) {
PSNodesSeq& ptan = built_blocks[&block];
// if the block does not contain any points-to relevant instruction,
// we get (nullptr, nullptr)
assert((ptan.first && ptan.second) || (!ptan.first && !ptan.second));
if (!ptan.first)
continue;
// add successors to this block (skipping the empty blocks).
// To avoid infinite loops we use found_blocks container that will
// server as a mark in BFS/DFS - the program should not contain
// so many blocks that this could have some big overhead. If proven
// otherwise later, we'll change this.
std::set<const llvm::BasicBlock *> found_blocks;
size_t succ_num = blockAddSuccessors(built_blocks,
found_blocks,
ptan, block);
// if we have not added any successor, then the last node
// of this block is a return node
if (succ_num == 0 && ptan.second->getType() == PSNodeType::RETURN)
rets.push_back(ptan.second);
assert(ptan.first && ptan.second);
}
// add successors edges from every real return to our artificial ret node
// NOTE: if the function has infinite loop we won't have any return nodes,
// so this assertion must not hold
//assert(!rets.empty() && "BUG: Did not find any return node in function");
for (PSNode *r : rets) {
r->addSuccessor(subg.ret);
}
// set parents of nodes
// FIXME: we should do this when creating the nodes
std::set<PSNode *> cont;
getNodes(cont, subg.root, subg.ret, 0xdead);
for (PSNode* n : cont) {
n->setParent(subg.root);
}
subg.has_structure = true;
}
} // namespace pta
} // namespace analysis
} // namespace dg
| 31.733083 | 89 | 0.594598 | [
"vector"
] |
7deb5d3a5e32e083d978320504f14aa3f67f4bd2 | 5,094 | cpp | C++ | cpp/src/render/utils/vega/vega_choropleth_map/vega_choropleth_map.cpp | xiaocai2333/arctern_test | 852b5d14f3669b16a76b3f7a93f62c51b7a707b9 | [
"Apache-2.0"
] | null | null | null | cpp/src/render/utils/vega/vega_choropleth_map/vega_choropleth_map.cpp | xiaocai2333/arctern_test | 852b5d14f3669b16a76b3f7a93f62c51b7a707b9 | [
"Apache-2.0"
] | null | null | null | cpp/src/render/utils/vega/vega_choropleth_map/vega_choropleth_map.cpp | xiaocai2333/arctern_test | 852b5d14f3669b16a76b3f7a93f62c51b7a707b9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019-2020 Zilliz. 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 <string>
#include <utility>
#include "render/utils/vega/vega_choropleth_map/vega_choropleth_map.h"
namespace zilliz {
namespace render {
VegaChoroplethMap::VegaChoroplethMap(const std::string& json) { Parse(json); }
std::string VegaChoroplethMap::Build() {
// TODO: add Build() api to build a vega json string.
return "";
}
void VegaChoroplethMap::Parse(const std::string& json) {
rapidjson::Document document;
document.Parse(json.c_str());
if (document.Parse(json.c_str()).HasParseError()) {
printf("json format error\n");
return;
}
if (!JsonLabelCheck(document, "width") || !JsonLabelCheck(document, "height") ||
!JsonTypeCheck(document["width"], rapidjson::Type::kNumberType) ||
!JsonTypeCheck(document["height"], rapidjson::Type::kNumberType)) {
return;
}
window_params_.mutable_width() = document["width"].GetInt();
window_params_.mutable_height() = document["height"].GetInt();
if (!JsonLabelCheck(document, "marks") ||
!JsonTypeCheck(document["marks"], rapidjson::Type::kArrayType) ||
!JsonSizeCheck(document["marks"], "marks", 1) ||
!JsonLabelCheck(document["marks"][0], "encode") ||
!JsonLabelCheck(document["marks"][0]["encode"], "enter")) {
return;
}
rapidjson::Value mark_enter;
mark_enter = document["marks"][0]["encode"]["enter"];
// parse bounding box
if (!JsonLabelCheck(mark_enter, "bounding_box") ||
!JsonLabelCheck(mark_enter["bounding_box"], "value") ||
!JsonTypeCheck(mark_enter["bounding_box"]["value"], rapidjson::Type::kArrayType) ||
!JsonSizeCheck(mark_enter["bounding_box"]["value"], "bounding_box.value", 4)) {
return;
}
for (int i = 0; i < 4; i++) {
if (!JsonTypeCheck(mark_enter["bounding_box"]["value"][i],
rapidjson::Type::kNumberType)) {
return;
}
}
bounding_box_.longitude_left = mark_enter["bounding_box"]["value"][0].GetDouble();
bounding_box_.latitude_left = mark_enter["bounding_box"]["value"][1].GetDouble();
bounding_box_.longitude_right = mark_enter["bounding_box"]["value"][2].GetDouble();
bounding_box_.latitude_right = mark_enter["bounding_box"]["value"][3].GetDouble();
// parse color style
if (!JsonLabelCheck(mark_enter, "color_style") ||
!JsonLabelCheck(mark_enter["color_style"], "value") ||
!JsonTypeCheck(mark_enter["color_style"]["value"], rapidjson::Type::kStringType)) {
return;
}
auto color_style_string = std::string(mark_enter["color_style"]["value"].GetString());
if (color_style_string == "blue_to_red") {
color_style_ = ColorStyle::kBlueToRed;
} else if (color_style_string == "skyblue_to_white") {
color_style_ = ColorStyle::kSkyBlueToWhite;
} else if (color_style_string == "purple_to_yellow") {
color_style_ = ColorStyle::kPurpleToYellow;
} else if (color_style_string == "red_transparency") {
color_style_ = ColorStyle::kRedTransParency;
} else if (color_style_string == "blue_transparency") {
color_style_ = ColorStyle::kBlueTransParency;
} else if (color_style_string == "blue_green_yellow") {
color_style_ = ColorStyle::kBlueGreenYellow;
} else if (color_style_string == "white_blue") {
color_style_ = ColorStyle::kWhiteToBlue;
} else if (color_style_string == "blue_white_red") {
color_style_ = ColorStyle::kBlueWhiteRed;
} else if (color_style_string == "green_yellow_red") {
color_style_ = ColorStyle::kGreenYellowRed;
} else {
std::string msg = "unsupported color style '" + color_style_string + "'.";
// TODO: add log here
}
// parse ruler
if (!JsonLabelCheck(mark_enter, "ruler") ||
!JsonLabelCheck(mark_enter["ruler"], "value") ||
!JsonTypeCheck(mark_enter["ruler"]["value"], rapidjson::Type::kArrayType) ||
!JsonSizeCheck(mark_enter["ruler"]["value"], "ruler.value", 2)) {
return;
}
for (int i = 0; i < 2; i++) {
if (!JsonTypeCheck(mark_enter["ruler"]["value"][i], rapidjson::Type::kNumberType)) {
return;
}
}
ruler_ = std::make_pair(mark_enter["ruler"]["value"][0].GetDouble(),
mark_enter["ruler"]["value"][1].GetDouble());
// parse opacity
if (!JsonLabelCheck(mark_enter, "opacity") ||
!JsonLabelCheck(mark_enter["opacity"], "value") ||
!JsonTypeCheck(mark_enter["opacity"]["value"], rapidjson::Type::kNumberType)) {
return;
}
opacity_ = mark_enter["opacity"]["value"].GetDouble();
}
} // namespace render
} // namespace zilliz
| 38.590909 | 89 | 0.677856 | [
"render"
] |
7deba866e2a8d2de079bfef0a0b3f2e295cbba79 | 1,565 | cpp | C++ | Sort-I/shell_sort.cpp | shunjilin/AOJ-algo-data-structures | 89ab47af6d836998db5a236bc2f1377d19317e49 | [
"MIT"
] | 2 | 2016-12-17T09:08:39.000Z | 2017-08-22T19:11:19.000Z | Sort-I/shell_sort.cpp | shunjilin/AOJ-algo-data-structures | 89ab47af6d836998db5a236bc2f1377d19317e49 | [
"MIT"
] | null | null | null | Sort-I/shell_sort.cpp | shunjilin/AOJ-algo-data-structures | 89ab47af6d836998db5a236bc2f1377d19317e49 | [
"MIT"
] | null | null | null | /**
Selection Sort
<Print # of swap operations>
Shunji Lin
10/12/2015
**/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int swap_count = 0; // number of swaps
void insertion_sort(vector<int> &sort_vec, int n, int interval) {
for (int i = interval; i < n; ++i) {
int pivot = sort_vec[i];
int j = i - interval;
while (j >= 0 && sort_vec[j] > pivot) { //
sort_vec[j + interval] = sort_vec[j]; // perform swap
j = j - interval; // drop by interval
swap_count++;
}
sort_vec[j + interval] = pivot; // put pivot in proper place
}
}
int main() {
int n; //number of entries
cin >> n;
vector<int> sort_vec;
//initialize unsorted vector
for (int i = 0; i < n; ++i) {
int entry;
cin >> entry;
sort_vec.push_back(entry);
}
vector<int> intervals;
//initialize array according to formula k_next = 3*k_prev + 1 (Knuth)
int next = 1;
while (true) {
intervals.push_back(next);
next = next * 3 + 1;
if (next >= n) break;
}
int intervals_size = intervals.size();
//shell sort
for (int i = intervals_size - 1; i >= 0; --i) {
insertion_sort(sort_vec, n, intervals[i]);
}
//print results
cout << intervals_size << endl; // number of intervals
for (int i = intervals_size - 1; i >= 0; --i) {
cout << intervals[i];
if (i <= n - 1) cout << " ";
}
cout << endl;
cout << swap_count << endl; // number of swaps
for (int i = 0; i < n; ++i) { // sorted vector
cout << sort_vec[i] << endl;
}
}
| 20.324675 | 71 | 0.573802 | [
"vector"
] |
7decf6261662672b605c9668004ec1f721ec1db7 | 958 | cc | C++ | codeforces/266/b.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | codeforces/266/b.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | codeforces/266/b.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
int main() {
ll n, a, b;
cin >> n >> a >> b;
n *= 6;
ll m = numeric_limits<ll>::max();
ll x, y;
while (a * b <= n) {
ll d = n / b;
if (n % b) ++d;
d = max(d, a);
if (m > d * b) {
x = d;
y = b;
m = d * b;
}
d = n / a;
if (n % a) ++d;
d = max(d, b);
if (m > d * a) {
x = a;
y = d;
m = d * a;
}
++a;
++b;
}
if (m > a * b) {
x = a;
y = b;
m = b * a;
}
printf("%llu\n%llu %llu\n", m, x, y);
}
| 15.966667 | 39 | 0.487474 | [
"vector"
] |
7df535c9d26b9e8ff89e63a388f6e4585a9b8bfe | 30,012 | cpp | C++ | source/matplot/axes_objects/surface.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | source/matplot/axes_objects/surface.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | source/matplot/axes_objects/surface.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | //
// Created by Alan Freitas on 2020-07-07.
//
#include <cmath>
#include <sstream>
#include <regex>
#include <matplot/axes_objects/surface.h>
#include <matplot/core/axes.h>
#include <matplot/util/common.h>
namespace matplot {
surface::surface(class axes* parent) : axes_object(parent) {}
surface::surface(class axes* parent, const vector_2d& X, const vector_2d& Y, const vector_2d& Z, const vector_2d& C, const std::string& line_spec)
: axes_object(parent), X_data_(X), Y_data_(Y), Z_data_(Z), C_data_(C), line_spec_(this, line_spec), contour_line_spec_(this, ""), is_parametric_(false) {
zmin_ = Z_data_[0][0];
zmax_ = Z_data_[0][0];
for (size_t i = 0; i < Z_data_.size(); ++i) {
auto [row_min, row_max] = std::minmax_element(Z_data_[i].begin(), Z_data_[i].end());
if (*row_min < zmin_) {
zmin_ = *row_min;
}
if (*row_max > zmax_) {
zmax_ = *row_max;
}
}
}
// surface::surface(class xlim* parent, const vector_1d& x, const vector_1d& y, const vector_1d& z, const vector_1d& c, const std::string& line_spec)
// : axes_object(parent), X_data_({x}), Y_data_({y}), Z_data_({z}), C_data_({c}), line_spec_(this, line_spec), contour_line_spec_(this, ""), is_parametric_(true) {
// auto [zmin_it, zmax_it] = std::minmax_element(z.begin(), z.end());
// zmin_ = *zmin_it;
// zmax_ = *zmax_it;
// }
size_t surface::create_line_index() {
auto it = std::find_if(parent_->children().begin(), parent_->children().end(),
[this](const auto& c) {
return c.get() == this;
});
if (it != parent_->children().end()) {
return 100 * (1 + it - parent_->children().begin());
} else {
std::cerr << "Cannot find surface in the parent xlim" << std::endl;
return 100;
}
}
std::string surface::set_variables_string() {
maybe_update_line_spec();
std::stringstream ss;
if (surface_in_2d_) {
ss << " set view map\n";
}
// We used to create a line style for the surface
// We now create the line style directly in the plot command
// size_t line_index = create_line_index();
// Line style for the surface
// if (line_spec_.user_color()) {
// ss << " set style line " << line_index << " " << line_spec_.plot_string(line_spec::style_to_plot::plot_line_only, false) << "\n";
// } else {
// ss << " set style line " << line_index << " linecolor rgb \"black\" dashtype 1 linewidth 0.5 linetype -1\n";
// }
// If there is any kind of palette surface being plotted besides the lines
// if there is a pm3d surface, set the options
const bool palette_map_3d = palette_map_at_bottom_ || palette_map_at_surface_ || palette_map_at_top_;
if (palette_map_3d) {
ss << " set pm3d";
ss << " noborder";
// explicit: only show surface if we use with 3dpm
ss << " explicit";
// simple lighting
if (lighting_) {
ss << " lighting";
if (primary_ >= 0) {
ss << " primary " << std::clamp(primary_,0.f,1.f);
}
if (specular_ >= 0) {
ss << " specular " << std::clamp(specular_,0.f,1.f);
}
}
if (depthorder_) {
// depthorder:
ss << " depthorder base";
}
// hidden3d hides what's behind / makes the surface solid
// - this makes the surface easier to visualize
// - 1 is the linestyle for pm3d lines
if (!fences_) {
// We used to create a line style for the surface
// We now create the line style directly in the plot command
// ss << " hidden3d " << line_index;
ss << " hidden3d ";
}
ss << "\n";
if (face_alpha_ != 1.) {
ss << " set style fill transparent solid " << face_alpha_ << " noborder\n";
}
}
// global hidden3d
if (hidden3d_) {
ss << " set hidden3d\n";
} else {
// unset the global hidden3d
ss << " unset hidden3d\n";
}
// set dgrid3d
constexpr bool use_gnuplots_grid3d = false;
if (use_gnuplots_grid3d) {
bool manual_color = size(C_data_) == size(Z_data_);
if (!manual_color) {
// dgrid ensures non-grid data is converted to grids
// dgrid3d does not work with the forth color column
ss << " set dgrid3d " << Y_data_.size() << "," << Y_data_[0].size() << " qnorm " << norm_ << "\n";
}
}
// include contour
const bool contour = (contour_base_ || contour_surface_);
if (contour) {
const bool explicit_contour_levels = !contour_values_.empty();
if (explicit_contour_levels) {
ss << " set cntrparam levels discrete " << contour_values_[0];
for (size_t i = 1; i < contour_values_.size(); ++i) {
ss << "," << contour_values_[i];
}
ss << "\n";
} else if (contour_levels_ != 0) {
ss << " set cntrparam levels " << contour_levels_ << "\n";
}
if (contour_base_ && contour_surface_) {
ss << " set contour both\n";
} else if (contour_surface_) {
ss << " set contour surface\n";
} else {
ss << " set contour base\n";
}
if (contour_text_) {
ss << " set style textbox opaque margins 0.5, 0.5 fc bgnd noborder linewidth 1.0\n";
ss << " set cntrlabel format '";
if (iequals(font_weight_,"bold")) {
ss << "{/:Bold %8.3g}";
} else {
ss << "%8.3g";
}
ss << "' font '" << escape(font()) << "," << font_size() << "' start 5 interval 10\n";
}
size_t n_contour_lines = explicit_contour_levels ? contour_values_.size() : contour_levels_;
// line types for contour
auto [min_level_it, max_level_it] = std::minmax_element(contour_values_.begin(), contour_values_.end());
for (size_t i = 0; i < n_contour_lines; ++i) {
// ss << " set linetype " << i + line_index + 1;
ss << " set linetype " << i + 1;
switch (contour_line_spec_.line_style()) {
case line_spec::line_style::solid_line:
ss << " dashtype 1";
break;
case line_spec::line_style::dashed_line:
ss << " dashtype '--'";
break;
case line_spec::line_style::dotted_line:
ss << " dashtype '.'";
break;
case line_spec::line_style::dash_dot_line:
ss << " dashtype '-.'";
break;
default:
break;
}
// user set the color and it was not for the surface
if (contour_line_spec_.user_color()) {
// use the user color for all contour lines
ss << " linecolor rgb '" << to_string(contour_line_spec_.color()) << "'";
} else {
// otherwise, use the colormap
if (contour_values_.empty()) {
// use the color map for contour lines
const bool not_using_palette = line_spec_.user_color() && !palette_map_at_bottom_ && !palette_map_at_top_ && !palette_map_at_surface_;
const bool using_palette = !not_using_palette;
if (using_palette) {
ss << " linecolor palette";
} else {
ss << " linecolor rgb '" << to_string(parent_->colormap_interpolation(i,0.,n_contour_lines)) << "'";
}
} else {
// if we know the values, get a more precise colormap interpolation
double zmax = *max_level_it;
double zmin = *min_level_it;
ss << " linecolor rgb '" << to_string(parent_->colormap_interpolation((zmax-zmin)-(contour_values_[i]-zmin),0.,zmax-zmin)) << "'";
}
}
ss << " linewidth " << contour_line_spec_.line_width() << "\n";
}
}
if (!surface_visible_) {
ss << " unset surface\n";
}
return ss.str();
}
std::string surface::plot_string() {
std::stringstream ss;
// plot surface
bool is_solid_surface = palette_map_at_bottom_ || palette_map_at_surface_ || palette_map_at_top_;
decltype(C_data_)::value_type::const_iterator min_it, max_it;
if (fences_ && !C_data_.empty()) {
std::tie(min_it, max_it) = std::minmax_element(C_data_[0].begin(), C_data_[0].end());
}
// if we have a waterfall or fences, we create one command per row
// if we have ribbons, we create one command per column
size_t n_plots = (waterfall_ || fences_) ? Z_data_.size() :
ribbons_ ? Z_data_[0].size() : 1;
for (size_t i = 0; i < n_plots; ++i) {
if (i != 0) {
ss << ",\\\n ";
}
if (is_solid_surface) {
// size_t line_index = create_line_index();
ss << " '-' with";
if (!fences_) {
ss << " pm3d at ";
if (palette_map_at_bottom_) {
ss << "b";
}
if (palette_map_at_surface_) {
ss << "s";
}
if (palette_map_at_top_) {
ss << "t";
}
// ss << " linestyle " << line_index;
if (line_spec_.user_color()) {
ss << " " << line_spec_.plot_string(line_spec::style_to_plot::plot_line_only, false);
} else {
// Default line style for surfaces is black
// we don't follow the color order from the axes
// This would just be too ugly for surfaces.
ss << " " << " linecolor rgb \"black\" dashtype 1 linewidth 0.5 linetype -1";
}
} else {
ss << " zerrorfill";
if (!line_spec_.user_color()) {
color_array c;
if (C_data_.empty()) {
size_t color_index = i % parent_->colororder().size();
c = parent_->colororder()[color_index];
} else {
c = parent_->colormap_interpolation(C_data_[0][i], *min_it, *max_it);
}
ss << " linecolor rgb '" << to_string(c) << "'";
} else {
ss << " linecolor rgb '" << to_string(line_spec_.color()) << "'";
}
}
} else {
if (!line_spec_.user_color()) {
ss << " '-' with lines linecolor palette";
} else {
ss << " '-' with lines linecolor rgb '" << to_string(line_spec_.color()) << "'";
}
}
}
// plot contour
const bool contour = (contour_base_ || contour_surface_);
if (contour && contour_text_) {
ss << ", '-' with labels ";
const bool only_contour = !surface_visible_ && !palette_map_at_bottom_ && !palette_map_at_surface_ && !palette_map_at_surface_;
if (only_contour && iequals(font_weight_,"normal")) {
ss << "boxed ";
}
ss << " textcolor '" << to_string(font_color_) << "' ";
}
return ss.str();
}
std::string surface::legend_string(const std::string& title) {
return " keyentry " + line_spec_.plot_string(line_spec::style_to_plot::plot_line_only) + " title \"" + escape(title) + "\"";
}
std::string surface::grid_data_string() {
std::stringstream ss;
const bool contour = (contour_base_ || contour_surface_);
const bool palette_map_3d = palette_map_at_bottom_ || palette_map_at_surface_ || palette_map_at_top_;
const bool repeat_data_for_contour_labels = contour && contour_text_;
const bool manual_color = size(Z_data_) == size(C_data_);
const size_t replicates = 1 + repeat_data_for_contour_labels;
auto send_point = [](std::stringstream& ss, double x, double y, double z, double c) {
ss << " " << x;
ss << " " << y;
ss << " " << z;
if (std::isfinite(c)) {
ss << " " << c;
}
ss << "\n";
};
auto send_point_fill = [](std::stringstream& ss, double x, double y, double z, double zlow, double zhigh, double c) {
ss << " " << x;
ss << " " << y;
ss << " " << z;
ss << " " << zlow;
ss << " " << zhigh;
if (std::isfinite(c)) {
ss << " " << c;
}
ss << "\n";
};
auto color_value = [&](size_t data_replicate, size_t i, size_t j) {
if (manual_color && data_replicate == 0) {
return C_data_[i][j];
} else if (!palette_map_3d && !line_spec_.user_color()) {
return Z_data_[i][j];
} else {
return NaN;
}
};
for (size_t data_replicate = 0; data_replicate < replicates; ++data_replicate) {
if (curtain_) {
// open curtain - first line with zmin instead of z
size_t i = Y_data_.size()-1;
send_point(ss, X_data_[i][0], Y_data_[i][0], zmin_, color_value(data_replicate,i,0));
for (size_t j = 0; j < Y_data_[i].size(); ++j) {
send_point(ss, X_data_[i][j], Y_data_[i][j], zmin_, color_value(data_replicate,i,j));
}
send_point(ss, X_data_[i][Y_data_[i].size()-1], Y_data_[i][Y_data_[i].size()-1], zmin_, color_value(data_replicate,i,Y_data_[i].size()-1));
ss << "\n";
}
// each row is an isoline
for (long i = Y_data_.size() - 1; i >= 0; --i) {
// open row curtain or waterfall
if (curtain_ || waterfall_) {
send_point(ss, X_data_[i][0], Y_data_[i][0], zmin_, color_value(data_replicate,i,0));
}
// send all points in that row
for (size_t j = 0; j < Y_data_[i].size(); ++j) {
if (!fences_) {
send_point(ss, X_data_[i][j], Y_data_[i][j], Z_data_[i][j], color_value(data_replicate,i,j));
} else {
send_point_fill(ss, X_data_[i][j], Y_data_[i][j], Z_data_[i][j], zmin_, Z_data_[i][j], color_value(data_replicate,i,j));
}
}
// close row curtain or waterfall
if (curtain_ || waterfall_) {
send_point(ss, X_data_[i][Y_data_[i].size()-1], Y_data_[i][Y_data_[i].size()-1], zmin_, color_value(data_replicate,i,Y_data_[i].size()-1));
}
// end the current isoline
if (!waterfall_ && !fences_) {
// usually an empty line to indicate this isoline is over
ss << "\n";
} else {
// waterfalls and fences have one splot per row
// so we end not only the isoline
ss << "e\n";
}
}
if (curtain_) {
// close curtain
size_t i = 0;
send_point(ss, X_data_[i][0], Y_data_[i][0], zmin_, color_value(data_replicate,i,0));
for (size_t j = 0; j < Y_data_[i].size(); ++j) {
send_point(ss, X_data_[i][j], Y_data_[i][j], zmin_, color_value(data_replicate,i,j));
}
send_point(ss, X_data_[i][Y_data_[i].size()-1], Y_data_[i][Y_data_[i].size()-1], zmin_, color_value(data_replicate,i,Y_data_[i].size()-1));
ss << "\n";
}
// finish the plot
// waterfalls don't need closing again
if (!waterfall_ && !fences_) {
ss << "e\n";
}
}
return ss.str();
}
std::string surface::ribbon_data_string() {
std::stringstream ss;
auto send_point = [](std::stringstream& ss, double x, double y, double z, double c) {
ss << " " << x;
ss << " " << y;
ss << " " << z;
if (std::isfinite(c)) {
ss << " " << c;
}
ss << "\n";
};
const bool manual_color = size(Z_data_) == size(C_data_);
const bool palette_map_3d = palette_map_at_bottom_ || palette_map_at_surface_ || palette_map_at_top_;
auto color_value = [&](size_t i, size_t j) {
if (manual_color) {
return C_data_[i][j];
} else if (!palette_map_3d && !line_spec_.user_color()) {
return Z_data_[i][j];
} else {
return NaN;
}
};
const size_t n_rows = Z_data_.size();
const size_t n_cols = Z_data_[0].size();
const double x_diff = X_data_[0][1] - X_data_[0][0];
const double absolute_width = ribbon_width_ * x_diff;
// one ribbon per col
for (size_t i = 0; i < n_cols; ++i) {
// two isolines per row
for (size_t j = 0; j < n_rows; ++j) {
send_point(ss, X_data_[j][i] - absolute_width / 2., Y_data_[j][i], Z_data_[j][i], color_value(j,i));
send_point(ss, X_data_[j][i] + absolute_width / 2., Y_data_[j][i], Z_data_[j][i], color_value(j,i));
ss << "\n";
}
ss << "e\n";
}
return ss.str();
}
std::string surface::data_string() {
return !ribbons_ ? grid_data_string() : ribbon_data_string();
}
void surface::maybe_update_line_spec() {
if (!line_spec_.user_color()) {
const bool plotting_contour = (contour_surface_ || contour_base_) && !contour_values_.empty();
if (plotting_contour) {
const bool using_colormap_for_contour = contour_values_.size() != 1;
if (!using_colormap_for_contour) {
auto c = parent_->get_color_and_bump();
contour_line_spec_.color(c);
}
}
}
}
double surface::xmax() {
double m = X_data_[0][0];
for (size_t i = 0; i < X_data_.size(); ++i) {
for (size_t j = 0; j < X_data_[i].size(); ++j) {
m = std::max(m,X_data_[i][j]);
}
}
return m;
}
double surface::xmin() {
double m = X_data_[0][0];
for (size_t i = 0; i < X_data_.size(); ++i) {
for (size_t j = 0; j < X_data_[i].size(); ++j) {
m = std::min(m,X_data_[i][j]);
}
}
return m;
}
double surface::ymax() {
double m = Y_data_[0][0];
for (size_t i = 0; i < Y_data_.size(); ++i) {
for (size_t j = 0; j < Y_data_[i].size(); ++j) {
m = std::max(m,Y_data_[i][j]);
}
}
return m;
}
double surface::ymin() {
double m = Y_data_[0][0];
for (size_t i = 0; i < Y_data_.size(); ++i) {
for (size_t j = 0; j < Y_data_[i].size(); ++j) {
m = std::min(m,Y_data_[i][j]);
}
}
return m;
}
enum axes_object::axes_category surface::axes_category() {
if (!surface_in_2d_) {
return axes_object::axes_category::three_dimensional;
} else {
return axes_object::axes_category::three_dimensional_map;
}
}
class surface& surface::line_style(const std::string& str) {
line_spec_.parse_string(str);
touch();
return *this;
}
const line_spec &surface::line_spec() const {
return line_spec_;
}
line_spec &surface::line_spec() {
return line_spec_;
}
class surface& surface::line_spec(const class line_spec &line_spec) {
line_spec_ = line_spec;
touch();
return *this;
}
const vector_2d &surface::Y_data() const {
return Y_data_;
}
class surface& surface::Y_data(const vector_2d &Y_data) {
Y_data_ = Y_data;
touch();
return *this;
}
const vector_2d &surface::X_data() const {
return X_data_;
}
class surface& surface::X_data(const vector_2d &X_data) {
X_data_ = X_data;
touch();
return *this;
}
const vector_2d &surface::Z_data() const {
return Z_data_;
}
class surface& surface::Z_data(const vector_2d &Z_data) {
Z_data_ = Z_data;
touch();
return *this;
}
float surface::line_width() const {
return line_spec().line_width();
}
class surface& surface::line_width(float line_width) {
line_spec().line_width(line_width);
return *this;
}
const std::array<float, 4>& surface::edge_color() const {
return line_spec().color();
}
size_t surface::norm() const {
return norm_;
}
class surface& surface::norm(size_t norm) {
norm_ = norm;
touch();
return *this;
}
const std::vector<vector_1d> &surface::x_data() const {
return X_data_;
}
class surface& surface::x_data(const std::vector<vector_1d> &x_data) {
X_data_ = x_data;
touch();
return *this;
}
const std::vector<vector_1d> &surface::y_data() const {
return Y_data_;
}
class surface& surface::y_data(const std::vector<vector_1d> &y_data) {
Y_data_ = y_data;
touch();
return *this;
}
const std::vector<vector_1d> &surface::z_data() const {
return Z_data_;
}
class surface& surface::z_data(const std::vector<vector_1d> &z_data) {
Z_data_ = z_data;
touch();
return *this;
}
bool surface::hidden_3d() const {
return hidden3d_;
}
class surface& surface::hidden_3d(bool hidden_3_d) {
hidden3d_ = hidden_3_d;
touch();
return *this;
}
bool surface::surface_visible() const {
return surface_visible_;
}
class surface& surface::surface_visible(bool surface_visible) {
surface_visible_ = surface_visible;
touch();
return *this;
}
bool surface::surface_in_2d() const {
return surface_in_2d_;
}
class surface& surface::surface_in_2d(bool surface_in_2d) {
surface_in_2d_ = surface_in_2d;
touch();
return *this;
}
bool surface::palette_map_at_bottom() const {
return palette_map_at_bottom_;
}
class surface& surface::palette_map_at_bottom(bool palette_map_at_bottom) {
palette_map_at_bottom_ = palette_map_at_bottom;
touch();
return *this;
}
bool surface::palette_map_at_surface() const {
return palette_map_at_surface_;
}
class surface& surface::palette_map_at_surface(bool palette_map_at_surface) {
palette_map_at_surface_ = palette_map_at_surface;
touch();
return *this;
}
bool surface::palette_map_at_top() const {
return palette_map_at_top_;
}
class surface& surface::palette_map_at_top(bool palette_map_at_top) {
palette_map_at_top_ = palette_map_at_top;
touch();
return *this;
}
bool surface::contour_base() const {
return contour_base_;
}
class surface& surface::contour_base(bool contour_base) {
contour_base_ = contour_base;
if (contour_base) {
hidden3d_ = true;
}
touch();
return *this;
}
bool surface::contour_surface() const {
return contour_surface_;
}
class surface& surface::contour_surface(bool contour_surface) {
contour_surface_ = contour_surface;
if (contour_surface) {
hidden3d_ = true;
}
touch();
return *this;
}
size_t surface::contour_levels() const {
return contour_levels_;
}
class surface& surface::contour_levels(size_t contour_levels) {
contour_levels_ = contour_levels;
touch();
return *this;
}
const std::vector<double> &surface::contour_values() const {
return contour_values_;
}
class surface& surface::contour_values(const std::vector<double> &contour_values) {
contour_values_ = contour_values;
touch();
return *this;
}
bool surface::contour_text() const {
return contour_text_;
}
class surface& surface::contour_text(bool contour_text) {
contour_text_ = contour_text;
touch();
return *this;
}
const float surface::font_size() const {
if (font_size_) {
return *font_size_;
} else {
return parent_->font_size();
}
}
class surface& surface::font_size(const float &font_size) {
font_size_ = font_size;
touch();
return *this;
}
const std::string surface::font() const {
if (font_) {
return *font_;
} else {
return parent_->font();
}
}
class surface& surface::font(const std::string &font) {
font_ = font;
touch();
return *this;
}
const std::string &surface::font_weight() const {
return font_weight_;
}
class surface& surface::font_weight(const std::string &font_weight) {
font_weight_ = font_weight;
touch();
return *this;
}
const color_array &surface::font_color() const {
return font_color_;
}
class surface& surface::font_color(const color_array &font_color) {
font_color_ = font_color;
touch();
return *this;
}
class surface& surface::font_color(const std::string &fc) {
font_color(to_array(fc));
return *this;
}
bool surface::depthorder() const {
return depthorder_;
}
class surface& surface::depthorder(bool depthorder) {
depthorder_ = depthorder;
touch();
return *this;
}
float surface::face_alpha() const {
return face_alpha_;
}
class surface& surface::face_alpha(float face_alpha) {
face_alpha_ = face_alpha;
touch();
return *this;
}
bool surface::lighting() const {
return lighting_;
}
class surface& surface::lighting(bool lighting) {
lighting_ = lighting;
touch();
return *this;
}
float surface::primary() const {
return primary_;
}
class surface& surface::primary(float primary) {
primary_ = primary;
touch();
return *this;
}
float surface::specular() const {
return specular_;
}
class surface& surface::specular(float specular) {
specular_ = specular;
touch();
return *this;
}
const class line_spec &surface::contour_line_spec() const {
return contour_line_spec_;
}
class line_spec &surface::contour_line_spec() {
return contour_line_spec_;
}
class surface& surface::contour_line_spec(const class line_spec &contour_line_spec) {
contour_line_spec_ = contour_line_spec;
return *this;
}
double surface::zmin() {
return zmin_;
}
double surface::zmax() {
return zmax_;
}
bool surface::curtain() const {
return curtain_;
}
class surface& surface::curtain(bool curtain) {
curtain_ = curtain;
touch();
return *this;
}
bool surface::waterfall() const {
return waterfall_;
}
class surface& surface::waterfall(bool waterfall) {
waterfall_ = waterfall;
touch();
return *this;
}
double surface::ribbon_width() const {
return ribbon_width_;
}
class surface& surface::ribbon_width(double ribbon_width) {
if (ribbon_width != ribbon_width_) {
ribbon_width_ = ribbon_width;
touch();
}
return *this;
}
bool surface::ribbons() const {
return ribbons_;
}
class surface& surface::ribbons(bool ribbons) {
ribbons_ = ribbons;
touch();
return *this;
}
bool surface::fences() const {
return fences_;
}
class surface& surface::fences(bool fences) {
fences_ = fences;
palette_map_at_surface_ = true;
depthorder_ = true;
touch();
return *this;
}
} | 33.272727 | 174 | 0.504398 | [
"vector",
"solid"
] |
7df60ec400138748898388bb146c25dfcdeabc51 | 3,506 | cpp | C++ | src/Vector3D.cpp | zellfaze/orbitalmechanicslibrary | d3c962133c326e768112ff6b907abbf88265bb16 | [
"CC0-1.0"
] | null | null | null | src/Vector3D.cpp | zellfaze/orbitalmechanicslibrary | d3c962133c326e768112ff6b907abbf88265bb16 | [
"CC0-1.0"
] | null | null | null | src/Vector3D.cpp | zellfaze/orbitalmechanicslibrary | d3c962133c326e768112ff6b907abbf88265bb16 | [
"CC0-1.0"
] | null | null | null | #include "Vector3D.h"
Vector3D::Vector3D() {
x(0);
y(0);
z(0);
}
Vector3D::Vector3D(double newx, double newy, double newz) {
x(newx);
y(newy);
z(newz);
}
Angle Vector3D::alpha() const {
double coa;
coa = x()/magnitude();
Angle result = Angle(acos(coa));
return result;
}
void Vector3D::alpha(Angle newa) {
double coa;
coa = cos(newa);
x(coa * magnitude());
}
Angle Vector3D::beta() const {
double cob;
cob = y()/magnitude();
Angle result = Angle(acos(cob));
return result;
}
void Vector3D::beta(Angle newa) {
double cob;
cob = cos(newa);
y(cob * magnitude());
}
Angle Vector3D::gamma() const {
double cog;
cog = z()/magnitude();
Angle result = Angle(acos(cog));
return result;
}
void Vector3D::gamma(Angle newa) {
double cog;
cog = cos(newa);
z(cog * magnitude());
}
Angle Vector3D::phi() const {
double cop;
cop = x()/sqrt(pow(y(),2)+pow(z(),2));
Angle result = Angle(acos(cop));
return result;
}
double Vector3D::magnitude() const {
return sqrt(pow(x(),2)+pow(y(),2)+pow(z(),2));
}
bool Vector3D::isZero() const {
if ((x()+y()+z()) == 0)
return true;
else
return false;
}
bool Vector3D::isUnit() const {
if (magnitude() == 1)
return true;
else
return false;
}
bool Vector3D::operator==(const Vector3D b) const {
if (x() != b.x())
return false;
if (y() != b.y())
return false;
if (z() != b.z())
return false;
return true;
}
bool Vector3D::isOpposite(const Vector3D b) const {
//Needs work
}
bool Vector3D::isParallel(const Vector3D b) const {
//Needs work
}
bool Vector3D::isAntiparallel(const Vector3D b) const {
//Needs work
}
Vector3D Vector3D::operator+(const Vector3D &b) const {
double newx, newy, newz;
newx = x() + b.x();
newy = y() + b.y();
newz = z() + b.z();
Vector3D result = Vector3D(newx, newy, newz);
return result;
}
Vector3D Vector3D::operator-(const Vector3D &b) const {
double newx, newy, newz;
newx = x() - b.x();
newy = y() - b.y();
newz = z() - b.z();
Vector3D result = Vector3D(newx, newy, newz);
return result;
}
Vector3D Vector3D::operator*(const double &b) const {
double newx, newy, newz;
newx = x() * b;
newy = y() * b;
newz = z() * b;
Vector3D result = Vector3D(newx, newy, newz);
return result;
}
Vector3D Vector3D::operator/(const double &b) const {
double newx, newy, newz;
newx = x() / b;
newy = y() / b;
newz = z() / b;
Vector3D result = Vector3D(newx, newy, newz);
return result;
}
double Vector3D::dotProduct(const Vector3D b) const {
std::vector<double> a{x(), y(), z()};
std::vector<double> c{b.x(), b.y(), b.z()};
double result = std::inner_product(a.begin(), a.end(), c.begin(), 0);
return result;
}
Vector3D Vector3D::crossProduct(const Vector3D b) const {
Vector3D result;
double newx, newy, newz;
newx = y()*b.z() - z()*b.y();
newy = z()*b.x() - x()*b.z();
newz = x()*b.y() - y()*b.x();
result = Vector3D(newx, newy, newz);
return result;
}
Vector3D::Vector3D(Point3D p1, Point3D p2) {
double newx, newy, newz;
newx = p2.x()-p1.x();
newy = p2.y()-p1.y();
newz = p2.z()-p1.z();
x(newx);
y(newy);
z(newz);
}
Angle Vector3D::findAngle(const Vector3D b) const {
Angle result;
double calcDot;
double combinedMagnitude;
calcDot = dotProduct(b);
combinedMagnitude = magnitude() * b.magnitude();
if (calcDot == combinedMagnitude)
result = Angle();
else
result = Angle(acos(calcDot/combinedMagnitude));
return result;
}
| 19.370166 | 71 | 0.608386 | [
"vector"
] |
7df9e7af758d217d8bb52adf23b91dd45600644b | 11,952 | cpp | C++ | applications/ContactStructuralMechanicsApplication/custom_processes/mpc_contact_search_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_processes/mpc_contact_search_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_processes/mpc_contact_search_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix
//
// System includes
// External includes
// Project includes
#include "contact_structural_mechanics_application_variables.h"
#include "custom_processes/mpc_contact_search_process.h"
#include "custom_master_slave_constraints/contact_master_slave_constraint.h"
/* Custom utilities */
#include "utilities/variable_utils.h"
namespace Kratos
{
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::MPCContactSearchProcess(
ModelPart & rMainModelPart,
Parameters ThisParameters,
Properties::Pointer pPairedProperties
) : BaseType(rMainModelPart, ThisParameters, pPairedProperties)
{
// If we are going to consider multple searchs
const std::string& id_name = BaseType::mThisParameters["id_name"].GetString();
// We get the contact model part
ModelPart& r_contact_model_part = BaseType::mrMainModelPart.GetSubModelPart("Contact");
ModelPart& r_sub_contact_model_part = this->IsNot(BaseType::MULTIPLE_SEARCHS) ? r_contact_model_part : r_contact_model_part.GetSubModelPart("ContactSub" + id_name);
// Iterate in the constraints
auto& r_constraints_array = r_sub_contact_model_part.MasterSlaveConstraints();
const auto it_const_begin = r_constraints_array.begin();
const int num_constraints = static_cast<int>(r_constraints_array.size());
#pragma omp parallel for
for(int i = 0; i < num_constraints; ++i)
(it_const_begin + i)->Set(ACTIVE, false);
}
/***********************************************************************************/
/***********************************************************************************/
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
void MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::CheckContactModelParts()
{
// Calling base class
BaseType::CheckContactModelParts();
// Iterate in the constraints
ModelPart& r_contact_model_part = BaseType::mrMainModelPart.GetSubModelPart("Contact");
ModelPart& r_sub_contact_model_part = this->IsNot(BaseType::MULTIPLE_SEARCHS) ? r_contact_model_part : r_contact_model_part.GetSubModelPart("ContactSub"+BaseType::mThisParameters["id_name"].GetString());
auto& r_constraints_array = r_sub_contact_model_part.MasterSlaveConstraints();
const SizeType total_number_constraints = BaseType::mrMainModelPart.GetRootModelPart().NumberOfMasterSlaveConstraints();
std::vector<MasterSlaveConstraint::Pointer> auxiliar_constraints_vector;
#pragma omp parallel
{
// Buffer for new constraints if created
std::vector<MasterSlaveConstraint::Pointer> auxiliar_constraints_vector_buffer;
#pragma omp for
for(int i = 0; i < static_cast<int>(r_constraints_array.size()); ++i) {
auto it_const = r_constraints_array.begin() + i;
if (it_const->Is(MARKER)) {
// Setting the flag to remove
it_const->Set(TO_ERASE, true);
// Creating new condition
MasterSlaveConstraint::Pointer p_new_const = it_const->Clone(total_number_constraints + it_const->Id());
auxiliar_constraints_vector_buffer.push_back(p_new_const);
p_new_const->SetData(it_const->GetData()); // TODO: Remove when fixed on the core
p_new_const->Set(Flags(*it_const));
p_new_const->Set(MARKER, true);
} else {
// Setting the flag to mark
it_const->Set(MARKER, true);
}
}
// Combine buffers together
#pragma omp critical
{
std::move(auxiliar_constraints_vector_buffer.begin(),auxiliar_constraints_vector_buffer.end(),back_inserter(auxiliar_constraints_vector));
}
}
// Finally we add the new constraints to the model part
r_sub_contact_model_part.RemoveMasterSlaveConstraints(TO_ERASE);
// Reorder ids (in order to keep the ids consistent)
for (int i = 0; i < static_cast<int>(auxiliar_constraints_vector.size()); ++i) {
auxiliar_constraints_vector[i]->SetId(total_number_constraints + i + 1);
}
ModelPart::MasterSlaveConstraintContainerType aux_conds;
aux_conds.GetContainer() = auxiliar_constraints_vector;
r_sub_contact_model_part.AddMasterSlaveConstraints(aux_conds.begin(), aux_conds.end());
// Unsetting TO_ERASE
VariableUtils().SetFlag(TO_ERASE, false, r_contact_model_part.MasterSlaveConstraints());
}
/***********************************************************************************/
/***********************************************************************************/
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
Condition::Pointer MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::AddPairing(
ModelPart& rComputingModelPart,
IndexType& rConditionId,
GeometricalObject::Pointer pObjectSlave,
const array_1d<double, 3>& rSlaveNormal,
GeometricalObject::Pointer pObjectMaster,
const array_1d<double, 3>& rMasterNormal,
IndexMap::Pointer pIndexesPairs,
Properties::Pointer pProperties
)
{
Condition::Pointer p_cond = BaseType::AddPairing(rComputingModelPart, rConditionId, pObjectSlave, rSlaveNormal, pObjectMaster, rMasterNormal, pIndexesPairs, pProperties);
const bool is_frictional = BaseType::mrMainModelPart.Is(SLIP);
const bool is_rigid = is_frictional ? false : BaseType::mrMainModelPart.Is(RIGID);
// Creating constraint
if (p_cond.get() != nullptr) {
MasterSlaveConstraint::Pointer p_new_const = Kratos::make_shared<ContactMasterSlaveConstraint>(GetMaximumConstraintsIds() + 1);
p_new_const->Set(ACTIVE);
const auto& r_process_info = rComputingModelPart.GetProcessInfo();
p_new_const->Initialize(r_process_info);
rComputingModelPart.AddMasterSlaveConstraint(p_new_const);
p_cond->SetValue(CONSTRAINT_POINTER, p_new_const);
if (is_frictional) p_cond->Set(SLIP);
if (is_rigid) p_cond->Set(RIGID);
p_cond->Initialize(r_process_info);
}
return p_cond;
}
/***********************************************************************************/
/***********************************************************************************/
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
void MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::CleanModelPart(ModelPart& rModelPart)
{
// Calling base class
BaseType::CleanModelPart(rModelPart);
// We clean the constraints
auto& r_constraints_array = rModelPart.MasterSlaveConstraints();
VariableUtils().SetFlag(TO_ERASE, true, r_constraints_array);
BaseType::mrMainModelPart.RemoveMasterSlaveConstraintFromAllLevels(TO_ERASE);
}
/***********************************************************************************/
/***********************************************************************************/
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
inline IndexType MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::GetMaximumConstraintsIds()
{
auto& r_constraints_array = BaseType::mrMainModelPart.MasterSlaveConstraints();
IndexType constraint_id = 0;
for(IndexType i = 0; i < r_constraints_array.size(); ++i) {
auto it_const = r_constraints_array.begin() + i;
const IndexType id = it_const->GetId();
if (id > constraint_id)
constraint_id = id;
}
return constraint_id;
}
/***********************************************************************************/
/***********************************************************************************/
template<SizeType TDim, SizeType TNumNodes, SizeType TNumNodesMaster>
void MPCContactSearchProcess<TDim, TNumNodes, TNumNodesMaster>::ResetContactOperators()
{
// Calling the base class
BaseType::ResetContactOperators();
// We iterate over the master nodes
ModelPart& r_contact_model_part = BaseType::mrMainModelPart.GetSubModelPart("Contact");
ModelPart& r_sub_contact_model_part = this->IsNot(BaseType::MULTIPLE_SEARCHS) ? r_contact_model_part : r_contact_model_part.GetSubModelPart("ContactSub"+BaseType::mThisParameters["id_name"].GetString());
NodesArrayType& r_nodes_array = r_sub_contact_model_part.Nodes();
if (BaseType::mrMainModelPart.Is(MODIFIED)) { // It has been remeshed. We remove everything
#pragma omp parallel for
for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) {
auto it_node = r_nodes_array.begin() + i;
if (it_node->Is(MASTER)) {
IndexMap::Pointer p_indexes_pairs = it_node->GetValue(INDEX_MAP);
if (p_indexes_pairs != nullptr) {
p_indexes_pairs->clear();
// p_indexes_pairs->reserve(mAllocationSize);
}
}
}
// We remove all the computing constraints
const std::string sub_computing_model_part_name = "ComputingContactSub" + BaseType::mThisParameters["id_name"].GetString();
ModelPart& r_computing_contact_model_part = BaseType::mrMainModelPart.GetSubModelPart("ComputingContact");
ModelPart& r_sub_computing_contact_model_part = this->IsNot(BaseType::MULTIPLE_SEARCHS) ? r_computing_contact_model_part : r_computing_contact_model_part.GetSubModelPart(sub_computing_model_part_name);
auto& r_computing_constraints_array = r_sub_computing_contact_model_part.MasterSlaveConstraints();
const int num_computing_constraints = static_cast<int>(r_computing_constraints_array.size());
#pragma omp parallel for
for(int i = 0; i < num_computing_constraints; ++i) {
auto it_const = r_computing_constraints_array.begin() + i;
it_const->Set(TO_ERASE, true);
}
} else {
// We iterate, but not in OMP
for(IndexType i = 0; i < r_nodes_array.size(); ++i) {
auto it_node = r_nodes_array.begin() + i;
if (it_node->Is(MASTER)) {
IndexMap::Pointer p_indexes_pairs = it_node->GetValue(INDEX_MAP);
if (p_indexes_pairs != nullptr) {
// The vector with the ids to remove
std::vector<IndexType> inactive_constraints_ids;
for (auto it_pair = p_indexes_pairs->begin(); it_pair != p_indexes_pairs->end(); ++it_pair ) {
MasterSlaveConstraint::Pointer p_const = BaseType::mrMainModelPart.pGetMasterSlaveConstraint(it_pair->second);
if (p_const->IsNot(ACTIVE)) {
p_const->Set(TO_ERASE, true);
inactive_constraints_ids.push_back(it_pair->first);
}
}
for (auto& i_to_remove : inactive_constraints_ids) {
p_indexes_pairs->RemoveId(inactive_constraints_ids[i_to_remove]);
}
}
}
}
}
BaseType::mrMainModelPart.RemoveMasterSlaveConstraintsFromAllLevels(TO_ERASE);
}
/***********************************************************************************/
/***********************************************************************************/
template class MPCContactSearchProcess<2, 2>;
template class MPCContactSearchProcess<3, 3>;
template class MPCContactSearchProcess<3, 4>;
template class MPCContactSearchProcess<3, 3, 4>;
template class MPCContactSearchProcess<3, 4, 3>;
} // namespace Kratos.
| 45.272727 | 209 | 0.632112 | [
"vector",
"model"
] |
7dfbfd818a20977781a35b7f83322a5610d0bbad | 22,649 | cpp | C++ | Sankore-3.1/src/pdf-merger/Page.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/pdf-merger/Page.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/pdf-merger/Page.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Page.h"
#include "Document.h"
#include "ContentHandler.h"
#include "Exception.h"
#include "MediaBoxElementHandler.h"
#include "CropBoxElementHandler.h"
#include "TypeElementHandler.h"
#include "RemoveHimSelfHandler.h"
#include "AnnotsHandler.h"
#include "RotationHandler.h"
#include "FlateDecode.h"
#include "Utils.h"
#include "Rectangle.h"
#include "Filter.h"
#include <iostream>
#include <string.h>
#include "Parser.h"
#include "core/memcheck.h"
using namespace merge_lib;
Page::Page(unsigned int pageNumber): _root(NULL),_pageNumber(pageNumber), _rotation(0)
{
}
Page::~Page()
{
}
std::string & Page::getPageContent()
{
return _root->getObjectContent();
}
const Object::Children & Page::getPageRefs()
{
return _root->getChildren();
}
void Page::recalculateObjectNumbers(unsigned int & newNumber)
{
_root->recalculateObjectNumbers(newNumber);
}
Object * Page::pageToXObject(std::vector<Object *> & allObjects, std::vector<Object *> & annots, bool isCloneNeeded)
{
Object * xObject = (isCloneNeeded) ? _root->getClone(allObjects) : _root;
return _pageToXObject(xObject, annots);
}
Object * Page::_pageToXObject(Object *& page, std::vector<Object *> & annots)
{
RemoveHimselfHandler * removeParent = new RemoveHimselfHandler(page, "/Parent");
RemoveHimselfHandler * removeBleedBox = new RemoveHimselfHandler(page, "/BleedBox");
RemoveHimselfHandler * removeTrimBox = new RemoveHimselfHandler(page, "/TrimBox");
RemoveHimselfHandler * removeArtBox = new RemoveHimselfHandler(page, "/ArtBox");
RemoveHimselfHandler * removeBoxColorInfo = new RemoveHimselfHandler(page, "/BoxColorInfo");
RemoveHimselfHandler * removeRotate = new RemoveHimselfHandler(page, "/Rotate");
RemoveHimselfHandler * removeThumb = new RemoveHimselfHandler(page, "/Thumb");
RemoveHimselfHandler * removeB = new RemoveHimselfHandler(page, "/B");
RemoveHimselfHandler * removeDur = new RemoveHimselfHandler(page, "/Dur");
RemoveHimselfHandler * removeTrans = new RemoveHimselfHandler(page, "/Trans");
AnnotsHandler * removeAnnots = new AnnotsHandler(page, "/Annots", annots);
RemoveHimselfHandler * removeAA = new RemoveHimselfHandler(page, "/AA");
RemoveHimselfHandler * removeID = new RemoveHimselfHandler(page, "/ID");
RemoveHimselfHandler * removePZ = new RemoveHimselfHandler(page, "/PZ");
RemoveHimselfHandler * removeSeparationInfo = new RemoveHimselfHandler(page, "/SeparationInfo");
RemoveHimselfHandler * removeTabs = new RemoveHimselfHandler(page, "/Tabs");
RemoveHimselfHandler * removeTemplateInstantiated = new RemoveHimselfHandler(page, "/TemplateInstantiated");
RemoveHimselfHandler * removePresSteps = new RemoveHimselfHandler(page, "/PresSteps");
RemoveHimselfHandler * removeUserUnit = new RemoveHimselfHandler(page, "/UserUnit");
RemoveHimselfHandler * removeVP = new RemoveHimselfHandler(page, "/VP");
ContentHandler * contentHandler = new ContentHandler(page, "/Contents");
CropBoxElementHandler * cropBoxElementHandler = new CropBoxElementHandler(page);
MediaBoxElementHandler * mediaBoxElementHandler = new MediaBoxElementHandler(page);
TypeElementHandler * typeElementHandler = new TypeElementHandler(page);
cropBoxElementHandler->addNextHandler(mediaBoxElementHandler);
mediaBoxElementHandler->addNextHandler(removeParent);
removeParent->addNextHandler(removeBleedBox);
removeBleedBox->addNextHandler(removeTrimBox);
removeTrimBox->addNextHandler(removeArtBox);
removeArtBox->addNextHandler(removeBoxColorInfo);
removeBoxColorInfo->addNextHandler(removeRotate);
removeRotate->addNextHandler(removeThumb);
removeThumb->addNextHandler(removeB);
removeB->addNextHandler(removeDur);
removeDur->addNextHandler(removeTrans);
removeTrans->addNextHandler(removeAnnots);
removeAnnots->addNextHandler(removeAA);
removeAA->addNextHandler(removeID);
removeID->addNextHandler(removePZ);
removePZ->addNextHandler(removeSeparationInfo);
removeSeparationInfo->addNextHandler(removeTabs);
removeTabs->addNextHandler(removeTemplateInstantiated);
removeTemplateInstantiated->addNextHandler(removePresSteps);
removePresSteps->addNextHandler(removeUserUnit);
removeUserUnit->addNextHandler(removeVP);
removeVP->addNextHandler(typeElementHandler);
typeElementHandler->addNextHandler(contentHandler);
cropBoxElementHandler->processObjectContent();
cropBoxElementHandler->changeObjectContent();
delete cropBoxElementHandler;
return page;
}
std::string _getContentOfContentObject(MergePageDescription & description)
{
std::string content("<<\n/Length ");
std::string stream = "";
if(!description.skipBasePage)
{
stream.append("1.000000 0 0 1.000000 0 0 cm\n"
"q\n");
stream.append(description.basePageTransformation.getCMT());
stream.append("/OriginalPage2 Do\n"
"Q\n");
}
if(!description.skipOverlayPage)
{
stream.append("1.000000 0 0 1.000000 0 0 cm\n"
"q\n");
stream.append(description.overlayPageTransformation.getCMT());
stream.append("/OriginalPage1 Do\n"
"Q\n");
}
FlateDecode encoder;
encoder.encode(stream);
content.append(Utils::uIntToStr(stream.size()));
content.append("\n/Filter /FlateDecode\n>>\nstream\n");
content.append(stream);
content.append("endstream\n");
return content;
}
void _recalculateAnnotsCoordinates(Object * annotation,
const Rectangle & basePagesRectangle,
const Rectangle & outputPagesRectangle,
const MergePageDescription & description)
{
Q_UNUSED(outputPagesRectangle);
Q_UNUSED(basePagesRectangle);
std::string annotsRectangleName("/Rect");
Object * objectWithRectangle;
unsigned int fake;
annotation->findObject(annotsRectangleName, objectWithRectangle, fake);
std::string annotContent = objectWithRectangle->getObjectContent();
Rectangle annotsRectangle(annotsRectangleName.c_str(), annotContent);
//we move annotation from base page to output page
//that's way annotation should be scaled before all transformations.
//Annotation's coordinates should be recalculated according to new
//page width and height
annotsRectangle.recalculateInternalRectangleCoordinates(description.basePageTransformation.getAnnotsTransformations());
annotsRectangle.updateRectangle(annotation, " ");
}
// function updates parent reference of annotation with new page object
static void _updateAnnotParentPage(Object *annotation,Object *newParentPage)
{
if( annotation )
{
std::string strP = "/P";
std::string &annotContent = annotation->getObjectContent();
size_t startOfP = Parser::findTokenName(annotContent,strP);
if((int) startOfP == -1 )
{
return;
}
size_t endOfP = Parser::findEndOfElementContent(annotContent,startOfP + strP.size());
// lets find object with reference to parent
std::vector<Object *> children = annotation->getChildrenByBounds(startOfP,endOfP);
if( children.size() == 0 )
{
return;
}
Object *childWithP = children[0];
if( childWithP )
{
Object::ReferencePositionsInContent pagePosition = annotation->removeChild(childWithP);
annotation->eraseContent(startOfP,endOfP-startOfP);
std::stringstream strout;
strout <<"/P "<<newParentPage->getObjectNumber()<<" "<<newParentPage->getgenerationNumber()<<" R\n";
// to compensate posible deviation
for(size_t i =strout.str().size();i<endOfP-startOfP;i++)
{
strout<<" ";
}
annotation->insertToContent(startOfP,strout.str());
annotation->addChild(newParentPage,pagePosition);
}
}
}
// function performs adjusting of some color parameters of annotation
// to avoid interference with overlay content
static void _updateAnnotFormColor(Object *annotation )
{
std::string &objectContent = annotation->getObjectContent();
if((int) objectContent.find("/Widget") == -1 )
{
return;
}
size_t startOfAP = Parser::findTokenName(objectContent,"/AP");
if((int) startOfAP == -1 )
{
return;
}
size_t endOfAP = objectContent.find(">>", startOfAP);
std::vector<Object *> aps = annotation->getChildrenByBounds(startOfAP, endOfAP);
for(size_t i = 0; i < aps.size(); ++i)
{
Object * childWithAP = aps[i];
if( !childWithAP->hasStream() )
{
continue;
}
// first lets obtain and decode stream of Annotation appearrence stream
std::string & content = childWithAP->getObjectContent();
Filter filter(childWithAP);
std::string decodedStream;
filter.getDecodedStream(decodedStream);
// lets iterate over stream and find operator f and remove it!
size_t beg = 0;
size_t found = 0;
std::string token;
while(Parser::getNextWord(token,decodedStream,beg,&found))
{
if( token == "f" || token == "F" )
{
if((int) found != -1 )
{
decodedStream[found] = ' ';
}
break;
}
}
// Then we need to update Filter section (if any)
std::string filterStr = "/Filter";
size_t startOfFlate = Parser::findTokenName(content,filterStr);
if((int) startOfFlate != -1 )
{
size_t endOfFlate = Parser::findEndOfElementContent(content,startOfFlate+filterStr.size());
childWithAP->eraseContent(startOfFlate,endOfFlate-startOfFlate);
//encode and put new stream to object content
childWithAP->insertToContent(startOfFlate,"/Filter /FlateDecode ");
FlateDecode flate;
flate.encode(decodedStream);
}
// update the length field
std::string lengthStr = "/Length";
size_t startOfLength = Parser::findTokenName(content,lengthStr,0);
if((int) startOfLength != -1 )
{
size_t endOfLength = Parser::findEndOfElementContent(content,startOfLength + lengthStr.size());
childWithAP->eraseContent(startOfLength,endOfLength-startOfLength);
std::stringstream ostr;
ostr<<"/Length "<< decodedStream.size()<<"\n";
childWithAP->insertToContent(startOfLength,ostr.str());
// update the stream of object with new content
std::string stream("stream");
size_t leftBoundOfContentStream = content.find(stream);
if((int) leftBoundOfContentStream != -1 )
{
size_t rightBoundOfContentStream = content.find("endstream", leftBoundOfContentStream);
if((int) rightBoundOfContentStream == -1 )
{
rightBoundOfContentStream = content.size() - 1;
}
childWithAP->eraseContent(leftBoundOfContentStream, rightBoundOfContentStream - leftBoundOfContentStream);
decodedStream.insert(0,"\nstream\n");
childWithAP->insertToContent(leftBoundOfContentStream,decodedStream);
childWithAP->appendContent("endstream\n");
childWithAP->forgetStreamInFile();
}
}
}
}
// sometimes page object does not have resources,
// they are inherited from parent object
// this method processes such cases and insert resources from parent to page
// for correct X-Object transformation
static void processBasePageResources(Object *basePage)
{
if( basePage == NULL )
{
return;
}
std::string resourceToken = "/Resources";
if((int) Parser::findTokenName(basePage->getObjectContent(),resourceToken) == -1 )
{
// it seems base page does not have resources, they can be located in parent!
Object *resource = basePage->findPatternInObjOrParents(resourceToken);
if( resource )
{
std::string &resContStr = resource->getObjectContent();
size_t startOfRes = Parser::findTokenName(resContStr,resourceToken);
if((int) startOfRes == -1 )
{
// no resources at all
return;
}
size_t endOfRes = Parser::findEndOfElementContent(resContStr,startOfRes + resourceToken.size());
if((int) endOfRes == -1 )
{
return; // broken resources
}
std::string resourceContent = resContStr.substr(startOfRes,endOfRes-startOfRes);
size_t positionToInsert = basePage->getObjectContent().find("<<");
if((int) positionToInsert == -1 )
{
positionToInsert = 0;
resourceContent.insert(0,"<<");
resourceContent.append(">>");
}
else
{
positionToInsert += strlen("<<");
}
// insert obtained resources to base page
basePage->insertToContent(positionToInsert,resourceContent);
// if resource contains childs, then we need to add reference to them to current object
std::vector<Object *> resChilds = resource->getChildrenByBounds(startOfRes, endOfRes);
std::vector<Object *>::const_iterator objectIt(resChilds.begin());
const Object::Children & children = resource->getChildren();
for(; objectIt != resChilds.end(); objectIt++ )
{
Object::Children::const_iterator childrenIt = children.find( (*objectIt)->getObjectNumber());
if( childrenIt != children.end() )
{
Object::ReferencePositionsInContent refPositionInCont = (*childrenIt).second.second;
Object::ReferencePositionsInContent::iterator positionIt(refPositionInCont.begin());
Object::ReferencePositionsInContent newPositions;
for( ;positionIt != refPositionInCont.end(); positionIt++ )
{
newPositions.push_back( (*positionIt) - startOfRes + positionToInsert );
}
basePage->addChild( (*objectIt),newPositions );
}
}
}
}
}
std::string Page::_getMergedPageContent( unsigned int & contentPosition,
unsigned int & parentPosition,
unsigned int & originalPage1Position,
unsigned int & originalPage2Position,
std::pair<unsigned int, unsigned int> originalPageNumbers,
const MergePageDescription & description,
Object * basePage,
const std::vector<Object *> & annots,
std::vector <Object::ChildAndItPositionInContent> & annotsPositions
)
{
std::string content("<<\n/Type /Page\n");
content.append("/Contents ");
contentPosition = content.size();
//object number 1 will be recalculated during serialization
content.append("1 0 R\n");
Rectangle mediaBox("/MediaBox");
mediaBox.x2 = description.outPageWidth;
mediaBox.y2 = description.outPageHeight;
mediaBox.appendRectangleToString(content, " ");
content.append("/Parent ");
parentPosition = content.size();
//object number 1 will be recalculated during serialization
content.append("1 0 R\n");
content.append("/Resources <<\n"
"/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]\n"
"/XObject <<\n");
if(!description.skipOverlayPage)
{
content.append("/OriginalPage1 ");
originalPage1Position = content.size();
content.append(Utils::uIntToStr(originalPageNumbers.first));
content.append(" 0 R\n");
}
if(!description.skipBasePage)
{
content.append("/OriginalPage2 ");
originalPage2Position = content.size();
content.append(Utils::uIntToStr(originalPageNumbers.second));
content.append(" ");
content.append(Utils::uIntToStr(basePage->getgenerationNumber()));
content.append(" R\n");
}
content.append(">>\n>>\n");
content.append("/Annots [ ");
if(!description.skipBasePage)
{
Rectangle basePageRectangle("/BBox", basePage->getObjectContent());
for(size_t i = 0; i < annots.size(); ++i)
{
_updateAnnotFormColor(annots[i]);
_recalculateAnnotsCoordinates(annots[i], basePageRectangle, mediaBox, description);
Object::ReferencePositionsInContent annotationPosition;
annotationPosition.push_back(content.size());
Object::ChildAndItPositionInContent annotAndItPosition(annots[i], annotationPosition);
annotsPositions.push_back(annotAndItPosition);
content.append(Utils::uIntToStr(annots[i]->getObjectNumber()));
content.append(" ");
content.append(Utils::uIntToStr(annots[i]->getgenerationNumber()));
content.append(" R ");
}
}
content.append("] \n>>\n");
return content;
}
void Page::merge(Page * sourcePage, Document * parentDocument, MergePageDescription & description, bool isPageDuplicated)
{
if( sourcePage == NULL )
{
description.skipBasePage = true;
}
if(!description.skipOverlayPage)
{
// Lets recalculate final transformation of overlay page
// before it will be places into XObject
Rectangle mediaBox("/MediaBox",_root->getObjectContent());
description.overlayPageTransformation.recalculateTranslation(mediaBox.getWidth(),mediaBox.getHeight());
std::vector<Object *> fake;
_pageToXObject(_root, fake);
}
std::vector<Object *> toAllObjects;
std::vector<Object *> annotations;
Object * sourcePageToXObject = 0;
if(!description.skipBasePage)
{
RotationHandler rotationHandler(sourcePage->_root, "/Rotate", *this);
rotationHandler.processObjectContent();
description.basePageTransformation.addRotation(_rotation);
if((int) sourcePage->_root->getObjectContent().find("/Annots") != -1 )
{
Object *crop = sourcePage->_root->findPatternInObjOrParents("/CropBox");
if( crop )
{
// we need to calculate special compensational shifting
// for annotations if cropbox is starting not from 0,0
Rectangle mediaBox("/CropBox", crop->getObjectContent());
if( !Utils::doubleEquals(mediaBox.x1,0) || !Utils::doubleEquals(mediaBox.y1,0) )
{
double shiftX = Utils::doubleEquals(mediaBox.x1,0)?0:-mediaBox.x1;
double shiftY = Utils::doubleEquals(mediaBox.y1,0)?0:-mediaBox.y1;
Translation compensation(shiftX,shiftY);
description.basePageTransformation.addAnnotsTransformation(compensation);
}
}
}
processBasePageResources(sourcePage->_root);
sourcePageToXObject = sourcePage->pageToXObject(toAllObjects, annotations, isPageDuplicated);
Rectangle mediaBox("/BBox", sourcePageToXObject->getObjectContent());
description.basePageTransformation.recalculateTranslation(mediaBox.getWidth(),mediaBox.getHeight());
}
Object * catalog = 0;
unsigned int fake;
if(!parentDocument->getDocumentObject()->findObject(std::string("/Kids"), catalog, fake))
{
std::string error("Wrong document ");
error.append("There is no object with Kids field");
throw Exception(error);
}
Object::ReferencePositionsInContent pagePosition = catalog->removeChild(_root);
//create merged Page
unsigned int contentPosition, parentPosition, originalPage1Position, originalPage2Position;
std::pair<unsigned int, unsigned int> originalPageNumbers(_root->getObjectNumber(), 0);
if(!description.skipBasePage)
originalPageNumbers.second = sourcePageToXObject->getObjectNumber();
std::vector <Object::ChildAndItPositionInContent> annotsAndItPositions;
std::string mergedPageContent = _getMergedPageContent(contentPosition,
parentPosition,
originalPage1Position,
originalPage2Position,
originalPageNumbers,
description,
sourcePageToXObject,
annotations,
annotsAndItPositions
);
Object * mergedPage = new Object(_root->getObjectNumber(), _root->getgenerationNumber(), mergedPageContent);
toAllObjects.push_back(mergedPage);
std::vector < unsigned int > contentPositionVec, parentPositionVec, originalPage1PositionVec, originalPage2PositionVec;
contentPositionVec.push_back(contentPosition);
parentPositionVec.push_back(parentPosition);
originalPage1PositionVec.push_back(originalPage1Position);
originalPage2PositionVec.push_back(originalPage2Position);
Object * contentOfMergedPage = new Object(1, 0, _getContentOfContentObject(description));
toAllObjects.push_back(contentOfMergedPage);
parentDocument->addToAllObjects(toAllObjects);
mergedPage->addChild(contentOfMergedPage, contentPositionVec);
mergedPage->addChild(catalog, parentPositionVec);
if(!description.skipOverlayPage)
mergedPage->addChild(_root, originalPage1PositionVec);
if(!description.skipBasePage)
mergedPage->addChild(sourcePageToXObject, originalPage2PositionVec);
// Annotation parent page should be changed, since we moved old page
// to Xobject
if( !description.skipBasePage )
{
for(size_t i = 0; i< annotations.size();i++)
{
_updateAnnotParentPage(annotations[i],mergedPage);
}
}
for(size_t i = 0; i < annotsAndItPositions.size(); ++i)
{
mergedPage->addChild(annotsAndItPositions[i].first, annotsAndItPositions[i].second);
}
catalog->addChild(mergedPage, pagePosition);
_root = mergedPage;
}
| 39.458188 | 122 | 0.675129 | [
"object",
"vector"
] |
7dfc3a573c84e1bfc3c0a6d21de050c293b07404 | 847 | cpp | C++ | Day 12 - Passage Pathing/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | 1 | 2021-12-02T19:07:17.000Z | 2021-12-02T19:07:17.000Z | Day 12 - Passage Pathing/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | Day 12 - Passage Pathing/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | //
// main.cpp
// ADVENT OF CODE 2021: Day 12 - Passage Pathing (Part 1)
//
// Created by diff-arch on 12/12/2021.
//
// Goal: How many paths through this cave system are there that visit small caves at most once?
//
// Compile: g++ -std=c++11 -o bin/a.out src/*.cpp
// Run: ./bin/a.out
//
#include <iostream>
#include <string>
#include <vector>
#include "Graph.h"
#include "Utils.h"
int main() {
const char* fpath = "../bin/data/passage-pathing.txt"; // insert your path
std::vector<std::string> lines = readData(fpath);
Graph g;
g.addEdges(lines);
// std::cout << g << "\n";
std::string from = "start";
std::string to = "end";
std::vector<std::string> visited;
visited.push_back(from);
std::vector<std::string> path;
std::cout << "Paths Count: " << g.countPathsRec(from, to, visited, path) << "\n";
}
| 21.717949 | 99 | 0.619835 | [
"vector"
] |
7dfe3688af8b722f1a6ba1475311c5f670a85431 | 10,882 | cpp | C++ | cdb/src/v20170320/model/TaskDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdb/src/v20170320/model/TaskDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdb/src/v20170320/model/TaskDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdb/v20170320/model/TaskDetail.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
TaskDetail::TaskDetail() :
m_codeHasBeenSet(false),
m_messageHasBeenSet(false),
m_jobIdHasBeenSet(false),
m_progressHasBeenSet(false),
m_taskStatusHasBeenSet(false),
m_taskTypeHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_instanceIdsHasBeenSet(false),
m_asyncRequestIdHasBeenSet(false)
{
}
CoreInternalOutcome TaskDetail::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Code") && !value["Code"].IsNull())
{
if (!value["Code"].IsInt64())
{
return CoreInternalOutcome(Error("response `TaskDetail.Code` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_code = value["Code"].GetInt64();
m_codeHasBeenSet = true;
}
if (value.HasMember("Message") && !value["Message"].IsNull())
{
if (!value["Message"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.Message` IsString=false incorrectly").SetRequestId(requestId));
}
m_message = string(value["Message"].GetString());
m_messageHasBeenSet = true;
}
if (value.HasMember("JobId") && !value["JobId"].IsNull())
{
if (!value["JobId"].IsInt64())
{
return CoreInternalOutcome(Error("response `TaskDetail.JobId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_jobId = value["JobId"].GetInt64();
m_jobIdHasBeenSet = true;
}
if (value.HasMember("Progress") && !value["Progress"].IsNull())
{
if (!value["Progress"].IsInt64())
{
return CoreInternalOutcome(Error("response `TaskDetail.Progress` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_progress = value["Progress"].GetInt64();
m_progressHasBeenSet = true;
}
if (value.HasMember("TaskStatus") && !value["TaskStatus"].IsNull())
{
if (!value["TaskStatus"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.TaskStatus` IsString=false incorrectly").SetRequestId(requestId));
}
m_taskStatus = string(value["TaskStatus"].GetString());
m_taskStatusHasBeenSet = true;
}
if (value.HasMember("TaskType") && !value["TaskType"].IsNull())
{
if (!value["TaskType"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.TaskType` IsString=false incorrectly").SetRequestId(requestId));
}
m_taskType = string(value["TaskType"].GetString());
m_taskTypeHasBeenSet = true;
}
if (value.HasMember("StartTime") && !value["StartTime"].IsNull())
{
if (!value["StartTime"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.StartTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_startTime = string(value["StartTime"].GetString());
m_startTimeHasBeenSet = true;
}
if (value.HasMember("EndTime") && !value["EndTime"].IsNull())
{
if (!value["EndTime"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.EndTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_endTime = string(value["EndTime"].GetString());
m_endTimeHasBeenSet = true;
}
if (value.HasMember("InstanceIds") && !value["InstanceIds"].IsNull())
{
if (!value["InstanceIds"].IsArray())
return CoreInternalOutcome(Error("response `TaskDetail.InstanceIds` is not array type"));
const rapidjson::Value &tmpValue = value["InstanceIds"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_instanceIds.push_back((*itr).GetString());
}
m_instanceIdsHasBeenSet = true;
}
if (value.HasMember("AsyncRequestId") && !value["AsyncRequestId"].IsNull())
{
if (!value["AsyncRequestId"].IsString())
{
return CoreInternalOutcome(Error("response `TaskDetail.AsyncRequestId` IsString=false incorrectly").SetRequestId(requestId));
}
m_asyncRequestId = string(value["AsyncRequestId"].GetString());
m_asyncRequestIdHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TaskDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_codeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Code";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_code, allocator);
}
if (m_messageHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Message";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_message.c_str(), allocator).Move(), allocator);
}
if (m_jobIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "JobId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_jobId, allocator);
}
if (m_progressHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Progress";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_progress, allocator);
}
if (m_taskStatusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TaskStatus";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_taskStatus.c_str(), allocator).Move(), allocator);
}
if (m_taskTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TaskType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_taskType.c_str(), allocator).Move(), allocator);
}
if (m_startTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_instanceIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceIds";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_instanceIds.begin(); itr != m_instanceIds.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_asyncRequestIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AsyncRequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_asyncRequestId.c_str(), allocator).Move(), allocator);
}
}
int64_t TaskDetail::GetCode() const
{
return m_code;
}
void TaskDetail::SetCode(const int64_t& _code)
{
m_code = _code;
m_codeHasBeenSet = true;
}
bool TaskDetail::CodeHasBeenSet() const
{
return m_codeHasBeenSet;
}
string TaskDetail::GetMessage() const
{
return m_message;
}
void TaskDetail::SetMessage(const string& _message)
{
m_message = _message;
m_messageHasBeenSet = true;
}
bool TaskDetail::MessageHasBeenSet() const
{
return m_messageHasBeenSet;
}
int64_t TaskDetail::GetJobId() const
{
return m_jobId;
}
void TaskDetail::SetJobId(const int64_t& _jobId)
{
m_jobId = _jobId;
m_jobIdHasBeenSet = true;
}
bool TaskDetail::JobIdHasBeenSet() const
{
return m_jobIdHasBeenSet;
}
int64_t TaskDetail::GetProgress() const
{
return m_progress;
}
void TaskDetail::SetProgress(const int64_t& _progress)
{
m_progress = _progress;
m_progressHasBeenSet = true;
}
bool TaskDetail::ProgressHasBeenSet() const
{
return m_progressHasBeenSet;
}
string TaskDetail::GetTaskStatus() const
{
return m_taskStatus;
}
void TaskDetail::SetTaskStatus(const string& _taskStatus)
{
m_taskStatus = _taskStatus;
m_taskStatusHasBeenSet = true;
}
bool TaskDetail::TaskStatusHasBeenSet() const
{
return m_taskStatusHasBeenSet;
}
string TaskDetail::GetTaskType() const
{
return m_taskType;
}
void TaskDetail::SetTaskType(const string& _taskType)
{
m_taskType = _taskType;
m_taskTypeHasBeenSet = true;
}
bool TaskDetail::TaskTypeHasBeenSet() const
{
return m_taskTypeHasBeenSet;
}
string TaskDetail::GetStartTime() const
{
return m_startTime;
}
void TaskDetail::SetStartTime(const string& _startTime)
{
m_startTime = _startTime;
m_startTimeHasBeenSet = true;
}
bool TaskDetail::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
string TaskDetail::GetEndTime() const
{
return m_endTime;
}
void TaskDetail::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool TaskDetail::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
vector<string> TaskDetail::GetInstanceIds() const
{
return m_instanceIds;
}
void TaskDetail::SetInstanceIds(const vector<string>& _instanceIds)
{
m_instanceIds = _instanceIds;
m_instanceIdsHasBeenSet = true;
}
bool TaskDetail::InstanceIdsHasBeenSet() const
{
return m_instanceIdsHasBeenSet;
}
string TaskDetail::GetAsyncRequestId() const
{
return m_asyncRequestId;
}
void TaskDetail::SetAsyncRequestId(const string& _asyncRequestId)
{
m_asyncRequestId = _asyncRequestId;
m_asyncRequestIdHasBeenSet = true;
}
bool TaskDetail::AsyncRequestIdHasBeenSet() const
{
return m_asyncRequestIdHasBeenSet;
}
| 27.205 | 137 | 0.667616 | [
"vector",
"model"
] |
7dfe8bb5323144306da0790c8e897a2cc60b8ef8 | 7,760 | cxx | C++ | Qt/Core/pqStandardServerManagerModelInterface.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-07-21T07:15:44.000Z | 2021-07-21T07:15:44.000Z | Qt/Core/pqStandardServerManagerModelInterface.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Qt/Core/pqStandardServerManagerModelInterface.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-03-13T03:35:01.000Z | 2021-03-13T03:35:01.000Z | /*=========================================================================
Program: ParaView
Module: pqStandardServerManagerModelInterface.cxx
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqStandardServerManagerModelInterface.h"
#include "pqAnimationCue.h"
#include "pqAnimationScene.h"
#include "pqBoxChartView.h"
#include "pqComparativeRenderView.h"
#include "pqComparativeXYBarChartView.h"
#include "pqComparativeXYChartView.h"
#include "pqMultiSliceView.h"
#include "pqParallelCoordinatesChartView.h"
#include "pqPipelineFilter.h"
#include "pqPipelineRepresentation.h"
#include "pqPlotMatrixView.h"
#include "pqRenderView.h"
#include "pqScalarBarRepresentation.h"
#include "pqScalarsToColors.h"
#include "pqServer.h"
#include "pqSpreadSheetView.h"
#include "pqTimeKeeper.h"
#include "pqXYBarChartView.h"
#include "pqXYChartView.h"
#include "pqXYHistogramChartView.h"
#include "vtkPVConfig.h"
#include "vtkSMComparativeViewProxy.h"
#include "vtkSMContextViewProxy.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMRenderViewProxy.h"
#include "vtkSMRepresentationProxy.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSpreadSheetViewProxy.h"
#if PARAVIEW_PQCORE_ENABLE_PYTHON
#include "pqPythonView.h"
#endif
#include <QtDebug>
namespace
{
//-----------------------------------------------------------------------------
inline pqProxy* CreatePQView(
const QString& group, const QString& name, vtkSMViewProxy* proxy, pqServer* server)
{
QObject* parent = NULL;
QString xmlname = proxy->GetXMLName();
if (vtkSMSpreadSheetViewProxy::SafeDownCast(proxy))
{
return new pqSpreadSheetView(group, name, proxy, server, parent);
}
if (xmlname == pqMultiSliceView::multiSliceViewType())
{
return new pqMultiSliceView(xmlname, group, name, proxy, server, parent);
}
#if PARAVIEW_PQCORE_ENABLE_PYTHON
if (xmlname == pqPythonView::pythonViewType())
{
return new pqPythonView(xmlname, group, name, proxy, server, parent);
}
#endif
if (vtkSMRenderViewProxy::SafeDownCast(proxy))
{
return new pqRenderView(group, name, proxy, server, parent);
}
if (vtkSMComparativeViewProxy::SafeDownCast(proxy))
{
if (xmlname == pqComparativeXYBarChartView::chartViewType())
{
return new pqComparativeXYBarChartView(
group, name, vtkSMComparativeViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == pqComparativeXYChartView::chartViewType())
{
return new pqComparativeXYChartView(
group, name, vtkSMComparativeViewProxy::SafeDownCast(proxy), server, parent);
}
// Handle the other comparative render views.
return new pqComparativeRenderView(group, name, proxy, server, parent);
}
if (vtkSMContextViewProxy::SafeDownCast(proxy))
{
if (xmlname == "XYChartView" || xmlname == "XYPointChartView" || xmlname == "QuartileChartView")
{
return new pqXYChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == "XYBarChartView")
{
return new pqXYBarChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == "XYHistogramChartView")
{
return new pqXYHistogramChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == "BoxChartView")
{
return new pqBoxChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == "ParallelCoordinatesChartView")
{
return new pqParallelCoordinatesChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
if (xmlname == "PlotMatrixView")
{
return new pqPlotMatrixView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
// View XML name have not been recognized, default to a pqXYChartView
return new pqXYChartView(
group, name, vtkSMContextViewProxy::SafeDownCast(proxy), server, parent);
}
return NULL;
}
}
//-----------------------------------------------------------------------------
pqStandardServerManagerModelInterface::pqStandardServerManagerModelInterface(QObject* _parent)
: QObject(_parent)
{
}
//-----------------------------------------------------------------------------
pqStandardServerManagerModelInterface::~pqStandardServerManagerModelInterface()
{
}
//-----------------------------------------------------------------------------
pqProxy* pqStandardServerManagerModelInterface::createPQProxy(
const QString& group, const QString& name, vtkSMProxy* proxy, pqServer* server) const
{
QString xml_type = proxy->GetXMLName();
if (group == "views" && vtkSMViewProxy::SafeDownCast(proxy))
{
return CreatePQView(group, name, vtkSMViewProxy::SafeDownCast(proxy), server);
}
else if (group == "layouts")
{
return new pqProxy(group, name, proxy, server, NULL);
}
else if (group == "sources")
{
if (pqPipelineFilter::getInputPorts(proxy).size() > 0)
{
return new pqPipelineFilter(name, proxy, server, 0);
}
else
{
return new pqPipelineSource(name, proxy, server, 0);
}
}
else if (group == "timekeeper")
{
return new pqTimeKeeper(group, name, proxy, server, 0);
}
else if (group == "lookup_tables")
{
return new pqScalarsToColors(group, name, proxy, server, 0);
}
else if (group == "scalar_bars")
{
return new pqScalarBarRepresentation(group, name, proxy, server, 0);
}
else if (group == "representations")
{
if (proxy->IsA("vtkSMRepresentationProxy") && proxy->GetProperty("Input"))
{
if (proxy->IsA("vtkSMPVRepresentationProxy") || xml_type == "ImageSliceRepresentation")
{
// pqPipelineRepresentation is a design flaw! We need to get rid of it
// and have helper code that manages the crap in that class
return new pqPipelineRepresentation(group, name, proxy, server, 0);
}
// If everything fails, simply create a pqDataRepresentation object.
return new pqDataRepresentation(group, name, proxy, server, 0);
}
}
else if (group == "animation")
{
if (xml_type == "AnimationScene")
{
return new pqAnimationScene(group, name, proxy, server, 0);
}
else if (xml_type == "KeyFrameAnimationCue" || xml_type == "CameraAnimationCue" ||
xml_type == "TimeAnimationCue" || xml_type == "PythonAnimationCue")
{
return new pqAnimationCue(group, name, proxy, server, 0);
}
}
return 0;
}
| 34.035088 | 100 | 0.675773 | [
"render",
"object"
] |
b400c99a8b1ff4d57ee93da1db5b944e2bd5cc76 | 5,869 | cc | C++ | modules/ofabmap/apps/live_fabmap.cc | grace-/opencv-3.0.0-cvpr | 6d854e002d60ed853732a051343ab48d5b8a30dd | [
"BSD-3-Clause"
] | 4 | 2015-03-30T14:02:41.000Z | 2016-12-10T05:42:59.000Z | modules/ofabmap/apps/live_fabmap.cc | grace-/opencv-3.0.0-cvpr | 6d854e002d60ed853732a051343ab48d5b8a30dd | [
"BSD-3-Clause"
] | null | null | null | modules/ofabmap/apps/live_fabmap.cc | grace-/opencv-3.0.0-cvpr | 6d854e002d60ed853732a051343ab48d5b8a30dd | [
"BSD-3-Clause"
] | 2 | 2017-12-15T08:26:45.000Z | 2019-02-10T19:50:16.000Z | /* this file is to demonstrate live FAB-MAP matching
* fabmap approach is based on the openfabmap implementation
* @author - Prasanna Krishnasamy (pras.bits@gmail.com)
*/
#include "opencv2/opencv.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdio>
using namespace cv;
using namespace std;
static void help() {
printf("Sample usage:\n"
"live_fabmap <ymlfile directory> <map data dir> <cameraid>\n\n"
" <ymlfile directory> where vocab and chow-liu tree ymls are stored\n"
" <map data dir> where images for map are stored\n"
" <cameraid> non-negative integer indicating cameraid\n"
);
}
int main(int argc, char * argv[]) {
printf("This sample program demonstrates live FAB-MAP image matching "
"algorithm\n\n");
string dataDir, mapDir;
int cam_deviceid = 0;
if (argc == 1) {
//incorrect arguments
help();
return (-1);
} else if (argc == 2) {
if(!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")) {
help();
return(-1);
}
dataDir = string(argv[1]);
dataDir += "/";
} else if (argc == 3) {
if(!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")) {
help();
return(-1);
}
dataDir = string(argv[1]);
dataDir += "/";
mapDir = string(argv[2]);
mapDir += "/";
} else if (argc == 4) {
if(!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")) {
help();
return(-1);
}
dataDir = string(argv[1]);
dataDir += "/";
mapDir = string(argv[2]);
mapDir += "/";
cam_deviceid = boost::lexical_cast<int>(argv[3]);
} else {
//incorrect arguments
help();
return -1;
}
FileStorage fs;
//load/generate vocab
cout << "Loading Vocabulary: " <<
dataDir + string("vocab_big.yml") << endl << endl;
fs.open(dataDir + string("vocab_big.yml"), FileStorage::READ);
Mat vocab;
fs["Vocabulary"] >> vocab;
if (vocab.empty()) {
cerr << "Vocabulary not found" << endl;
return -1;
}
fs.release();
//load/generate training data
cout << "Loading Training Data: " <<
dataDir + string("training_data.yml") << endl << endl;
fs.open(dataDir + string("training_data.yml"), FileStorage::READ);
Mat trainData;
fs["BOWImageDescs"] >> trainData;
if (trainData.empty()) {
cerr << "Training Data not found" << endl;
return -1;
}
fs.release();
//create Chow-liu tree
printf("Making Chow-Liu Tree from training data\n");
of2::ChowLiuTree treeBuilder;
treeBuilder.add(trainData);
Mat tree = treeBuilder.make();
//generate test data
printf("Extracting Test Data from images\n");
Ptr<FeatureDetector> detector =
new DynamicAdaptedFeatureDetector(
AdjusterAdapter::create("SURF"), 100, 130, 5);
Ptr<DescriptorExtractor> extractor =
// DescriptorExtractor::create("SIFT");
new SurfDescriptorExtractor(1000, 4, 2, false, true);
Ptr<DescriptorMatcher> matcher =
DescriptorMatcher::create("FlannBased");
BOWImgDescriptorExtractor bide(extractor, matcher);
bide.setVocabulary(vocab);
vector<string> imageNames;
namespace bfs = boost::filesystem;
bfs::path p(mapDir);
bfs::directory_iterator end_iter;
if (bfs::is_directory(p)) {
for (bfs::directory_iterator dir_iter(p); dir_iter != end_iter;
++dir_iter) {
if (bfs::is_regular_file(dir_iter->status()) ) {
printf("%s\n", dir_iter->path().c_str());
imageNames.push_back(dir_iter->path().native());
}
}
}
std::sort(imageNames.begin(), imageNames.end());
printf("Number of image files being processed is %lu\n", imageNames.size());
Mat testData;
Mat frame;
Mat bow;
vector<KeyPoint> kpts;
vector<Mat> map_images;
for(size_t i = 0; i < imageNames.size(); i++) {
cout << imageNames[i] << endl;
frame = imread(imageNames[i]);
if (frame.empty()) {
printf("Test images not found\n");
return -1;
}
map_images.push_back(frame);
detector->detect(frame, kpts);
bide.compute(frame, kpts, bow);
testData.push_back(bow);
// drawKeypoints(frame, kpts, frame);
// imshow(imageNames[i], frame);
// waitKey(10);
}
//run fabmap
printf("Running FAB-MAP algorithm\n\n");
Ptr<of2::FabMap> fabmap;
fabmap = new of2::FabMap2(tree, 0.39, 0, of2::FabMap::SAMPLED |
of2::FabMap::CHOW_LIU);
fabmap->addTraining(trainData);
vector<of2::IMatch> matches;
fabmap->compare(testData, matches, true);
// read images from camera
cv::VideoCapture cap(cam_deviceid);
if (!cap.isOpened()) {
printf("Opening the default camera did not succeed\n");
return -1;
}
int framenum = 0;
for (;;) {
Mat frame;
cap >> frame;
Mat visualword_descriptor;
vector<KeyPoint> kpts;
detector->detect(frame, kpts);
drawKeypoints(frame, kpts, frame);
imshow("input RGB image", frame);
bide.compute(frame, kpts, visualword_descriptor);
vector<of2::IMatch> matches;
fabmap->compare(visualword_descriptor, matches);
vector<of2::IMatch>::iterator l;
double max_prob = 0;
int max_img_idx = -1;
printf("---------------------\n");
for (l = matches.begin(); l != matches.end(); l++) {
printf("prob is %f\n", l->match);
if (max_prob < l->match) {
max_prob = l->match;
max_img_idx = l->imgIdx;
}
}
// cout << " Max idx is " << max_img_idx << endl;
cv::Mat disp_image;
if (max_img_idx == -1) {
disp_image = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
} else {
disp_image = map_images[max_img_idx];
}
cv::imshow("Closest Map image", disp_image);
int keyp = cv::waitKey(10);
if (keyp == 27) {
printf("Done capturing.\n");
break;
} else if (keyp == 'h') {
help();
}
}
return 0;
}
| 26.556561 | 78 | 0.608962 | [
"vector"
] |
b402b5c4a54c264bfa251de0743762b01aac56ce | 425,255 | cpp | C++ | src/llvm-4.0.0.src/tools/clang/unittests/Format/FormatTest.cpp | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | 12 | 2018-09-18T19:51:27.000Z | 2022-01-18T15:31:41.000Z | src/llvm-4.0.0.src/tools/clang/unittests/Format/FormatTest.cpp | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | 4 | 2021-01-08T07:55:34.000Z | 2021-08-06T12:06:02.000Z | src/llvm-4.0.0.src/tools/clang/unittests/Format/FormatTest.cpp | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | 3 | 2019-06-12T19:38:54.000Z | 2020-03-05T19:17:23.000Z | //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Format/Format.h"
#include "../Tooling/ReplacementTest.h"
#include "FormatTestUtils.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MemoryBuffer.h"
#include "gtest/gtest.h"
#define DEBUG_TYPE "format-test"
using clang::tooling::ReplacementTest;
using clang::tooling::toReplacements;
namespace clang {
namespace format {
namespace {
FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
class FormatTest : public ::testing::Test {
protected:
enum IncompleteCheck {
IC_ExpectComplete,
IC_ExpectIncomplete,
IC_DoNotCheck
};
std::string format(llvm::StringRef Code,
const FormatStyle &Style = getLLVMStyle(),
IncompleteCheck CheckIncomplete = IC_ExpectComplete) {
DEBUG(llvm::errs() << "---\n");
DEBUG(llvm::errs() << Code << "\n\n");
std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
bool IncompleteFormat = false;
tooling::Replacements Replaces =
reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
if (CheckIncomplete != IC_DoNotCheck) {
bool ExpectedIncompleteFormat = CheckIncomplete == IC_ExpectIncomplete;
EXPECT_EQ(ExpectedIncompleteFormat, IncompleteFormat) << Code << "\n\n";
}
ReplacementCount = Replaces.size();
auto Result = applyAllReplacements(Code, Replaces);
EXPECT_TRUE(static_cast<bool>(Result));
DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
return *Result;
}
FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
FormatStyle Style = getLLVMStyle();
Style.ColumnLimit = ColumnLimit;
return Style;
}
FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
FormatStyle Style = getGoogleStyle();
Style.ColumnLimit = ColumnLimit;
return Style;
}
void verifyFormat(llvm::StringRef Code,
const FormatStyle &Style = getLLVMStyle()) {
EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
}
void verifyIncompleteFormat(llvm::StringRef Code,
const FormatStyle &Style = getLLVMStyle()) {
EXPECT_EQ(Code.str(),
format(test::messUp(Code), Style, IC_ExpectIncomplete));
}
void verifyGoogleFormat(llvm::StringRef Code) {
verifyFormat(Code, getGoogleStyle());
}
void verifyIndependentOfContext(llvm::StringRef text) {
verifyFormat(text);
verifyFormat(llvm::Twine("void f() { " + text + " }").str());
}
/// \brief Verify that clang-format does not crash on the given input.
void verifyNoCrash(llvm::StringRef Code,
const FormatStyle &Style = getLLVMStyle()) {
format(Code, Style, IC_DoNotCheck);
}
int ReplacementCount;
};
TEST_F(FormatTest, MessUp) {
EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
}
//===----------------------------------------------------------------------===//
// Basic function tests.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
EXPECT_EQ(";", format(";"));
}
TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
EXPECT_EQ("int i;", format(" int i;"));
EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;"));
EXPECT_EQ("int i;\nint j;", format(" int i; int j;"));
EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;"));
}
TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
EXPECT_EQ("int i;", format("int\ni;"));
}
TEST_F(FormatTest, FormatsNestedBlockStatements) {
EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}"));
}
TEST_F(FormatTest, FormatsNestedCall) {
verifyFormat("Method(f1, f2(f3));");
verifyFormat("Method(f1(f2, f3()));");
verifyFormat("Method(f1(f2, (f3())));");
}
TEST_F(FormatTest, NestedNameSpecifiers) {
verifyFormat("vector<::Type> v;");
verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
verifyFormat("bool a = 2 < ::SomeFunction();");
}
TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
EXPECT_EQ("if (a) {\n"
" f();\n"
"}",
format("if(a){f();}"));
EXPECT_EQ(4, ReplacementCount);
EXPECT_EQ("if (a) {\n"
" f();\n"
"}",
format("if (a) {\n"
" f();\n"
"}"));
EXPECT_EQ(0, ReplacementCount);
EXPECT_EQ("/*\r\n"
"\r\n"
"*/\r\n",
format("/*\r\n"
"\r\n"
"*/\r\n"));
EXPECT_EQ(0, ReplacementCount);
}
TEST_F(FormatTest, RemovesEmptyLines) {
EXPECT_EQ("class C {\n"
" int i;\n"
"};",
format("class C {\n"
" int i;\n"
"\n"
"};"));
// Don't remove empty lines at the start of namespaces or extern "C" blocks.
EXPECT_EQ("namespace N {\n"
"\n"
"int i;\n"
"}",
format("namespace N {\n"
"\n"
"int i;\n"
"}",
getGoogleStyle()));
EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
"\n"
"int i;\n"
"}",
format("extern /**/ \"C\" /**/ {\n"
"\n"
"int i;\n"
"}",
getGoogleStyle()));
// ...but do keep inlining and removing empty lines for non-block extern "C"
// functions.
verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
EXPECT_EQ("extern \"C\" int f() {\n"
" int i = 42;\n"
" return i;\n"
"}",
format("extern \"C\" int f() {\n"
"\n"
" int i = 42;\n"
" return i;\n"
"}",
getGoogleStyle()));
// Remove empty lines at the beginning and end of blocks.
EXPECT_EQ("void f() {\n"
"\n"
" if (a) {\n"
"\n"
" f();\n"
" }\n"
"}",
format("void f() {\n"
"\n"
" if (a) {\n"
"\n"
" f();\n"
"\n"
" }\n"
"\n"
"}",
getLLVMStyle()));
EXPECT_EQ("void f() {\n"
" if (a) {\n"
" f();\n"
" }\n"
"}",
format("void f() {\n"
"\n"
" if (a) {\n"
"\n"
" f();\n"
"\n"
" }\n"
"\n"
"}",
getGoogleStyle()));
// Don't remove empty lines in more complex control statements.
EXPECT_EQ("void f() {\n"
" if (a) {\n"
" f();\n"
"\n"
" } else if (b) {\n"
" f();\n"
" }\n"
"}",
format("void f() {\n"
" if (a) {\n"
" f();\n"
"\n"
" } else if (b) {\n"
" f();\n"
"\n"
" }\n"
"\n"
"}"));
// FIXME: This is slightly inconsistent.
EXPECT_EQ("namespace {\n"
"int i;\n"
"}",
format("namespace {\n"
"int i;\n"
"\n"
"}"));
EXPECT_EQ("namespace {\n"
"int i;\n"
"\n"
"} // namespace",
format("namespace {\n"
"int i;\n"
"\n"
"} // namespace"));
FormatStyle Style = getLLVMStyle();
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Style.MaxEmptyLinesToKeep = 2;
Style.BreakBeforeBraces = FormatStyle::BS_Custom;
Style.BraceWrapping.AfterClass = true;
Style.BraceWrapping.AfterFunction = true;
Style.KeepEmptyLinesAtTheStartOfBlocks = false;
EXPECT_EQ("class Foo\n"
"{\n"
" Foo() {}\n"
"\n"
" void funk() {}\n"
"};",
format("class Foo\n"
"{\n"
" Foo()\n"
" {\n"
" }\n"
"\n"
" void funk() {}\n"
"};",
Style));
}
TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
verifyFormat("x = (a) and (b);");
verifyFormat("x = (a) or (b);");
verifyFormat("x = (a) bitand (b);");
verifyFormat("x = (a) bitor (b);");
verifyFormat("x = (a) not_eq (b);");
verifyFormat("x = (a) and_eq (b);");
verifyFormat("x = (a) or_eq (b);");
verifyFormat("x = (a) xor (b);");
}
//===----------------------------------------------------------------------===//
// Tests for control statements.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
verifyFormat("if (true)\n f();\ng();");
verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();");
verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
FormatStyle AllowsMergedIf = getLLVMStyle();
AllowsMergedIf.AlignEscapedNewlinesLeft = true;
AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
verifyFormat("if (a)\n"
" // comment\n"
" f();",
AllowsMergedIf);
verifyFormat("{\n"
" if (a)\n"
" label:\n"
" f();\n"
"}",
AllowsMergedIf);
verifyFormat("#define A \\\n"
" if (a) \\\n"
" label: \\\n"
" f()",
AllowsMergedIf);
verifyFormat("if (a)\n"
" ;",
AllowsMergedIf);
verifyFormat("if (a)\n"
" if (b) return;",
AllowsMergedIf);
verifyFormat("if (a) // Can't merge this\n"
" f();\n",
AllowsMergedIf);
verifyFormat("if (a) /* still don't merge */\n"
" f();",
AllowsMergedIf);
verifyFormat("if (a) { // Never merge this\n"
" f();\n"
"}",
AllowsMergedIf);
verifyFormat("if (a) { /* Never merge this */\n"
" f();\n"
"}",
AllowsMergedIf);
AllowsMergedIf.ColumnLimit = 14;
verifyFormat("if (a) return;", AllowsMergedIf);
verifyFormat("if (aaaaaaaaa)\n"
" return;",
AllowsMergedIf);
AllowsMergedIf.ColumnLimit = 13;
verifyFormat("if (a)\n return;", AllowsMergedIf);
}
TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
FormatStyle AllowsMergedLoops = getLLVMStyle();
AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
verifyFormat("while (true) continue;", AllowsMergedLoops);
verifyFormat("for (;;) continue;", AllowsMergedLoops);
verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
verifyFormat("while (true)\n"
" ;",
AllowsMergedLoops);
verifyFormat("for (;;)\n"
" ;",
AllowsMergedLoops);
verifyFormat("for (;;)\n"
" for (;;) continue;",
AllowsMergedLoops);
verifyFormat("for (;;) // Can't merge this\n"
" continue;",
AllowsMergedLoops);
verifyFormat("for (;;) /* still don't merge */\n"
" continue;",
AllowsMergedLoops);
}
TEST_F(FormatTest, FormatShortBracedStatements) {
FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = true;
AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
verifyFormat("if (true) {}", AllowSimpleBracedStatements);
verifyFormat("while (true) {}", AllowSimpleBracedStatements);
verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
verifyFormat("if (true) { //\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
verifyFormat("if (true) {\n"
" f();\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
verifyFormat("if (true) {\n"
" f();\n"
"} else {\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
verifyFormat("template <int> struct A2 {\n"
" struct B {};\n"
"};",
AllowSimpleBracedStatements);
AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
verifyFormat("if (true) {\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
verifyFormat("if (true) {\n"
" f();\n"
"} else {\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
verifyFormat("while (true) {\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
verifyFormat("for (;;) {\n"
" f();\n"
"}",
AllowSimpleBracedStatements);
}
TEST_F(FormatTest, ParseIfElse) {
verifyFormat("if (true)\n"
" if (true)\n"
" if (true)\n"
" f();\n"
" else\n"
" g();\n"
" else\n"
" h();\n"
"else\n"
" i();");
verifyFormat("if (true)\n"
" if (true)\n"
" if (true) {\n"
" if (true)\n"
" f();\n"
" } else {\n"
" g();\n"
" }\n"
" else\n"
" h();\n"
"else {\n"
" i();\n"
"}");
verifyFormat("void f() {\n"
" if (a) {\n"
" } else {\n"
" }\n"
"}");
}
TEST_F(FormatTest, ElseIf) {
verifyFormat("if (a) {\n} else if (b) {\n}");
verifyFormat("if (a)\n"
" f();\n"
"else if (b)\n"
" g();\n"
"else\n"
" h();");
verifyFormat("if (a) {\n"
" f();\n"
"}\n"
"// or else ..\n"
"else {\n"
" g()\n"
"}");
verifyFormat("if (a) {\n"
"} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
"}");
verifyFormat("if (a) {\n"
"} else if (\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
"}",
getLLVMStyleWithColumns(62));
}
TEST_F(FormatTest, FormatsForLoop) {
verifyFormat(
"for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
" ++VeryVeryLongLoopVariable)\n"
" ;");
verifyFormat("for (;;)\n"
" f();");
verifyFormat("for (;;) {\n}");
verifyFormat("for (;;) {\n"
" f();\n"
"}");
verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
verifyFormat(
"for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
" E = UnwrappedLines.end();\n"
" I != E; ++I) {\n}");
verifyFormat(
"for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
" ++IIIII) {\n}");
verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
" aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
" I = FD->getDeclsInPrototypeScope().begin(),\n"
" E = FD->getDeclsInPrototypeScope().end();\n"
" I != E; ++I) {\n}");
verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
" I = Container.begin(),\n"
" E = Container.end();\n"
" I != E; ++I) {\n}",
getLLVMStyleWithColumns(76));
verifyFormat(
"for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
" ++aaaaaaaaaaa) {\n}");
verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
" ++i) {\n}");
verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
" aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
"}");
verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
" aaaaaaaaaa);\n"
" iter; ++iter) {\n"
"}");
verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
" ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
verifyFormat("for (int aaaaaaaaaaa = 1;\n"
" aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa);\n"
" aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
"}",
NoBinPacking);
verifyFormat(
"for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
" E = UnwrappedLines.end();\n"
" I != E;\n"
" ++I) {\n}",
NoBinPacking);
}
TEST_F(FormatTest, RangeBasedForLoops) {
verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
}
TEST_F(FormatTest, ForEachLoops) {
verifyFormat("void f() {\n"
" foreach (Item *item, itemlist) {}\n"
" Q_FOREACH (Item *item, itemlist) {}\n"
" BOOST_FOREACH (Item *item, itemlist) {}\n"
" UNKNOWN_FORACH(Item * item, itemlist) {}\n"
"}");
// As function-like macros.
verifyFormat("#define foreach(x, y)\n"
"#define Q_FOREACH(x, y)\n"
"#define BOOST_FOREACH(x, y)\n"
"#define UNKNOWN_FOREACH(x, y)\n");
// Not as function-like macros.
verifyFormat("#define foreach (x, y)\n"
"#define Q_FOREACH (x, y)\n"
"#define BOOST_FOREACH (x, y)\n"
"#define UNKNOWN_FOREACH (x, y)\n");
}
TEST_F(FormatTest, FormatsWhileLoop) {
verifyFormat("while (true) {\n}");
verifyFormat("while (true)\n"
" f();");
verifyFormat("while () {\n}");
verifyFormat("while () {\n"
" f();\n"
"}");
}
TEST_F(FormatTest, FormatsDoWhile) {
verifyFormat("do {\n"
" do_something();\n"
"} while (something());");
verifyFormat("do\n"
" do_something();\n"
"while (something());");
}
TEST_F(FormatTest, FormatsSwitchStatement) {
verifyFormat("switch (x) {\n"
"case 1:\n"
" f();\n"
" break;\n"
"case kFoo:\n"
"case ns::kBar:\n"
"case kBaz:\n"
" break;\n"
"default:\n"
" g();\n"
" break;\n"
"}");
verifyFormat("switch (x) {\n"
"case 1: {\n"
" f();\n"
" break;\n"
"}\n"
"case 2: {\n"
" break;\n"
"}\n"
"}");
verifyFormat("switch (x) {\n"
"case 1: {\n"
" f();\n"
" {\n"
" g();\n"
" h();\n"
" }\n"
" break;\n"
"}\n"
"}");
verifyFormat("switch (x) {\n"
"case 1: {\n"
" f();\n"
" if (foo) {\n"
" g();\n"
" h();\n"
" }\n"
" break;\n"
"}\n"
"}");
verifyFormat("switch (x) {\n"
"case 1: {\n"
" f();\n"
" g();\n"
"} break;\n"
"}");
verifyFormat("switch (test)\n"
" ;");
verifyFormat("switch (x) {\n"
"default: {\n"
" // Do nothing.\n"
"}\n"
"}");
verifyFormat("switch (x) {\n"
"// comment\n"
"// if 1, do f()\n"
"case 1:\n"
" f();\n"
"}");
verifyFormat("switch (x) {\n"
"case 1:\n"
" // Do amazing stuff\n"
" {\n"
" f();\n"
" g();\n"
" }\n"
" break;\n"
"}");
verifyFormat("#define A \\\n"
" switch (x) { \\\n"
" case a: \\\n"
" foo = b; \\\n"
" }",
getLLVMStyleWithColumns(20));
verifyFormat("#define OPERATION_CASE(name) \\\n"
" case OP_name: \\\n"
" return operations::Operation##name\n",
getLLVMStyleWithColumns(40));
verifyFormat("switch (x) {\n"
"case 1:;\n"
"default:;\n"
" int i;\n"
"}");
verifyGoogleFormat("switch (x) {\n"
" case 1:\n"
" f();\n"
" break;\n"
" case kFoo:\n"
" case ns::kBar:\n"
" case kBaz:\n"
" break;\n"
" default:\n"
" g();\n"
" break;\n"
"}");
verifyGoogleFormat("switch (x) {\n"
" case 1: {\n"
" f();\n"
" break;\n"
" }\n"
"}");
verifyGoogleFormat("switch (test)\n"
" ;");
verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
" case OP_name: \\\n"
" return operations::Operation##name\n");
verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
" // Get the correction operation class.\n"
" switch (OpCode) {\n"
" CASE(Add);\n"
" CASE(Subtract);\n"
" default:\n"
" return operations::Unknown;\n"
" }\n"
"#undef OPERATION_CASE\n"
"}");
verifyFormat("DEBUG({\n"
" switch (x) {\n"
" case A:\n"
" f();\n"
" break;\n"
" // On B:\n"
" case B:\n"
" g();\n"
" break;\n"
" }\n"
"});");
verifyFormat("switch (a) {\n"
"case (b):\n"
" return;\n"
"}");
verifyFormat("switch (a) {\n"
"case some_namespace::\n"
" some_constant:\n"
" return;\n"
"}",
getLLVMStyleWithColumns(34));
}
TEST_F(FormatTest, CaseRanges) {
verifyFormat("switch (x) {\n"
"case 'A' ... 'Z':\n"
"case 1 ... 5:\n"
"case a ... b:\n"
" break;\n"
"}");
}
TEST_F(FormatTest, ShortCaseLabels) {
FormatStyle Style = getLLVMStyle();
Style.AllowShortCaseLabelsOnASingleLine = true;
verifyFormat("switch (a) {\n"
"case 1: x = 1; break;\n"
"case 2: return;\n"
"case 3:\n"
"case 4:\n"
"case 5: return;\n"
"case 6: // comment\n"
" return;\n"
"case 7:\n"
" // comment\n"
" return;\n"
"case 8:\n"
" x = 8; // comment\n"
" break;\n"
"default: y = 1; break;\n"
"}",
Style);
verifyFormat("switch (a) {\n"
"#if FOO\n"
"case 0: return 0;\n"
"#endif\n"
"}",
Style);
verifyFormat("switch (a) {\n"
"case 1: {\n"
"}\n"
"case 2: {\n"
" return;\n"
"}\n"
"case 3: {\n"
" x = 1;\n"
" return;\n"
"}\n"
"case 4:\n"
" if (x)\n"
" return;\n"
"}",
Style);
Style.ColumnLimit = 21;
verifyFormat("switch (a) {\n"
"case 1: x = 1; break;\n"
"case 2: return;\n"
"case 3:\n"
"case 4:\n"
"case 5: return;\n"
"default:\n"
" y = 1;\n"
" break;\n"
"}",
Style);
}
TEST_F(FormatTest, FormatsLabels) {
verifyFormat("void f() {\n"
" some_code();\n"
"test_label:\n"
" some_other_code();\n"
" {\n"
" some_more_code();\n"
" another_label:\n"
" some_more_code();\n"
" }\n"
"}");
verifyFormat("{\n"
" some_code();\n"
"test_label:\n"
" some_other_code();\n"
"}");
verifyFormat("{\n"
" some_code();\n"
"test_label:;\n"
" int i = 0;\n"
"}");
}
//===----------------------------------------------------------------------===//
// Tests for comments.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, UnderstandsSingleLineComments) {
verifyFormat("//* */");
verifyFormat("// line 1\n"
"// line 2\n"
"void f() {}\n");
verifyFormat("void f() {\n"
" // Doesn't do anything\n"
"}");
verifyFormat("SomeObject\n"
" // Calling someFunction on SomeObject\n"
" .someFunction();");
verifyFormat("auto result = SomeObject\n"
" // Calling someFunction on SomeObject\n"
" .someFunction();");
verifyFormat("void f(int i, // some comment (probably for i)\n"
" int j, // some comment (probably for j)\n"
" int k); // some comment (probably for k)");
verifyFormat("void f(int i,\n"
" // some comment (probably for j)\n"
" int j,\n"
" // some comment (probably for k)\n"
" int k);");
verifyFormat("int i // This is a fancy variable\n"
" = 5; // with nicely aligned comment.");
verifyFormat("// Leading comment.\n"
"int a; // Trailing comment.");
verifyFormat("int a; // Trailing comment\n"
" // on 2\n"
" // or 3 lines.\n"
"int b;");
verifyFormat("int a; // Trailing comment\n"
"\n"
"// Leading comment.\n"
"int b;");
verifyFormat("int a; // Comment.\n"
" // More details.\n"
"int bbbb; // Another comment.");
verifyFormat(
"int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
"int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // comment\n"
"int cccccccccccccccccccccccccccccc; // comment\n"
"int ddd; // looooooooooooooooooooooooong comment\n"
"int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
"int bbbbbbbbbbbbbbbbbbbbb; // comment\n"
"int ccccccccccccccccccc; // comment");
verifyFormat("#include \"a\" // comment\n"
"#include \"a/b/c\" // comment");
verifyFormat("#include <a> // comment\n"
"#include <a/b/c> // comment");
EXPECT_EQ("#include \"a\" // comment\n"
"#include \"a/b/c\" // comment",
format("#include \\\n"
" \"a\" // comment\n"
"#include \"a/b/c\" // comment"));
verifyFormat("enum E {\n"
" // comment\n"
" VAL_A, // comment\n"
" VAL_B\n"
"};");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" // Comment inside a statement.\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
verifyFormat("SomeFunction(a,\n"
" // comment\n"
" b + x);");
verifyFormat("SomeFunction(a, a,\n"
" // comment\n"
" b + x);");
verifyFormat(
"bool aaaaaaaaaaaaa = // comment\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("int aaaa; // aaaaa\n"
"int aa; // aaaaaaa",
getLLVMStyleWithColumns(20));
EXPECT_EQ("void f() { // This does something ..\n"
"}\n"
"int a; // This is unrelated",
format("void f() { // This does something ..\n"
" }\n"
"int a; // This is unrelated"));
EXPECT_EQ("class C {\n"
" void f() { // This does something ..\n"
" } // awesome..\n"
"\n"
" int a; // This is unrelated\n"
"};",
format("class C{void f() { // This does something ..\n"
" } // awesome..\n"
" \n"
"int a; // This is unrelated\n"
"};"));
EXPECT_EQ("int i; // single line trailing comment",
format("int i;\\\n// single line trailing comment"));
verifyGoogleFormat("int a; // Trailing comment.");
verifyFormat("someFunction(anotherFunction( // Force break.\n"
" parameter));");
verifyGoogleFormat("#endif // HEADER_GUARD");
verifyFormat("const char *test[] = {\n"
" // A\n"
" \"aaaa\",\n"
" // B\n"
" \"aaaaa\"};");
verifyGoogleFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaa); // 81_cols_with_this_comment");
EXPECT_EQ("D(a, {\n"
" // test\n"
" int a;\n"
"});",
format("D(a, {\n"
"// test\n"
"int a;\n"
"});"));
EXPECT_EQ("lineWith(); // comment\n"
"// at start\n"
"otherLine();",
format("lineWith(); // comment\n"
"// at start\n"
"otherLine();"));
EXPECT_EQ("lineWith(); // comment\n"
"/*\n"
" * at start */\n"
"otherLine();",
format("lineWith(); // comment\n"
"/*\n"
" * at start */\n"
"otherLine();"));
EXPECT_EQ("lineWith(); // comment\n"
" // at start\n"
"otherLine();",
format("lineWith(); // comment\n"
" // at start\n"
"otherLine();"));
EXPECT_EQ("lineWith(); // comment\n"
"// at start\n"
"otherLine(); // comment",
format("lineWith(); // comment\n"
"// at start\n"
"otherLine(); // comment"));
EXPECT_EQ("lineWith();\n"
"// at start\n"
"otherLine(); // comment",
format("lineWith();\n"
" // at start\n"
"otherLine(); // comment"));
EXPECT_EQ("// first\n"
"// at start\n"
"otherLine(); // comment",
format("// first\n"
" // at start\n"
"otherLine(); // comment"));
EXPECT_EQ("f();\n"
"// first\n"
"// at start\n"
"otherLine(); // comment",
format("f();\n"
"// first\n"
" // at start\n"
"otherLine(); // comment"));
verifyFormat("f(); // comment\n"
"// first\n"
"// at start\n"
"otherLine();");
EXPECT_EQ("f(); // comment\n"
"// first\n"
"// at start\n"
"otherLine();",
format("f(); // comment\n"
"// first\n"
" // at start\n"
"otherLine();"));
EXPECT_EQ("f(); // comment\n"
" // first\n"
"// at start\n"
"otherLine();",
format("f(); // comment\n"
" // first\n"
"// at start\n"
"otherLine();"));
EXPECT_EQ("void f() {\n"
" lineWith(); // comment\n"
" // at start\n"
"}",
format("void f() {\n"
" lineWith(); // comment\n"
" // at start\n"
"}"));
EXPECT_EQ("int xy; // a\n"
"int z; // b",
format("int xy; // a\n"
"int z; //b"));
EXPECT_EQ("int xy; // a\n"
"int z; // bb",
format("int xy; // a\n"
"int z; //bb",
getLLVMStyleWithColumns(12)));
verifyFormat("#define A \\\n"
" int i; /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
" int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
getLLVMStyleWithColumns(60));
verifyFormat(
"#define A \\\n"
" int i; /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
" int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
getLLVMStyleWithColumns(61));
verifyFormat("if ( // This is some comment\n"
" x + 3) {\n"
"}");
EXPECT_EQ("if ( // This is some comment\n"
" // spanning two lines\n"
" x + 3) {\n"
"}",
format("if( // This is some comment\n"
" // spanning two lines\n"
" x + 3) {\n"
"}"));
verifyNoCrash("/\\\n/");
verifyNoCrash("/\\\n* */");
// The 0-character somehow makes the lexer return a proper comment.
verifyNoCrash(StringRef("/*\\\0\n/", 6));
}
TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) {
EXPECT_EQ("SomeFunction(a,\n"
" b, // comment\n"
" c);",
format("SomeFunction(a,\n"
" b, // comment\n"
" c);"));
EXPECT_EQ("SomeFunction(a, b,\n"
" // comment\n"
" c);",
format("SomeFunction(a,\n"
" b,\n"
" // comment\n"
" c);"));
EXPECT_EQ("SomeFunction(a, b, // comment (unclear relation)\n"
" c);",
format("SomeFunction(a, b, // comment (unclear relation)\n"
" c);"));
EXPECT_EQ("SomeFunction(a, // comment\n"
" b,\n"
" c); // comment",
format("SomeFunction(a, // comment\n"
" b,\n"
" c); // comment"));
EXPECT_EQ("aaaaaaaaaa(aaaa(aaaa,\n"
" aaaa), //\n"
" aaaa, bbbbb);",
format("aaaaaaaaaa(aaaa(aaaa,\n"
"aaaa), //\n"
"aaaa, bbbbb);"));
}
TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
EXPECT_EQ("// comment", format("// comment "));
EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
format("int aaaaaaa, bbbbbbb; // comment ",
getLLVMStyleWithColumns(33)));
EXPECT_EQ("// comment\\\n", format("// comment\\\n \t \v \f "));
EXPECT_EQ("// comment \\\n", format("// comment \\\n \t \v \f "));
}
TEST_F(FormatTest, UnderstandsBlockComments) {
verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y, /*c=*/::c); }");
EXPECT_EQ("f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb);",
format("f(aaaaaaaaaaaaaaaaaaaaaaaaa , \\\n"
"/* Trailing comment for aa... */\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb);"));
EXPECT_EQ(
"f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
format("f(aaaaaaaaaaaaaaaaaaaaaaaaa , \n"
"/* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);"));
EXPECT_EQ(
"void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
"}",
format("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaa ,\n"
" aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
"}"));
verifyFormat("f(/* aaaaaaaaaaaaaaaaaa = */\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
" /* parameter 2 */ aaaaaa,\n"
" /* parameter 3 */ aaaaaa,\n"
" /* parameter 4 */ aaaaaa);",
NoBinPacking);
// Aligning block comments in macros.
verifyGoogleFormat("#define A \\\n"
" int i; /*a*/ \\\n"
" int jjj; /*b*/");
}
TEST_F(FormatTest, AlignsBlockComments) {
EXPECT_EQ("/*\n"
" * Really multi-line\n"
" * comment.\n"
" */\n"
"void f() {}",
format(" /*\n"
" * Really multi-line\n"
" * comment.\n"
" */\n"
" void f() {}"));
EXPECT_EQ("class C {\n"
" /*\n"
" * Another multi-line\n"
" * comment.\n"
" */\n"
" void f() {}\n"
"};",
format("class C {\n"
"/*\n"
" * Another multi-line\n"
" * comment.\n"
" */\n"
"void f() {}\n"
"};"));
EXPECT_EQ("/*\n"
" 1. This is a comment with non-trivial formatting.\n"
" 1.1. We have to indent/outdent all lines equally\n"
" 1.1.1. to keep the formatting.\n"
" */",
format(" /*\n"
" 1. This is a comment with non-trivial formatting.\n"
" 1.1. We have to indent/outdent all lines equally\n"
" 1.1.1. to keep the formatting.\n"
" */"));
EXPECT_EQ("/*\n"
"Don't try to outdent if there's not enough indentation.\n"
"*/",
format(" /*\n"
" Don't try to outdent if there's not enough indentation.\n"
" */"));
EXPECT_EQ("int i; /* Comment with empty...\n"
" *\n"
" * line. */",
format("int i; /* Comment with empty...\n"
" *\n"
" * line. */"));
EXPECT_EQ("int foobar = 0; /* comment */\n"
"int bar = 0; /* multiline\n"
" comment 1 */\n"
"int baz = 0; /* multiline\n"
" comment 2 */\n"
"int bzz = 0; /* multiline\n"
" comment 3 */",
format("int foobar = 0; /* comment */\n"
"int bar = 0; /* multiline\n"
" comment 1 */\n"
"int baz = 0; /* multiline\n"
" comment 2 */\n"
"int bzz = 0; /* multiline\n"
" comment 3 */"));
EXPECT_EQ("int foobar = 0; /* comment */\n"
"int bar = 0; /* multiline\n"
" comment */\n"
"int baz = 0; /* multiline\n"
"comment */",
format("int foobar = 0; /* comment */\n"
"int bar = 0; /* multiline\n"
"comment */\n"
"int baz = 0; /* multiline\n"
"comment */"));
}
TEST_F(FormatTest, CommentReflowingCanBeTurnedOff) {
FormatStyle Style = getLLVMStyleWithColumns(20);
Style.ReflowComments = false;
verifyFormat("// aaaaaaaaa aaaaaaaaaa aaaaaaaaaa", Style);
verifyFormat("/* aaaaaaaaa aaaaaaaaaa aaaaaaaaaa */", Style);
}
TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
EXPECT_EQ(
"void ffffffffffff(\n"
" int aaaaaaaa, int bbbbbbbb,\n"
" int cccccccccccc) { /*\n"
" aaaaaaaaaa\n"
" aaaaaaaaaaaaa\n"
" bbbbbbbbbbbbbb\n"
" bbbbbbbbbb\n"
" */\n"
"}",
format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
"{ /*\n"
" aaaaaaaaaa aaaaaaaaaaaaa\n"
" bbbbbbbbbbbbbb bbbbbbbbbb\n"
" */\n"
"}",
getLLVMStyleWithColumns(40)));
}
TEST_F(FormatTest, DontBreakNonTrailingBlockComments) {
EXPECT_EQ("void ffffffffff(\n"
" int aaaaa /* test */);",
format("void ffffffffff(int aaaaa /* test */);",
getLLVMStyleWithColumns(35)));
}
TEST_F(FormatTest, SplitsLongCxxComments) {
EXPECT_EQ("// A comment that\n"
"// doesn't fit on\n"
"// one line",
format("// A comment that doesn't fit on one line",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/// A comment that\n"
"/// doesn't fit on\n"
"/// one line",
format("/// A comment that doesn't fit on one line",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("//! A comment that\n"
"//! doesn't fit on\n"
"//! one line",
format("//! A comment that doesn't fit on one line",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("// a b c d\n"
"// e f g\n"
"// h i j k",
format("// a b c d e f g h i j k", getLLVMStyleWithColumns(10)));
EXPECT_EQ(
"// a b c d\n"
"// e f g\n"
"// h i j k",
format("\\\n// a b c d e f g h i j k", getLLVMStyleWithColumns(10)));
EXPECT_EQ("if (true) // A comment that\n"
" // doesn't fit on\n"
" // one line",
format("if (true) // A comment that doesn't fit on one line ",
getLLVMStyleWithColumns(30)));
EXPECT_EQ("// Don't_touch_leading_whitespace",
format("// Don't_touch_leading_whitespace",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("// Add leading\n"
"// whitespace",
format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
EXPECT_EQ("/// Add leading\n"
"/// whitespace",
format("///Add leading whitespace", getLLVMStyleWithColumns(20)));
EXPECT_EQ("//! Add leading\n"
"//! whitespace",
format("//!Add leading whitespace", getLLVMStyleWithColumns(20)));
EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
EXPECT_EQ("// Even if it makes the line exceed the column\n"
"// limit",
format("//Even if it makes the line exceed the column limit",
getLLVMStyleWithColumns(51)));
EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
EXPECT_EQ("// aa bb cc dd",
format("// aa bb cc dd ",
getLLVMStyleWithColumns(15)));
EXPECT_EQ("// A comment before\n"
"// a macro\n"
"// definition\n"
"#define a b",
format("// A comment before a macro definition\n"
"#define a b",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("void ffffff(\n"
" int aaaaaaaaa, // wwww\n"
" int bbbbbbbbbb, // xxxxxxx\n"
" // yyyyyyyyyy\n"
" int c, int d, int e) {}",
format("void ffffff(\n"
" int aaaaaaaaa, // wwww\n"
" int bbbbbbbbbb, // xxxxxxx yyyyyyyyyy\n"
" int c, int d, int e) {}",
getLLVMStyleWithColumns(40)));
EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
getLLVMStyleWithColumns(20)));
EXPECT_EQ(
"#define XXX // a b c d\n"
" // e f g h",
format("#define XXX // a b c d e f g h", getLLVMStyleWithColumns(22)));
EXPECT_EQ(
"#define XXX // q w e r\n"
" // t y u i",
format("#define XXX //q w e r t y u i", getLLVMStyleWithColumns(22)));
}
TEST_F(FormatTest, PreservesHangingIndentInCxxComments) {
EXPECT_EQ("// A comment\n"
"// that doesn't\n"
"// fit on one\n"
"// line",
format("// A comment that doesn't fit on one line",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/// A comment\n"
"/// that doesn't\n"
"/// fit on one\n"
"/// line",
format("/// A comment that doesn't fit on one line",
getLLVMStyleWithColumns(20)));
}
TEST_F(FormatTest, DontSplitLineCommentsWithEscapedNewlines) {
EXPECT_EQ("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
"// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
"// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
format("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
"// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
"// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
EXPECT_EQ("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
getLLVMStyleWithColumns(50)));
// FIXME: One day we might want to implement adjustment of leading whitespace
// of the consecutive lines in this kind of comment:
EXPECT_EQ("double\n"
" a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
format("double a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
" // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
getLLVMStyleWithColumns(49)));
}
TEST_F(FormatTest, DontSplitLineCommentsWithPragmas) {
FormatStyle Pragmas = getLLVMStyleWithColumns(30);
Pragmas.CommentPragmas = "^ IWYU pragma:";
EXPECT_EQ(
"// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb",
format("// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb", Pragmas));
EXPECT_EQ(
"/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */",
format("/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */", Pragmas));
}
TEST_F(FormatTest, PriorityOfCommentBreaking) {
EXPECT_EQ("if (xxx ==\n"
" yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
" zzz)\n"
" q();",
format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
" zzz) q();",
getLLVMStyleWithColumns(40)));
EXPECT_EQ("if (xxxxxxxxxx ==\n"
" yyy && // aaaaaa bbbbbbbb cccc\n"
" zzz)\n"
" q();",
format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
" zzz) q();",
getLLVMStyleWithColumns(40)));
EXPECT_EQ("if (xxxxxxxxxx &&\n"
" yyy || // aaaaaa bbbbbbbb cccc\n"
" zzz)\n"
" q();",
format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
" zzz) q();",
getLLVMStyleWithColumns(40)));
EXPECT_EQ("fffffffff(\n"
" &xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
" zzz);",
format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
" zzz);",
getLLVMStyleWithColumns(40)));
}
TEST_F(FormatTest, MultiLineCommentsInDefines) {
EXPECT_EQ("#define A(x) /* \\\n"
" a comment \\\n"
" inside */ \\\n"
" f();",
format("#define A(x) /* \\\n"
" a comment \\\n"
" inside */ \\\n"
" f();",
getLLVMStyleWithColumns(17)));
EXPECT_EQ("#define A( \\\n"
" x) /* \\\n"
" a comment \\\n"
" inside */ \\\n"
" f();",
format("#define A( \\\n"
" x) /* \\\n"
" a comment \\\n"
" inside */ \\\n"
" f();",
getLLVMStyleWithColumns(17)));
}
TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
EXPECT_EQ("namespace {}\n// Test\n#define A",
format("namespace {}\n // Test\n#define A"));
EXPECT_EQ("namespace {}\n/* Test */\n#define A",
format("namespace {}\n /* Test */\n#define A"));
EXPECT_EQ("namespace {}\n/* Test */ #define A",
format("namespace {}\n /* Test */ #define A"));
}
TEST_F(FormatTest, SplitsLongLinesInComments) {
EXPECT_EQ("/* This is a long\n"
" * comment that\n"
" * doesn't\n"
" * fit on one line.\n"
" */",
format("/* "
"This is a long "
"comment that "
"doesn't "
"fit on one line. */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ(
"/* a b c d\n"
" * e f g\n"
" * h i j k\n"
" */",
format("/* a b c d e f g h i j k */", getLLVMStyleWithColumns(10)));
EXPECT_EQ(
"/* a b c d\n"
" * e f g\n"
" * h i j k\n"
" */",
format("\\\n/* a b c d e f g h i j k */", getLLVMStyleWithColumns(10)));
EXPECT_EQ("/*\n"
"This is a long\n"
"comment that doesn't\n"
"fit on one line.\n"
"*/",
format("/*\n"
"This is a long "
"comment that doesn't "
"fit on one line. \n"
"*/",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/*\n"
" * This is a long\n"
" * comment that\n"
" * doesn't fit on\n"
" * one line.\n"
" */",
format("/* \n"
" * This is a long "
" comment that "
" doesn't fit on "
" one line. \n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/*\n"
" * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
" * so_it_should_be_broken\n"
" * wherever_a_space_occurs\n"
" */",
format("/*\n"
" * This_is_a_comment_with_words_that_dont_fit_on_one_line "
" so_it_should_be_broken "
" wherever_a_space_occurs \n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/*\n"
" * This_comment_can_not_be_broken_into_lines\n"
" */",
format("/*\n"
" * This_comment_can_not_be_broken_into_lines\n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("{\n"
" /*\n"
" This is another\n"
" long comment that\n"
" doesn't fit on one\n"
" line 1234567890\n"
" */\n"
"}",
format("{\n"
"/*\n"
"This is another "
" long comment that "
" doesn't fit on one"
" line 1234567890\n"
"*/\n"
"}",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("{\n"
" /*\n"
" * This i s\n"
" * another comment\n"
" * t hat doesn' t\n"
" * fit on one l i\n"
" * n e\n"
" */\n"
"}",
format("{\n"
"/*\n"
" * This i s"
" another comment"
" t hat doesn' t"
" fit on one l i"
" n e\n"
" */\n"
"}",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/*\n"
" * This is a long\n"
" * comment that\n"
" * doesn't fit on\n"
" * one line\n"
" */",
format(" /*\n"
" * This is a long comment that doesn't fit on one line\n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("{\n"
" if (something) /* This is a\n"
" long\n"
" comment */\n"
" ;\n"
"}",
format("{\n"
" if (something) /* This is a long comment */\n"
" ;\n"
"}",
getLLVMStyleWithColumns(30)));
EXPECT_EQ("/* A comment before\n"
" * a macro\n"
" * definition */\n"
"#define a b",
format("/* A comment before a macro definition */\n"
"#define a b",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/* some comment\n"
" * a comment\n"
"* that we break\n"
" * another comment\n"
"* we have to break\n"
"* a left comment\n"
" */",
format(" /* some comment\n"
" * a comment that we break\n"
" * another comment we have to break\n"
"* a left comment\n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/**\n"
" * multiline block\n"
" * comment\n"
" *\n"
" */",
format("/**\n"
" * multiline block comment\n"
" *\n"
" */",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("/*\n"
"\n"
"\n"
" */\n",
format(" /* \n"
" \n"
" \n"
" */\n"));
EXPECT_EQ("/* a a */",
format("/* a a */", getLLVMStyleWithColumns(15)));
EXPECT_EQ("/* a a bc */",
format("/* a a bc */", getLLVMStyleWithColumns(15)));
EXPECT_EQ("/* aaa aaa\n"
" * aaaaa */",
format("/* aaa aaa aaaaa */", getLLVMStyleWithColumns(15)));
EXPECT_EQ("/* aaa aaa\n"
" * aaaaa */",
format("/* aaa aaa aaaaa */", getLLVMStyleWithColumns(15)));
}
TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
EXPECT_EQ("#define X \\\n"
" /* \\\n"
" Test \\\n"
" Macro comment \\\n"
" with a long \\\n"
" line \\\n"
" */ \\\n"
" A + B",
format("#define X \\\n"
" /*\n"
" Test\n"
" Macro comment with a long line\n"
" */ \\\n"
" A + B",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("#define X \\\n"
" /* Macro comment \\\n"
" with a long \\\n"
" line */ \\\n"
" A + B",
format("#define X \\\n"
" /* Macro comment with a long\n"
" line */ \\\n"
" A + B",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("#define X \\\n"
" /* Macro comment \\\n"
" * with a long \\\n"
" * line */ \\\n"
" A + B",
format("#define X \\\n"
" /* Macro comment with a long line */ \\\n"
" A + B",
getLLVMStyleWithColumns(20)));
}
TEST_F(FormatTest, CommentsInStaticInitializers) {
EXPECT_EQ(
"static SomeType type = {aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
" aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
" /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaa, // comment\n"
" aaaaaaaaaaaaaaaaaaaa};",
format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa , /* comment */\n"
" aaaaaaaaaaaaaaaaaaaa /* comment */ ,\n"
" /* comment */ aaaaaaaaaaaaaaaaaaaa ,\n"
" aaaaaaaaaaaaaaaaaaaa , // comment\n"
" aaaaaaaaaaaaaaaaaaaa };"));
verifyFormat("static SomeType type = {aaaaaaaaaaa, // comment for aa...\n"
" bbbbbbbbbbb, ccccccccccc};");
verifyFormat("static SomeType type = {aaaaaaaaaaa,\n"
" // comment for bb....\n"
" bbbbbbbbbbb, ccccccccccc};");
verifyGoogleFormat(
"static SomeType type = {aaaaaaaaaaa, // comment for aa...\n"
" bbbbbbbbbbb, ccccccccccc};");
verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
" // comment for bb....\n"
" bbbbbbbbbbb, ccccccccccc};");
verifyFormat("S s = {{a, b, c}, // Group #1\n"
" {d, e, f}, // Group #2\n"
" {g, h, i}}; // Group #3");
verifyFormat("S s = {{// Group #1\n"
" a, b, c},\n"
" {// Group #2\n"
" d, e, f},\n"
" {// Group #3\n"
" g, h, i}};");
EXPECT_EQ("S s = {\n"
" // Some comment\n"
" a,\n"
"\n"
" // Comment after empty line\n"
" b}",
format("S s = {\n"
" // Some comment\n"
" a,\n"
" \n"
" // Comment after empty line\n"
" b\n"
"}"));
EXPECT_EQ("S s = {\n"
" /* Some comment */\n"
" a,\n"
"\n"
" /* Comment after empty line */\n"
" b}",
format("S s = {\n"
" /* Some comment */\n"
" a,\n"
" \n"
" /* Comment after empty line */\n"
" b\n"
"}"));
verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
" 0x00, 0x00, 0x00, 0x00}; // comment\n");
}
TEST_F(FormatTest, IgnoresIf0Contents) {
EXPECT_EQ("#if 0\n"
"}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
"#endif\n"
"void f() {}",
format("#if 0\n"
"}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
"#endif\n"
"void f( ) { }"));
EXPECT_EQ("#if false\n"
"void f( ) { }\n"
"#endif\n"
"void g() {}\n",
format("#if false\n"
"void f( ) { }\n"
"#endif\n"
"void g( ) { }\n"));
EXPECT_EQ("enum E {\n"
" One,\n"
" Two,\n"
"#if 0\n"
"Three,\n"
" Four,\n"
"#endif\n"
" Five\n"
"};",
format("enum E {\n"
" One,Two,\n"
"#if 0\n"
"Three,\n"
" Four,\n"
"#endif\n"
" Five};"));
EXPECT_EQ("enum F {\n"
" One,\n"
"#if 1\n"
" Two,\n"
"#if 0\n"
"Three,\n"
" Four,\n"
"#endif\n"
" Five\n"
"#endif\n"
"};",
format("enum F {\n"
"One,\n"
"#if 1\n"
"Two,\n"
"#if 0\n"
"Three,\n"
" Four,\n"
"#endif\n"
"Five\n"
"#endif\n"
"};"));
EXPECT_EQ("enum G {\n"
" One,\n"
"#if 0\n"
"Two,\n"
"#else\n"
" Three,\n"
"#endif\n"
" Four\n"
"};",
format("enum G {\n"
"One,\n"
"#if 0\n"
"Two,\n"
"#else\n"
"Three,\n"
"#endif\n"
"Four\n"
"};"));
EXPECT_EQ("enum H {\n"
" One,\n"
"#if 0\n"
"#ifdef Q\n"
"Two,\n"
"#else\n"
"Three,\n"
"#endif\n"
"#endif\n"
" Four\n"
"};",
format("enum H {\n"
"One,\n"
"#if 0\n"
"#ifdef Q\n"
"Two,\n"
"#else\n"
"Three,\n"
"#endif\n"
"#endif\n"
"Four\n"
"};"));
EXPECT_EQ("enum I {\n"
" One,\n"
"#if /* test */ 0 || 1\n"
"Two,\n"
"Three,\n"
"#endif\n"
" Four\n"
"};",
format("enum I {\n"
"One,\n"
"#if /* test */ 0 || 1\n"
"Two,\n"
"Three,\n"
"#endif\n"
"Four\n"
"};"));
EXPECT_EQ("enum J {\n"
" One,\n"
"#if 0\n"
"#if 0\n"
"Two,\n"
"#else\n"
"Three,\n"
"#endif\n"
"Four,\n"
"#endif\n"
" Five\n"
"};",
format("enum J {\n"
"One,\n"
"#if 0\n"
"#if 0\n"
"Two,\n"
"#else\n"
"Three,\n"
"#endif\n"
"Four,\n"
"#endif\n"
"Five\n"
"};"));
}
//===----------------------------------------------------------------------===//
// Tests for classes, namespaces, etc.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
verifyFormat("class A {};");
}
TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
verifyFormat("class A {\n"
"public:\n"
"public: // comment\n"
"protected:\n"
"private:\n"
" void f() {}\n"
"};");
verifyGoogleFormat("class A {\n"
" public:\n"
" protected:\n"
" private:\n"
" void f() {}\n"
"};");
verifyFormat("class A {\n"
"public slots:\n"
" void f1() {}\n"
"public Q_SLOTS:\n"
" void f2() {}\n"
"protected slots:\n"
" void f3() {}\n"
"protected Q_SLOTS:\n"
" void f4() {}\n"
"private slots:\n"
" void f5() {}\n"
"private Q_SLOTS:\n"
" void f6() {}\n"
"signals:\n"
" void g1();\n"
"Q_SIGNALS:\n"
" void g2();\n"
"};");
// Don't interpret 'signals' the wrong way.
verifyFormat("signals.set();");
verifyFormat("for (Signals signals : f()) {\n}");
verifyFormat("{\n"
" signals.set(); // This needs indentation.\n"
"}");
verifyFormat("void f() {\n"
"label:\n"
" signals.baz();\n"
"}");
}
TEST_F(FormatTest, SeparatesLogicalBlocks) {
EXPECT_EQ("class A {\n"
"public:\n"
" void f();\n"
"\n"
"private:\n"
" void g() {}\n"
" // test\n"
"protected:\n"
" int h;\n"
"};",
format("class A {\n"
"public:\n"
"void f();\n"
"private:\n"
"void g() {}\n"
"// test\n"
"protected:\n"
"int h;\n"
"};"));
EXPECT_EQ("class A {\n"
"protected:\n"
"public:\n"
" void f();\n"
"};",
format("class A {\n"
"protected:\n"
"\n"
"public:\n"
"\n"
" void f();\n"
"};"));
// Even ensure proper spacing inside macros.
EXPECT_EQ("#define B \\\n"
" class A { \\\n"
" protected: \\\n"
" public: \\\n"
" void f(); \\\n"
" };",
format("#define B \\\n"
" class A { \\\n"
" protected: \\\n"
" \\\n"
" public: \\\n"
" \\\n"
" void f(); \\\n"
" };",
getGoogleStyle()));
// But don't remove empty lines after macros ending in access specifiers.
EXPECT_EQ("#define A private:\n"
"\n"
"int i;",
format("#define A private:\n"
"\n"
"int i;"));
}
TEST_F(FormatTest, FormatsClasses) {
verifyFormat("class A : public B {};");
verifyFormat("class A : public ::B {};");
verifyFormat(
"class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
" public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
" : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
" public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
verifyFormat(
"class A : public B, public C, public D, public E, public F {};");
verifyFormat("class AAAAAAAAAAAA : public B,\n"
" public C,\n"
" public D,\n"
" public E,\n"
" public F,\n"
" public G {};");
verifyFormat("class\n"
" ReallyReallyLongClassName {\n"
" int i;\n"
"};",
getLLVMStyleWithColumns(32));
verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
" aaaaaaaaaaaaaaaa> {};");
verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
" : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaa> {};");
verifyFormat("template <class R, class C>\n"
"struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
" : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
verifyFormat("class ::A::B {};");
}
TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
verifyFormat("class A {\n} a, b;");
verifyFormat("struct A {\n} a, b;");
verifyFormat("union A {\n} a;");
}
TEST_F(FormatTest, FormatsEnum) {
verifyFormat("enum {\n"
" Zero,\n"
" One = 1,\n"
" Two = One + 1,\n"
" Three = (One + Two),\n"
" Four = (Zero && (One ^ Two)) | (One << Two),\n"
" Five = (One, Two, Three, Four, 5)\n"
"};");
verifyGoogleFormat("enum {\n"
" Zero,\n"
" One = 1,\n"
" Two = One + 1,\n"
" Three = (One + Two),\n"
" Four = (Zero && (One ^ Two)) | (One << Two),\n"
" Five = (One, Two, Three, Four, 5)\n"
"};");
verifyFormat("enum Enum {};");
verifyFormat("enum {};");
verifyFormat("enum X E {} d;");
verifyFormat("enum __attribute__((...)) E {} d;");
verifyFormat("enum __declspec__((...)) E {} d;");
verifyFormat("enum {\n"
" Bar = Foo<int, int>::value\n"
"};",
getLLVMStyleWithColumns(30));
verifyFormat("enum ShortEnum { A, B, C };");
verifyGoogleFormat("enum ShortEnum { A, B, C };");
EXPECT_EQ("enum KeepEmptyLines {\n"
" ONE,\n"
"\n"
" TWO,\n"
"\n"
" THREE\n"
"}",
format("enum KeepEmptyLines {\n"
" ONE,\n"
"\n"
" TWO,\n"
"\n"
"\n"
" THREE\n"
"}"));
verifyFormat("enum E { // comment\n"
" ONE,\n"
" TWO\n"
"};\n"
"int i;");
// Not enums.
verifyFormat("enum X f() {\n"
" a();\n"
" return 42;\n"
"}");
verifyFormat("enum X Type::f() {\n"
" a();\n"
" return 42;\n"
"}");
verifyFormat("enum ::X f() {\n"
" a();\n"
" return 42;\n"
"}");
verifyFormat("enum ns::X f() {\n"
" a();\n"
" return 42;\n"
"}");
}
TEST_F(FormatTest, FormatsEnumsWithErrors) {
verifyFormat("enum Type {\n"
" One = 0; // These semicolons should be commas.\n"
" Two = 1;\n"
"};");
verifyFormat("namespace n {\n"
"enum Type {\n"
" One,\n"
" Two, // missing };\n"
" int i;\n"
"}\n"
"void g() {}");
}
TEST_F(FormatTest, FormatsEnumStruct) {
verifyFormat("enum struct {\n"
" Zero,\n"
" One = 1,\n"
" Two = One + 1,\n"
" Three = (One + Two),\n"
" Four = (Zero && (One ^ Two)) | (One << Two),\n"
" Five = (One, Two, Three, Four, 5)\n"
"};");
verifyFormat("enum struct Enum {};");
verifyFormat("enum struct {};");
verifyFormat("enum struct X E {} d;");
verifyFormat("enum struct __attribute__((...)) E {} d;");
verifyFormat("enum struct __declspec__((...)) E {} d;");
verifyFormat("enum struct X f() {\n a();\n return 42;\n}");
}
TEST_F(FormatTest, FormatsEnumClass) {
verifyFormat("enum class {\n"
" Zero,\n"
" One = 1,\n"
" Two = One + 1,\n"
" Three = (One + Two),\n"
" Four = (Zero && (One ^ Two)) | (One << Two),\n"
" Five = (One, Two, Three, Four, 5)\n"
"};");
verifyFormat("enum class Enum {};");
verifyFormat("enum class {};");
verifyFormat("enum class X E {} d;");
verifyFormat("enum class __attribute__((...)) E {} d;");
verifyFormat("enum class __declspec__((...)) E {} d;");
verifyFormat("enum class X f() {\n a();\n return 42;\n}");
}
TEST_F(FormatTest, FormatsEnumTypes) {
verifyFormat("enum X : int {\n"
" A, // Force multiple lines.\n"
" B\n"
"};");
verifyFormat("enum X : int { A, B };");
verifyFormat("enum X : std::uint32_t { A, B };");
}
TEST_F(FormatTest, FormatsNSEnums) {
verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
" // Information about someDecentlyLongValue.\n"
" someDecentlyLongValue,\n"
" // Information about anotherDecentlyLongValue.\n"
" anotherDecentlyLongValue,\n"
" // Information about aThirdDecentlyLongValue.\n"
" aThirdDecentlyLongValue\n"
"};");
verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
" a = 1,\n"
" b = 2,\n"
" c = 3,\n"
"};");
verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
" a = 1,\n"
" b = 2,\n"
" c = 3,\n"
"};");
verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
" a = 1,\n"
" b = 2,\n"
" c = 3,\n"
"};");
}
TEST_F(FormatTest, FormatsBitfields) {
verifyFormat("struct Bitfields {\n"
" unsigned sClass : 8;\n"
" unsigned ValueKind : 2;\n"
"};");
verifyFormat("struct A {\n"
" int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
"};");
verifyFormat("struct MyStruct {\n"
" uchar data;\n"
" uchar : 8;\n"
" uchar : 8;\n"
" uchar other;\n"
"};");
}
TEST_F(FormatTest, FormatsNamespaces) {
verifyFormat("namespace some_namespace {\n"
"class A {};\n"
"void f() { f(); }\n"
"}");
verifyFormat("namespace {\n"
"class A {};\n"
"void f() { f(); }\n"
"}");
verifyFormat("inline namespace X {\n"
"class A {};\n"
"void f() { f(); }\n"
"}");
verifyFormat("using namespace some_namespace;\n"
"class A {};\n"
"void f() { f(); }");
// This code is more common than we thought; if we
// layout this correctly the semicolon will go into
// its own line, which is undesirable.
verifyFormat("namespace {};");
verifyFormat("namespace {\n"
"class A {};\n"
"};");
verifyFormat("namespace {\n"
"int SomeVariable = 0; // comment\n"
"} // namespace");
EXPECT_EQ("#ifndef HEADER_GUARD\n"
"#define HEADER_GUARD\n"
"namespace my_namespace {\n"
"int i;\n"
"} // my_namespace\n"
"#endif // HEADER_GUARD",
format("#ifndef HEADER_GUARD\n"
" #define HEADER_GUARD\n"
" namespace my_namespace {\n"
"int i;\n"
"} // my_namespace\n"
"#endif // HEADER_GUARD"));
EXPECT_EQ("namespace A::B {\n"
"class C {};\n"
"}",
format("namespace A::B {\n"
"class C {};\n"
"}"));
FormatStyle Style = getLLVMStyle();
Style.NamespaceIndentation = FormatStyle::NI_All;
EXPECT_EQ("namespace out {\n"
" int i;\n"
" namespace in {\n"
" int i;\n"
" } // namespace\n"
"} // namespace",
format("namespace out {\n"
"int i;\n"
"namespace in {\n"
"int i;\n"
"} // namespace\n"
"} // namespace",
Style));
Style.NamespaceIndentation = FormatStyle::NI_Inner;
EXPECT_EQ("namespace out {\n"
"int i;\n"
"namespace in {\n"
" int i;\n"
"} // namespace\n"
"} // namespace",
format("namespace out {\n"
"int i;\n"
"namespace in {\n"
"int i;\n"
"} // namespace\n"
"} // namespace",
Style));
}
TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
TEST_F(FormatTest, FormatsInlineASM) {
verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
verifyFormat("asm(\"nop\" ::: \"memory\");");
verifyFormat(
"asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
" \"cpuid\\n\\t\"\n"
" \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
" : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
" : \"a\"(value));");
EXPECT_EQ(
"void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
" __asm {\n"
" mov edx,[that] // vtable in edx\n"
" mov eax,methodIndex\n"
" call [edx][eax*4] // stdcall\n"
" }\n"
"}",
format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
" __asm {\n"
" mov edx,[that] // vtable in edx\n"
" mov eax,methodIndex\n"
" call [edx][eax*4] // stdcall\n"
" }\n"
"}"));
EXPECT_EQ("_asm {\n"
" xor eax, eax;\n"
" cpuid;\n"
"}",
format("_asm {\n"
" xor eax, eax;\n"
" cpuid;\n"
"}"));
verifyFormat("void function() {\n"
" // comment\n"
" asm(\"\");\n"
"}");
EXPECT_EQ("__asm {\n"
"}\n"
"int i;",
format("__asm {\n"
"}\n"
"int i;"));
}
TEST_F(FormatTest, FormatTryCatch) {
verifyFormat("try {\n"
" throw a * b;\n"
"} catch (int a) {\n"
" // Do nothing.\n"
"} catch (...) {\n"
" exit(42);\n"
"}");
// Function-level try statements.
verifyFormat("int f() try { return 4; } catch (...) {\n"
" return 5;\n"
"}");
verifyFormat("class A {\n"
" int a;\n"
" A() try : a(0) {\n"
" } catch (...) {\n"
" throw;\n"
" }\n"
"};\n");
// Incomplete try-catch blocks.
verifyIncompleteFormat("try {} catch (");
}
TEST_F(FormatTest, FormatSEHTryCatch) {
verifyFormat("__try {\n"
" int a = b * c;\n"
"} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
" // Do nothing.\n"
"}");
verifyFormat("__try {\n"
" int a = b * c;\n"
"} __finally {\n"
" // Do nothing.\n"
"}");
verifyFormat("DEBUG({\n"
" __try {\n"
" } __finally {\n"
" }\n"
"});\n");
}
TEST_F(FormatTest, IncompleteTryCatchBlocks) {
verifyFormat("try {\n"
" f();\n"
"} catch {\n"
" g();\n"
"}");
verifyFormat("try {\n"
" f();\n"
"} catch (A a) MACRO(x) {\n"
" g();\n"
"} catch (B b) MACRO(x) {\n"
" g();\n"
"}");
}
TEST_F(FormatTest, FormatTryCatchBraceStyles) {
FormatStyle Style = getLLVMStyle();
for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
FormatStyle::BS_WebKit}) {
Style.BreakBeforeBraces = BraceStyle;
verifyFormat("try {\n"
" // something\n"
"} catch (...) {\n"
" // something\n"
"}",
Style);
}
Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
verifyFormat("try {\n"
" // something\n"
"}\n"
"catch (...) {\n"
" // something\n"
"}",
Style);
verifyFormat("__try {\n"
" // something\n"
"}\n"
"__finally {\n"
" // something\n"
"}",
Style);
verifyFormat("@try {\n"
" // something\n"
"}\n"
"@finally {\n"
" // something\n"
"}",
Style);
Style.BreakBeforeBraces = FormatStyle::BS_Allman;
verifyFormat("try\n"
"{\n"
" // something\n"
"}\n"
"catch (...)\n"
"{\n"
" // something\n"
"}",
Style);
Style.BreakBeforeBraces = FormatStyle::BS_GNU;
verifyFormat("try\n"
" {\n"
" // something\n"
" }\n"
"catch (...)\n"
" {\n"
" // something\n"
" }",
Style);
Style.BreakBeforeBraces = FormatStyle::BS_Custom;
Style.BraceWrapping.BeforeCatch = true;
verifyFormat("try {\n"
" // something\n"
"}\n"
"catch (...) {\n"
" // something\n"
"}",
Style);
}
TEST_F(FormatTest, StaticInitializers) {
verifyFormat("static SomeClass SC = {1, 'a'};");
verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
" 100000000, "
"\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
// Here, everything other than the "}" would fit on a line.
verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
" 10000000000000000000000000};");
EXPECT_EQ("S s = {a,\n"
"\n"
" b};",
format("S s = {\n"
" a,\n"
"\n"
" b\n"
"};"));
// FIXME: This would fit into the column limit if we'd fit "{ {" on the first
// line. However, the formatting looks a bit off and this probably doesn't
// happen often in practice.
verifyFormat("static int Variable[1] = {\n"
" {1000000000000000000000000000000000000}};",
getLLVMStyleWithColumns(40));
}
TEST_F(FormatTest, DesignatedInitializers) {
verifyFormat("const struct A a = {.a = 1, .b = 2};");
verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
" .bbbbbbbbbb = 2,\n"
" .cccccccccc = 3,\n"
" .dddddddddd = 4,\n"
" .eeeeeeeeee = 5};");
verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
" .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
" .ccccccccccccccccccccccccccc = 3,\n"
" .ddddddddddddddddddddddddddd = 4,\n"
" .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
}
TEST_F(FormatTest, NestedStaticInitializers) {
verifyFormat("static A x = {{{}}};\n");
verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
" {init1, init2, init3, init4}}};",
getLLVMStyleWithColumns(50));
verifyFormat("somes Status::global_reps[3] = {\n"
" {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
" {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
" {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
getLLVMStyleWithColumns(60));
verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
" {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
" {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
" {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
" {rect.fRight - rect.fLeft, rect.fBottom - "
"rect.fTop}};");
verifyFormat(
"SomeArrayOfSomeType a = {\n"
" {{1, 2, 3},\n"
" {1, 2, 3},\n"
" {111111111111111111111111111111, 222222222222222222222222222222,\n"
" 333333333333333333333333333333},\n"
" {1, 2, 3},\n"
" {1, 2, 3}}};");
verifyFormat(
"SomeArrayOfSomeType a = {\n"
" {{1, 2, 3}},\n"
" {{1, 2, 3}},\n"
" {{111111111111111111111111111111, 222222222222222222222222222222,\n"
" 333333333333333333333333333333}},\n"
" {{1, 2, 3}},\n"
" {{1, 2, 3}}};");
verifyFormat("struct {\n"
" unsigned bit;\n"
" const char *const name;\n"
"} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
" {kOsWin, \"Windows\"},\n"
" {kOsLinux, \"Linux\"},\n"
" {kOsCrOS, \"Chrome OS\"}};");
verifyFormat("struct {\n"
" unsigned bit;\n"
" const char *const name;\n"
"} kBitsToOs[] = {\n"
" {kOsMac, \"Mac\"},\n"
" {kOsWin, \"Windows\"},\n"
" {kOsLinux, \"Linux\"},\n"
" {kOsCrOS, \"Chrome OS\"},\n"
"};");
}
TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
" \\\n"
" aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
}
TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
verifyFormat("virtual void write(ELFWriter *writerrr,\n"
" OwningPtr<FileOutputBuffer> &buffer) = 0;");
// Do break defaulted and deleted functions.
verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
" default;",
getLLVMStyleWithColumns(40));
verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
" delete;",
getLLVMStyleWithColumns(40));
}
TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
getLLVMStyleWithColumns(40));
verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
getLLVMStyleWithColumns(40));
EXPECT_EQ("#define Q \\\n"
" \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n"
" \"aaaaaaaa.cpp\"",
format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
getLLVMStyleWithColumns(40)));
}
TEST_F(FormatTest, UnderstandsLinePPDirective) {
EXPECT_EQ("# 123 \"A string literal\"",
format(" # 123 \"A string literal\""));
}
TEST_F(FormatTest, LayoutUnknownPPDirective) {
EXPECT_EQ("#;", format("#;"));
verifyFormat("#\n;\n;\n;");
}
TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
EXPECT_EQ("#line 42 \"test\"\n",
format("# \\\n line \\\n 42 \\\n \"test\"\n"));
EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n",
getLLVMStyleWithColumns(12)));
}
TEST_F(FormatTest, EndOfFileEndsPPDirective) {
EXPECT_EQ("#line 42 \"test\"",
format("# \\\n line \\\n 42 \\\n \"test\""));
EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B"));
}
TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
verifyFormat("#define A \\x20");
verifyFormat("#define A \\ x20");
EXPECT_EQ("#define A \\ x20", format("#define A \\ x20"));
verifyFormat("#define A ''");
verifyFormat("#define A ''qqq");
verifyFormat("#define A `qqq");
verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
EXPECT_EQ("const char *c = STRINGIFY(\n"
"\\na : b);",
format("const char * c = STRINGIFY(\n"
"\\na : b);"));
verifyFormat("a\r\\");
verifyFormat("a\v\\");
verifyFormat("a\f\\");
}
TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12));
verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12));
// FIXME: We never break before the macro name.
verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12));
verifyFormat("#define A A\n#define A A");
verifyFormat("#define A(X) A\n#define A A");
verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22));
}
TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
EXPECT_EQ("// somecomment\n"
"#include \"a.h\"\n"
"#define A( \\\n"
" A, B)\n"
"#include \"b.h\"\n"
"// somecomment\n",
format(" // somecomment\n"
" #include \"a.h\"\n"
"#define A(A,\\\n"
" B)\n"
" #include \"b.h\"\n"
" // somecomment\n",
getLLVMStyleWithColumns(13)));
}
TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
EXPECT_EQ("#define A \\\n"
" c; \\\n"
" e;\n"
"f;",
format("#define A c; e;\n"
"f;",
getLLVMStyleWithColumns(14)));
}
TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
TEST_F(FormatTest, MacroDefinitionInsideStatement) {
EXPECT_EQ("int x,\n"
"#define A\n"
" y;",
format("int x,\n#define A\ny;"));
}
TEST_F(FormatTest, HashInMacroDefinition) {
EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11));
verifyFormat("#define A \\\n"
" { \\\n"
" f(#c); \\\n"
" }",
getLLVMStyleWithColumns(11));
verifyFormat("#define A(X) \\\n"
" void function##X()",
getLLVMStyleWithColumns(22));
verifyFormat("#define A(a, b, c) \\\n"
" void a##b##c()",
getLLVMStyleWithColumns(22));
verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
}
TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
EXPECT_EQ("#define A (x)", format("#define A (x)"));
EXPECT_EQ("#define A(x)", format("#define A(x)"));
}
TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
EXPECT_EQ("#define A b;", format("#define A \\\n"
" \\\n"
" b;",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("#define A \\\n"
" \\\n"
" a; \\\n"
" b;",
format("#define A \\\n"
" \\\n"
" a; \\\n"
" b;",
getLLVMStyleWithColumns(11)));
EXPECT_EQ("#define A \\\n"
" a; \\\n"
" \\\n"
" b;",
format("#define A \\\n"
" a; \\\n"
" \\\n"
" b;",
getLLVMStyleWithColumns(11)));
}
TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
verifyIncompleteFormat("#define A :");
verifyFormat("#define SOMECASES \\\n"
" case 1: \\\n"
" case 2\n",
getLLVMStyleWithColumns(20));
verifyFormat("#define MACRO(a) \\\n"
" if (a) \\\n"
" f(); \\\n"
" else \\\n"
" g()",
getLLVMStyleWithColumns(18));
verifyFormat("#define A template <typename T>");
verifyIncompleteFormat("#define STR(x) #x\n"
"f(STR(this_is_a_string_literal{));");
verifyFormat("#pragma omp threadprivate( \\\n"
" y)), // expected-warning",
getLLVMStyleWithColumns(28));
verifyFormat("#d, = };");
verifyFormat("#if \"a");
verifyIncompleteFormat("({\n"
"#define b \\\n"
" } \\\n"
" a\n"
"a",
getLLVMStyleWithColumns(15));
verifyFormat("#define A \\\n"
" { \\\n"
" {\n"
"#define B \\\n"
" } \\\n"
" }",
getLLVMStyleWithColumns(15));
verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}");
}
TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
EXPECT_EQ("class A : public QObject {\n"
" Q_OBJECT\n"
"\n"
" A() {}\n"
"};",
format("class A : public QObject {\n"
" Q_OBJECT\n"
"\n"
" A() {\n}\n"
"} ;"));
EXPECT_EQ("MACRO\n"
"/*static*/ int i;",
format("MACRO\n"
" /*static*/ int i;"));
EXPECT_EQ("SOME_MACRO\n"
"namespace {\n"
"void f();\n"
"}",
format("SOME_MACRO\n"
" namespace {\n"
"void f( );\n"
"}"));
// Only if the identifier contains at least 5 characters.
EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
// Only if everything is upper case.
EXPECT_EQ("class A : public QObject {\n"
" Q_Object A() {}\n"
"};",
format("class A : public QObject {\n"
" Q_Object\n"
" A() {\n}\n"
"} ;"));
// Only if the next line can actually start an unwrapped line.
EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
format("SOME_WEIRD_LOG_MACRO\n"
"<< SomeThing;"));
verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
"(n, buffers))\n",
getChromiumStyle(FormatStyle::LK_Cpp));
}
TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
"INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
"INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
"class X {};\n"
"INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
"int *createScopDetectionPass() { return 0; }",
format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
" INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
" INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
" class X {};\n"
" INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
" int *createScopDetectionPass() { return 0; }"));
// FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
// braces, so that inner block is indented one level more.
EXPECT_EQ("int q() {\n"
" IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
" IPC_MESSAGE_HANDLER(xxx, qqq)\n"
" IPC_END_MESSAGE_MAP()\n"
"}",
format("int q() {\n"
" IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
" IPC_MESSAGE_HANDLER(xxx, qqq)\n"
" IPC_END_MESSAGE_MAP()\n"
"}"));
// Same inside macros.
EXPECT_EQ("#define LIST(L) \\\n"
" L(A) \\\n"
" L(B) \\\n"
" L(C)",
format("#define LIST(L) \\\n"
" L(A) \\\n"
" L(B) \\\n"
" L(C)",
getGoogleStyle()));
// These must not be recognized as macros.
EXPECT_EQ("int q() {\n"
" f(x);\n"
" f(x) {}\n"
" f(x)->g();\n"
" f(x)->*g();\n"
" f(x).g();\n"
" f(x) = x;\n"
" f(x) += x;\n"
" f(x) -= x;\n"
" f(x) *= x;\n"
" f(x) /= x;\n"
" f(x) %= x;\n"
" f(x) &= x;\n"
" f(x) |= x;\n"
" f(x) ^= x;\n"
" f(x) >>= x;\n"
" f(x) <<= x;\n"
" f(x)[y].z();\n"
" LOG(INFO) << x;\n"
" ifstream(x) >> x;\n"
"}\n",
format("int q() {\n"
" f(x)\n;\n"
" f(x)\n {}\n"
" f(x)\n->g();\n"
" f(x)\n->*g();\n"
" f(x)\n.g();\n"
" f(x)\n = x;\n"
" f(x)\n += x;\n"
" f(x)\n -= x;\n"
" f(x)\n *= x;\n"
" f(x)\n /= x;\n"
" f(x)\n %= x;\n"
" f(x)\n &= x;\n"
" f(x)\n |= x;\n"
" f(x)\n ^= x;\n"
" f(x)\n >>= x;\n"
" f(x)\n <<= x;\n"
" f(x)\n[y].z();\n"
" LOG(INFO)\n << x;\n"
" ifstream(x)\n >> x;\n"
"}\n"));
EXPECT_EQ("int q() {\n"
" F(x)\n"
" if (1) {\n"
" }\n"
" F(x)\n"
" while (1) {\n"
" }\n"
" F(x)\n"
" G(x);\n"
" F(x)\n"
" try {\n"
" Q();\n"
" } catch (...) {\n"
" }\n"
"}\n",
format("int q() {\n"
"F(x)\n"
"if (1) {}\n"
"F(x)\n"
"while (1) {}\n"
"F(x)\n"
"G(x);\n"
"F(x)\n"
"try { Q(); } catch (...) {}\n"
"}\n"));
EXPECT_EQ("class A {\n"
" A() : t(0) {}\n"
" A(int i) noexcept() : {}\n"
" A(X x)\n" // FIXME: function-level try blocks are broken.
" try : t(0) {\n"
" } catch (...) {\n"
" }\n"
"};",
format("class A {\n"
" A()\n : t(0) {}\n"
" A(int i)\n noexcept() : {}\n"
" A(X x)\n"
" try : t(0) {} catch (...) {}\n"
"};"));
EXPECT_EQ("class SomeClass {\n"
"public:\n"
" SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
"};",
format("class SomeClass {\n"
"public:\n"
" SomeClass()\n"
" EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
"};"));
EXPECT_EQ("class SomeClass {\n"
"public:\n"
" SomeClass()\n"
" EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
"};",
format("class SomeClass {\n"
"public:\n"
" SomeClass()\n"
" EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
"};",
getLLVMStyleWithColumns(40)));
verifyFormat("MACRO(>)");
}
TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
verifyFormat("#define A \\\n"
" f({ \\\n"
" g(); \\\n"
" });",
getLLVMStyleWithColumns(11));
}
TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
EXPECT_EQ("{\n {\n#define A\n }\n}", format("{{\n#define A\n}}"));
}
TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
verifyFormat("{\n { a #c; }\n}");
}
TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
EXPECT_EQ("#define A \\\n { \\\n {\nint i;",
format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
EXPECT_EQ("#define A \\\n } \\\n }\nint i;",
format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
}
TEST_F(FormatTest, EscapedNewlines) {
EXPECT_EQ(
"#define A \\\n int i; \\\n int j;",
format("#define A \\\nint i;\\\n int j;", getLLVMStyleWithColumns(11)));
EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
EXPECT_EQ("/* \\ \\ \\\n*/", format("\\\n/* \\ \\ \\\n*/"));
EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
}
TEST_F(FormatTest, DontCrashOnBlockComments) {
EXPECT_EQ(
"int xxxxxxxxx; /* "
"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n"
"zzzzzz\n"
"0*/",
format("int xxxxxxxxx; /* "
"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzz\n"
"0*/"));
}
TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
verifyFormat("#define A \\\n"
" int v( \\\n"
" a); \\\n"
" int i;",
getLLVMStyleWithColumns(11));
}
TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
EXPECT_EQ(
"#define ALooooooooooooooooooooooooooooooooooooooongMacro("
" \\\n"
" aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
"\n"
"AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
" aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro("
"\\\n"
"aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
" \n"
" AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
" aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
}
TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
EXPECT_EQ("int\n"
"#define A\n"
" a;",
format("int\n#define A\na;"));
verifyFormat("functionCallTo(\n"
" someOtherFunction(\n"
" withSomeParameters, whichInSequence,\n"
" areLongerThanALine(andAnotherCall,\n"
"#define A B\n"
" withMoreParamters,\n"
" whichStronglyInfluenceTheLayout),\n"
" andMoreParameters),\n"
" trailing);",
getLLVMStyleWithColumns(69));
verifyFormat("Foo::Foo()\n"
"#ifdef BAR\n"
" : baz(0)\n"
"#endif\n"
"{\n"
"}");
verifyFormat("void f() {\n"
" if (true)\n"
"#ifdef A\n"
" f(42);\n"
" x();\n"
"#else\n"
" g();\n"
" x();\n"
"#endif\n"
"}");
verifyFormat("void f(param1, param2,\n"
" param3,\n"
"#ifdef A\n"
" param4(param5,\n"
"#ifdef A1\n"
" param6,\n"
"#ifdef A2\n"
" param7),\n"
"#else\n"
" param8),\n"
" param9,\n"
"#endif\n"
" param10,\n"
"#endif\n"
" param11)\n"
"#else\n"
" param12)\n"
"#endif\n"
"{\n"
" x();\n"
"}",
getLLVMStyleWithColumns(28));
verifyFormat("#if 1\n"
"int i;");
verifyFormat("#if 1\n"
"#endif\n"
"#if 1\n"
"#else\n"
"#endif\n");
verifyFormat("DEBUG({\n"
" return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
"});\n"
"#if a\n"
"#else\n"
"#endif");
verifyIncompleteFormat("void f(\n"
"#if A\n"
" );\n"
"#else\n"
"#endif");
}
TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
verifyFormat("#endif\n"
"#if B");
}
TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
FormatStyle SingleLine = getLLVMStyle();
SingleLine.AllowShortIfStatementsOnASingleLine = true;
verifyFormat("#if 0\n"
"#elif 1\n"
"#endif\n"
"void foo() {\n"
" if (test) foo2();\n"
"}",
SingleLine);
}
TEST_F(FormatTest, LayoutBlockInsideParens) {
verifyFormat("functionCall({ int i; });");
verifyFormat("functionCall({\n"
" int i;\n"
" int j;\n"
"});");
verifyFormat("functionCall(\n"
" {\n"
" int i;\n"
" int j;\n"
" },\n"
" aaaa, bbbb, cccc);");
verifyFormat("functionA(functionB({\n"
" int i;\n"
" int j;\n"
" }),\n"
" aaaa, bbbb, cccc);");
verifyFormat("functionCall(\n"
" {\n"
" int i;\n"
" int j;\n"
" },\n"
" aaaa, bbbb, // comment\n"
" cccc);");
verifyFormat("functionA(functionB({\n"
" int i;\n"
" int j;\n"
" }),\n"
" aaaa, bbbb, // comment\n"
" cccc);");
verifyFormat("functionCall(aaaa, bbbb, { int i; });");
verifyFormat("functionCall(aaaa, bbbb, {\n"
" int i;\n"
" int j;\n"
"});");
verifyFormat(
"Aaa(\n" // FIXME: There shouldn't be a linebreak here.
" {\n"
" int i; // break\n"
" },\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
" ccccccccccccccccc));");
verifyFormat("DEBUG({\n"
" if (a)\n"
" f();\n"
"});");
}
TEST_F(FormatTest, LayoutBlockInsideStatement) {
EXPECT_EQ("SOME_MACRO { int i; }\n"
"int i;",
format(" SOME_MACRO {int i;} int i;"));
}
TEST_F(FormatTest, LayoutNestedBlocks) {
verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
" struct s {\n"
" int i;\n"
" };\n"
" s kBitsToOs[] = {{10}};\n"
" for (int i = 0; i < 10; ++i)\n"
" return;\n"
"}");
verifyFormat("call(parameter, {\n"
" something();\n"
" // Comment using all columns.\n"
" somethingelse();\n"
"});",
getLLVMStyleWithColumns(40));
verifyFormat("DEBUG( //\n"
" { f(); }, a);");
verifyFormat("DEBUG( //\n"
" {\n"
" f(); //\n"
" },\n"
" a);");
EXPECT_EQ("call(parameter, {\n"
" something();\n"
" // Comment too\n"
" // looooooooooong.\n"
" somethingElse();\n"
"});",
format("call(parameter, {\n"
" something();\n"
" // Comment too looooooooooong.\n"
" somethingElse();\n"
"});",
getLLVMStyleWithColumns(29)));
EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });"));
EXPECT_EQ("DEBUG({ // comment\n"
" int i;\n"
"});",
format("DEBUG({ // comment\n"
"int i;\n"
"});"));
EXPECT_EQ("DEBUG({\n"
" int i;\n"
"\n"
" // comment\n"
" int j;\n"
"});",
format("DEBUG({\n"
" int i;\n"
"\n"
" // comment\n"
" int j;\n"
"});"));
verifyFormat("DEBUG({\n"
" if (a)\n"
" return;\n"
"});");
verifyGoogleFormat("DEBUG({\n"
" if (a) return;\n"
"});");
FormatStyle Style = getGoogleStyle();
Style.ColumnLimit = 45;
verifyFormat("Debug(aaaaa,\n"
" {\n"
" if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
" },\n"
" a);",
Style);
verifyFormat("SomeFunction({MACRO({ return output; }), b});");
verifyNoCrash("^{v^{a}}");
}
TEST_F(FormatTest, FormatNestedBlocksInMacros) {
EXPECT_EQ("#define MACRO() \\\n"
" Debug(aaa, /* force line break */ \\\n"
" { \\\n"
" int i; \\\n"
" int j; \\\n"
" })",
format("#define MACRO() Debug(aaa, /* force line break */ \\\n"
" { int i; int j; })",
getGoogleStyle()));
EXPECT_EQ("#define A \\\n"
" [] { \\\n"
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
" }",
format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
getGoogleStyle()));
}
TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
EXPECT_EQ("{}", format("{}"));
verifyFormat("enum E {};");
verifyFormat("enum E {}");
}
TEST_F(FormatTest, FormatBeginBlockEndMacros) {
FormatStyle Style = getLLVMStyle();
Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
Style.MacroBlockEnd = "^[A-Z_]+_END$";
verifyFormat("FOO_BEGIN\n"
" FOO_ENTRY\n"
"FOO_END", Style);
verifyFormat("FOO_BEGIN\n"
" NESTED_FOO_BEGIN\n"
" NESTED_FOO_ENTRY\n"
" NESTED_FOO_END\n"
"FOO_END", Style);
verifyFormat("FOO_BEGIN(Foo, Bar)\n"
" int x;\n"
" x = 1;\n"
"FOO_END(Baz)", Style);
}
//===----------------------------------------------------------------------===//
// Line break tests.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, PreventConfusingIndents) {
verifyFormat(
"void f() {\n"
" SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
" parameter, parameter, parameter)),\n"
" SecondLongCall(parameter));\n"
"}");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [aaaaaaaaaaaaaaaaaaaaaaaa\n"
" [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [aaaaaaaaaaaaaaaaaaaaaaaa]];");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
" aaaaaaaaaaaaaaaaaaaaaaaa<\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
" aaaaaaaaaaaaaaaaaaaaaaaa>;");
verifyFormat("int a = bbbb && ccc && fffff(\n"
"#define A Just forcing a new line\n"
" ddd);");
}
TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
verifyFormat(
"bool aaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
" bbbbbbbb();");
verifyFormat(
"bool aaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
" bbbbbbbb();");
verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
" ccccccccc == ddddddddddd;");
verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
" ccccccccc == ddddddddddd;");
verifyFormat(
"bool aaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
" ccccccccc == ddddddddddd;");
verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
" aaaaaa) &&\n"
" bbbbbb && cccccc;");
verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
" aaaaaa) >>\n"
" bbbbbb;");
verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
" SourceMgr.getSpellingColumnNumber(\n"
" TheLine.Last->FormatTok.Tok.getLocation()) -\n"
" 1);");
verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
" cccccc) {\n}");
verifyFormat("b = a &&\n"
" // Comment\n"
" b.c && d;");
// If the LHS of a comparison is not a binary expression itself, the
// additional linebreak confuses many people.
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
"}");
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
"}");
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
"}");
// Even explicit parentheses stress the precedence enough to make the
// additional break unnecessary.
verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
"}");
// This cases is borderline, but with the indentation it is still readable.
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
"}",
getLLVMStyleWithColumns(75));
// If the LHS is a binary expression, we should still use the additional break
// as otherwise the formatting hides the operator precedence.
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
" 5) {\n"
"}");
FormatStyle OnePerLine = getLLVMStyle();
OnePerLine.BinPackParameters = false;
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
OnePerLine);
}
TEST_F(FormatTest, ExpressionIndentation) {
verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
" ccccccccccccccccccccccccccccccccccccccccc;");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
verifyFormat("if () {\n"
"} else if (aaaaa &&\n"
" bbbbb > // break\n"
" ccccc) {\n"
"}");
// Presence of a trailing comment used to change indentation of b.
verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
" b;\n"
"return aaaaaaaaaaaaaaaaaaa +\n"
" b; //",
getLLVMStyleWithColumns(30));
}
TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
// Not sure what the best system is here. Like this, the LHS can be found
// immediately above an operator (everything with the same or a higher
// indent). The RHS is aligned right of the operator and so compasses
// everything until something with the same indent as the operator is found.
// FIXME: Is this a good system?
FormatStyle Style = getLLVMStyle();
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
verifyFormat(
"bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" > ccccccccccccccccccccccccccccccccccccccccc;",
Style);
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
Style);
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
Style);
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
Style);
verifyFormat("if () {\n"
"} else if (aaaaa\n"
" && bbbbb // break\n"
" > ccccc) {\n"
"}",
Style);
verifyFormat("return (a)\n"
" // comment\n"
" + b;",
Style);
verifyFormat(
"int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" + cc;",
Style);
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
Style);
// Forced by comments.
verifyFormat(
"unsigned ContentSize =\n"
" sizeof(int16_t) // DWARF ARange version number\n"
" + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
" + sizeof(int8_t) // Pointer Size (in bytes)\n"
" + sizeof(int8_t); // Segment Size (in bytes)");
verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
" == boost::fusion::at_c<1>(iiii).second;",
Style);
Style.ColumnLimit = 60;
verifyFormat("zzzzzzzzzz\n"
" = bbbbbbbbbbbbbbbbb\n"
" >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
}
TEST_F(FormatTest, NoOperandAlignment) {
FormatStyle Style = getLLVMStyle();
Style.AlignOperands = false;
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" > ccccccccccccccccccccccccccccccccccccccccc;",
Style);
verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" + cc;",
Style);
verifyFormat("int a = aa\n"
" + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
" * cccccccccccccccccccccccccccccccccccc;",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
verifyFormat("return (a > b\n"
" // comment1\n"
" // comment2\n"
" || c);",
Style);
}
TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
FormatStyle Style = getLLVMStyle();
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
Style);
}
TEST_F(FormatTest, ConstructorInitializers) {
verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
getLLVMStyleWithColumns(45));
verifyFormat("Constructor()\n"
" : Inttializer(FitsOnTheLine) {}",
getLLVMStyleWithColumns(44));
verifyFormat("Constructor()\n"
" : Inttializer(FitsOnTheLine) {}",
getLLVMStyleWithColumns(43));
verifyFormat("template <typename T>\n"
"Constructor() : Initializer(FitsOnTheLine) {}",
getLLVMStyleWithColumns(45));
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" : aaaaaaaaaa(aaaaaa) {}");
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaa() {}");
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
verifyFormat("Constructor(int Parameter = 0)\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
"}",
getLLVMStyleWithColumns(60));
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
// Here a line could be saved by splitting the second initializer onto two
// lines, but that is not desirable.
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaa(aaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
FormatStyle OnePerLine = getLLVMStyle();
OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
verifyFormat("SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
OnePerLine);
verifyFormat("SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
OnePerLine);
verifyFormat("MyClass::MyClass(int var)\n"
" : some_var_(var), // 4 space indent\n"
" some_other_var_(var + 1) { // lined up\n"
"}",
OnePerLine);
verifyFormat("Constructor()\n"
" : aaaaa(aaaaaa),\n"
" aaaaa(aaaaaa),\n"
" aaaaa(aaaaaa),\n"
" aaaaa(aaaaaa),\n"
" aaaaa(aaaaaa) {}",
OnePerLine);
verifyFormat("Constructor()\n"
" : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaa) {}",
OnePerLine);
OnePerLine.BinPackParameters = false;
verifyFormat(
"Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaa().aaa(),\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
OnePerLine);
OnePerLine.ColumnLimit = 60;
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaa(a),\n"
" bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
OnePerLine);
EXPECT_EQ("Constructor()\n"
" : // Comment forcing unwanted break.\n"
" aaaa(aaaa) {}",
format("Constructor() :\n"
" // Comment forcing unwanted break.\n"
" aaaa(aaaa) {}"));
}
TEST_F(FormatTest, MemoizationTests) {
// This breaks if the memoization lookup does not take \c Indent and
// \c LastSpace into account.
verifyFormat(
"extern CFRunLoopTimerRef\n"
"CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
" CFTimeInterval interval, CFOptionFlags flags,\n"
" CFIndex order, CFRunLoopTimerCallBack callout,\n"
" CFRunLoopTimerContext *context) {}");
// Deep nesting somewhat works around our memoization.
verifyFormat(
"aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
" aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
" aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
" aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
" aaaaa())))))))))))))))))))))))))))))))))))))));",
getLLVMStyleWithColumns(65));
verifyFormat(
"aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa(\n"
" aaaaa,\n"
" aaaaa))))))))))));",
getLLVMStyleWithColumns(65));
verifyFormat(
"a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a),\n"
" a)",
getLLVMStyleWithColumns(65));
// This test takes VERY long when memoization is broken.
FormatStyle OnePerLine = getLLVMStyle();
OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
OnePerLine.BinPackParameters = false;
std::string input = "Constructor()\n"
" : aaaa(a,\n";
for (unsigned i = 0, e = 80; i != e; ++i) {
input += " a,\n";
}
input += " a) {}";
verifyFormat(input, OnePerLine);
}
TEST_F(FormatTest, BreaksAsHighAsPossible) {
verifyFormat(
"void f() {\n"
" if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
" (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
" f();\n"
"}");
verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
" Intervals[i - 1].getRange().getLast()) {\n}");
}
TEST_F(FormatTest, BreaksFunctionDeclarations) {
// Principially, we break function declarations in a certain order:
// 1) break amongst arguments.
verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
" Cccccccccccccc cccccccccccccc);");
verifyFormat("template <class TemplateIt>\n"
"SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
" TemplateIt *stop) {}");
// 2) break after return type.
verifyFormat(
"Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
getGoogleStyle());
// 3) break after (.
verifyFormat(
"Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
" Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
getGoogleStyle());
// 4) break before after nested name specifiers.
verifyFormat(
"Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"SomeClasssssssssssssssssssssssssssssssssssssss::\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
getGoogleStyle());
// However, there are exceptions, if a sufficient amount of lines can be
// saved.
// FIXME: The precise cut-offs wrt. the number of saved lines might need some
// more adjusting.
verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc);");
verifyFormat(
"Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
getGoogleStyle());
verifyFormat(
"Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc);");
verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
" Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
// Break after multi-line parameters.
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" bbbb bbbb);");
verifyFormat("void SomeLoooooooooooongFunction(\n"
" std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" int bbbbbbbbbbbbb);");
// Treat overloaded operators like other functions.
verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
"operator>(const SomeLoooooooooooooooooooooooooogType &other);");
verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
"operator>>(const SomeLooooooooooooooooooooooooogType &other);");
verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
"operator<<(const SomeLooooooooooooooooooooooooogType &other);");
verifyGoogleFormat(
"SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
" const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
verifyGoogleFormat(
"SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
" const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
"aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
verifyGoogleFormat(
"typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
"aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
verifyGoogleFormat(
"template <typename T>\n"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
FormatStyle Style = getLLVMStyle();
Style.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
Style);
verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
Style);
}
TEST_F(FormatTest, TrailingReturnType) {
verifyFormat("auto foo() -> int;\n");
verifyFormat("struct S {\n"
" auto bar() const -> int;\n"
"};");
verifyFormat("template <size_t Order, typename T>\n"
"auto load_img(const std::string &filename)\n"
" -> alias::tensor<Order, T, mem::tag::cpu> {}");
verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
" -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
verifyFormat("template <typename T>\n"
"auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
" -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
// Not trailing return types.
verifyFormat("void f() { auto a = b->c(); }");
}
TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
// Avoid breaking before trailing 'const' or other trailing annotations, if
// they are not function-like.
FormatStyle Style = getGoogleStyle();
Style.ColumnLimit = 47;
verifyFormat("void someLongFunction(\n"
" int someLoooooooooooooongParameter) const {\n}",
getLLVMStyleWithColumns(47));
verifyFormat("LoooooongReturnType\n"
"someLoooooooongFunction() const {}",
getLLVMStyleWithColumns(47));
verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
" const {}",
Style);
verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
" aaaaaaaaaaa aaaaa) const override;");
verifyGoogleFormat(
"virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" const override;");
// Even if the first parameter has to be wrapped.
verifyFormat("void someLongFunction(\n"
" int someLongParameter) const {}",
getLLVMStyleWithColumns(46));
verifyFormat("void someLongFunction(\n"
" int someLongParameter) const {}",
Style);
verifyFormat("void someLongFunction(\n"
" int someLongParameter) override {}",
Style);
verifyFormat("void someLongFunction(\n"
" int someLongParameter) OVERRIDE {}",
Style);
verifyFormat("void someLongFunction(\n"
" int someLongParameter) final {}",
Style);
verifyFormat("void someLongFunction(\n"
" int someLongParameter) FINAL {}",
Style);
verifyFormat("void someLongFunction(\n"
" int parameter) const override {}",
Style);
Style.BreakBeforeBraces = FormatStyle::BS_Allman;
verifyFormat("void someLongFunction(\n"
" int someLongParameter) const\n"
"{\n"
"}",
Style);
// Unless these are unknown annotations.
verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
" aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" LONG_AND_UGLY_ANNOTATION;");
// Breaking before function-like trailing annotations is fine to keep them
// close to their arguments.
verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
" LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
" LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
" AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
verifyFormat(
"void aaaaaaaaaaaaaaaaaa()\n"
" __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa));");
verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" __attribute__((unused));");
verifyGoogleFormat(
"bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" GUARDED_BY(aaaaaaaaaaaa);");
verifyGoogleFormat(
"bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" GUARDED_BY(aaaaaaaaaaaa);");
verifyGoogleFormat(
"bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
" aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyGoogleFormat(
"bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa;");
}
TEST_F(FormatTest, FunctionAnnotations) {
verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
"int OldFunction(const string ¶meter) {}");
verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
"string OldFunction(const string ¶meter) {}");
verifyFormat("template <typename T>\n"
"DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
"string OldFunction(const string ¶meter) {}");
// Not function annotations.
verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
" ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
verifyFormat("MACRO(abc).function() // wrap\n"
" << abc;");
verifyFormat("MACRO(abc)->function() // wrap\n"
" << abc;");
verifyFormat("MACRO(abc)::function() // wrap\n"
" << abc;");
}
TEST_F(FormatTest, BreaksDesireably) {
verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
" aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
" aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
"}");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
verifyFormat(
"aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
" aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"void f() {\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
"}");
verifyFormat(
"aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
verifyFormat(
"aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
// Indent consistently independent of call expression and unary operator.
verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
" dddddddddddddddddddddddddddddd));");
verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
" dddddddddddddddddddddddddddddd));");
verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
" dddddddddddddddddddddddddddddd));");
// This test case breaks on an incorrect memoization, i.e. an optimization not
// taking into account the StopAt value.
verifyFormat(
"return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
" (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("{\n {\n {\n"
" Annotation.SpaceRequiredBefore =\n"
" Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
" Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
" }\n }\n}");
// Break on an outer level if there was a break on an inner level.
EXPECT_EQ("f(g(h(a, // comment\n"
" b, c),\n"
" d, e),\n"
" x, y);",
format("f(g(h(a, // comment\n"
" b, c), d, e), x, y);"));
// Prefer breaking similar line breaks.
verifyFormat(
"const int kTrackingOptions = NSTrackingMouseMoved |\n"
" NSTrackingMouseEnteredAndExited |\n"
" NSTrackingActiveAlways;");
}
TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
FormatStyle NoBinPacking = getGoogleStyle();
NoBinPacking.BinPackParameters = false;
NoBinPacking.BinPackArguments = true;
verifyFormat("void f() {\n"
" f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
"}",
NoBinPacking);
verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
" int aaaaaaaaaaaaaaaaaaaa,\n"
" int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
NoBinPacking);
NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" vector<int> bbbbbbbbbbbbbbb);",
NoBinPacking);
// FIXME: This behavior difference is probably not wanted. However, currently
// we cannot distinguish BreakBeforeParameter being set because of the wrapped
// template arguments from BreakBeforeParameter being set because of the
// one-per-line formatting.
verifyFormat(
"void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaa> aaaaaaaaaa);",
NoBinPacking);
verifyFormat(
"void fffffffffff(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
" aaaaaaaaaa);");
}
TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
FormatStyle NoBinPacking = getGoogleStyle();
NoBinPacking.BinPackParameters = false;
NoBinPacking.BinPackArguments = false;
verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
NoBinPacking);
verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
NoBinPacking);
verifyFormat(
"aaaaaaaa(aaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
" aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
NoBinPacking);
verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaaaaa();",
NoBinPacking);
verifyFormat("void f() {\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
"}",
NoBinPacking);
verifyFormat(
"aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaa,\n"
" aaaaaaaaaaaa);",
NoBinPacking);
verifyFormat(
"somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
" ddddddddddddddddddddddddddddd),\n"
" test);",
NoBinPacking);
verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaa>\n"
" aaaaaaaaaaaaaaaaaa;",
NoBinPacking);
verifyFormat("a(\"a\"\n"
" \"a\",\n"
" a);");
NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
" aaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
NoBinPacking);
verifyFormat(
"void f() {\n"
" aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaa();\n"
"}",
NoBinPacking);
verifyFormat(
"template <class SomeType, class SomeOtherType>\n"
"SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
NoBinPacking);
}
TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
FormatStyle Style = getLLVMStyleWithColumns(15);
Style.ExperimentalAutoDetectBinPacking = true;
EXPECT_EQ("aaa(aaaa,\n"
" aaaa,\n"
" aaaa);\n"
"aaa(aaaa,\n"
" aaaa,\n"
" aaaa);",
format("aaa(aaaa,\n" // one-per-line
" aaaa,\n"
" aaaa );\n"
"aaa(aaaa, aaaa, aaaa);", // inconclusive
Style));
EXPECT_EQ("aaa(aaaa, aaaa,\n"
" aaaa);\n"
"aaa(aaaa, aaaa,\n"
" aaaa);",
format("aaa(aaaa, aaaa,\n" // bin-packed
" aaaa );\n"
"aaa(aaaa, aaaa, aaaa);", // inconclusive
Style));
}
TEST_F(FormatTest, FormatsBuilderPattern) {
verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
" .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
" .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
" .StartsWith(\".init\", ORDER_INIT)\n"
" .StartsWith(\".fini\", ORDER_FINI)\n"
" .StartsWith(\".hash\", ORDER_HASH)\n"
" .Default(ORDER_TEXT);\n");
verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
" aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
verifyFormat(
"aaaaaaa->aaaaaaa\n"
" ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" ->aaaaaaaa(aaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaa->aaaaaaa\n"
" ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" ->aaaaaaaa(aaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
" aaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
" aaaaaa->aaaaaaaaaaaa()\n"
" ->aaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" ->aaaaaaaaaaaaaaaaa();");
verifyGoogleFormat(
"void f() {\n"
" someo->Add((new util::filetools::Handler(dir))\n"
" ->OnEvent1(NewPermanentCallback(\n"
" this, &HandlerHolderClass::EventHandlerCBA))\n"
" ->OnEvent2(NewPermanentCallback(\n"
" this, &HandlerHolderClass::EventHandlerCBB))\n"
" ->OnEvent3(NewPermanentCallback(\n"
" this, &HandlerHolderClass::EventHandlerCBC))\n"
" ->OnEvent5(NewPermanentCallback(\n"
" this, &HandlerHolderClass::EventHandlerCBD))\n"
" ->OnEvent6(NewPermanentCallback(\n"
" this, &HandlerHolderClass::EventHandlerCBE)));\n"
"}");
verifyFormat(
"aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
verifyFormat("aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa();");
verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa();");
verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaa();");
verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
" ->aaaaaaaaaaaaaae(0)\n"
" ->aaaaaaaaaaaaaaa();");
// Don't linewrap after very short segments.
verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("aaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" .has<bbbbbbbbbbbbbbbbbbbbb>();");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
// Prefer not to break after empty parentheses.
verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
" First->LastNewlineOffset);");
// Prefer not to create "hanging" indents.
verifyFormat(
"return !soooooooooooooome_map\n"
" .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .second;");
verifyFormat(
"return aaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
" .aaaa(aaaaaaaaaaaaaa);");
// No hanging indent here.
verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
" .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
getLLVMStyleWithColumns(60));
verifyFormat("aaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
" .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
getLLVMStyleWithColumns(59));
verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
}
TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat(
"if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat(
"if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
" ccccccccccccccccccccccccc) {\n}");
verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
" bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
" cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
" dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
" bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
" cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
" dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
" aaaaaaaaaaaaaaa != aa) {\n}");
verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
" aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
" aaaaaaaaaaaaaaa != aa) {\n}");
}
TEST_F(FormatTest, BreaksAfterAssignments) {
verifyFormat(
"unsigned Cost =\n"
" TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
" SI->getPointerAddressSpaceee());\n");
verifyFormat(
"CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
" Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("unsigned OriginalStartColumn =\n"
" SourceMgr.getSpellingColumnNumber(\n"
" Current.FormatTok.getStartOfNonWhitespace()) -\n"
" 1;");
}
TEST_F(FormatTest, AlignsAfterAssignments) {
verifyFormat(
"int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaa;");
}
TEST_F(FormatTest, AlignsAfterReturn) {
verifyFormat(
"return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
" aaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat(
"return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
" aaaaaaaaaaaaaaaaaaaaaa());");
verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("return\n"
" // true if code is one of a or b.\n"
" code == a || code == b;");
}
TEST_F(FormatTest, AlignsAfterOpenBracket) {
verifyFormat(
"void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
" aaaaaaaaa aaaaaaa) {}");
verifyFormat(
"SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
" aaaaaaaaaaa aaaaaaaaa);");
verifyFormat(
"SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaa));");
FormatStyle Style = getLLVMStyle();
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
Style);
verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
" aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
Style);
verifyFormat("SomeLongVariableName->someFunction(\n"
" foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
Style);
verifyFormat(
"void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
" aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
Style);
verifyFormat(
"SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
" aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat(
"SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
Style);
verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
" ccccccc(aaaaaaaaaaaaaaaaa, //\n"
" b));",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Style.BinPackArguments = false;
Style.BinPackParameters = false;
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaa aaaaaaaa,\n"
" aaaaaaaaa aaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
Style);
verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
" aaaaaaaaaaa aaaaaaaaa,\n"
" aaaaaaaaaaa aaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
" aaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
" aaaaaaaaaaaaaaaa);",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
" aaaaaaaaaaaaaaaa);",
Style);
}
TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
FormatStyle Style = getLLVMStyleWithColumns(40);
verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
" bbbbbbbbbbbbbbbbbbbbbb);",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Style.AlignOperands = false;
verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
" bbbbbbbbbbbbbbbbbbbbbb);",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Style.AlignOperands = true;
verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
" bbbbbbbbbbbbbbbbbbbbbb);",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Style.AlignOperands = false;
verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
" bbbbbbbbbbbbbbbbbbbbbb);",
Style);
}
TEST_F(FormatTest, BreaksConditionalExpressions) {
verifyFormat(
"aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
" : aaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa);");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaa;");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaa;");
verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
" aaaaaaaaa\n"
" ? b\n"
" : c);");
verifyFormat("return aaaa == bbbb\n"
" // comment\n"
" ? aaaa\n"
" : bbbb;");
verifyFormat("unsigned Indent =\n"
" format(TheLine.First,\n"
" IndentForLevel[TheLine.Level] >= 0\n"
" ? IndentForLevel[TheLine.Level]\n"
" : TheLine * 2,\n"
" TheLine.InPPDirective, PreviousEndOfLineColumn);",
getLLVMStyleWithColumns(60));
verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
" ? aaaaaaaaaaaaaaa\n"
" : bbbbbbbbbbbbbbb //\n"
" ? ccccccccccccccc\n"
" : ddddddddddddddd;");
verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
" ? aaaaaaaaaaaaaaa\n"
" : (bbbbbbbbbbbbbbb //\n"
" ? ccccccccccccccc\n"
" : ddddddddddddddd);");
verifyFormat(
"int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaa +\n"
" aaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaa;");
verifyFormat(
"aaaaaa = aaaaaaaaaaaa\n"
" ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackArguments = false;
verifyFormat(
"void f() {\n"
" g(aaa,\n"
" aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ? aaaaaaaaaaaaaaa\n"
" : aaaaaaaaaaaaaaa);\n"
"}",
NoBinPacking);
verifyFormat(
"void f() {\n"
" g(aaa,\n"
" aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" ?: aaaaaaaaaaaaaaa);\n"
"}",
NoBinPacking);
verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
" // comment.\n"
" ccccccccccccccccccccccccccccccccccccccc\n"
" ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
// Assignments in conditional expressions. Apparently not uncommon :-(.
verifyFormat("return a != b\n"
" // comment\n"
" ? a = b\n"
" : a = b;");
verifyFormat("return a != b\n"
" // comment\n"
" ? a = a != b\n"
" // comment\n"
" ? a = b\n"
" : a\n"
" : a;\n");
verifyFormat("return a != b\n"
" // comment\n"
" ? a\n"
" : a = a != b\n"
" // comment\n"
" ? a = b\n"
" : a;");
}
TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
FormatStyle Style = getLLVMStyle();
Style.BreakBeforeTernaryOperators = false;
Style.ColumnLimit = 70;
verifyFormat(
"aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat(
"aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
" aaaaaaaaaaaaa);",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa);",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaa);",
Style);
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
Style);
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
Style);
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaaaaaaaaaaaa :\n"
" aaaaaaaaaaaaaaa;",
Style);
verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
" aaaaaaaaa ?\n"
" b :\n"
" c);",
Style);
verifyFormat("unsigned Indent =\n"
" format(TheLine.First,\n"
" IndentForLevel[TheLine.Level] >= 0 ?\n"
" IndentForLevel[TheLine.Level] :\n"
" TheLine * 2,\n"
" TheLine.InPPDirective, PreviousEndOfLineColumn);",
Style);
verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
" aaaaaaaaaaaaaaa :\n"
" bbbbbbbbbbbbbbb ? //\n"
" ccccccccccccccc :\n"
" ddddddddddddddd;",
Style);
verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
" aaaaaaaaaaaaaaa :\n"
" (bbbbbbbbbbbbbbb ? //\n"
" ccccccccccccccc :\n"
" ddddddddddddddd);",
Style);
verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
" ccccccccccccccccccccccccccc;",
Style);
verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
" aaaaa :\n"
" bbbbbbbbbbbbbbb + cccccccccccccccc;",
Style);
}
TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
" aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
verifyFormat("bool a = true, b = false;");
verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
verifyFormat(
"bool aaaaaaaaaaaaaaaaaaaaa =\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
" d = e && f;");
verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
" c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
" *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
" ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
FormatStyle Style = getGoogleStyle();
Style.PointerAlignment = FormatStyle::PAS_Left;
Style.DerivePointerAlignment = false;
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
" *b = bbbbbbbbbbbbbbbbbbb;",
Style);
verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
" *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
Style);
verifyFormat("vector<int*> a, b;", Style);
verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
}
TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
verifyFormat("arr[foo ? bar : baz];");
verifyFormat("f()[foo ? bar : baz];");
verifyFormat("(a + b)[foo ? bar : baz];");
verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
}
TEST_F(FormatTest, AlignsStringLiterals) {
verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
" \"short literal\");");
verifyFormat(
"looooooooooooooooooooooooongFunction(\n"
" \"short literal\"\n"
" \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
verifyFormat("someFunction(\"Always break between multi-line\"\n"
" \" string literals\",\n"
" and, other, parameters);");
EXPECT_EQ("fun + \"1243\" /* comment */\n"
" \"5678\";",
format("fun + \"1243\" /* comment */\n"
" \"5678\";",
getLLVMStyleWithColumns(28)));
EXPECT_EQ(
"aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
" \"aaaaaaaaaaaaaaaaaaaaa\"\n"
" \"aaaaaaaaaaaaaaaa\";",
format("aaaaaa ="
"\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaa\" "
"\"aaaaaaaaaaaaaaaa\";"));
verifyFormat("a = a + \"a\"\n"
" \"a\"\n"
" \"a\";");
verifyFormat("f(\"a\", \"b\"\n"
" \"c\");");
verifyFormat(
"#define LL_FORMAT \"ll\"\n"
"printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
" \"d, ddddddddd: %\" LL_FORMAT \"d\");");
verifyFormat("#define A(X) \\\n"
" \"aaaaa\" #X \"bbbbbb\" \\\n"
" \"ccccc\"",
getLLVMStyleWithColumns(23));
verifyFormat("#define A \"def\"\n"
"f(\"abc\" A \"ghi\"\n"
" \"jkl\");");
verifyFormat("f(L\"a\"\n"
" L\"b\");");
verifyFormat("#define A(X) \\\n"
" L\"aaaaa\" #X L\"bbbbbb\" \\\n"
" L\"ccccc\"",
getLLVMStyleWithColumns(25));
verifyFormat("f(@\"a\"\n"
" @\"b\");");
verifyFormat("NSString s = @\"a\"\n"
" @\"b\"\n"
" @\"c\";");
verifyFormat("NSString s = @\"a\"\n"
" \"b\"\n"
" \"c\";");
}
TEST_F(FormatTest, ReturnTypeBreakingStyle) {
FormatStyle Style = getLLVMStyle();
// No declarations or definitions should be moved to own line.
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
verifyFormat("class A {\n"
" int f() { return 1; }\n"
" int g();\n"
"};\n"
"int f() { return 1; }\n"
"int g();\n",
Style);
// All declarations and definitions should have the return type moved to its
// own
// line.
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
verifyFormat("class E {\n"
" int\n"
" f() {\n"
" return 1;\n"
" }\n"
" int\n"
" g();\n"
"};\n"
"int\n"
"f() {\n"
" return 1;\n"
"}\n"
"int\n"
"g();\n",
Style);
// Top-level definitions, and no kinds of declarations should have the
// return type moved to its own line.
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
verifyFormat("class B {\n"
" int f() { return 1; }\n"
" int g();\n"
"};\n"
"int\n"
"f() {\n"
" return 1;\n"
"}\n"
"int g();\n",
Style);
// Top-level definitions and declarations should have the return type moved
// to its own line.
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
verifyFormat("class C {\n"
" int f() { return 1; }\n"
" int g();\n"
"};\n"
"int\n"
"f() {\n"
" return 1;\n"
"}\n"
"int\n"
"g();\n",
Style);
// All definitions should have the return type moved to its own line, but no
// kinds of declarations.
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
verifyFormat("class D {\n"
" int\n"
" f() {\n"
" return 1;\n"
" }\n"
" int g();\n"
"};\n"
"int\n"
"f() {\n"
" return 1;\n"
"}\n"
"int g();\n",
Style);
verifyFormat("const char *\n"
"f(void) {\n" // Break here.
" return \"\";\n"
"}\n"
"const char *bar(void);\n", // No break here.
Style);
verifyFormat("template <class T>\n"
"T *\n"
"f(T &c) {\n" // Break here.
" return NULL;\n"
"}\n"
"template <class T> T *f(T &c);\n", // No break here.
Style);
verifyFormat("class C {\n"
" int\n"
" operator+() {\n"
" return 1;\n"
" }\n"
" int\n"
" operator()() {\n"
" return 1;\n"
" }\n"
"};\n",
Style);
verifyFormat("void\n"
"A::operator()() {}\n"
"void\n"
"A::operator>>() {}\n"
"void\n"
"A::operator+() {}\n",
Style);
verifyFormat("void *operator new(std::size_t s);", // No break here.
Style);
verifyFormat("void *\n"
"operator new(std::size_t s) {}",
Style);
verifyFormat("void *\n"
"operator delete[](void *ptr) {}",
Style);
Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
verifyFormat("const char *\n"
"f(void)\n" // Break here.
"{\n"
" return \"\";\n"
"}\n"
"const char *bar(void);\n", // No break here.
Style);
verifyFormat("template <class T>\n"
"T *\n" // Problem here: no line break
"f(T &c)\n" // Break here.
"{\n"
" return NULL;\n"
"}\n"
"template <class T> T *f(T &c);\n", // No break here.
Style);
}
TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
FormatStyle NoBreak = getLLVMStyle();
NoBreak.AlwaysBreakBeforeMultilineStrings = false;
FormatStyle Break = getLLVMStyle();
Break.AlwaysBreakBeforeMultilineStrings = true;
verifyFormat("aaaa = \"bbbb\"\n"
" \"cccc\";",
NoBreak);
verifyFormat("aaaa =\n"
" \"bbbb\"\n"
" \"cccc\";",
Break);
verifyFormat("aaaa(\"bbbb\"\n"
" \"cccc\");",
NoBreak);
verifyFormat("aaaa(\n"
" \"bbbb\"\n"
" \"cccc\");",
Break);
verifyFormat("aaaa(qqq, \"bbbb\"\n"
" \"cccc\");",
NoBreak);
verifyFormat("aaaa(qqq,\n"
" \"bbbb\"\n"
" \"cccc\");",
Break);
verifyFormat("aaaa(qqq,\n"
" L\"bbbb\"\n"
" L\"cccc\");",
Break);
verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
" \"bbbb\"));",
Break);
verifyFormat("string s = someFunction(\n"
" \"abc\"\n"
" \"abc\");",
Break);
// As we break before unary operators, breaking right after them is bad.
verifyFormat("string foo = abc ? \"x\"\n"
" \"blah blah blah blah blah blah\"\n"
" : \"y\";",
Break);
// Don't break if there is no column gain.
verifyFormat("f(\"aaaa\"\n"
" \"bbbb\");",
Break);
// Treat literals with escaped newlines like multi-line string literals.
EXPECT_EQ("x = \"a\\\n"
"b\\\n"
"c\";",
format("x = \"a\\\n"
"b\\\n"
"c\";",
NoBreak));
EXPECT_EQ("xxxx =\n"
" \"a\\\n"
"b\\\n"
"c\";",
format("xxxx = \"a\\\n"
"b\\\n"
"c\";",
Break));
// Exempt ObjC strings for now.
EXPECT_EQ("NSString *const kString = @\"aaaa\"\n"
" @\"bbbb\";",
format("NSString *const kString = @\"aaaa\"\n"
"@\"bbbb\";",
Break));
Break.ColumnLimit = 0;
verifyFormat("const char *hello = \"hello llvm\";", Break);
}
TEST_F(FormatTest, AlignsPipes) {
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
" \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
" << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
verifyFormat(
"aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
verifyFormat(
"llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaa)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("LOG_IF(aaa == //\n"
" bbb)\n"
" << a << b;");
// But sometimes, breaking before the first "<<" is desirable.
verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
" << BEF << IsTemplate << Description << E->getType();");
verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" << aaa;");
verifyFormat(
"llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
// Incomplete string literal.
EXPECT_EQ("llvm::errs() << \"\n"
" << a;",
format("llvm::errs() << \"\n<<a;"));
verifyFormat("void f() {\n"
" CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
" << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
"}");
// Handle 'endl'.
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
" << bbbbbbbbbbbbbbbbbbbbbb << endl;");
verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
// Handle '\n'.
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
" << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
" << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
}
TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
verifyFormat("return out << \"somepacket = {\\n\"\n"
" << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
" << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
" << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
" << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
" << \"}\";");
verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
verifyFormat(
"llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
" << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
" << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
" << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
" << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
" << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
verifyFormat(
"void f() {\n"
" llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
"}");
// Breaking before the first "<<" is generally not desirable.
verifyFormat(
"llvm::errs()\n"
" << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
getLLVMStyleWithColumns(70));
verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" << \"aaaaaaaaaaaaaaaaaaa: \"\n"
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
getLLVMStyleWithColumns(70));
verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
" \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
" \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
" \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
" \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
" (aaaa + aaaa);",
getLLVMStyleWithColumns(40));
verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
" (aaaaaaa + aaaaa));",
getLLVMStyleWithColumns(40));
verifyFormat(
"string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
" SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
" bbbbbbbbbbbbbbbbbbbbbbb);");
}
TEST_F(FormatTest, UnderstandsEquals) {
verifyFormat(
"aaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat(
"if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
verifyFormat(
"if (a) {\n"
" f();\n"
"} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
"}");
verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" 100000000 + 10000000) {\n}");
}
TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
" .looooooooooooooooooooooooooooooooooooooongFunction();");
verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
" ->looooooooooooooooooooooooooooooooooooooongFunction();");
verifyFormat(
"LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
" Parameter2);");
verifyFormat(
"ShortObject->shortFunction(\n"
" LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
" LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
verifyFormat("loooooooooooooongFunction(\n"
" LoooooooooooooongObject->looooooooooooooooongFunction());");
verifyFormat(
"function(LoooooooooooooooooooooooooooooooooooongObject\n"
" ->loooooooooooooooooooooooooooooooooooooooongFunction());");
verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
" .WillRepeatedly(Return(SomeValue));");
verifyFormat("void f() {\n"
" EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
" .Times(2)\n"
" .WillRepeatedly(Return(SomeValue));\n"
"}");
verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
" ccccccccccccccccccccccc);");
verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaa(aaaaa),\n"
" aaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("void f() {\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
"}");
verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
"}");
// Here, it is not necessary to wrap at "." or "->".
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
" aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
verifyFormat(
"aaaaaaaaaaa->aaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
" aaaaaaaaa()->aaaaaa()->aaaaa());");
verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
" aaaaaaaaa()->aaaaaa()->aaaaa());");
verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .a();");
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
NoBinPacking);
// If there is a subsequent call, change to hanging indentation.
verifyFormat(
"aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
}
TEST_F(FormatTest, WrapsTemplateDeclarations) {
verifyFormat("template <typename T>\n"
"virtual void loooooooooooongFunction(int Param1, int Param2);");
verifyFormat("template <typename T>\n"
"// T should be one of {A, B}.\n"
"virtual void loooooooooooongFunction(int Param1, int Param2);");
verifyFormat(
"template <typename T>\n"
"using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
verifyFormat("template <typename T>\n"
"void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
" int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
verifyFormat(
"template <typename T>\n"
"void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
" int Paaaaaaaaaaaaaaaaaaaaram2);");
verifyFormat(
"template <typename T>\n"
"aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("template <typename T>\n"
"void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" int aaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"template <typename T1, typename T2 = char, typename T3 = char,\n"
" typename T4 = char>\n"
"void f();");
verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
" template <typename> class cccccccccccccccccccccc,\n"
" typename ddddddddddddd>\n"
"class C {};");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("void f() {\n"
" a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
" a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
"}");
verifyFormat("template <typename T> class C {};");
verifyFormat("template <typename T> void f();");
verifyFormat("template <typename T> void f() {}");
verifyFormat(
"aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
" new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
" bbbbbbbbbbbbbbbbbbbbbbbb);",
getLLVMStyleWithColumns(72));
EXPECT_EQ("static_cast<A< //\n"
" B> *>(\n"
"\n"
" );",
format("static_cast<A<//\n"
" B>*>(\n"
"\n"
" );"));
verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
FormatStyle AlwaysBreak = getLLVMStyle();
AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
" ccccccccccccccccccccccccccccccccccccccccccccccc);");
verifyFormat("template <template <typename> class Fooooooo,\n"
" template <typename> class Baaaaaaar>\n"
"struct C {};",
AlwaysBreak);
verifyFormat("template <typename T> // T can be A, B or C.\n"
"struct C {};",
AlwaysBreak);
verifyFormat("template <enum E> class A {\n"
"public:\n"
" E *f();\n"
"};");
}
TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
// FIXME: Should we have the extra indent after the second break?
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat(
"aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
" cccccccccccccccccccccccccccccccccccccccccccccc());");
// Breaking at nested name specifiers is generally not desirable.
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaa);",
getLLVMStyleWithColumns(74));
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
}
TEST_F(FormatTest, UnderstandsTemplateParameters) {
verifyFormat("A<int> a;");
verifyFormat("A<A<A<int>>> a;");
verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
verifyFormat("bool x = a < 1 || 2 > a;");
verifyFormat("bool x = 5 < f<int>();");
verifyFormat("bool x = f<int>() > 5;");
verifyFormat("bool x = 5 < a<int>::x;");
verifyFormat("bool x = a < 4 ? a > 2 : false;");
verifyFormat("bool x = f() ? a < 2 : a > 2;");
verifyGoogleFormat("A<A<int>> a;");
verifyGoogleFormat("A<A<A<int>>> a;");
verifyGoogleFormat("A<A<A<A<int>>>> a;");
verifyGoogleFormat("A<A<int> > a;");
verifyGoogleFormat("A<A<A<int> > > a;");
verifyGoogleFormat("A<A<A<A<int> > > > a;");
verifyGoogleFormat("A<::A<int>> a;");
verifyGoogleFormat("A<::A> a;");
verifyGoogleFormat("A< ::A> a;");
verifyGoogleFormat("A< ::A<int> > a;");
EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
verifyFormat("A<A>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
verifyFormat("test >> a >> b;");
verifyFormat("test << a >> b;");
verifyFormat("f<int>();");
verifyFormat("template <typename T> void f() {}");
verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
"sizeof(char)>::type>;");
verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
verifyFormat("f(a.operator()<A>());");
verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" .template operator()<A>());",
getLLVMStyleWithColumns(35));
// Not template parameters.
verifyFormat("return a < b && c > d;");
verifyFormat("void f() {\n"
" while (a < b && c > d) {\n"
" }\n"
"}");
verifyFormat("template <typename... Types>\n"
"typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
getLLVMStyleWithColumns(60));
verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
}
TEST_F(FormatTest, BitshiftOperatorWidth) {
EXPECT_EQ("int a = 1 << 2; /* foo\n"
" bar */",
format("int a=1<<2; /* foo\n"
" bar */"));
EXPECT_EQ("int b = 256 >> 1; /* foo\n"
" bar */",
format("int b =256>>1 ; /* foo\n"
" bar */"));
}
TEST_F(FormatTest, UnderstandsBinaryOperators) {
verifyFormat("COMPARE(a, ==, b);");
verifyFormat("auto s = sizeof...(Ts) - 1;");
}
TEST_F(FormatTest, UnderstandsPointersToMembers) {
verifyFormat("int A::*x;");
verifyFormat("int (S::*func)(void *);");
verifyFormat("void f() { int (S::*func)(void *); }");
verifyFormat("typedef bool *(Class::*Member)() const;");
verifyFormat("void f() {\n"
" (a->*f)();\n"
" a->*x;\n"
" (a.*f)();\n"
" ((*a).*f)();\n"
" a.*x;\n"
"}");
verifyFormat("void f() {\n"
" (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
" aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
"}");
verifyFormat(
"(aaaaaaaaaa->*bbbbbbb)(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
FormatStyle Style = getLLVMStyle();
Style.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("typedef bool* (Class::*Member)() const;", Style);
}
TEST_F(FormatTest, UnderstandsUnaryOperators) {
verifyFormat("int a = -2;");
verifyFormat("f(-1, -2, -3);");
verifyFormat("a[-1] = 5;");
verifyFormat("int a = 5 + -2;");
verifyFormat("if (i == -1) {\n}");
verifyFormat("if (i != -1) {\n}");
verifyFormat("if (i > -1) {\n}");
verifyFormat("if (i < -1) {\n}");
verifyFormat("++(a->f());");
verifyFormat("--(a->f());");
verifyFormat("(a->f())++;");
verifyFormat("a[42]++;");
verifyFormat("if (!(a->f())) {\n}");
verifyFormat("a-- > b;");
verifyFormat("b ? -a : c;");
verifyFormat("n * sizeof char16;");
verifyFormat("n * alignof char16;", getGoogleStyle());
verifyFormat("sizeof(char);");
verifyFormat("alignof(char);", getGoogleStyle());
verifyFormat("return -1;");
verifyFormat("switch (a) {\n"
"case -1:\n"
" break;\n"
"}");
verifyFormat("#define X -1");
verifyFormat("#define X -kConstant");
verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
verifyFormat("int a = /* confusing comment */ -1;");
// FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
verifyFormat("int a = i /* confusing comment */++;");
}
TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
verifyFormat("if (!aaaaaaaaaa( // break\n"
" aaaaa)) {\n"
"}");
verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
" aaaaa));");
verifyFormat("*aaa = aaaaaaa( // break\n"
" bbbbbb);");
}
TEST_F(FormatTest, UnderstandsOverloadedOperators) {
verifyFormat("bool operator<();");
verifyFormat("bool operator>();");
verifyFormat("bool operator=();");
verifyFormat("bool operator==();");
verifyFormat("bool operator!=();");
verifyFormat("int operator+();");
verifyFormat("int operator++();");
verifyFormat("bool operator,();");
verifyFormat("bool operator();");
verifyFormat("bool operator()();");
verifyFormat("bool operator[]();");
verifyFormat("operator bool();");
verifyFormat("operator int();");
verifyFormat("operator void *();");
verifyFormat("operator SomeType<int>();");
verifyFormat("operator SomeType<int, int>();");
verifyFormat("operator SomeType<SomeType<int>>();");
verifyFormat("void *operator new(std::size_t size);");
verifyFormat("void *operator new[](std::size_t size);");
verifyFormat("void operator delete(void *ptr);");
verifyFormat("void operator delete[](void *ptr);");
verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
"AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
" aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
verifyFormat(
"ostream &operator<<(ostream &OutputStream,\n"
" SomeReallyLongType WithSomeReallyLongValue);");
verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
" const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
" return left.group < right.group;\n"
"}");
verifyFormat("SomeType &operator=(const SomeType &S);");
verifyFormat("f.template operator()<int>();");
verifyGoogleFormat("operator void*();");
verifyGoogleFormat("operator SomeType<SomeType<int>>();");
verifyGoogleFormat("operator ::A();");
verifyFormat("using A::operator+;");
verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
"int i;");
}
TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
verifyFormat("Deleted &operator=(const Deleted &) & = default;");
verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
verifyFormat("Deleted &operator=(const Deleted &) &;");
verifyFormat("Deleted &operator=(const Deleted &) &&;");
verifyFormat("SomeType MemberFunction(const Deleted &) &;");
verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
verifyFormat("SomeType MemberFunction(const Deleted &) const &;");
verifyFormat("template <typename T>\n"
"void F(T) && = delete;",
getGoogleStyle());
FormatStyle AlignLeft = getLLVMStyle();
AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("void A::b() && {}", AlignLeft);
verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
AlignLeft);
verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
verifyFormat("auto Function(T) & -> void {}", AlignLeft);
verifyFormat("auto Function(T) & -> void;", AlignLeft);
verifyFormat("SomeType MemberFunction(const Deleted&) const &;", AlignLeft);
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInCStyleCastParentheses = true;
verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
Spaces.SpacesInCStyleCastParentheses = false;
Spaces.SpacesInParentheses = true;
verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", Spaces);
verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
}
TEST_F(FormatTest, UnderstandsNewAndDelete) {
verifyFormat("void f() {\n"
" A *a = new A;\n"
" A *a = new (placement) A;\n"
" delete a;\n"
" delete (A *)a;\n"
"}");
verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
" typename aaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
" typename aaaaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("delete[] h->p;");
}
TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
verifyFormat("int *f(int *a) {}");
verifyFormat("int main(int argc, char **argv) {}");
verifyFormat("Test::Test(int b) : a(b * b) {}");
verifyIndependentOfContext("f(a, *a);");
verifyFormat("void g() { f(*a); }");
verifyIndependentOfContext("int a = b * 10;");
verifyIndependentOfContext("int a = 10 * b;");
verifyIndependentOfContext("int a = b * c;");
verifyIndependentOfContext("int a += b * c;");
verifyIndependentOfContext("int a -= b * c;");
verifyIndependentOfContext("int a *= b * c;");
verifyIndependentOfContext("int a /= b * c;");
verifyIndependentOfContext("int a = *b;");
verifyIndependentOfContext("int a = *b * c;");
verifyIndependentOfContext("int a = b * *c;");
verifyIndependentOfContext("int a = b * (10);");
verifyIndependentOfContext("S << b * (10);");
verifyIndependentOfContext("return 10 * b;");
verifyIndependentOfContext("return *b * *c;");
verifyIndependentOfContext("return a & ~b;");
verifyIndependentOfContext("f(b ? *c : *d);");
verifyIndependentOfContext("int a = b ? *c : *d;");
verifyIndependentOfContext("*b = a;");
verifyIndependentOfContext("a * ~b;");
verifyIndependentOfContext("a * !b;");
verifyIndependentOfContext("a * +b;");
verifyIndependentOfContext("a * -b;");
verifyIndependentOfContext("a * ++b;");
verifyIndependentOfContext("a * --b;");
verifyIndependentOfContext("a[4] * b;");
verifyIndependentOfContext("a[a * a] = 1;");
verifyIndependentOfContext("f() * b;");
verifyIndependentOfContext("a * [self dostuff];");
verifyIndependentOfContext("int x = a * (a + b);");
verifyIndependentOfContext("(a *)(a + b);");
verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
verifyIndependentOfContext("int *pa = (int *)&a;");
verifyIndependentOfContext("return sizeof(int **);");
verifyIndependentOfContext("return sizeof(int ******);");
verifyIndependentOfContext("return (int **&)a;");
verifyIndependentOfContext("f((*PointerToArray)[10]);");
verifyFormat("void f(Type (*parameter)[10]) {}");
verifyFormat("void f(Type (¶meter)[10]) {}");
verifyGoogleFormat("return sizeof(int**);");
verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
verifyFormat("auto a = [](int **&, int ***) {};");
verifyFormat("auto PointerBinding = [](const char *S) {};");
verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
verifyFormat("[](const decltype(*a) &value) {}");
verifyFormat("decltype(a * b) F();");
verifyFormat("#define MACRO() [](A *a) { return 1; }");
verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
verifyIndependentOfContext("typedef void (*f)(int *a);");
verifyIndependentOfContext("int i{a * b};");
verifyIndependentOfContext("aaa && aaa->f();");
verifyIndependentOfContext("int x = ~*p;");
verifyFormat("Constructor() : a(a), area(width * height) {}");
verifyFormat("Constructor() : a(a), area(a, width * height) {}");
verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
verifyFormat("void f() { f(a, c * d); }");
verifyFormat("void f() { f(new a(), c * d); }");
verifyFormat("void f(const MyOverride &override);");
verifyFormat("void f(const MyFinal &final);");
verifyIndependentOfContext("bool a = f() && override.f();");
verifyIndependentOfContext("bool a = f() && final.f();");
verifyIndependentOfContext("InvalidRegions[*R] = 0;");
verifyIndependentOfContext("A<int *> a;");
verifyIndependentOfContext("A<int **> a;");
verifyIndependentOfContext("A<int *, int *> a;");
verifyIndependentOfContext("A<int *[]> a;");
verifyIndependentOfContext(
"const char *const p = reinterpret_cast<const char *const>(q);");
verifyIndependentOfContext("A<int **, int **> a;");
verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
verifyFormat("for (char **a = b; *a; ++a) {\n}");
verifyFormat("for (; a && b;) {\n}");
verifyFormat("bool foo = true && [] { return false; }();");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyGoogleFormat("int const* a = &b;");
verifyGoogleFormat("**outparam = 1;");
verifyGoogleFormat("*outparam = a * b;");
verifyGoogleFormat("int main(int argc, char** argv) {}");
verifyGoogleFormat("A<int*> a;");
verifyGoogleFormat("A<int**> a;");
verifyGoogleFormat("A<int*, int*> a;");
verifyGoogleFormat("A<int**, int**> a;");
verifyGoogleFormat("f(b ? *c : *d);");
verifyGoogleFormat("int a = b ? *c : *d;");
verifyGoogleFormat("Type* t = **x;");
verifyGoogleFormat("Type* t = *++*x;");
verifyGoogleFormat("*++*x;");
verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
verifyGoogleFormat("Type* t = x++ * y;");
verifyGoogleFormat(
"const char* const p = reinterpret_cast<const char* const>(q);");
verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
verifyGoogleFormat("template <typename T>\n"
"void f(int i = 0, SomeType** temps = NULL);");
FormatStyle Left = getLLVMStyle();
Left.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("x = *a(x) = *a(y);", Left);
verifyFormat("for (;; *a = b) {\n}", Left);
verifyFormat("return *this += 1;", Left);
verifyIndependentOfContext("a = *(x + y);");
verifyIndependentOfContext("a = &(x + y);");
verifyIndependentOfContext("*(x + y).call();");
verifyIndependentOfContext("&(x + y)->call();");
verifyFormat("void f() { &(*I).first; }");
verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
verifyFormat(
"int *MyValues = {\n"
" *A, // Operator detection might be confused by the '{'\n"
" *BB // Operator detection might be confused by previous comment\n"
"};");
verifyIndependentOfContext("if (int *a = &b)");
verifyIndependentOfContext("if (int &a = *b)");
verifyIndependentOfContext("if (a & b[i])");
verifyIndependentOfContext("if (a::b::c::d & b[i])");
verifyIndependentOfContext("if (*b[i])");
verifyIndependentOfContext("if (int *a = (&b))");
verifyIndependentOfContext("while (int *a = &b)");
verifyIndependentOfContext("size = sizeof *a;");
verifyIndependentOfContext("if (a && (b = c))");
verifyFormat("void f() {\n"
" for (const int &v : Values) {\n"
" }\n"
"}");
verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
verifyFormat("#define A (!a * b)");
verifyFormat("#define MACRO \\\n"
" int *i = a * b; \\\n"
" void f(a *b);",
getLLVMStyleWithColumns(19));
verifyIndependentOfContext("A = new SomeType *[Length];");
verifyIndependentOfContext("A = new SomeType *[Length]();");
verifyIndependentOfContext("T **t = new T *;");
verifyIndependentOfContext("T **t = new T *();");
verifyGoogleFormat("A = new SomeType*[Length]();");
verifyGoogleFormat("A = new SomeType*[Length];");
verifyGoogleFormat("T** t = new T*;");
verifyGoogleFormat("T** t = new T*();");
FormatStyle PointerLeft = getLLVMStyle();
PointerLeft.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("delete *x;", PointerLeft);
verifyFormat("STATIC_ASSERT((a & b) == 0);");
verifyFormat("STATIC_ASSERT(0 == (a & b));");
verifyFormat("template <bool a, bool b> "
"typename t::if<x && y>::type f() {}");
verifyFormat("template <int *y> f() {}");
verifyFormat("vector<int *> v;");
verifyFormat("vector<int *const> v;");
verifyFormat("vector<int *const **const *> v;");
verifyFormat("vector<int *volatile> v;");
verifyFormat("vector<a * b> v;");
verifyFormat("foo<b && false>();");
verifyFormat("foo<b & 1>();");
verifyFormat("decltype(*::std::declval<const T &>()) void F();");
verifyFormat(
"template <class T,\n"
" class = typename std::enable_if<\n"
" std::is_integral<T>::value &&\n"
" (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
"void F();",
getLLVMStyleWithColumns(70));
verifyFormat(
"template <class T,\n"
" class = typename ::std::enable_if<\n"
" ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
"void F();",
getGoogleStyleWithColumns(68));
verifyIndependentOfContext("MACRO(int *i);");
verifyIndependentOfContext("MACRO(auto *a);");
verifyIndependentOfContext("MACRO(const A *a);");
verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
verifyFormat("void f() { f(float{1}, a * a); }");
// FIXME: Is there a way to make this work?
// verifyIndependentOfContext("MACRO(A *a);");
verifyFormat("DatumHandle const *operator->() const { return input_; }");
verifyFormat("return options != nullptr && operator==(*options);");
EXPECT_EQ("#define OP(x) \\\n"
" ostream &operator<<(ostream &s, const A &a) { \\\n"
" return s << a.DebugString(); \\\n"
" }",
format("#define OP(x) \\\n"
" ostream &operator<<(ostream &s, const A &a) { \\\n"
" return s << a.DebugString(); \\\n"
" }",
getLLVMStyleWithColumns(50)));
// FIXME: We cannot handle this case yet; we might be able to figure out that
// foo<x> d > v; doesn't make sense.
verifyFormat("foo<a<b && c> d> v;");
FormatStyle PointerMiddle = getLLVMStyle();
PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
verifyFormat("delete *x;", PointerMiddle);
verifyFormat("int * x;", PointerMiddle);
verifyFormat("template <int * y> f() {}", PointerMiddle);
verifyFormat("int * f(int * a) {}", PointerMiddle);
verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
verifyFormat("A<int *> a;", PointerMiddle);
verifyFormat("A<int **> a;", PointerMiddle);
verifyFormat("A<int *, int *> a;", PointerMiddle);
verifyFormat("A<int * []> a;", PointerMiddle);
verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
verifyFormat("A = new SomeType *[Length];", PointerMiddle);
verifyFormat("T ** t = new T *;", PointerMiddle);
// Member function reference qualifiers aren't binary operators.
verifyFormat("string // break\n"
"operator()() & {}");
verifyFormat("string // break\n"
"operator()() && {}");
verifyGoogleFormat("template <typename T>\n"
"auto x() & -> int {}");
}
TEST_F(FormatTest, UnderstandsAttributes) {
verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
"aaaaaaaaaaaaaaaaaaaaaaa(int i);");
FormatStyle AfterType = getLLVMStyle();
AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
verifyFormat("__attribute__((nodebug)) void\n"
"foo() {}\n",
AfterType);
}
TEST_F(FormatTest, UnderstandsEllipsis) {
verifyFormat("int printf(const char *fmt, ...);");
verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
FormatStyle PointersLeft = getLLVMStyle();
PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
}
TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
EXPECT_EQ("int *a;\n"
"int *a;\n"
"int *a;",
format("int *a;\n"
"int* a;\n"
"int *a;",
getGoogleStyle()));
EXPECT_EQ("int* a;\n"
"int* a;\n"
"int* a;",
format("int* a;\n"
"int* a;\n"
"int *a;",
getGoogleStyle()));
EXPECT_EQ("int *a;\n"
"int *a;\n"
"int *a;",
format("int *a;\n"
"int * a;\n"
"int * a;",
getGoogleStyle()));
EXPECT_EQ("auto x = [] {\n"
" int *a;\n"
" int *a;\n"
" int *a;\n"
"};",
format("auto x=[]{int *a;\n"
"int * a;\n"
"int * a;};",
getGoogleStyle()));
}
TEST_F(FormatTest, UnderstandsRvalueReferences) {
verifyFormat("int f(int &&a) {}");
verifyFormat("int f(int a, char &&b) {}");
verifyFormat("void f() { int &&a = b; }");
verifyGoogleFormat("int f(int a, char&& b) {}");
verifyGoogleFormat("void f() { int&& a = b; }");
verifyIndependentOfContext("A<int &&> a;");
verifyIndependentOfContext("A<int &&, int &&> a;");
verifyGoogleFormat("A<int&&> a;");
verifyGoogleFormat("A<int&&, int&&> a;");
// Not rvalue references:
verifyFormat("template <bool B, bool C> class A {\n"
" static_assert(B && C, \"Something is wrong\");\n"
"};");
verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
verifyFormat("#define A(a, b) (a && b)");
}
TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
verifyFormat("void f() {\n"
" x[aaaaaaaaa -\n"
" b] = 23;\n"
"}",
getLLVMStyleWithColumns(15));
}
TEST_F(FormatTest, FormatsCasts) {
verifyFormat("Type *A = static_cast<Type *>(P);");
verifyFormat("Type *A = (Type *)P;");
verifyFormat("Type *A = (vector<Type *, int *>)P;");
verifyFormat("int a = (int)(2.0f);");
verifyFormat("int a = (int)2.0f;");
verifyFormat("x[(int32)y];");
verifyFormat("x = (int32)y;");
verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
verifyFormat("int a = (int)*b;");
verifyFormat("int a = (int)2.0f;");
verifyFormat("int a = (int)~0;");
verifyFormat("int a = (int)++a;");
verifyFormat("int a = (int)sizeof(int);");
verifyFormat("int a = (int)+2;");
verifyFormat("my_int a = (my_int)2.0f;");
verifyFormat("my_int a = (my_int)sizeof(int);");
verifyFormat("return (my_int)aaa;");
verifyFormat("#define x ((int)-1)");
verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
verifyFormat("#define p(q) ((int *)&q)");
verifyFormat("fn(a)(b) + 1;");
verifyFormat("void f() { my_int a = (my_int)*b; }");
verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
verifyFormat("my_int a = (my_int)~0;");
verifyFormat("my_int a = (my_int)++a;");
verifyFormat("my_int a = (my_int)-2;");
verifyFormat("my_int a = (my_int)1;");
verifyFormat("my_int a = (my_int *)1;");
verifyFormat("my_int a = (const my_int)-1;");
verifyFormat("my_int a = (const my_int *)-1;");
verifyFormat("my_int a = (my_int)(my_int)-1;");
verifyFormat("my_int a = (ns::my_int)-2;");
verifyFormat("case (my_int)ONE:");
verifyFormat("auto x = (X)this;");
// FIXME: single value wrapped with paren will be treated as cast.
verifyFormat("void f(int i = (kValue)*kMask) {}");
verifyFormat("{ (void)F; }");
// Don't break after a cast's
verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
" bbbbbbbbbbbbbbbbbbbbbb);");
// These are not casts.
verifyFormat("void f(int *) {}");
verifyFormat("f(foo)->b;");
verifyFormat("f(foo).b;");
verifyFormat("f(foo)(b);");
verifyFormat("f(foo)[b];");
verifyFormat("[](foo) { return 4; }(bar);");
verifyFormat("(*funptr)(foo)[4];");
verifyFormat("funptrs[4](foo)[4];");
verifyFormat("void f(int *);");
verifyFormat("void f(int *) = 0;");
verifyFormat("void f(SmallVector<int>) {}");
verifyFormat("void f(SmallVector<int>);");
verifyFormat("void f(SmallVector<int>) = 0;");
verifyFormat("void f(int i = (kA * kB) & kMask) {}");
verifyFormat("int a = sizeof(int) * b;");
verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
// These are not casts, but at some point were confused with casts.
verifyFormat("virtual void foo(int *) override;");
verifyFormat("virtual void foo(char &) const;");
verifyFormat("virtual void foo(int *a, char *) const;");
verifyFormat("int a = sizeof(int *) + b;");
verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
verifyFormat("bool b = f(g<int>) && c;");
verifyFormat("typedef void (*f)(int i) func;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
// FIXME: The indentation here is not ideal.
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
" [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
}
TEST_F(FormatTest, FormatsFunctionTypes) {
verifyFormat("A<bool()> a;");
verifyFormat("A<SomeType()> a;");
verifyFormat("A<void (*)(int, std::string)> a;");
verifyFormat("A<void *(int)>;");
verifyFormat("void *(*a)(int *, SomeType *);");
verifyFormat("int (*func)(void *);");
verifyFormat("void f() { int (*func)(void *); }");
verifyFormat("template <class CallbackClass>\n"
"using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
verifyGoogleFormat("A<void*(int*, SomeType*)>;");
verifyGoogleFormat("void* (*a)(int);");
verifyGoogleFormat(
"template <class CallbackClass>\n"
"using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
// Other constructs can look somewhat like function types:
verifyFormat("A<sizeof(*x)> a;");
verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
verifyFormat("some_var = function(*some_pointer_var)[0];");
verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
verifyFormat("int x = f(&h)();");
verifyFormat("returnsFunction(¶m1, ¶m2)(param);");
}
TEST_F(FormatTest, FormatsPointersToArrayTypes) {
verifyFormat("A (*foo_)[6];");
verifyFormat("vector<int> (*foo_)[6];");
}
TEST_F(FormatTest, BreaksLongVariableDeclarations) {
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" LoooooooooooooooooooooooooooooooooooooooongVariable;");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
" LoooooooooooooooooooooooooooooooooooooooongVariable;");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" *LoooooooooooooooooooooooooooooooooooooooongVariable;");
// Different ways of ()-initializiation.
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" LoooooooooooooooooooooooooooooooooooooooongVariable({});");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
" LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
}
TEST_F(FormatTest, BreaksLongDeclarations) {
verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
" AnotherNameForTheLongType;");
verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
"LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
"LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
"LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
"LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
FormatStyle Indented = getLLVMStyle();
Indented.IndentWrappedFunctionNames = true;
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
" LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
Indented);
verifyFormat(
"LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
" LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
Indented);
verifyFormat(
"LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
" LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
Indented);
verifyFormat(
"decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
" LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
Indented);
// FIXME: Without the comment, this breaks after "(".
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n"
" (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
getGoogleStyle());
verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
" int LoooooooooooooooooooongParam2) {}");
verifyFormat(
"TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
" SourceLocation L, IdentifierIn *II,\n"
" Type *T) {}");
verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
"ReallyReaaallyLongFunctionName(\n"
" const std::string &SomeParameter,\n"
" const SomeType<string, SomeOtherTemplateParameter>\n"
" &ReallyReallyLongParameterName,\n"
" const SomeType<string, SomeOtherTemplateParameter>\n"
" &AnotherLongParameterName) {}");
verifyFormat("template <typename A>\n"
"SomeLoooooooooooooooooooooongType<\n"
" typename some_namespace::SomeOtherType<A>::Type>\n"
"Function() {}");
verifyGoogleFormat(
"aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
" aaaaaaaaaaaaaaaaaaaaaaa;");
verifyGoogleFormat(
"TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
" SourceLocation L) {}");
verifyGoogleFormat(
"some_namespace::LongReturnType\n"
"long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
" int first_long_parameter, int second_parameter) {}");
verifyGoogleFormat("template <typename T>\n"
"aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
"aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" int aaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
" const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
" aaaaaaaaaaaaaaaaaaaaaaaa);");
verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
}
TEST_F(FormatTest, FormatsArrays) {
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
" [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
" aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
verifyFormat(
"llvm::outs() << \"aaaaaaaaaaaa: \"\n"
" << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
" .aaaaaaaaaaaaaaaaaaaaaa();");
verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
verifyFormat(
"aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
" .aaaaaaa[0]\n"
" .aaaaaaaaaaaaaaaaaaaaaa();");
verifyFormat("a[::b::c];");
verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
}
TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
verifyFormat("(a)->b();");
verifyFormat("--a;");
}
TEST_F(FormatTest, HandlesIncludeDirectives) {
verifyFormat("#include <string>\n"
"#include <a/b/c.h>\n"
"#include \"a/b/string\"\n"
"#include \"string.h\"\n"
"#include \"string.h\"\n"
"#include <a-a>\n"
"#include < path with space >\n"
"#include_next <test.h>"
"#include \"abc.h\" // this is included for ABC\n"
"#include \"some long include\" // with a comment\n"
"#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
getLLVMStyleWithColumns(35));
EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\""));
EXPECT_EQ("#include <a>", format("#include<a>"));
verifyFormat("#import <string>");
verifyFormat("#import <a/b/c.h>");
verifyFormat("#import \"a/b/string\"");
verifyFormat("#import \"string.h\"");
verifyFormat("#import \"string.h\"");
verifyFormat("#if __has_include(<strstream>)\n"
"#include <strstream>\n"
"#endif");
verifyFormat("#define MY_IMPORT <a/b>");
// Protocol buffer definition or missing "#".
verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
getLLVMStyleWithColumns(30));
FormatStyle Style = getLLVMStyle();
Style.AlwaysBreakBeforeMultilineStrings = true;
Style.ColumnLimit = 0;
verifyFormat("#import \"abc.h\"", Style);
// But 'import' might also be a regular C++ namespace.
verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
}
//===----------------------------------------------------------------------===//
// Error recovery tests.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, IncompleteParameterLists) {
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
" double *min_x,\n"
" double *max_x,\n"
" double *min_y,\n"
" double *max_y,\n"
" double *min_z,\n"
" double *max_z, ) {}",
NoBinPacking);
}
TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
verifyFormat("void f() { return; }\n42");
verifyFormat("void f() {\n"
" if (0)\n"
" return;\n"
"}\n"
"42");
verifyFormat("void f() { return }\n42");
verifyFormat("void f() {\n"
" if (0)\n"
" return\n"
"}\n"
"42");
}
TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
EXPECT_EQ("void f() { return }", format("void f ( ) { return }"));
EXPECT_EQ("void f() {\n"
" if (a)\n"
" return\n"
"}",
format("void f ( ) { if ( a ) return }"));
EXPECT_EQ("namespace N {\n"
"void f()\n"
"}",
format("namespace N { void f() }"));
EXPECT_EQ("namespace N {\n"
"void f() {}\n"
"void g()\n"
"}",
format("namespace N { void f( ) { } void g( ) }"));
}
TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
verifyFormat("int aaaaaaaa =\n"
" // Overlylongcomment\n"
" b;",
getLLVMStyleWithColumns(20));
verifyFormat("function(\n"
" ShortArgument,\n"
" LoooooooooooongArgument);\n",
getLLVMStyleWithColumns(20));
}
TEST_F(FormatTest, IncorrectAccessSpecifier) {
verifyFormat("public:");
verifyFormat("class A {\n"
"public\n"
" void f() {}\n"
"};");
verifyFormat("public\n"
"int qwerty;");
verifyFormat("public\n"
"B {}");
verifyFormat("public\n"
"{}");
verifyFormat("public\n"
"B { int x; }");
}
TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
verifyFormat("{");
verifyFormat("#})");
verifyNoCrash("(/**/[:!] ?[).");
}
TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
verifyFormat("do {\n}");
verifyFormat("do {\n}\n"
"f();");
verifyFormat("do {\n}\n"
"wheeee(fun);");
verifyFormat("do {\n"
" f();\n"
"}");
}
TEST_F(FormatTest, IncorrectCodeMissingParens) {
verifyFormat("if {\n foo;\n foo();\n}");
verifyFormat("switch {\n foo;\n foo();\n}");
verifyIncompleteFormat("for {\n foo;\n foo();\n}");
verifyFormat("while {\n foo;\n foo();\n}");
verifyFormat("do {\n foo;\n foo();\n} while;");
}
TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
verifyIncompleteFormat("namespace {\n"
"class Foo { Foo (\n"
"};\n"
"} // comment");
}
TEST_F(FormatTest, IncorrectCodeErrorDetection) {
EXPECT_EQ("{\n {}\n", format("{\n{\n}\n"));
EXPECT_EQ("{\n {}\n", format("{\n {\n}\n"));
EXPECT_EQ("{\n {}\n", format("{\n {\n }\n"));
EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n"));
EXPECT_EQ("{\n"
" {\n"
" breakme(\n"
" qwe);\n"
" }\n",
format("{\n"
" {\n"
" breakme(qwe);\n"
"}\n",
getLLVMStyleWithColumns(10)));
}
TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
verifyFormat("int x = {\n"
" avariable,\n"
" b(alongervariable)};",
getLLVMStyleWithColumns(25));
}
TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
verifyFormat("return (a)(b){1, 2, 3};");
}
TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
verifyFormat("vector<int> x{1, 2, 3, 4};");
verifyFormat("vector<int> x{\n"
" 1, 2, 3, 4,\n"
"};");
verifyFormat("vector<T> x{{}, {}, {}, {}};");
verifyFormat("f({1, 2});");
verifyFormat("auto v = Foo{-1};");
verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
verifyFormat("Class::Class : member{1, 2, 3} {}");
verifyFormat("new vector<int>{1, 2, 3};");
verifyFormat("new int[3]{1, 2, 3};");
verifyFormat("new int{1};");
verifyFormat("return {arg1, arg2};");
verifyFormat("return {arg1, SomeType{parameter}};");
verifyFormat("int count = set<int>{f(), g(), h()}.size();");
verifyFormat("new T{arg1, arg2};");
verifyFormat("f(MyMap[{composite, key}]);");
verifyFormat("class Class {\n"
" T member = {arg1, arg2};\n"
"};");
verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
verifyFormat("int a = std::is_integral<int>{} + 0;");
verifyFormat("int foo(int i) { return fo1{}(i); }");
verifyFormat("int foo(int i) { return fo1{}(i); }");
verifyFormat("auto i = decltype(x){};");
verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
verifyFormat("Node n{1, Node{1000}, //\n"
" 2};");
verifyFormat("Aaaa aaaaaaa{\n"
" {\n"
" aaaa,\n"
" },\n"
"};");
verifyFormat("class C : public D {\n"
" SomeClass SC{2};\n"
"};");
verifyFormat("class C : public A {\n"
" class D : public B {\n"
" void f() { int i{2}; }\n"
" };\n"
"};");
verifyFormat("#define A {a, a},");
// Cases where distinguising braced lists and blocks is hard.
verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
verifyFormat("void f() {\n"
" return; // comment\n"
"}\n"
"SomeType t;");
verifyFormat("void f() {\n"
" if (a) {\n"
" f();\n"
" }\n"
"}\n"
"SomeType t;");
// In combination with BinPackArguments = false.
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackArguments = false;
verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
" bbbbb,\n"
" ccccc,\n"
" ddddd,\n"
" eeeee,\n"
" ffffff,\n"
" ggggg,\n"
" hhhhhh,\n"
" iiiiii,\n"
" jjjjjj,\n"
" kkkkkk};",
NoBinPacking);
verifyFormat("const Aaaaaa aaaaa = {\n"
" aaaaa,\n"
" bbbbb,\n"
" ccccc,\n"
" ddddd,\n"
" eeeee,\n"
" ffffff,\n"
" ggggg,\n"
" hhhhhh,\n"
" iiiiii,\n"
" jjjjjj,\n"
" kkkkkk,\n"
"};",
NoBinPacking);
verifyFormat(
"const Aaaaaa aaaaa = {\n"
" aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n"
" iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n"
" ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
"};",
NoBinPacking);
// FIXME: The alignment of these trailing comments might be bad. Then again,
// this might be utterly useless in real code.
verifyFormat("Constructor::Constructor()\n"
" : some_value{ //\n"
" aaaaaaa, //\n"
" bbbbbbb} {}");
// In braced lists, the first comment is always assumed to belong to the
// first element. Thus, it can be moved to the next or previous line as
// appropriate.
EXPECT_EQ("function({// First element:\n"
" 1,\n"
" // Second element:\n"
" 2});",
format("function({\n"
" // First element:\n"
" 1,\n"
" // Second element:\n"
" 2});"));
EXPECT_EQ("std::vector<int> MyNumbers{\n"
" // First element:\n"
" 1,\n"
" // Second element:\n"
" 2};",
format("std::vector<int> MyNumbers{// First element:\n"
" 1,\n"
" // Second element:\n"
" 2};",
getLLVMStyleWithColumns(30)));
// A trailing comma should still lead to an enforced line break.
EXPECT_EQ("vector<int> SomeVector = {\n"
" // aaa\n"
" 1, 2,\n"
"};",
format("vector<int> SomeVector = { // aaa\n"
" 1, 2, };"));
FormatStyle ExtraSpaces = getLLVMStyle();
ExtraSpaces.Cpp11BracedListStyle = false;
ExtraSpaces.ColumnLimit = 75;
verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
verifyFormat("f({ 1, 2 });", ExtraSpaces);
verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
verifyFormat("return { arg1, arg2 };", ExtraSpaces);
verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
verifyFormat("class Class {\n"
" T member = { arg1, arg2 };\n"
"};",
ExtraSpaces);
verifyFormat(
"foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
" : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
" bbbbbbbbbbbbbbbbbbbb, bbbbb };",
ExtraSpaces);
verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
ExtraSpaces);
verifyFormat(
"someFunction(OtherParam,\n"
" BracedList{ // comment 1 (Forcing interesting break)\n"
" param1, param2,\n"
" // comment 2\n"
" param3, param4 });",
ExtraSpaces);
verifyFormat(
"std::this_thread::sleep_for(\n"
" std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
ExtraSpaces);
verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
" aaaaaaa,\n"
" aaaaaaaaaa,\n"
" aaaaa,\n"
" aaaaaaaaaaaaaaa,\n"
" aaa,\n"
" aaaaaaaaaa,\n"
" a,\n"
" aaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaa,\n"
" a};");
verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
}
TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777};");
verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, //\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777};");
verifyFormat(
"vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, // comment\n"
" 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
" 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
" 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
" 7777777};");
verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
" X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
" X86::R8, X86::R9, X86::R10, X86::R11, 0};");
verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
" X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
" // Separating comment.\n"
" X86::R8, X86::R9, X86::R10, X86::R11, 0};");
verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
" // Leading comment\n"
" X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
" X86::R8, X86::R9, X86::R10, X86::R11, 0};");
verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
" 1, 1, 1, 1};",
getLLVMStyleWithColumns(39));
verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
" 1, 1, 1, 1};",
getLLVMStyleWithColumns(38));
verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
getLLVMStyleWithColumns(43));
verifyFormat(
"static unsigned SomeValues[10][3] = {\n"
" {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n"
" {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
verifyFormat("static auto fields = new vector<string>{\n"
" \"aaaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaa\",\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
"};");
verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
" 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
" 3, cccccccccccccccccccccc};",
getLLVMStyleWithColumns(60));
// Trailing commas.
verifyFormat("vector<int> x = {\n"
" 1, 1, 1, 1, 1, 1, 1, 1,\n"
"};",
getLLVMStyleWithColumns(39));
verifyFormat("vector<int> x = {\n"
" 1, 1, 1, 1, 1, 1, 1, 1, //\n"
"};",
getLLVMStyleWithColumns(39));
verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
" 1, 1, 1, 1,\n"
" /**/ /**/};",
getLLVMStyleWithColumns(39));
// Trailing comment in the first line.
verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n"
" 1111111111, 2222222222, 33333333333, 4444444444, //\n"
" 111111111, 222222222, 3333333333, 444444444, //\n"
" 11111111, 22222222, 333333333, 44444444};");
// Trailing comment in the last line.
verifyFormat("int aaaaa[] = {\n"
" 1, 2, 3, // comment\n"
" 4, 5, 6 // comment\n"
"};");
// With nested lists, we should either format one item per line or all nested
// lists one on line.
// FIXME: For some nested lists, we can do better.
verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
" {aaaaaaaaaaaaaaaaaaa},\n"
" {aaaaaaaaaaaaaaaaaaaaa},\n"
" {aaaaaaaaaaaaaaaaa}};",
getLLVMStyleWithColumns(60));
verifyFormat(
"SomeStruct my_struct_array = {\n"
" {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
" aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
" {aaa, aaa},\n"
" {aaa, aaa},\n"
" {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
" {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
// No column layout should be used here.
verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
verifyNoCrash("a<,");
// No braced initializer here.
verifyFormat("void f() {\n"
" struct Dummy {};\n"
" f(v);\n"
"}");
// Long lists should be formatted in columns even if they are nested.
verifyFormat(
"vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
" 1, 22, 333, 4444, 55555, 666666, 7777777});");
// Allow "single-column" layout even if that violates the column limit. There
// isn't going to be a better way.
verifyFormat("std::vector<int> a = {\n"
" aaaaaaaa,\n"
" aaaaaaaa,\n"
" aaaaaaaa,\n"
" aaaaaaaa,\n"
" aaaaaaaaaa,\n"
" aaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
getLLVMStyleWithColumns(30));
verifyFormat("vector<int> aaaa = {\n"
" aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaa.aaaaaaa,\n"
" aaaaaa.aaaaaaa,\n"
" aaaaaa.aaaaaaa,\n"
" aaaaaa.aaaaaaa,\n"
"};");
// Don't create hanging lists.
verifyFormat("someFunction(Param,\n"
" {List1, List2,\n"
" List3});",
getLLVMStyleWithColumns(35));
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
" aaaaaaaaaaaaaaaaaaaaaaa);");
}
TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
FormatStyle DoNotMerge = getLLVMStyle();
DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
verifyFormat("void f() { return 42; }");
verifyFormat("void f() {\n"
" return 42;\n"
"}",
DoNotMerge);
verifyFormat("void f() {\n"
" // Comment\n"
"}");
verifyFormat("{\n"
"#error {\n"
" int a;\n"
"}");
verifyFormat("{\n"
" int a;\n"
"#error {\n"
"}");
verifyFormat("void f() {} // comment");
verifyFormat("void f() { int a; } // comment");
verifyFormat("void f() {\n"
"} // comment",
DoNotMerge);
verifyFormat("void f() {\n"
" int a;\n"
"} // comment",
DoNotMerge);
verifyFormat("void f() {\n"
"} // comment",
getLLVMStyleWithColumns(15));
verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22));
verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
verifyFormat("class C {\n"
" C()\n"
" : iiiiiiii(nullptr),\n"
" kkkkkkk(nullptr),\n"
" mmmmmmm(nullptr),\n"
" nnnnnnn(nullptr) {}\n"
"};",
getGoogleStyle());
FormatStyle NoColumnLimit = getLLVMStyle();
NoColumnLimit.ColumnLimit = 0;
EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
EXPECT_EQ("class C {\n"
" A() : b(0) {}\n"
"};",
format("class C{A():b(0){}};", NoColumnLimit));
EXPECT_EQ("A()\n"
" : b(0) {\n"
"}",
format("A()\n:b(0)\n{\n}", NoColumnLimit));
FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
FormatStyle::SFS_None;
EXPECT_EQ("A()\n"
" : b(0) {\n"
"}",
format("A():b(0){}", DoNotMergeNoColumnLimit));
EXPECT_EQ("A()\n"
" : b(0) {\n"
"}",
format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
verifyFormat("#define A \\\n"
" void f() { \\\n"
" int i; \\\n"
" }",
getLLVMStyleWithColumns(20));
verifyFormat("#define A \\\n"
" void f() { int i; }",
getLLVMStyleWithColumns(21));
verifyFormat("#define A \\\n"
" void f() { \\\n"
" int i; \\\n"
" } \\\n"
" int j;",
getLLVMStyleWithColumns(22));
verifyFormat("#define A \\\n"
" void f() { int i; } \\\n"
" int j;",
getLLVMStyleWithColumns(23));
}
TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
FormatStyle MergeInlineOnly = getLLVMStyle();
MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
verifyFormat("class C {\n"
" int f() { return 42; }\n"
"};",
MergeInlineOnly);
verifyFormat("int f() {\n"
" return 42;\n"
"}",
MergeInlineOnly);
}
TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
// Elaborate type variable declarations.
verifyFormat("struct foo a = {bar};\nint n;");
verifyFormat("class foo a = {bar};\nint n;");
verifyFormat("union foo a = {bar};\nint n;");
// Elaborate types inside function definitions.
verifyFormat("struct foo f() {}\nint n;");
verifyFormat("class foo f() {}\nint n;");
verifyFormat("union foo f() {}\nint n;");
// Templates.
verifyFormat("template <class X> void f() {}\nint n;");
verifyFormat("template <struct X> void f() {}\nint n;");
verifyFormat("template <union X> void f() {}\nint n;");
// Actual definitions...
verifyFormat("struct {\n} n;");
verifyFormat(
"template <template <class T, class Y>, class Z> class X {\n} n;");
verifyFormat("union Z {\n int n;\n} x;");
verifyFormat("class MACRO Z {\n} n;");
verifyFormat("class MACRO(X) Z {\n} n;");
verifyFormat("class __attribute__(X) Z {\n} n;");
verifyFormat("class __declspec(X) Z {\n} n;");
verifyFormat("class A##B##C {\n} n;");
verifyFormat("class alignas(16) Z {\n} n;");
verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
verifyFormat("class MACROA MACRO(X) Z {\n} n;");
// Redefinition from nested context:
verifyFormat("class A::B::C {\n} n;");
// Template definitions.
verifyFormat(
"template <typename F>\n"
"Matcher(const Matcher<F> &Other,\n"
" typename enable_if_c<is_base_of<F, T>::value &&\n"
" !is_same<F, T>::value>::type * = 0)\n"
" : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
// FIXME: This is still incorrectly handled at the formatter side.
verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
verifyFormat("int i = SomeFunction(a<b, a> b);");
// FIXME:
// This now gets parsed incorrectly as class definition.
// verifyFormat("class A<int> f() {\n}\nint n;");
// Elaborate types where incorrectly parsing the structural element would
// break the indent.
verifyFormat("if (true)\n"
" class X x;\n"
"else\n"
" f();\n");
// This is simply incomplete. Formatting is not important, but must not crash.
verifyFormat("class A:");
}
TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
EXPECT_EQ("#error Leave all white!!!!! space* alone!\n",
format("#error Leave all white!!!!! space* alone!\n"));
EXPECT_EQ(
"#warning Leave all white!!!!! space* alone!\n",
format("#warning Leave all white!!!!! space* alone!\n"));
EXPECT_EQ("#error 1", format(" # error 1"));
EXPECT_EQ("#warning 1", format(" # warning 1"));
}
TEST_F(FormatTest, FormatHashIfExpressions) {
verifyFormat("#if AAAA && BBBB");
verifyFormat("#if (AAAA && BBBB)");
verifyFormat("#elif (AAAA && BBBB)");
// FIXME: Come up with a better indentation for #elif.
verifyFormat(
"#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n"
" defined(BBBBBBBB)\n"
"#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n"
" defined(BBBBBBBB)\n"
"#endif",
getLLVMStyleWithColumns(65));
}
TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
FormatStyle AllowsMergedIf = getGoogleStyle();
AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf);
EXPECT_EQ("if (true) return 42;",
format("if (true)\nreturn 42;", AllowsMergedIf));
FormatStyle ShortMergedIf = AllowsMergedIf;
ShortMergedIf.ColumnLimit = 25;
verifyFormat("#define A \\\n"
" if (true) return 42;",
ShortMergedIf);
verifyFormat("#define A \\\n"
" f(); \\\n"
" if (true)\n"
"#define B",
ShortMergedIf);
verifyFormat("#define A \\\n"
" f(); \\\n"
" if (true)\n"
"g();",
ShortMergedIf);
verifyFormat("{\n"
"#ifdef A\n"
" // Comment\n"
" if (true) continue;\n"
"#endif\n"
" // Comment\n"
" if (true) continue;\n"
"}",
ShortMergedIf);
ShortMergedIf.ColumnLimit = 29;
verifyFormat("#define A \\\n"
" if (aaaaaaaaaa) return 1; \\\n"
" return 2;",
ShortMergedIf);
ShortMergedIf.ColumnLimit = 28;
verifyFormat("#define A \\\n"
" if (aaaaaaaaaa) \\\n"
" return 1; \\\n"
" return 2;",
ShortMergedIf);
}
TEST_F(FormatTest, BlockCommentsInControlLoops) {
verifyFormat("if (0) /* a comment in a strange place */ {\n"
" f();\n"
"}");
verifyFormat("if (0) /* a comment in a strange place */ {\n"
" f();\n"
"} /* another comment */ else /* comment #3 */ {\n"
" g();\n"
"}");
verifyFormat("while (0) /* a comment in a strange place */ {\n"
" f();\n"
"}");
verifyFormat("for (;;) /* a comment in a strange place */ {\n"
" f();\n"
"}");
verifyFormat("do /* a comment in a strange place */ {\n"
" f();\n"
"} /* another comment */ while (0);");
}
TEST_F(FormatTest, BlockComments) {
EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
format("/* *//* */ /* */\n/* *//* */ /* */"));
EXPECT_EQ("/* */ a /* */ b;", format(" /* */ a/* */ b;"));
EXPECT_EQ("#define A /*123*/ \\\n"
" b\n"
"/* */\n"
"someCall(\n"
" parameter);",
format("#define A /*123*/ b\n"
"/* */\n"
"someCall(parameter);",
getLLVMStyleWithColumns(15)));
EXPECT_EQ("#define A\n"
"/* */ someCall(\n"
" parameter);",
format("#define A\n"
"/* */someCall(parameter);",
getLLVMStyleWithColumns(15)));
EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
EXPECT_EQ("/*\n"
"*\n"
" * aaaaaa\n"
" * aaaaaa\n"
"*/",
format("/*\n"
"*\n"
" * aaaaaa aaaaaa\n"
"*/",
getLLVMStyleWithColumns(10)));
EXPECT_EQ("/*\n"
"**\n"
"* aaaaaa\n"
"*aaaaaa\n"
"*/",
format("/*\n"
"**\n"
"* aaaaaa aaaaaa\n"
"*/",
getLLVMStyleWithColumns(10)));
EXPECT_EQ("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" /* line 1\n"
" bbbbbbbbbbbb */\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
" /* line 1\n"
" bbbbbbbbbbbb */ bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
getLLVMStyleWithColumns(50)));
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
EXPECT_EQ("someFunction(1, /* comment 1 */\n"
" 2, /* comment 2 */\n"
" 3, /* comment 3 */\n"
" aaaa,\n"
" bbbb);",
format("someFunction (1, /* comment 1 */\n"
" 2, /* comment 2 */ \n"
" 3, /* comment 3 */\n"
"aaaa, bbbb );",
NoBinPacking));
verifyFormat(
"bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
EXPECT_EQ(
"bool aaaaaaaaaaaaa = /* trailing comment */\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
format(
"bool aaaaaaaaaaaaa = /* trailing comment */\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
EXPECT_EQ(
"int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
"int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
"int cccccccccccccccccccccccccccccc; /* comment */\n",
format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
"int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
"int cccccccccccccccccccccccccccccc; /* comment */\n"));
verifyFormat("void f(int * /* unused */) {}");
EXPECT_EQ("/*\n"
" **\n"
" */",
format("/*\n"
" **\n"
" */"));
EXPECT_EQ("/*\n"
" *q\n"
" */",
format("/*\n"
" *q\n"
" */"));
EXPECT_EQ("/*\n"
" * q\n"
" */",
format("/*\n"
" * q\n"
" */"));
EXPECT_EQ("/*\n"
" **/",
format("/*\n"
" **/"));
EXPECT_EQ("/*\n"
" ***/",
format("/*\n"
" ***/"));
}
TEST_F(FormatTest, BlockCommentsInMacros) {
EXPECT_EQ("#define A \\\n"
" { \\\n"
" /* one line */ \\\n"
" someCall();",
format("#define A { \\\n"
" /* one line */ \\\n"
" someCall();",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("#define A \\\n"
" { \\\n"
" /* previous */ \\\n"
" /* one line */ \\\n"
" someCall();",
format("#define A { \\\n"
" /* previous */ \\\n"
" /* one line */ \\\n"
" someCall();",
getLLVMStyleWithColumns(20)));
}
TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
EXPECT_EQ("a = {\n"
" 1111 /* */\n"
"};",
format("a = {1111 /* */\n"
"};",
getLLVMStyleWithColumns(15)));
EXPECT_EQ("a = {\n"
" 1111 /* */\n"
"};",
format("a = {1111 /* */\n"
"};",
getLLVMStyleWithColumns(15)));
// FIXME: The formatting is still wrong here.
EXPECT_EQ("a = {\n"
" 1111 /* a\n"
" */\n"
"};",
format("a = {1111 /* a */\n"
"};",
getLLVMStyleWithColumns(15)));
}
TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
verifyFormat("{\n"
" // a\n"
" // b");
}
TEST_F(FormatTest, FormatStarDependingOnContext) {
verifyFormat("void f(int *a);");
verifyFormat("void f() { f(fint * b); }");
verifyFormat("class A {\n void f(int *a);\n};");
verifyFormat("class A {\n int *a;\n};");
verifyFormat("namespace a {\n"
"namespace b {\n"
"class A {\n"
" void f() {}\n"
" int *a;\n"
"};\n"
"}\n"
"}");
}
TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
verifyFormat("while");
verifyFormat("operator");
}
TEST_F(FormatTest, SkipsDeeplyNestedLines) {
// This code would be painfully slow to format if we didn't skip it.
std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
"A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
"A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
"A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
"A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
"A(1, 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
// Deeply nested part is untouched, rest is formatted.
EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
format(std::string("int i;\n") + Code + "int j;\n",
getLLVMStyle(), IC_ExpectIncomplete));
}
//===----------------------------------------------------------------------===//
// Objective-C tests.
//===----------------------------------------------------------------------===//
TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
format("-(NSUInteger)indexOfObject:(id)anObject;"));
EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
format("-(NSInteger)Method3:(id)anObject;"));
EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
format("-(NSInteger)Method4:(id)anObject;"));
EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
"forAllCells:(BOOL)flag;",
format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
"forAllCells:(BOOL)flag;"));
// Very long objectiveC method declaration.
verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
" (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
" inRange:(NSRange)range\n"
" outRange:(NSRange)out_range\n"
" outRange1:(NSRange)out_range1\n"
" outRange2:(NSRange)out_range2\n"
" outRange3:(NSRange)out_range3\n"
" outRange4:(NSRange)out_range4\n"
" outRange5:(NSRange)out_range5\n"
" outRange6:(NSRange)out_range6\n"
" outRange7:(NSRange)out_range7\n"
" outRange8:(NSRange)out_range8\n"
" outRange9:(NSRange)out_range9;");
// When the function name has to be wrapped.
FormatStyle Style = getLLVMStyle();
Style.IndentWrappedFunctionNames = false;
verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
"veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
" anotherName:(NSString)bbbbbbbbbbbbbb {\n"
"}",
Style);
Style.IndentWrappedFunctionNames = true;
verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
" veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
" anotherName:(NSString)bbbbbbbbbbbbbb {\n"
"}",
Style);
verifyFormat("- (int)sum:(vector<int>)numbers;");
verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
// FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
// protocol lists (but not for template classes):
// verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
verifyFormat("- (int (*)())foo:(int (*)())f;");
verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
// If there's no return type (very rare in practice!), LLVM and Google style
// agree.
verifyFormat("- foo;");
verifyFormat("- foo:(int)f;");
verifyGoogleFormat("- foo:(int)foo;");
}
TEST_F(FormatTest, BreaksStringLiterals) {
EXPECT_EQ("\"some text \"\n"
"\"other\";",
format("\"some text other\";", getLLVMStyleWithColumns(12)));
EXPECT_EQ("\"some text \"\n"
"\"other\";",
format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
EXPECT_EQ(
"#define A \\\n"
" \"some \" \\\n"
" \"text \" \\\n"
" \"other\";",
format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
EXPECT_EQ(
"#define A \\\n"
" \"so \" \\\n"
" \"text \" \\\n"
" \"other\";",
format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
EXPECT_EQ("\"some text\"",
format("\"some text\"", getLLVMStyleWithColumns(1)));
EXPECT_EQ("\"some text\"",
format("\"some text\"", getLLVMStyleWithColumns(11)));
EXPECT_EQ("\"some \"\n"
"\"text\"",
format("\"some text\"", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"some \"\n"
"\"text\"",
format("\"some text\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"some\"\n"
"\" tex\"\n"
"\"t\"",
format("\"some text\"", getLLVMStyleWithColumns(6)));
EXPECT_EQ("\"some\"\n"
"\" tex\"\n"
"\" and\"",
format("\"some tex and\"", getLLVMStyleWithColumns(6)));
EXPECT_EQ("\"some\"\n"
"\"/tex\"\n"
"\"/and\"",
format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
EXPECT_EQ("variable =\n"
" \"long string \"\n"
" \"literal\";",
format("variable = \"long string literal\";",
getLLVMStyleWithColumns(20)));
EXPECT_EQ("variable = f(\n"
" \"long string \"\n"
" \"literal\",\n"
" short,\n"
" loooooooooooooooooooong);",
format("variable = f(\"long string literal\", short, "
"loooooooooooooooooooong);",
getLLVMStyleWithColumns(20)));
EXPECT_EQ(
"f(g(\"long string \"\n"
" \"literal\"),\n"
" b);",
format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
EXPECT_EQ("f(g(\"long string \"\n"
" \"literal\",\n"
" a),\n"
" b);",
format("f(g(\"long string literal\", a), b);",
getLLVMStyleWithColumns(20)));
EXPECT_EQ(
"f(\"one two\".split(\n"
" variable));",
format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
EXPECT_EQ("f(\"one two three four five six \"\n"
" \"seven\".split(\n"
" really_looooong_variable));",
format("f(\"one two three four five six seven\"."
"split(really_looooong_variable));",
getLLVMStyleWithColumns(33)));
EXPECT_EQ("f(\"some \"\n"
" \"text\",\n"
" other);",
format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
// Only break as a last resort.
verifyFormat(
"aaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
EXPECT_EQ("\"splitmea\"\n"
"\"trandomp\"\n"
"\"oint\"",
format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"split/\"\n"
"\"pathat/\"\n"
"\"slashes\"",
format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"split/\"\n"
"\"pathat/\"\n"
"\"slashes\"",
format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"split at \"\n"
"\"spaces/at/\"\n"
"\"slashes.at.any$\"\n"
"\"non-alphanumeric%\"\n"
"\"1111111111characte\"\n"
"\"rs\"",
format("\"split at "
"spaces/at/"
"slashes.at."
"any$non-"
"alphanumeric%"
"1111111111characte"
"rs\"",
getLLVMStyleWithColumns(20)));
// Verify that splitting the strings understands
// Style::AlwaysBreakBeforeMultilineStrings.
EXPECT_EQ(
"aaaaaaaaaaaa(\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaaa\");",
getGoogleStyle()));
EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
format("return \"aaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaaa\";",
getGoogleStyle()));
EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
format("llvm::outs() << "
"\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaa\";"));
EXPECT_EQ("ffff(\n"
" {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
getGoogleStyle()));
FormatStyle Style = getLLVMStyleWithColumns(12);
Style.BreakStringLiterals = false;
EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
AlignLeft.AlignEscapedNewlinesLeft = true;
EXPECT_EQ("#define A \\\n"
" \"some \" \\\n"
" \"text \" \\\n"
" \"other\";",
format("#define A \"some text other\";", AlignLeft));
}
TEST_F(FormatTest, FullyRemoveEmptyLines) {
FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
NoEmptyLines.MaxEmptyLinesToKeep = 0;
EXPECT_EQ("int i = a(b());",
format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
}
TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
EXPECT_EQ(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"(\n"
" \"x\t\");",
format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaa("
"\"x\t\");"));
}
TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
EXPECT_EQ(
"u8\"utf8 string \"\n"
"u8\"literal\";",
format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
EXPECT_EQ(
"u\"utf16 string \"\n"
"u\"literal\";",
format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
EXPECT_EQ(
"U\"utf32 string \"\n"
"U\"literal\";",
format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
EXPECT_EQ("L\"wide string \"\n"
"L\"literal\";",
format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
EXPECT_EQ("@\"NSString \"\n"
"@\"literal\";",
format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
// This input makes clang-format try to split the incomplete unicode escape
// sequence, which used to lead to a crasher.
verifyNoCrash(
"aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
getLLVMStyleWithColumns(60));
}
TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
FormatStyle Style = getGoogleStyleWithColumns(15);
EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
EXPECT_EQ("u8R\"x(raw literal)x\";",
format("u8R\"x(raw literal)x\";", Style));
}
TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
FormatStyle Style = getLLVMStyleWithColumns(20);
EXPECT_EQ(
"_T(\"aaaaaaaaaaaaaa\")\n"
"_T(\"aaaaaaaaaaaaaa\")\n"
"_T(\"aaaaaaaaaaaa\")",
format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
EXPECT_EQ("f(x, _T(\"aaaaaaaaa\")\n"
" _T(\"aaaaaa\"),\n"
" z);",
format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
// FIXME: Handle embedded spaces in one iteration.
// EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
// "_T(\"aaaaaaaaaaaaa\")\n"
// "_T(\"aaaaaaaaaaaaa\")\n"
// "_T(\"a\")",
// format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
// getLLVMStyleWithColumns(20)));
EXPECT_EQ(
"_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
EXPECT_EQ("f(\n"
"#if !TEST\n"
" _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
"#endif\n"
" );",
format("f(\n"
"#if !TEST\n"
"_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
"#endif\n"
");"));
EXPECT_EQ("f(\n"
"\n"
" _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
format("f(\n"
"\n"
"_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
}
TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
EXPECT_EQ(
"aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
}
TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle()));
EXPECT_EQ("fffffffffff(g(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\",\n"
" a),\n"
" b);",
format("fffffffffff(g(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\", a), b);",
getGoogleStyleWithColumns(20)));
EXPECT_EQ("fffffffffff(\n"
" g(R\"x(qqq\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\",\n"
" a),\n"
" b);",
format("fffffffffff(g(R\"x(qqq\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\", a), b);",
getGoogleStyleWithColumns(20)));
EXPECT_EQ("fffffffffff(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\");",
format("fffffffffff(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\");",
getGoogleStyleWithColumns(20)));
EXPECT_EQ("fffffffffff(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\" + bbbbbb);",
format("fffffffffff(R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\" + bbbbbb);",
getGoogleStyleWithColumns(20)));
EXPECT_EQ("fffffffffff(\n"
" R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\" +\n"
" bbbbbb);",
format("fffffffffff(\n"
" R\"x(\n"
"multiline raw string literal xxxxxxxxxxxxxx\n"
")x\" + bbbbbb);",
getGoogleStyleWithColumns(20)));
}
TEST_F(FormatTest, SkipsUnknownStringLiterals) {
verifyFormat("string a = \"unterminated;");
EXPECT_EQ("function(\"unterminated,\n"
" OtherParameter);",
format("function( \"unterminated,\n"
" OtherParameter);"));
}
TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
FormatStyle Style = getLLVMStyle();
Style.Standard = FormatStyle::LS_Cpp03;
EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
format("#define x(_a) printf(\"foo\"_a);", Style));
}
TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
" \"ddeeefff\");",
format("someFunction(\"aaabbbcccdddeeefff\");",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("someFunction1234567890(\n"
" \"aaabbbcccdddeeefff\");",
format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
getLLVMStyleWithColumns(26)));
EXPECT_EQ("someFunction1234567890(\n"
" \"aaabbbcccdddeeeff\"\n"
" \"f\");",
format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("someFunction1234567890(\n"
" \"aaabbbcccdddeeeff\"\n"
" \"f\");",
format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
getLLVMStyleWithColumns(24)));
EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
" \"ddde \"\n"
" \"efff\");",
format("someFunction(\"aaabbbcc ddde efff\");",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
" \"ddeeefff\");",
format("someFunction(\"aaabbbccc ddeeefff\");",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("someFunction1234567890(\n"
" \"aaabb \"\n"
" \"cccdddeeefff\");",
format("someFunction1234567890(\"aaabb cccdddeeefff\");",
getLLVMStyleWithColumns(25)));
EXPECT_EQ("#define A \\\n"
" string s = \\\n"
" \"123456789\" \\\n"
" \"0\"; \\\n"
" int i;",
format("#define A string s = \"1234567890\"; int i;",
getLLVMStyleWithColumns(20)));
// FIXME: Put additional penalties on breaking at non-whitespace locations.
EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
" \"dddeeeff\"\n"
" \"f\");",
format("someFunction(\"aaabbbcc dddeeefff\");",
getLLVMStyleWithColumns(25)));
}
TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
EXPECT_EQ("\"test\"\n"
"\"\\n\"",
format("\"test\\n\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"tes\\\\\"\n"
"\"n\"",
format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"\\\\\\\\\"\n"
"\"\\n\"",
format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"\\uff01\"\n"
"\"test\"",
format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
EXPECT_EQ("\"\\Uff01ff02\"",
format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
EXPECT_EQ("\"\\x000000000001\"\n"
"\"next\"",
format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
EXPECT_EQ("\"\\x000000000001next\"",
format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
EXPECT_EQ("\"\\x000000000001\"",
format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
EXPECT_EQ("\"test\"\n"
"\"\\000000\"\n"
"\"000001\"",
format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
EXPECT_EQ("\"test\\000\"\n"
"\"00000000\"\n"
"\"1\"",
format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
}
TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
verifyFormat("void f() {\n"
" return g() {}\n"
" void h() {}");
verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
"g();\n"
"}");
}
TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
verifyFormat(
"void f() { return C{param1, param2}.SomeCall(param1, param2); }");
}
TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
verifyFormat("class X {\n"
" void f() {\n"
" }\n"
"};",
getLLVMStyleWithColumns(12));
}
TEST_F(FormatTest, ConfigurableIndentWidth) {
FormatStyle EightIndent = getLLVMStyleWithColumns(18);
EightIndent.IndentWidth = 8;
EightIndent.ContinuationIndentWidth = 8;
verifyFormat("void f() {\n"
" someFunction();\n"
" if (true) {\n"
" f();\n"
" }\n"
"}",
EightIndent);
verifyFormat("class X {\n"
" void f() {\n"
" }\n"
"};",
EightIndent);
verifyFormat("int x[] = {\n"
" call(),\n"
" call()};",
EightIndent);
}
TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
verifyFormat("double\n"
"f();",
getLLVMStyleWithColumns(8));
}
TEST_F(FormatTest, ConfigurableUseOfTab) {
FormatStyle Tab = getLLVMStyleWithColumns(42);
Tab.IndentWidth = 8;
Tab.UseTab = FormatStyle::UT_Always;
Tab.AlignEscapedNewlinesLeft = true;
EXPECT_EQ("if (aaaaaaaa && // q\n"
" bb)\t\t// w\n"
"\t;",
format("if (aaaaaaaa &&// q\n"
"bb)// w\n"
";",
Tab));
EXPECT_EQ("if (aaa && bbb) // w\n"
"\t;",
format("if(aaa&&bbb)// w\n"
";",
Tab));
verifyFormat("class X {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
verifyFormat("#define A \\\n"
"\tvoid f() { \\\n"
"\t\tsomeFunction( \\\n"
"\t\t parameter1, \\\n"
"\t\t parameter2); \\\n"
"\t}",
Tab);
Tab.TabWidth = 4;
Tab.IndentWidth = 8;
verifyFormat("class TabWidth4Indent8 {\n"
"\t\tvoid f() {\n"
"\t\t\t\tsomeFunction(parameter1,\n"
"\t\t\t\t\t\t\t parameter2);\n"
"\t\t}\n"
"};",
Tab);
Tab.TabWidth = 4;
Tab.IndentWidth = 4;
verifyFormat("class TabWidth4Indent4 {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t\t\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
Tab.TabWidth = 8;
Tab.IndentWidth = 4;
verifyFormat("class TabWidth8Indent4 {\n"
" void f() {\n"
"\tsomeFunction(parameter1,\n"
"\t\t parameter2);\n"
" }\n"
"};",
Tab);
Tab.TabWidth = 8;
Tab.IndentWidth = 8;
EXPECT_EQ("/*\n"
"\t a\t\tcomment\n"
"\t in multiple lines\n"
" */",
format(" /*\t \t \n"
" \t \t a\t\tcomment\t \t\n"
" \t \t in multiple lines\t\n"
" \t */",
Tab));
Tab.UseTab = FormatStyle::UT_ForIndentation;
verifyFormat("{\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"};",
Tab);
verifyFormat("enum AA {\n"
"\ta1, // Force multiple lines\n"
"\ta2,\n"
"\ta3\n"
"};",
Tab);
EXPECT_EQ("if (aaaaaaaa && // q\n"
" bb) // w\n"
"\t;",
format("if (aaaaaaaa &&// q\n"
"bb)// w\n"
";",
Tab));
verifyFormat("class X {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
verifyFormat("{\n"
"\tQ(\n"
"\t {\n"
"\t\t int a;\n"
"\t\t someFunction(aaaaaaaa,\n"
"\t\t bbbbbbb);\n"
"\t },\n"
"\t p);\n"
"}",
Tab);
EXPECT_EQ("{\n"
"\t/* aaaa\n"
"\t bbbb */\n"
"}",
format("{\n"
"/* aaaa\n"
" bbbb */\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
format("{\n"
"/*\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t// bbbbbbbbbbbbb\n"
"}",
format("{\n"
"\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
"\n"
"\t*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
" asdf\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
" asdf\n"
"\t*/\n"
"}",
Tab));
Tab.UseTab = FormatStyle::UT_Never;
EXPECT_EQ("/*\n"
" a\t\tcomment\n"
" in multiple lines\n"
" */",
format(" /*\t \t \n"
" \t \t a\t\tcomment\t \t\n"
" \t \t in multiple lines\t\n"
" \t */",
Tab));
EXPECT_EQ("/* some\n"
" comment */",
format(" \t \t /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("int a; /* some\n"
" comment */",
format(" \t \t int a; /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("int a; /* some\n"
"comment */",
format(" \t \t int\ta; /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("f(\"\t\t\"); /* some\n"
" comment */",
format(" \t \t f(\"\t\t\"); /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("{\n"
" /*\n"
" * Comment\n"
" */\n"
" int i;\n"
"}",
format("{\n"
"\t/*\n"
"\t * Comment\n"
"\t */\n"
"\t int i;\n"
"}"));
Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
Tab.TabWidth = 8;
Tab.IndentWidth = 8;
EXPECT_EQ("if (aaaaaaaa && // q\n"
" bb) // w\n"
"\t;",
format("if (aaaaaaaa &&// q\n"
"bb)// w\n"
";",
Tab));
EXPECT_EQ("if (aaa && bbb) // w\n"
"\t;",
format("if(aaa&&bbb)// w\n"
";",
Tab));
verifyFormat("class X {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
verifyFormat("#define A \\\n"
"\tvoid f() { \\\n"
"\t\tsomeFunction( \\\n"
"\t\t parameter1, \\\n"
"\t\t parameter2); \\\n"
"\t}",
Tab);
Tab.TabWidth = 4;
Tab.IndentWidth = 8;
verifyFormat("class TabWidth4Indent8 {\n"
"\t\tvoid f() {\n"
"\t\t\t\tsomeFunction(parameter1,\n"
"\t\t\t\t\t\t\t parameter2);\n"
"\t\t}\n"
"};",
Tab);
Tab.TabWidth = 4;
Tab.IndentWidth = 4;
verifyFormat("class TabWidth4Indent4 {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t\t\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
Tab.TabWidth = 8;
Tab.IndentWidth = 4;
verifyFormat("class TabWidth8Indent4 {\n"
" void f() {\n"
"\tsomeFunction(parameter1,\n"
"\t\t parameter2);\n"
" }\n"
"};",
Tab);
Tab.TabWidth = 8;
Tab.IndentWidth = 8;
EXPECT_EQ("/*\n"
"\t a\t\tcomment\n"
"\t in multiple lines\n"
" */",
format(" /*\t \t \n"
" \t \t a\t\tcomment\t \t\n"
" \t \t in multiple lines\t\n"
" \t */",
Tab));
verifyFormat("{\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"};",
Tab);
verifyFormat("enum AA {\n"
"\ta1, // Force multiple lines\n"
"\ta2,\n"
"\ta3\n"
"};",
Tab);
EXPECT_EQ("if (aaaaaaaa && // q\n"
" bb) // w\n"
"\t;",
format("if (aaaaaaaa &&// q\n"
"bb)// w\n"
";",
Tab));
verifyFormat("class X {\n"
"\tvoid f() {\n"
"\t\tsomeFunction(parameter1,\n"
"\t\t\t parameter2);\n"
"\t}\n"
"};",
Tab);
verifyFormat("{\n"
"\tQ(\n"
"\t {\n"
"\t\t int a;\n"
"\t\t someFunction(aaaaaaaa,\n"
"\t\t\t\t bbbbbbb);\n"
"\t },\n"
"\t p);\n"
"}",
Tab);
EXPECT_EQ("{\n"
"\t/* aaaa\n"
"\t bbbb */\n"
"}",
format("{\n"
"/* aaaa\n"
" bbbb */\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
format("{\n"
"/*\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t// bbbbbbbbbbbbb\n"
"}",
format("{\n"
"\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
"\t bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
"\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
"\t*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
"\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
"\n"
"\t*/\n"
"}",
Tab));
EXPECT_EQ("{\n"
"\t/*\n"
" asdf\n"
"\t*/\n"
"}",
format("{\n"
"\t/*\n"
" asdf\n"
"\t*/\n"
"}",
Tab));
EXPECT_EQ("/*\n"
"\t a\t\tcomment\n"
"\t in multiple lines\n"
" */",
format(" /*\t \t \n"
" \t \t a\t\tcomment\t \t\n"
" \t \t in multiple lines\t\n"
" \t */",
Tab));
EXPECT_EQ("/* some\n"
" comment */",
format(" \t \t /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("int a; /* some\n"
" comment */",
format(" \t \t int a; /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("int a; /* some\n"
"comment */",
format(" \t \t int\ta; /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("f(\"\t\t\"); /* some\n"
" comment */",
format(" \t \t f(\"\t\t\"); /* some\n"
" \t \t comment */",
Tab));
EXPECT_EQ("{\n"
" /*\n"
" * Comment\n"
" */\n"
" int i;\n"
"}",
format("{\n"
"\t/*\n"
"\t * Comment\n"
"\t */\n"
"\t int i;\n"
"}"));
Tab.AlignConsecutiveAssignments = true;
Tab.AlignConsecutiveDeclarations = true;
Tab.TabWidth = 4;
Tab.IndentWidth = 4;
verifyFormat("class Assign {\n"
"\tvoid f() {\n"
"\t\tint x = 123;\n"
"\t\tint random = 4;\n"
"\t\tstd::string alphabet =\n"
"\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
"\t}\n"
"};",
Tab);
}
TEST_F(FormatTest, CalculatesOriginalColumn) {
EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"q\"; /* some\n"
" comment */",
format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"q\"; /* some\n"
" comment */",
getLLVMStyle()));
EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
"/* some\n"
" comment */",
format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
" /* some\n"
" comment */",
getLLVMStyle()));
EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"qqq\n"
"/* some\n"
" comment */",
format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"qqq\n"
" /* some\n"
" comment */",
getLLVMStyle()));
EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"wwww; /* some\n"
" comment */",
format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
"wwww; /* some\n"
" comment */",
getLLVMStyle()));
}
TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
FormatStyle NoSpace = getLLVMStyle();
NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
verifyFormat("while(true)\n"
" continue;",
NoSpace);
verifyFormat("for(;;)\n"
" continue;",
NoSpace);
verifyFormat("if(true)\n"
" f();\n"
"else if(true)\n"
" f();",
NoSpace);
verifyFormat("do {\n"
" do_something();\n"
"} while(something());",
NoSpace);
verifyFormat("switch(x) {\n"
"default:\n"
" break;\n"
"}",
NoSpace);
verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
verifyFormat("size_t x = sizeof(x);", NoSpace);
verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
verifyFormat("alignas(128) char a[128];", NoSpace);
verifyFormat("size_t x = alignof(MyType);", NoSpace);
verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
verifyFormat("int f() throw(Deprecated);", NoSpace);
verifyFormat("typedef void (*cb)(int);", NoSpace);
verifyFormat("T A::operator()();", NoSpace);
verifyFormat("X A::operator++(T);", NoSpace);
FormatStyle Space = getLLVMStyle();
Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
verifyFormat("int f ();", Space);
verifyFormat("void f (int a, T b) {\n"
" while (true)\n"
" continue;\n"
"}",
Space);
verifyFormat("if (true)\n"
" f ();\n"
"else if (true)\n"
" f ();",
Space);
verifyFormat("do {\n"
" do_something ();\n"
"} while (something ());",
Space);
verifyFormat("switch (x) {\n"
"default:\n"
" break;\n"
"}",
Space);
verifyFormat("A::A () : a (1) {}", Space);
verifyFormat("void f () __attribute__ ((asdf));", Space);
verifyFormat("*(&a + 1);\n"
"&((&a)[1]);\n"
"a[(b + c) * d];\n"
"(((a + 1) * 2) + 3) * 4;",
Space);
verifyFormat("#define A(x) x", Space);
verifyFormat("#define A (x) x", Space);
verifyFormat("#if defined(x)\n"
"#endif",
Space);
verifyFormat("auto i = std::make_unique<int> (5);", Space);
verifyFormat("size_t x = sizeof (x);", Space);
verifyFormat("auto f (int x) -> decltype (x);", Space);
verifyFormat("int f (T x) noexcept (x.create ());", Space);
verifyFormat("alignas (128) char a[128];", Space);
verifyFormat("size_t x = alignof (MyType);", Space);
verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
verifyFormat("int f () throw (Deprecated);", Space);
verifyFormat("typedef void (*cb) (int);", Space);
verifyFormat("T A::operator() ();", Space);
verifyFormat("X A::operator++ (T);", Space);
}
TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInParentheses = true;
verifyFormat("call( x, y, z );", Spaces);
verifyFormat("call();", Spaces);
verifyFormat("std::function<void( int, int )> callback;", Spaces);
verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
Spaces);
verifyFormat("while ( (bool)1 )\n"
" continue;",
Spaces);
verifyFormat("for ( ;; )\n"
" continue;",
Spaces);
verifyFormat("if ( true )\n"
" f();\n"
"else if ( true )\n"
" f();",
Spaces);
verifyFormat("do {\n"
" do_something( (int)i );\n"
"} while ( something() );",
Spaces);
verifyFormat("switch ( x ) {\n"
"default:\n"
" break;\n"
"}",
Spaces);
Spaces.SpacesInParentheses = false;
Spaces.SpacesInCStyleCastParentheses = true;
verifyFormat("Type *A = ( Type * )P;", Spaces);
verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
verifyFormat("x = ( int32 )y;", Spaces);
verifyFormat("int a = ( int )(2.0f);", Spaces);
verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
verifyFormat("#define x (( int )-1)", Spaces);
// Run the first set of tests again with:
Spaces.SpacesInParentheses = false;
Spaces.SpaceInEmptyParentheses = true;
Spaces.SpacesInCStyleCastParentheses = true;
verifyFormat("call(x, y, z);", Spaces);
verifyFormat("call( );", Spaces);
verifyFormat("std::function<void(int, int)> callback;", Spaces);
verifyFormat("while (( bool )1)\n"
" continue;",
Spaces);
verifyFormat("for (;;)\n"
" continue;",
Spaces);
verifyFormat("if (true)\n"
" f( );\n"
"else if (true)\n"
" f( );",
Spaces);
verifyFormat("do {\n"
" do_something(( int )i);\n"
"} while (something( ));",
Spaces);
verifyFormat("switch (x) {\n"
"default:\n"
" break;\n"
"}",
Spaces);
// Run the first set of tests again with:
Spaces.SpaceAfterCStyleCast = true;
verifyFormat("call(x, y, z);", Spaces);
verifyFormat("call( );", Spaces);
verifyFormat("std::function<void(int, int)> callback;", Spaces);
verifyFormat("while (( bool ) 1)\n"
" continue;",
Spaces);
verifyFormat("for (;;)\n"
" continue;",
Spaces);
verifyFormat("if (true)\n"
" f( );\n"
"else if (true)\n"
" f( );",
Spaces);
verifyFormat("do {\n"
" do_something(( int ) i);\n"
"} while (something( ));",
Spaces);
verifyFormat("switch (x) {\n"
"default:\n"
" break;\n"
"}",
Spaces);
// Run subset of tests again with:
Spaces.SpacesInCStyleCastParentheses = false;
Spaces.SpaceAfterCStyleCast = true;
verifyFormat("while ((bool) 1)\n"
" continue;",
Spaces);
verifyFormat("do {\n"
" do_something((int) i);\n"
"} while (something( ));",
Spaces);
}
TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
verifyFormat("int a[5];");
verifyFormat("a[3] += 42;");
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInSquareBrackets = true;
// Lambdas unchanged.
verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
verifyFormat("return [i, args...] {};", Spaces);
// Not lambdas.
verifyFormat("int a[ 5 ];", Spaces);
verifyFormat("a[ 3 ] += 42;", Spaces);
verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
verifyFormat("double &operator[](int i) { return 0; }\n"
"int i;",
Spaces);
verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
verifyFormat("int i = (*b)[ a ]->f();", Spaces);
}
TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
verifyFormat("int a = 5;");
verifyFormat("a += 42;");
verifyFormat("a or_eq 8;");
FormatStyle Spaces = getLLVMStyle();
Spaces.SpaceBeforeAssignmentOperators = false;
verifyFormat("int a= 5;", Spaces);
verifyFormat("a+= 42;", Spaces);
verifyFormat("a or_eq 8;", Spaces);
}
TEST_F(FormatTest, AlignConsecutiveAssignments) {
FormatStyle Alignment = getLLVMStyle();
Alignment.AlignConsecutiveAssignments = false;
verifyFormat("int a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
verifyFormat("int a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
Alignment.AlignConsecutiveAssignments = true;
verifyFormat("int a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
verifyFormat("int a = method();\n"
"int oneTwoThree = 133;",
Alignment);
verifyFormat("a &= 5;\n"
"bcd *= 5;\n"
"ghtyf += 5;\n"
"dvfvdb -= 5;\n"
"a /= 5;\n"
"vdsvsv %= 5;\n"
"sfdbddfbdfbb ^= 5;\n"
"dvsdsv |= 5;\n"
"int dsvvdvsdvvv = 123;",
Alignment);
verifyFormat("int i = 1, j = 10;\n"
"something = 2000;",
Alignment);
verifyFormat("something = 2000;\n"
"int i = 1, j = 10;\n",
Alignment);
verifyFormat("something = 2000;\n"
"another = 911;\n"
"int i = 1, j = 10;\n"
"oneMore = 1;\n"
"i = 2;",
Alignment);
verifyFormat("int a = 5;\n"
"int one = 1;\n"
"method();\n"
"int oneTwoThree = 123;\n"
"int oneTwo = 12;",
Alignment);
verifyFormat("int oneTwoThree = 123;\n"
"int oneTwo = 12;\n"
"method();\n",
Alignment);
verifyFormat("int oneTwoThree = 123; // comment\n"
"int oneTwo = 12; // comment",
Alignment);
EXPECT_EQ("int a = 5;\n"
"\n"
"int oneTwoThree = 123;",
format("int a = 5;\n"
"\n"
"int oneTwoThree= 123;",
Alignment));
EXPECT_EQ("int a = 5;\n"
"int one = 1;\n"
"\n"
"int oneTwoThree = 123;",
format("int a = 5;\n"
"int one = 1;\n"
"\n"
"int oneTwoThree = 123;",
Alignment));
EXPECT_EQ("int a = 5;\n"
"int one = 1;\n"
"\n"
"int oneTwoThree = 123;\n"
"int oneTwo = 12;",
format("int a = 5;\n"
"int one = 1;\n"
"\n"
"int oneTwoThree = 123;\n"
"int oneTwo = 12;",
Alignment));
Alignment.AlignEscapedNewlinesLeft = true;
verifyFormat("#define A \\\n"
" int aaaa = 12; \\\n"
" int b = 23; \\\n"
" int ccc = 234; \\\n"
" int dddddddddd = 2345;",
Alignment);
Alignment.AlignEscapedNewlinesLeft = false;
verifyFormat("#define A "
" \\\n"
" int aaaa = 12; "
" \\\n"
" int b = 23; "
" \\\n"
" int ccc = 234; "
" \\\n"
" int dddddddddd = 2345;",
Alignment);
verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
"k = 4, int l = 5,\n"
" int m = 6) {\n"
" int j = 10;\n"
" otherThing = 1;\n"
"}",
Alignment);
verifyFormat("void SomeFunction(int parameter = 0) {\n"
" int i = 1;\n"
" int j = 2;\n"
" int big = 10000;\n"
"}",
Alignment);
verifyFormat("class C {\n"
"public:\n"
" int i = 1;\n"
" virtual void f() = 0;\n"
"};",
Alignment);
verifyFormat("int i = 1;\n"
"if (SomeType t = getSomething()) {\n"
"}\n"
"int j = 2;\n"
"int big = 10000;",
Alignment);
verifyFormat("int j = 7;\n"
"for (int k = 0; k < N; ++k) {\n"
"}\n"
"int j = 2;\n"
"int big = 10000;\n"
"}",
Alignment);
Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
verifyFormat("int i = 1;\n"
"LooooooooooongType loooooooooooooooooooooongVariable\n"
" = someLooooooooooooooooongFunction();\n"
"int j = 2;",
Alignment);
Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
verifyFormat("int i = 1;\n"
"LooooooooooongType loooooooooooooooooooooongVariable =\n"
" someLooooooooooooooooongFunction();\n"
"int j = 2;",
Alignment);
verifyFormat("auto lambda = []() {\n"
" auto i = 0;\n"
" return 0;\n"
"};\n"
"int i = 0;\n"
"auto v = type{\n"
" i = 1, //\n"
" (i = 2), //\n"
" i = 3 //\n"
"};",
Alignment);
// FIXME: Should align all three assignments
verifyFormat(
"int i = 1;\n"
"SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
" loooooooooooooooooooooongParameterB);\n"
"int j = 2;",
Alignment);
verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
" typename B = very_long_type_name_1,\n"
" typename T_2 = very_long_type_name_2>\n"
"auto foo() {}\n",
Alignment);
verifyFormat("int a, b = 1;\n"
"int c = 2;\n"
"int dd = 3;\n",
Alignment);
verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
"float b[1][] = {{3.f}};\n",
Alignment);
}
TEST_F(FormatTest, AlignConsecutiveDeclarations) {
FormatStyle Alignment = getLLVMStyle();
Alignment.AlignConsecutiveDeclarations = false;
verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
verifyFormat("int a = 5;\n"
"float const oneTwoThree = 123;",
Alignment);
Alignment.AlignConsecutiveDeclarations = true;
verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
verifyFormat("int a = method();\n"
"float const oneTwoThree = 133;",
Alignment);
verifyFormat("int i = 1, j = 10;\n"
"something = 2000;",
Alignment);
verifyFormat("something = 2000;\n"
"int i = 1, j = 10;\n",
Alignment);
verifyFormat("float something = 2000;\n"
"double another = 911;\n"
"int i = 1, j = 10;\n"
"const int *oneMore = 1;\n"
"unsigned i = 2;",
Alignment);
verifyFormat("float a = 5;\n"
"int one = 1;\n"
"method();\n"
"const double oneTwoThree = 123;\n"
"const unsigned int oneTwo = 12;",
Alignment);
verifyFormat("int oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
EXPECT_EQ("float const a = 5;\n"
"\n"
"int oneTwoThree = 123;",
format("float const a = 5;\n"
"\n"
"int oneTwoThree= 123;",
Alignment));
EXPECT_EQ("float a = 5;\n"
"int one = 1;\n"
"\n"
"unsigned oneTwoThree = 123;",
format("float a = 5;\n"
"int one = 1;\n"
"\n"
"unsigned oneTwoThree = 123;",
Alignment));
EXPECT_EQ("float a = 5;\n"
"int one = 1;\n"
"\n"
"unsigned oneTwoThree = 123;\n"
"int oneTwo = 12;",
format("float a = 5;\n"
"int one = 1;\n"
"\n"
"unsigned oneTwoThree = 123;\n"
"int oneTwo = 12;",
Alignment));
Alignment.AlignConsecutiveAssignments = true;
verifyFormat("float something = 2000;\n"
"double another = 911;\n"
"int i = 1, j = 10;\n"
"const int *oneMore = 1;\n"
"unsigned i = 2;",
Alignment);
verifyFormat("int oneTwoThree = {0}; // comment\n"
"unsigned oneTwo = 0; // comment",
Alignment);
EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
" int const i = 1;\n"
" int * j = 2;\n"
" int big = 10000;\n"
"\n"
" unsigned oneTwoThree = 123;\n"
" int oneTwo = 12;\n"
" method();\n"
" float k = 2;\n"
" int ll = 10000;\n"
"}",
format("void SomeFunction(int parameter= 0) {\n"
" int const i= 1;\n"
" int *j=2;\n"
" int big = 10000;\n"
"\n"
"unsigned oneTwoThree =123;\n"
"int oneTwo = 12;\n"
" method();\n"
"float k= 2;\n"
"int ll=10000;\n"
"}",
Alignment));
Alignment.AlignConsecutiveAssignments = false;
Alignment.AlignEscapedNewlinesLeft = true;
verifyFormat("#define A \\\n"
" int aaaa = 12; \\\n"
" float b = 23; \\\n"
" const int ccc = 234; \\\n"
" unsigned dddddddddd = 2345;",
Alignment);
Alignment.AlignEscapedNewlinesLeft = false;
Alignment.ColumnLimit = 30;
verifyFormat("#define A \\\n"
" int aaaa = 12; \\\n"
" float b = 23; \\\n"
" const int ccc = 234; \\\n"
" int dddddddddd = 2345;",
Alignment);
Alignment.ColumnLimit = 80;
verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
"k = 4, int l = 5,\n"
" int m = 6) {\n"
" const int j = 10;\n"
" otherThing = 1;\n"
"}",
Alignment);
verifyFormat("void SomeFunction(int parameter = 0) {\n"
" int const i = 1;\n"
" int * j = 2;\n"
" int big = 10000;\n"
"}",
Alignment);
verifyFormat("class C {\n"
"public:\n"
" int i = 1;\n"
" virtual void f() = 0;\n"
"};",
Alignment);
verifyFormat("float i = 1;\n"
"if (SomeType t = getSomething()) {\n"
"}\n"
"const unsigned j = 2;\n"
"int big = 10000;",
Alignment);
verifyFormat("float j = 7;\n"
"for (int k = 0; k < N; ++k) {\n"
"}\n"
"unsigned j = 2;\n"
"int big = 10000;\n"
"}",
Alignment);
Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
verifyFormat("float i = 1;\n"
"LooooooooooongType loooooooooooooooooooooongVariable\n"
" = someLooooooooooooooooongFunction();\n"
"int j = 2;",
Alignment);
Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
verifyFormat("int i = 1;\n"
"LooooooooooongType loooooooooooooooooooooongVariable =\n"
" someLooooooooooooooooongFunction();\n"
"int j = 2;",
Alignment);
Alignment.AlignConsecutiveAssignments = true;
verifyFormat("auto lambda = []() {\n"
" auto ii = 0;\n"
" float j = 0;\n"
" return 0;\n"
"};\n"
"int i = 0;\n"
"float i2 = 0;\n"
"auto v = type{\n"
" i = 1, //\n"
" (i = 2), //\n"
" i = 3 //\n"
"};",
Alignment);
Alignment.AlignConsecutiveAssignments = false;
// FIXME: Should align all three declarations
verifyFormat(
"int i = 1;\n"
"SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
" loooooooooooooooooooooongParameterB);\n"
"int j = 2;",
Alignment);
// Test interactions with ColumnLimit and AlignConsecutiveAssignments:
// We expect declarations and assignments to align, as long as it doesn't
// exceed the column limit, starting a new alignemnt sequence whenever it
// happens.
Alignment.AlignConsecutiveAssignments = true;
Alignment.ColumnLimit = 30;
verifyFormat("float ii = 1;\n"
"unsigned j = 2;\n"
"int someVerylongVariable = 1;\n"
"AnotherLongType ll = 123456;\n"
"VeryVeryLongType k = 2;\n"
"int myvar = 1;",
Alignment);
Alignment.ColumnLimit = 80;
Alignment.AlignConsecutiveAssignments = false;
verifyFormat(
"template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
" typename LongType, typename B>\n"
"auto foo() {}\n",
Alignment);
verifyFormat("float a, b = 1;\n"
"int c = 2;\n"
"int dd = 3;\n",
Alignment);
verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
"float b[1][] = {{3.f}};\n",
Alignment);
Alignment.AlignConsecutiveAssignments = true;
verifyFormat("float a, b = 1;\n"
"int c = 2;\n"
"int dd = 3;\n",
Alignment);
verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
"float b[1][] = {{3.f}};\n",
Alignment);
Alignment.AlignConsecutiveAssignments = false;
Alignment.ColumnLimit = 30;
Alignment.BinPackParameters = false;
verifyFormat("void foo(float a,\n"
" float b,\n"
" int c,\n"
" uint32_t *d) {\n"
" int * e = 0;\n"
" float f = 0;\n"
" double g = 0;\n"
"}\n"
"void bar(ino_t a,\n"
" int b,\n"
" uint32_t *c,\n"
" bool d) {}\n",
Alignment);
Alignment.BinPackParameters = true;
Alignment.ColumnLimit = 80;
}
TEST_F(FormatTest, LinuxBraceBreaking) {
FormatStyle LinuxBraceStyle = getLLVMStyle();
LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
verifyFormat("namespace a\n"
"{\n"
"class A\n"
"{\n"
" void f()\n"
" {\n"
" if (true) {\n"
" a();\n"
" b();\n"
" } else {\n"
" a();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"};\n"
"struct B {\n"
" int x;\n"
"};\n"
"}\n",
LinuxBraceStyle);
verifyFormat("enum X {\n"
" Y = 0,\n"
"}\n",
LinuxBraceStyle);
verifyFormat("struct S {\n"
" int Type;\n"
" union {\n"
" int x;\n"
" double y;\n"
" } Value;\n"
" class C\n"
" {\n"
" MyFavoriteType Value;\n"
" } Class;\n"
"}\n",
LinuxBraceStyle);
}
TEST_F(FormatTest, MozillaBraceBreaking) {
FormatStyle MozillaBraceStyle = getLLVMStyle();
MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
verifyFormat("namespace a {\n"
"class A\n"
"{\n"
" void f()\n"
" {\n"
" if (true) {\n"
" a();\n"
" b();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"};\n"
"enum E\n"
"{\n"
" A,\n"
" // foo\n"
" B,\n"
" C\n"
"};\n"
"struct B\n"
"{\n"
" int x;\n"
"};\n"
"}\n",
MozillaBraceStyle);
verifyFormat("struct S\n"
"{\n"
" int Type;\n"
" union\n"
" {\n"
" int x;\n"
" double y;\n"
" } Value;\n"
" class C\n"
" {\n"
" MyFavoriteType Value;\n"
" } Class;\n"
"}\n",
MozillaBraceStyle);
}
TEST_F(FormatTest, StroustrupBraceBreaking) {
FormatStyle StroustrupBraceStyle = getLLVMStyle();
StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
verifyFormat("namespace a {\n"
"class A {\n"
" void f()\n"
" {\n"
" if (true) {\n"
" a();\n"
" b();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"};\n"
"struct B {\n"
" int x;\n"
"};\n"
"}\n",
StroustrupBraceStyle);
verifyFormat("void foo()\n"
"{\n"
" if (a) {\n"
" a();\n"
" }\n"
" else {\n"
" b();\n"
" }\n"
"}\n",
StroustrupBraceStyle);
verifyFormat("#ifdef _DEBUG\n"
"int foo(int i = 0)\n"
"#else\n"
"int foo(int i = 5)\n"
"#endif\n"
"{\n"
" return i;\n"
"}",
StroustrupBraceStyle);
verifyFormat("void foo() {}\n"
"void bar()\n"
"#ifdef _DEBUG\n"
"{\n"
" foo();\n"
"}\n"
"#else\n"
"{\n"
"}\n"
"#endif",
StroustrupBraceStyle);
verifyFormat("void foobar() { int i = 5; }\n"
"#ifdef _DEBUG\n"
"void bar() {}\n"
"#else\n"
"void bar() { foobar(); }\n"
"#endif",
StroustrupBraceStyle);
}
TEST_F(FormatTest, AllmanBraceBreaking) {
FormatStyle AllmanBraceStyle = getLLVMStyle();
AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
verifyFormat("namespace a\n"
"{\n"
"class A\n"
"{\n"
" void f()\n"
" {\n"
" if (true)\n"
" {\n"
" a();\n"
" b();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"};\n"
"struct B\n"
"{\n"
" int x;\n"
"};\n"
"}",
AllmanBraceStyle);
verifyFormat("void f()\n"
"{\n"
" if (true)\n"
" {\n"
" a();\n"
" }\n"
" else if (false)\n"
" {\n"
" b();\n"
" }\n"
" else\n"
" {\n"
" c();\n"
" }\n"
"}\n",
AllmanBraceStyle);
verifyFormat("void f()\n"
"{\n"
" for (int i = 0; i < 10; ++i)\n"
" {\n"
" a();\n"
" }\n"
" while (false)\n"
" {\n"
" b();\n"
" }\n"
" do\n"
" {\n"
" c();\n"
" } while (false)\n"
"}\n",
AllmanBraceStyle);
verifyFormat("void f(int a)\n"
"{\n"
" switch (a)\n"
" {\n"
" case 0:\n"
" break;\n"
" case 1:\n"
" {\n"
" break;\n"
" }\n"
" case 2:\n"
" {\n"
" }\n"
" break;\n"
" default:\n"
" break;\n"
" }\n"
"}\n",
AllmanBraceStyle);
verifyFormat("enum X\n"
"{\n"
" Y = 0,\n"
"}\n",
AllmanBraceStyle);
verifyFormat("enum X\n"
"{\n"
" Y = 0\n"
"}\n",
AllmanBraceStyle);
verifyFormat("@interface BSApplicationController ()\n"
"{\n"
"@private\n"
" id _extraIvar;\n"
"}\n"
"@end\n",
AllmanBraceStyle);
verifyFormat("#ifdef _DEBUG\n"
"int foo(int i = 0)\n"
"#else\n"
"int foo(int i = 5)\n"
"#endif\n"
"{\n"
" return i;\n"
"}",
AllmanBraceStyle);
verifyFormat("void foo() {}\n"
"void bar()\n"
"#ifdef _DEBUG\n"
"{\n"
" foo();\n"
"}\n"
"#else\n"
"{\n"
"}\n"
"#endif",
AllmanBraceStyle);
verifyFormat("void foobar() { int i = 5; }\n"
"#ifdef _DEBUG\n"
"void bar() {}\n"
"#else\n"
"void bar() { foobar(); }\n"
"#endif",
AllmanBraceStyle);
// This shouldn't affect ObjC blocks..
verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
" // ...\n"
" int i;\n"
"}];",
AllmanBraceStyle);
verifyFormat("void (^block)(void) = ^{\n"
" // ...\n"
" int i;\n"
"};",
AllmanBraceStyle);
// .. or dict literals.
verifyFormat("void f()\n"
"{\n"
" [object someMethod:@{ @\"a\" : @\"b\" }];\n"
"}",
AllmanBraceStyle);
verifyFormat("int f()\n"
"{ // comment\n"
" return 42;\n"
"}",
AllmanBraceStyle);
AllmanBraceStyle.ColumnLimit = 19;
verifyFormat("void f() { int i; }", AllmanBraceStyle);
AllmanBraceStyle.ColumnLimit = 18;
verifyFormat("void f()\n"
"{\n"
" int i;\n"
"}",
AllmanBraceStyle);
AllmanBraceStyle.ColumnLimit = 80;
FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = true;
BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
verifyFormat("void f(bool b)\n"
"{\n"
" if (b)\n"
" {\n"
" return;\n"
" }\n"
"}\n",
BreakBeforeBraceShortIfs);
verifyFormat("void f(bool b)\n"
"{\n"
" if (b) return;\n"
"}\n",
BreakBeforeBraceShortIfs);
verifyFormat("void f(bool b)\n"
"{\n"
" while (b)\n"
" {\n"
" return;\n"
" }\n"
"}\n",
BreakBeforeBraceShortIfs);
}
TEST_F(FormatTest, GNUBraceBreaking) {
FormatStyle GNUBraceStyle = getLLVMStyle();
GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
verifyFormat("namespace a\n"
"{\n"
"class A\n"
"{\n"
" void f()\n"
" {\n"
" int a;\n"
" {\n"
" int b;\n"
" }\n"
" if (true)\n"
" {\n"
" a();\n"
" b();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"}\n"
"}",
GNUBraceStyle);
verifyFormat("void f()\n"
"{\n"
" if (true)\n"
" {\n"
" a();\n"
" }\n"
" else if (false)\n"
" {\n"
" b();\n"
" }\n"
" else\n"
" {\n"
" c();\n"
" }\n"
"}\n",
GNUBraceStyle);
verifyFormat("void f()\n"
"{\n"
" for (int i = 0; i < 10; ++i)\n"
" {\n"
" a();\n"
" }\n"
" while (false)\n"
" {\n"
" b();\n"
" }\n"
" do\n"
" {\n"
" c();\n"
" }\n"
" while (false);\n"
"}\n",
GNUBraceStyle);
verifyFormat("void f(int a)\n"
"{\n"
" switch (a)\n"
" {\n"
" case 0:\n"
" break;\n"
" case 1:\n"
" {\n"
" break;\n"
" }\n"
" case 2:\n"
" {\n"
" }\n"
" break;\n"
" default:\n"
" break;\n"
" }\n"
"}\n",
GNUBraceStyle);
verifyFormat("enum X\n"
"{\n"
" Y = 0,\n"
"}\n",
GNUBraceStyle);
verifyFormat("@interface BSApplicationController ()\n"
"{\n"
"@private\n"
" id _extraIvar;\n"
"}\n"
"@end\n",
GNUBraceStyle);
verifyFormat("#ifdef _DEBUG\n"
"int foo(int i = 0)\n"
"#else\n"
"int foo(int i = 5)\n"
"#endif\n"
"{\n"
" return i;\n"
"}",
GNUBraceStyle);
verifyFormat("void foo() {}\n"
"void bar()\n"
"#ifdef _DEBUG\n"
"{\n"
" foo();\n"
"}\n"
"#else\n"
"{\n"
"}\n"
"#endif",
GNUBraceStyle);
verifyFormat("void foobar() { int i = 5; }\n"
"#ifdef _DEBUG\n"
"void bar() {}\n"
"#else\n"
"void bar() { foobar(); }\n"
"#endif",
GNUBraceStyle);
}
TEST_F(FormatTest, WebKitBraceBreaking) {
FormatStyle WebKitBraceStyle = getLLVMStyle();
WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
verifyFormat("namespace a {\n"
"class A {\n"
" void f()\n"
" {\n"
" if (true) {\n"
" a();\n"
" b();\n"
" }\n"
" }\n"
" void g() { return; }\n"
"};\n"
"enum E {\n"
" A,\n"
" // foo\n"
" B,\n"
" C\n"
"};\n"
"struct B {\n"
" int x;\n"
"};\n"
"}\n",
WebKitBraceStyle);
verifyFormat("struct S {\n"
" int Type;\n"
" union {\n"
" int x;\n"
" double y;\n"
" } Value;\n"
" class C {\n"
" MyFavoriteType Value;\n"
" } Class;\n"
"};\n",
WebKitBraceStyle);
}
TEST_F(FormatTest, CatchExceptionReferenceBinding) {
verifyFormat("void f() {\n"
" try {\n"
" } catch (const Exception &e) {\n"
" }\n"
"}\n",
getLLVMStyle());
}
TEST_F(FormatTest, UnderstandsPragmas) {
verifyFormat("#pragma omp reduction(| : var)");
verifyFormat("#pragma omp reduction(+ : var)");
EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
"(including parentheses).",
format("#pragma mark Any non-hyphenated or hyphenated string "
"(including parentheses)."));
}
TEST_F(FormatTest, UnderstandPragmaOption) {
verifyFormat("#pragma option -C -A");
EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A"));
}
#define EXPECT_ALL_STYLES_EQUAL(Styles) \
for (size_t i = 1; i < Styles.size(); ++i) \
EXPECT_EQ(Styles[0], Styles[i]) << "Style #" << i << " of " << Styles.size() \
<< " differs from Style #0"
TEST_F(FormatTest, GetsPredefinedStyleByName) {
SmallVector<FormatStyle, 3> Styles;
Styles.resize(3);
Styles[0] = getLLVMStyle();
EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getGoogleStyle();
EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
EXPECT_TRUE(
getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
EXPECT_TRUE(
getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getMozillaStyle();
EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getWebKitStyle();
EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles[0] = getGNUStyle();
EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
EXPECT_ALL_STYLES_EQUAL(Styles);
EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
}
TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
SmallVector<FormatStyle, 8> Styles;
Styles.resize(2);
Styles[0] = getGoogleStyle();
Styles[1] = getLLVMStyle();
EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
EXPECT_ALL_STYLES_EQUAL(Styles);
Styles.resize(5);
Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
Styles[1] = getLLVMStyle();
Styles[1].Language = FormatStyle::LK_JavaScript;
EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
Styles[2] = getLLVMStyle();
Styles[2].Language = FormatStyle::LK_JavaScript;
EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
"BasedOnStyle: Google",
&Styles[2])
.value());
Styles[3] = getLLVMStyle();
Styles[3].Language = FormatStyle::LK_JavaScript;
EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
"Language: JavaScript",
&Styles[3])
.value());
Styles[4] = getLLVMStyle();
Styles[4].Language = FormatStyle::LK_JavaScript;
EXPECT_EQ(0, parseConfiguration("---\n"
"BasedOnStyle: LLVM\n"
"IndentWidth: 123\n"
"---\n"
"BasedOnStyle: Google\n"
"Language: JavaScript",
&Styles[4])
.value());
EXPECT_ALL_STYLES_EQUAL(Styles);
}
#define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \
Style.FIELD = false; \
EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \
EXPECT_TRUE(Style.FIELD); \
EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \
EXPECT_FALSE(Style.FIELD);
#define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
#define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \
Style.STRUCT.FIELD = false; \
EXPECT_EQ(0, \
parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \
.value()); \
EXPECT_TRUE(Style.STRUCT.FIELD); \
EXPECT_EQ(0, \
parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \
.value()); \
EXPECT_FALSE(Style.STRUCT.FIELD);
#define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \
CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
#define CHECK_PARSE(TEXT, FIELD, VALUE) \
EXPECT_NE(VALUE, Style.FIELD); \
EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \
EXPECT_EQ(VALUE, Style.FIELD)
TEST_F(FormatTest, ParsesConfigurationBools) {
FormatStyle Style = {};
Style.Language = FormatStyle::LK_Cpp;
CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
CHECK_PARSE_BOOL(AlignOperands);
CHECK_PARSE_BOOL(AlignTrailingComments);
CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
CHECK_PARSE_BOOL(AllowShortBlocksOnASingleLine);
CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
CHECK_PARSE_BOOL(BinPackArguments);
CHECK_PARSE_BOOL(BinPackParameters);
CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
CHECK_PARSE_BOOL(BreakStringLiterals);
CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
CHECK_PARSE_BOOL(DerivePointerAlignment);
CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
CHECK_PARSE_BOOL(DisableFormat);
CHECK_PARSE_BOOL(IndentCaseLabels);
CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
CHECK_PARSE_BOOL(Cpp11BracedListStyle);
CHECK_PARSE_BOOL(ReflowComments);
CHECK_PARSE_BOOL(SortIncludes);
CHECK_PARSE_BOOL(SpacesInParentheses);
CHECK_PARSE_BOOL(SpacesInSquareBrackets);
CHECK_PARSE_BOOL(SpacesInAngles);
CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
CHECK_PARSE_BOOL(SpacesInContainerLiterals);
CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterControlStatement);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
}
#undef CHECK_PARSE_BOOL
TEST_F(FormatTest, ParsesConfiguration) {
FormatStyle Style = {};
Style.Language = FormatStyle::LK_Cpp;
CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
ConstructorInitializerIndentWidth, 1234u);
CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
PenaltyBreakBeforeFirstCallParameter, 1234u);
CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
PenaltyReturnTypeOnItsOwnLine, 1234u);
CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
SpacesBeforeTrailingComments, 1234u);
CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
Style.PointerAlignment = FormatStyle::PAS_Middle;
CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
FormatStyle::PAS_Left);
CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
FormatStyle::PAS_Right);
CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
FormatStyle::PAS_Middle);
// For backward compatibility:
CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
FormatStyle::PAS_Left);
CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
FormatStyle::PAS_Right);
CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
FormatStyle::PAS_Middle);
Style.Standard = FormatStyle::LS_Auto;
CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Cpp11);
CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
FormatStyle::BOS_None);
CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
FormatStyle::BOS_All);
// For backward compatibility:
CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
FormatStyle::BOS_None);
CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
FormatStyle::BOS_All);
Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
FormatStyle::BAS_Align);
CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
FormatStyle::BAS_DontAlign);
CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
FormatStyle::BAS_AlwaysBreak);
// For backward compatibility:
CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
FormatStyle::BAS_DontAlign);
CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
FormatStyle::BAS_Align);
Style.UseTab = FormatStyle::UT_ForIndentation;
CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
FormatStyle::UT_ForContinuationAndIndentation);
// For backward compatibility:
CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
// For backward compatibility:
CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
FormatStyle::SBPO_Never);
CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
FormatStyle::SBPO_Always);
CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
FormatStyle::SBPO_ControlStatements);
// For backward compatibility:
CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
FormatStyle::SBPO_Never);
CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
FormatStyle::SBPO_ControlStatements);
Style.ColumnLimit = 123;
FormatStyle BaseStyle = getLLVMStyle();
CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
FormatStyle::BS_Attach);
CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
FormatStyle::BS_Linux);
CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
FormatStyle::BS_Mozilla);
CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
FormatStyle::BS_Stroustrup);
CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
FormatStyle::BS_Allman);
CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
FormatStyle::BS_WebKit);
CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
FormatStyle::BS_Custom);
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
FormatStyle::RTBS_None);
CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
FormatStyle::RTBS_All);
CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
AlwaysBreakAfterReturnType,
FormatStyle::RTBS_TopLevelDefinitions);
Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
AlwaysBreakAfterDefinitionReturnType,
FormatStyle::DRTBS_TopLevel);
Style.NamespaceIndentation = FormatStyle::NI_All;
CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
FormatStyle::NI_None);
CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
FormatStyle::NI_Inner);
CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
FormatStyle::NI_All);
// FIXME: This is required because parsing a configuration simply overwrites
// the first N elements of the list instead of resetting it.
Style.ForEachMacros.clear();
std::vector<std::string> BoostForeach;
BoostForeach.push_back("BOOST_FOREACH");
CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
std::vector<std::string> BoostAndQForeach;
BoostAndQForeach.push_back("BOOST_FOREACH");
BoostAndQForeach.push_back("Q_FOREACH");
CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
BoostAndQForeach);
Style.IncludeCategories.clear();
std::vector<FormatStyle::IncludeCategory> ExpectedCategories = {{"abc/.*", 2},
{".*", 1}};
CHECK_PARSE("IncludeCategories:\n"
" - Regex: abc/.*\n"
" Priority: 2\n"
" - Regex: .*\n"
" Priority: 1",
IncludeCategories, ExpectedCategories);
CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeIsMainRegex, "abc$");
}
TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
FormatStyle Style = {};
Style.Language = FormatStyle::LK_Cpp;
CHECK_PARSE("Language: Cpp\n"
"IndentWidth: 12",
IndentWidth, 12u);
EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
"IndentWidth: 34",
&Style),
ParseError::Unsuitable);
EXPECT_EQ(12u, Style.IndentWidth);
CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
Style.Language = FormatStyle::LK_JavaScript;
CHECK_PARSE("Language: JavaScript\n"
"IndentWidth: 12",
IndentWidth, 12u);
CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
EXPECT_EQ(parseConfiguration("Language: Cpp\n"
"IndentWidth: 34",
&Style),
ParseError::Unsuitable);
EXPECT_EQ(23u, Style.IndentWidth);
CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
CHECK_PARSE("BasedOnStyle: LLVM\n"
"IndentWidth: 67",
IndentWidth, 67u);
CHECK_PARSE("---\n"
"Language: JavaScript\n"
"IndentWidth: 12\n"
"---\n"
"Language: Cpp\n"
"IndentWidth: 34\n"
"...\n",
IndentWidth, 12u);
Style.Language = FormatStyle::LK_Cpp;
CHECK_PARSE("---\n"
"Language: JavaScript\n"
"IndentWidth: 12\n"
"---\n"
"Language: Cpp\n"
"IndentWidth: 34\n"
"...\n",
IndentWidth, 34u);
CHECK_PARSE("---\n"
"IndentWidth: 78\n"
"---\n"
"Language: JavaScript\n"
"IndentWidth: 56\n"
"...\n",
IndentWidth, 78u);
Style.ColumnLimit = 123;
Style.IndentWidth = 234;
Style.BreakBeforeBraces = FormatStyle::BS_Linux;
Style.TabWidth = 345;
EXPECT_FALSE(parseConfiguration("---\n"
"IndentWidth: 456\n"
"BreakBeforeBraces: Allman\n"
"---\n"
"Language: JavaScript\n"
"IndentWidth: 111\n"
"TabWidth: 111\n"
"---\n"
"Language: Cpp\n"
"BreakBeforeBraces: Stroustrup\n"
"TabWidth: 789\n"
"...\n",
&Style));
EXPECT_EQ(123u, Style.ColumnLimit);
EXPECT_EQ(456u, Style.IndentWidth);
EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
EXPECT_EQ(789u, Style.TabWidth);
EXPECT_EQ(parseConfiguration("---\n"
"Language: JavaScript\n"
"IndentWidth: 56\n"
"---\n"
"IndentWidth: 78\n"
"...\n",
&Style),
ParseError::Error);
EXPECT_EQ(parseConfiguration("---\n"
"Language: JavaScript\n"
"IndentWidth: 56\n"
"---\n"
"Language: JavaScript\n"
"IndentWidth: 78\n"
"...\n",
&Style),
ParseError::Error);
EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
}
#undef CHECK_PARSE
TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
FormatStyle Style = {};
Style.Language = FormatStyle::LK_JavaScript;
Style.BreakBeforeTernaryOperators = true;
EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
Style.BreakBeforeTernaryOperators = true;
EXPECT_EQ(0, parseConfiguration("---\n"
"BasedOnStyle: Google\n"
"---\n"
"Language: JavaScript\n"
"IndentWidth: 76\n"
"...\n",
&Style)
.value());
EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
EXPECT_EQ(76u, Style.IndentWidth);
EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
}
TEST_F(FormatTest, ConfigurationRoundTripTest) {
FormatStyle Style = getLLVMStyle();
std::string YAML = configurationAsText(Style);
FormatStyle ParsedStyle = {};
ParsedStyle.Language = FormatStyle::LK_Cpp;
EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
EXPECT_EQ(Style, ParsedStyle);
}
TEST_F(FormatTest, WorksFor8bitEncodings) {
EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
"\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
"\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
"\"\xef\xee\xf0\xf3...\"",
format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
"\xef\xee\xf0\xf3...\"",
getLLVMStyleWithColumns(12)));
}
TEST_F(FormatTest, HandlesUTF8BOM) {
EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
format("\xef\xbb\xbf#include <iostream>"));
EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
format("\xef\xbb\xbf\n#include <iostream>"));
}
// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
#if !defined(_MSC_VER)
TEST_F(FormatTest, CountsUTF8CharactersProperly) {
verifyFormat("\"Однажды в студёную зимнюю пору...\"",
getLLVMStyleWithColumns(35));
verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
getLLVMStyleWithColumns(31));
verifyFormat("// Однажды в студёную зимнюю пору...",
getLLVMStyleWithColumns(36));
verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
verifyFormat("/* Однажды в студёную зимнюю пору... */",
getLLVMStyleWithColumns(39));
verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
getLLVMStyleWithColumns(35));
}
TEST_F(FormatTest, SplitsUTF8Strings) {
// Non-printable characters' width is currently considered to be the length in
// bytes in UTF8. The characters can be displayed in very different manner
// (zero-width, single width with a substitution glyph, expanded to their code
// (e.g. "<8d>"), so there's no single correct way to handle them.
EXPECT_EQ("\"aaaaÄ\"\n"
"\"\xc2\x8d\";",
format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"aaaaaaaÄ\"\n"
"\"\xc2\x8d\";",
format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
EXPECT_EQ("\"Однажды, в \"\n"
"\"студёную \"\n"
"\"зимнюю \"\n"
"\"пору,\"",
format("\"Однажды, в студёную зимнюю пору,\"",
getLLVMStyleWithColumns(13)));
EXPECT_EQ(
"\"一 二 三 \"\n"
"\"四 五六 \"\n"
"\"七 八 九 \"\n"
"\"十\"",
format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
EXPECT_EQ("\"一\t二 \"\n"
"\"\t三 \"\n"
"\"四 五\t六 \"\n"
"\"\t七 \"\n"
"\"八九十\tqq\"",
format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
getLLVMStyleWithColumns(11)));
// UTF8 character in an escape sequence.
EXPECT_EQ("\"aaaaaa\"\n"
"\"\\\xC2\x8D\"",
format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
}
TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
EXPECT_EQ("const char *sssss =\n"
" \"一二三四五六七八\\\n"
" 九 十\";",
format("const char *sssss = \"一二三四五六七八\\\n"
" 九 十\";",
getLLVMStyleWithColumns(30)));
}
TEST_F(FormatTest, SplitsUTF8LineComments) {
EXPECT_EQ("// aaaaÄ\xc2\x8d",
format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
EXPECT_EQ("// Я из лесу\n"
"// вышел; был\n"
"// сильный\n"
"// мороз.",
format("// Я из лесу вышел; был сильный мороз.",
getLLVMStyleWithColumns(13)));
EXPECT_EQ("// 一二三\n"
"// 四五六七\n"
"// 八 九\n"
"// 十",
format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9)));
}
TEST_F(FormatTest, SplitsUTF8BlockComments) {
EXPECT_EQ("/* Гляжу,\n"
" * поднимается\n"
" * медленно в\n"
" * гору\n"
" * Лошадка,\n"
" * везущая\n"
" * хворосту\n"
" * воз. */",
format("/* Гляжу, поднимается медленно в гору\n"
" * Лошадка, везущая хворосту воз. */",
getLLVMStyleWithColumns(13)));
EXPECT_EQ(
"/* 一二三\n"
" * 四五六七\n"
" * 八 九\n"
" * 十 */",
format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9)));
EXPECT_EQ("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯\n"
" * 𝕓𝕪𝕥𝕖\n"
" * 𝖀𝕿𝕱-𝟠 */",
format("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯 𝕓𝕪𝕥𝕖 𝖀𝕿𝕱-𝟠 */", getLLVMStyleWithColumns(12)));
}
#endif // _MSC_VER
TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
FormatStyle Style = getLLVMStyle();
Style.ConstructorInitializerIndentWidth = 4;
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
Style);
Style.ConstructorInitializerIndentWidth = 2;
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
Style);
Style.ConstructorInitializerIndentWidth = 0;
verifyFormat(
"SomeClass::Constructor()\n"
": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
Style);
Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
verifyFormat(
"SomeLongTemplateVariableName<\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
Style);
verifyFormat(
"bool smaller = 1 < bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
}
TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
FormatStyle Style = getLLVMStyle();
Style.BreakConstructorInitializersBeforeComma = true;
Style.ConstructorInitializerIndentWidth = 4;
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
" , c(c) {}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a) {}",
Style);
Style.ColumnLimit = 0;
verifyFormat("SomeClass::Constructor()\n"
" : a(a) {}",
Style);
verifyFormat("SomeClass::Constructor() noexcept\n"
" : a(a) {}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
" , c(c) {}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a) {\n"
" foo();\n"
" bar();\n"
"}",
Style);
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
" , c(c) {\n}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a) {\n}",
Style);
Style.ColumnLimit = 80;
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Style.ConstructorInitializerIndentWidth = 2;
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
" , c(c) {}",
Style);
Style.ConstructorInitializerIndentWidth = 0;
verifyFormat("SomeClass::Constructor()\n"
": a(a)\n"
", b(b)\n"
", c(c) {}",
Style);
Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Style.ConstructorInitializerIndentWidth = 4;
verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
verifyFormat(
"SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
Style);
verifyFormat(
"SomeClass::Constructor()\n"
" : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
Style);
Style.ConstructorInitializerIndentWidth = 4;
Style.ColumnLimit = 60;
verifyFormat("SomeClass::Constructor()\n"
" : aaaaaaaa(aaaaaaaa)\n"
" , aaaaaaaa(aaaaaaaa)\n"
" , aaaaaaaa(aaaaaaaa) {}",
Style);
}
TEST_F(FormatTest, Destructors) {
verifyFormat("void F(int &i) { i.~int(); }");
verifyFormat("void F(int &i) { i->~int(); }");
}
TEST_F(FormatTest, FormatsWithWebKitStyle) {
FormatStyle Style = getWebKitStyle();
// Don't indent in outer namespaces.
verifyFormat("namespace outer {\n"
"int i;\n"
"namespace inner {\n"
" int i;\n"
"} // namespace inner\n"
"} // namespace outer\n"
"namespace other_outer {\n"
"int i;\n"
"}",
Style);
// Don't indent case labels.
verifyFormat("switch (variable) {\n"
"case 1:\n"
"case 2:\n"
" doSomething();\n"
" break;\n"
"default:\n"
" ++variable;\n"
"}",
Style);
// Wrap before binary operators.
EXPECT_EQ("void f()\n"
"{\n"
" if (aaaaaaaaaaaaaaaa\n"
" && bbbbbbbbbbbbbbbbbbbbbbbb\n"
" && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
" return;\n"
"}",
format("void f() {\n"
"if (aaaaaaaaaaaaaaaa\n"
"&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
"&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
"return;\n"
"}",
Style));
// Allow functions on a single line.
verifyFormat("void f() { return; }", Style);
// Constructor initializers are formatted one per line with the "," on the
// new line.
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
" aaaaaaaaaaaaaa)\n"
" , aaaaaaaaaaaaaaaaaaaaaaa()\n"
"{\n"
"}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
"{\n"
"}",
Style);
EXPECT_EQ("SomeClass::Constructor()\n"
" : a(a)\n"
"{\n"
"}",
format("SomeClass::Constructor():a(a){}", Style));
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
" , c(c)\n"
"{\n"
"}",
Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
"{\n"
" foo();\n"
" bar();\n"
"}",
Style);
// Access specifiers should be aligned left.
verifyFormat("class C {\n"
"public:\n"
" int i;\n"
"};",
Style);
// Do not align comments.
verifyFormat("int a; // Do not\n"
"double b; // align comments.",
Style);
// Do not align operands.
EXPECT_EQ("ASSERT(aaaa\n"
" || bbbb);",
format("ASSERT ( aaaa\n||bbbb);", Style));
// Accept input's line breaks.
EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
" || bbbbbbbbbbbbbbb) {\n"
" i++;\n"
"}",
format("if (aaaaaaaaaaaaaaa\n"
"|| bbbbbbbbbbbbbbb) { i++; }",
Style));
EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
" i++;\n"
"}",
format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
// Don't automatically break all macro definitions (llvm.org/PR17842).
verifyFormat("#define aNumber 10", Style);
// However, generally keep the line breaks that the user authored.
EXPECT_EQ("#define aNumber \\\n"
" 10",
format("#define aNumber \\\n"
" 10",
Style));
// Keep empty and one-element array literals on a single line.
EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
" copyItems:YES];",
format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
"copyItems:YES];",
Style));
EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
" copyItems:YES];",
format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
" copyItems:YES];",
Style));
// FIXME: This does not seem right, there should be more indentation before
// the array literal's entries. Nested blocks have the same problem.
EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
" @\"a\",\n"
" @\"a\"\n"
"]\n"
" copyItems:YES];",
format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
" @\"a\",\n"
" @\"a\"\n"
" ]\n"
" copyItems:YES];",
Style));
EXPECT_EQ(
"NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
" copyItems:YES];",
format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
" copyItems:YES];",
Style));
verifyFormat("[self.a b:c c:d];", Style);
EXPECT_EQ("[self.a b:c\n"
" c:d];",
format("[self.a b:c\n"
"c:d];",
Style));
}
TEST_F(FormatTest, FormatsLambdas) {
verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
verifyFormat("int x = f(*+[] {});");
verifyFormat("void f() {\n"
" other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
"}\n");
verifyFormat("void f() {\n"
" other(x.begin(), //\n"
" x.end(), //\n"
" [&](int, int) { return 1; });\n"
"}\n");
verifyFormat("SomeFunction([]() { // A cool function...\n"
" return 43;\n"
"});");
EXPECT_EQ("SomeFunction([]() {\n"
"#define A a\n"
" return 43;\n"
"});",
format("SomeFunction([](){\n"
"#define A a\n"
"return 43;\n"
"});"));
verifyFormat("void f() {\n"
" SomeFunction([](decltype(x), A *a) {});\n"
"}");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" [](const aaaaaaaaaa &a) { return a; });");
verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
" SomeOtherFunctioooooooooooooooooooooooooon();\n"
"});");
verifyFormat("Constructor()\n"
" : Field([] { // comment\n"
" int i;\n"
" }) {}");
verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
" return some_parameter.size();\n"
"};");
verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
" [](const string &s) { return s; };");
verifyFormat("int i = aaaaaa ? 1 //\n"
" : [] {\n"
" return 2; //\n"
" }();");
verifyFormat("llvm::errs() << \"number of twos is \"\n"
" << std::count_if(v.begin(), v.end(), [](int x) {\n"
" return x == 2; // force break\n"
" });");
verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa([=](\n"
" int iiiiiiiiiiii) {\n"
" return aaaaaaaaaaaaaaaaaaaaaaa != aaaaaaaaaaaaaaaaaaaaaaa;\n"
"});",
getLLVMStyleWithColumns(60));
verifyFormat("SomeFunction({[&] {\n"
" // comment\n"
" },\n"
" [&] {\n"
" // comment\n"
" }});");
verifyFormat("SomeFunction({[&] {\n"
" // comment\n"
"}});");
verifyFormat("virtual aaaaaaaaaaaaaaaa(std::function<bool()> bbbbbbbbbbbb =\n"
" [&]() { return true; },\n"
" aaaaa aaaaaaaaa);");
// Lambdas with return types.
verifyFormat("int c = []() -> int { return 2; }();\n");
verifyFormat("int c = []() -> int * { return 2; }();\n");
verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
verifyFormat("[a, a]() -> a<1> {};");
verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
" int j) -> int {\n"
" return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
"};");
verifyFormat(
"aaaaaaaaaaaaaaaaaaaaaa(\n"
" [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
" return aaaaaaaaaaaaaaaaa;\n"
" });",
getLLVMStyleWithColumns(70));
verifyFormat("[]() //\n"
" -> int {\n"
" return 1; //\n"
"};");
// Multiple lambdas in the same parentheses change indentation rules.
verifyFormat("SomeFunction(\n"
" []() {\n"
" int i = 42;\n"
" return i;\n"
" },\n"
" []() {\n"
" int j = 43;\n"
" return j;\n"
" });");
// More complex introducers.
verifyFormat("return [i, args...] {};");
// Not lambdas.
verifyFormat("constexpr char hello[]{\"hello\"};");
verifyFormat("double &operator[](int i) { return 0; }\n"
"int i;");
verifyFormat("std::unique_ptr<int[]> foo() {}");
verifyFormat("int i = a[a][a]->f();");
verifyFormat("int i = (*b)[a]->f();");
// Other corner cases.
verifyFormat("void f() {\n"
" bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
" );\n"
"}");
// Lambdas created through weird macros.
verifyFormat("void f() {\n"
" MACRO((const AA &a) { return 1; });\n"
" MACRO((AA &a) { return 1; });\n"
"}");
verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
" doo_dah();\n"
" doo_dah();\n"
" })) {\n"
"}");
verifyFormat("auto lambda = []() {\n"
" int a = 2\n"
"#if A\n"
" + 2\n"
"#endif\n"
" ;\n"
"};");
}
TEST_F(FormatTest, FormatsBlocks) {
FormatStyle ShortBlocks = getLLVMStyle();
ShortBlocks.AllowShortBlocksOnASingleLine = true;
verifyFormat("int (^Block)(int, int);", ShortBlocks);
verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
verifyFormat("foo(^{ bar(); });", ShortBlocks);
verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
verifyFormat("[operation setCompletionBlock:^{\n"
" [self onOperationDone];\n"
"}];");
verifyFormat("int i = {[operation setCompletionBlock:^{\n"
" [self onOperationDone];\n"
"}]};");
verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
" f();\n"
"}];");
verifyFormat("int a = [operation block:^int(int *i) {\n"
" return 1;\n"
"}];");
verifyFormat("[myObject doSomethingWith:arg1\n"
" aaa:^int(int *a) {\n"
" return 1;\n"
" }\n"
" bbb:f(a * bbbbbbbb)];");
verifyFormat("[operation setCompletionBlock:^{\n"
" [self.delegate newDataAvailable];\n"
"}];",
getLLVMStyleWithColumns(60));
verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
" NSString *path = [self sessionFilePath];\n"
" if (path) {\n"
" // ...\n"
" }\n"
"});");
verifyFormat("[[SessionService sharedService]\n"
" loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
" if (window) {\n"
" [self windowDidLoad:window];\n"
" } else {\n"
" [self errorLoadingWindow];\n"
" }\n"
" }];");
verifyFormat("void (^largeBlock)(void) = ^{\n"
" // ...\n"
"};\n",
getLLVMStyleWithColumns(40));
verifyFormat("[[SessionService sharedService]\n"
" loadWindowWithCompletionBlock: //\n"
" ^(SessionWindow *window) {\n"
" if (window) {\n"
" [self windowDidLoad:window];\n"
" } else {\n"
" [self errorLoadingWindow];\n"
" }\n"
" }];",
getLLVMStyleWithColumns(60));
verifyFormat("[myObject doSomethingWith:arg1\n"
" firstBlock:^(Foo *a) {\n"
" // ...\n"
" int i;\n"
" }\n"
" secondBlock:^(Bar *b) {\n"
" // ...\n"
" int i;\n"
" }\n"
" thirdBlock:^Foo(Bar *b) {\n"
" // ...\n"
" int i;\n"
" }];");
verifyFormat("[myObject doSomethingWith:arg1\n"
" firstBlock:-1\n"
" secondBlock:^(Bar *b) {\n"
" // ...\n"
" int i;\n"
" }];");
verifyFormat("f(^{\n"
" @autoreleasepool {\n"
" if (a) {\n"
" g();\n"
" }\n"
" }\n"
"});");
verifyFormat("Block b = ^int *(A *a, B *b) {}");
verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
"};");
FormatStyle FourIndent = getLLVMStyle();
FourIndent.ObjCBlockIndentWidth = 4;
verifyFormat("[operation setCompletionBlock:^{\n"
" [self onOperationDone];\n"
"}];",
FourIndent);
}
TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
FormatStyle ZeroColumn = getLLVMStyle();
ZeroColumn.ColumnLimit = 0;
verifyFormat("[[SessionService sharedService] "
"loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
" if (window) {\n"
" [self windowDidLoad:window];\n"
" } else {\n"
" [self errorLoadingWindow];\n"
" }\n"
"}];",
ZeroColumn);
EXPECT_EQ("[[SessionService sharedService]\n"
" loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
" if (window) {\n"
" [self windowDidLoad:window];\n"
" } else {\n"
" [self errorLoadingWindow];\n"
" }\n"
" }];",
format("[[SessionService sharedService]\n"
"loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
" if (window) {\n"
" [self windowDidLoad:window];\n"
" } else {\n"
" [self errorLoadingWindow];\n"
" }\n"
"}];",
ZeroColumn));
verifyFormat("[myObject doSomethingWith:arg1\n"
" firstBlock:^(Foo *a) {\n"
" // ...\n"
" int i;\n"
" }\n"
" secondBlock:^(Bar *b) {\n"
" // ...\n"
" int i;\n"
" }\n"
" thirdBlock:^Foo(Bar *b) {\n"
" // ...\n"
" int i;\n"
" }];",
ZeroColumn);
verifyFormat("f(^{\n"
" @autoreleasepool {\n"
" if (a) {\n"
" g();\n"
" }\n"
" }\n"
"});",
ZeroColumn);
verifyFormat("void (^largeBlock)(void) = ^{\n"
" // ...\n"
"};",
ZeroColumn);
ZeroColumn.AllowShortBlocksOnASingleLine = true;
EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
ZeroColumn.AllowShortBlocksOnASingleLine = false;
EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
" int i;\n"
"};",
format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
}
TEST_F(FormatTest, SupportsCRLF) {
EXPECT_EQ("int a;\r\n"
"int b;\r\n"
"int c;\r\n",
format("int a;\r\n"
" int b;\r\n"
" int c;\r\n",
getLLVMStyle()));
EXPECT_EQ("int a;\r\n"
"int b;\r\n"
"int c;\r\n",
format("int a;\r\n"
" int b;\n"
" int c;\r\n",
getLLVMStyle()));
EXPECT_EQ("int a;\n"
"int b;\n"
"int c;\n",
format("int a;\r\n"
" int b;\n"
" int c;\n",
getLLVMStyle()));
EXPECT_EQ("\"aaaaaaa \"\r\n"
"\"bbbbbbb\";\r\n",
format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
EXPECT_EQ("#define A \\\r\n"
" b; \\\r\n"
" c; \\\r\n"
" d;\r\n",
format("#define A \\\r\n"
" b; \\\r\n"
" c; d; \r\n",
getGoogleStyle()));
EXPECT_EQ("/*\r\n"
"multi line block comments\r\n"
"should not introduce\r\n"
"an extra carriage return\r\n"
"*/\r\n",
format("/*\r\n"
"multi line block comments\r\n"
"should not introduce\r\n"
"an extra carriage return\r\n"
"*/\r\n"));
}
TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
verifyFormat("MY_CLASS(C) {\n"
" int i;\n"
" int j;\n"
"};");
}
TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
TwoIndent.ContinuationIndentWidth = 2;
EXPECT_EQ("int i =\n"
" longFunction(\n"
" arg);",
format("int i = longFunction(arg);", TwoIndent));
FormatStyle SixIndent = getLLVMStyleWithColumns(20);
SixIndent.ContinuationIndentWidth = 6;
EXPECT_EQ("int i =\n"
" longFunction(\n"
" arg);",
format("int i = longFunction(arg);", SixIndent));
}
TEST_F(FormatTest, SpacesInAngles) {
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInAngles = true;
verifyFormat("static_cast< int >(arg);", Spaces);
verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
verifyFormat("f< int, float >();", Spaces);
verifyFormat("template <> g() {}", Spaces);
verifyFormat("template < std::vector< int > > f() {}", Spaces);
verifyFormat("std::function< void(int, int) > fct;", Spaces);
verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
Spaces);
Spaces.Standard = FormatStyle::LS_Cpp03;
Spaces.SpacesInAngles = true;
verifyFormat("A< A< int > >();", Spaces);
Spaces.SpacesInAngles = false;
verifyFormat("A<A<int> >();", Spaces);
Spaces.Standard = FormatStyle::LS_Cpp11;
Spaces.SpacesInAngles = true;
verifyFormat("A< A< int > >();", Spaces);
Spaces.SpacesInAngles = false;
verifyFormat("A<A<int>>();", Spaces);
}
TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
FormatStyle Style = getLLVMStyle();
Style.SpaceAfterTemplateKeyword = false;
verifyFormat("template<int> void foo();", Style);
}
TEST_F(FormatTest, TripleAngleBrackets) {
verifyFormat("f<<<1, 1>>>();");
verifyFormat("f<<<1, 1, 1, s>>>();");
verifyFormat("f<<<a, b, c, d>>>();");
EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
verifyFormat("f<param><<<1, 1>>>();");
verifyFormat("f<1><<<1, 1>>>();");
EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaa<<<\n 1, 1>>>();");
verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
" <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
}
TEST_F(FormatTest, MergeLessLessAtEnd) {
verifyFormat("<<");
EXPECT_EQ("< < <", format("\\\n<<<"));
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaallvm::outs() <<");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaallvm::outs()\n <<");
}
TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
std::string code = "#if A\n"
"#if B\n"
"a.\n"
"#endif\n"
" a = 1;\n"
"#else\n"
"#endif\n"
"#if C\n"
"#else\n"
"#endif\n";
EXPECT_EQ(code, format(code));
}
TEST_F(FormatTest, HandleConflictMarkers) {
// Git/SVN conflict markers.
EXPECT_EQ("int a;\n"
"void f() {\n"
" callme(some(parameter1,\n"
"<<<<<<< text by the vcs\n"
" parameter2),\n"
"||||||| text by the vcs\n"
" parameter2),\n"
" parameter3,\n"
"======= text by the vcs\n"
" parameter2, parameter3),\n"
">>>>>>> text by the vcs\n"
" otherparameter);\n",
format("int a;\n"
"void f() {\n"
" callme(some(parameter1,\n"
"<<<<<<< text by the vcs\n"
" parameter2),\n"
"||||||| text by the vcs\n"
" parameter2),\n"
" parameter3,\n"
"======= text by the vcs\n"
" parameter2,\n"
" parameter3),\n"
">>>>>>> text by the vcs\n"
" otherparameter);\n"));
// Perforce markers.
EXPECT_EQ("void f() {\n"
" function(\n"
">>>> text by the vcs\n"
" parameter,\n"
"==== text by the vcs\n"
" parameter,\n"
"==== text by the vcs\n"
" parameter,\n"
"<<<< text by the vcs\n"
" parameter);\n",
format("void f() {\n"
" function(\n"
">>>> text by the vcs\n"
" parameter,\n"
"==== text by the vcs\n"
" parameter,\n"
"==== text by the vcs\n"
" parameter,\n"
"<<<< text by the vcs\n"
" parameter);\n"));
EXPECT_EQ("<<<<<<<\n"
"|||||||\n"
"=======\n"
">>>>>>>",
format("<<<<<<<\n"
"|||||||\n"
"=======\n"
">>>>>>>"));
EXPECT_EQ("<<<<<<<\n"
"|||||||\n"
"int i;\n"
"=======\n"
">>>>>>>",
format("<<<<<<<\n"
"|||||||\n"
"int i;\n"
"=======\n"
">>>>>>>"));
// FIXME: Handle parsing of macros around conflict markers correctly:
EXPECT_EQ("#define Macro \\\n"
"<<<<<<<\n"
"Something \\\n"
"|||||||\n"
"Else \\\n"
"=======\n"
"Other \\\n"
">>>>>>>\n"
" End int i;\n",
format("#define Macro \\\n"
"<<<<<<<\n"
" Something \\\n"
"|||||||\n"
" Else \\\n"
"=======\n"
" Other \\\n"
">>>>>>>\n"
" End\n"
"int i;\n"));
}
TEST_F(FormatTest, DisableRegions) {
EXPECT_EQ("int i;\n"
"// clang-format off\n"
" int j;\n"
"// clang-format on\n"
"int k;",
format(" int i;\n"
" // clang-format off\n"
" int j;\n"
" // clang-format on\n"
" int k;"));
EXPECT_EQ("int i;\n"
"/* clang-format off */\n"
" int j;\n"
"/* clang-format on */\n"
"int k;",
format(" int i;\n"
" /* clang-format off */\n"
" int j;\n"
" /* clang-format on */\n"
" int k;"));
}
TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
format("? ) =");
verifyNoCrash("#define a\\\n /**/}");
}
TEST_F(FormatTest, FormatsTableGenCode) {
FormatStyle Style = getLLVMStyle();
Style.Language = FormatStyle::LK_TableGen;
verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
}
TEST_F(FormatTest, ArrayOfTemplates) {
EXPECT_EQ("auto a = new unique_ptr<int>[10];",
format("auto a = new unique_ptr<int > [ 10];"));
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInSquareBrackets = true;
EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
format("auto a = new unique_ptr<int > [10];", Spaces));
}
TEST_F(FormatTest, ArrayAsTemplateType) {
EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInSquareBrackets = true;
EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
}
TEST(FormatStyle, GetStyleOfFile) {
vfs::InMemoryFileSystem FS;
// Test 1: format file in the same directory.
ASSERT_TRUE(
FS.addFile("/a/.clang-format", 0,
llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
ASSERT_TRUE(
FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
ASSERT_EQ(Style1, getLLVMStyle());
// Test 2: fallback to default.
ASSERT_TRUE(
FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
ASSERT_EQ(Style2, getMozillaStyle());
// Test 3: format file in parent directory.
ASSERT_TRUE(
FS.addFile("/c/.clang-format", 0,
llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
llvm::MemoryBuffer::getMemBuffer("int i;")));
auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
ASSERT_EQ(Style3, getGoogleStyle());
}
TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
// Column limit is 20.
std::string Code = "Type *a =\n"
" new Type();\n"
"g(iiiii, 0, jjjjj,\n"
" 0, kkkkk, 0, mm);\n"
"int bad = format ;";
std::string Expected = "auto a = new Type();\n"
"g(iiiii, nullptr,\n"
" jjjjj, nullptr,\n"
" kkkkk, nullptr,\n"
" mm);\n"
"int bad = format ;";
FileID ID = Context.createInMemoryFile("format.cpp", Code);
tooling::Replacements Replaces = toReplacements(
{tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
"auto "),
tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
"nullptr"),
tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
"nullptr"),
tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
"nullptr")});
format::FormatStyle Style = format::getLLVMStyle();
Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
<< llvm::toString(FormattedReplaces.takeError()) << "\n";
auto Result = applyAllReplacements(Code, *FormattedReplaces);
EXPECT_TRUE(static_cast<bool>(Result));
EXPECT_EQ(Expected, *Result);
}
TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
std::string Code = "#include \"a.h\"\n"
"#include \"c.h\"\n"
"\n"
"int main() {\n"
" return 0;\n"
"}";
std::string Expected = "#include \"a.h\"\n"
"#include \"b.h\"\n"
"#include \"c.h\"\n"
"\n"
"int main() {\n"
" return 0;\n"
"}";
FileID ID = Context.createInMemoryFile("fix.cpp", Code);
tooling::Replacements Replaces = toReplacements(
{tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
"#include \"b.h\"\n")});
format::FormatStyle Style = format::getLLVMStyle();
Style.SortIncludes = true;
auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
<< llvm::toString(FormattedReplaces.takeError()) << "\n";
auto Result = applyAllReplacements(Code, *FormattedReplaces);
EXPECT_TRUE(static_cast<bool>(Result));
EXPECT_EQ(Expected, *Result);
}
TEST_F(FormatTest, AllignTrailingComments) {
EXPECT_EQ("#define MACRO(V) \\\n"
" V(Rt2) /* one more char */ \\\n"
" V(Rs) /* than here */ \\\n"
"/* comment 3 */\n",
format("#define MACRO(V)\\\n"
"V(Rt2) /* one more char */ \\\n"
"V(Rs) /* than here */ \\\n"
"/* comment 3 */ \\\n",
getLLVMStyleWithColumns(40)));
}
} // end namespace
} // end namespace format
} // end namespace clang
| 38.453296 | 83 | 0.48921 | [
"object",
"vector"
] |
b403105cb121d57d64e2bdbbdadb5520094ac14f | 2,849 | cpp | C++ | libcxx/test/std/utilities/format/format.functions/format_to.locale.pass.cpp | rastogishubham/llvm-project | 1785d49d77a82222d33122ab6e2a115c91d007a1 | [
"Apache-2.0"
] | null | null | null | libcxx/test/std/utilities/format/format.functions/format_to.locale.pass.cpp | rastogishubham/llvm-project | 1785d49d77a82222d33122ab6e2a115c91d007a1 | [
"Apache-2.0"
] | null | null | null | libcxx/test/std/utilities/format/format.functions/format_to.locale.pass.cpp | rastogishubham/llvm-project | 1785d49d77a82222d33122ab6e2a115c91d007a1 | [
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// UNSUPPORTED: libcpp-no-concepts
// UNSUPPORTED: libcpp-has-no-localization
// UNSUPPORTED: libcpp-has-no-incomplete-format
// TODO FMT Evaluate gcc-11 status
// UNSUPPORTED: gcc-11
// <format>
// template<class Out, class... Args>
// Out format_to(Out out, const locale& loc,
// string_view fmt, const Args&... args);
// template<class Out, class... Args>
// Out format_to(Out out, const locale& loc,
// wstring_view fmt, const Args&... args);
#include <format>
#include <algorithm>
#include <cassert>
#include <list>
#include <vector>
#include "test_macros.h"
#include "format_tests.h"
auto test = []<class CharT, class... Args>(std::basic_string<CharT> expected, std::basic_string<CharT> fmt,
const Args&... args) {
{
std::basic_string<CharT> out(expected.size(), CharT(' '));
auto it = std::format_to(out.begin(), std::locale(), fmt, args...);
assert(it == out.end());
assert(out == expected);
}
{
std::list<CharT> out;
std::format_to(std::back_inserter(out), std::locale(), fmt, args...);
assert(std::equal(out.begin(), out.end(), expected.begin(), expected.end()));
}
{
std::vector<CharT> out;
std::format_to(std::back_inserter(out), std::locale(), fmt, args...);
assert(std::equal(out.begin(), out.end(), expected.begin(), expected.end()));
}
{
assert(expected.size() < 4096 && "Update the size of the buffer.");
CharT out[4096];
CharT* it = std::format_to(out, std::locale(), fmt, args...);
assert(std::distance(out, it) == int(expected.size()));
// Convert to std::string since output contains '\0' for boolean tests.
assert(std::basic_string<CharT>(out, it) == expected);
}
};
auto test_exception =
[]<class CharT, class... Args>(std::string_view what, std::basic_string<CharT> fmt, const Args&... args) {
#ifndef TEST_HAS_NO_EXCEPTIONS
try {
std::basic_string<CharT> out;
std::format_to(std::back_inserter(out), std::locale(), fmt, args...);
assert(false);
} catch (std::format_error& e) {
LIBCPP_ASSERT(e.what() == what);
return;
}
assert(false);
#else
(void)what;
(void)fmt;
(void)sizeof...(args);
#endif
};
int main(int, char**) {
format_tests<char>(test, test_exception);
#ifndef TEST_HAS_NO_WIDE_CHARACTERS
format_tests_char_to_wchar_t(test);
format_tests<wchar_t>(test, test_exception);
#endif
return 0;
}
| 31.655556 | 110 | 0.604072 | [
"vector"
] |
b404294ef39380ac268fef4614e33b27fc7fa002 | 4,522 | hpp | C++ | src/radiance/WindowGroup.hpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 354 | 2015-01-10T17:46:11.000Z | 2022-03-29T10:00:00.000Z | src/radiance/WindowGroup.hpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3,243 | 2015-01-02T04:54:45.000Z | 2022-03-31T17:22:22.000Z | src/radiance/WindowGroup.hpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 157 | 2015-01-07T15:59:55.000Z | 2022-03-30T07:46:09.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef RADIANCE_WINDOWGROUP_HPP
#define RADIANCE_WINDOWGROUP_HPP
#include "RadianceAPI.hpp"
#include "../model/Space.hpp"
#include "../model/ConstructionBase.hpp"
#include "../model/ShadingControl.hpp"
#include "../utilities/geometry/Point3d.hpp"
#include "../utilities/geometry/Vector3d.hpp"
#include "../utilities/core/Logger.hpp"
namespace openstudio {
namespace radiance {
struct RADIANCE_API WindowGroupControl
{
boost::optional<double> largestArea;
boost::optional<openstudio::Point3d> centroid;
boost::optional<openstudio::Vector3d> outwardNormal;
};
/** A WindowGroup represents a group of windows which are simulated together in the single or three phase method.
*/
class RADIANCE_API WindowGroup
{
public:
WindowGroup(const openstudio::Vector3d& outwardNormal, const model::Space& space, const model::ConstructionBase& construction,
const boost::optional<model::ShadingControl>& shadingControl);
bool operator==(const WindowGroup& other) const;
std::string name() const;
void setName(const std::string& name);
openstudio::Vector3d outwardNormal() const;
model::Space space() const;
model::ConstructionBase construction() const;
boost::optional<model::ShadingControl> shadingControl() const;
std::string interiorShadeBSDF() const;
std::string shadingControlType() const;
// returns numeric value if it exists, returns schedule name for scheduled control, n/a otherwise
std::string shadingControlSetpoint() const;
void addWindowPolygon(const openstudio::Point3dVector& windowPolygon);
WindowGroupControl windowGroupControl() const;
std::string windowGroupPoints() const;
private:
std::string m_name;
openstudio::Vector3d m_outwardNormal;
model::Space m_space;
model::ConstructionBase m_construction;
boost::optional<model::ShadingControl> m_shadingControl;
std::vector<openstudio::Point3dVector> m_windowPolygons;
REGISTER_LOGGER("openstudio.radiance.ForwardTranslator");
};
// vector of WindowGroup
typedef std::vector<WindowGroup> WindowGroupVector;
} // namespace radiance
} // namespace openstudio
#endif //RADIANCE_LIGHTFIXTURE_HPP
| 42.261682 | 130 | 0.721141 | [
"geometry",
"vector",
"model"
] |
b4058ecf219336f07e6762f4d576adf461d7f5ae | 596 | cpp | C++ | hiro/core/sizable.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 10 | 2019-12-19T01:19:41.000Z | 2021-02-18T16:30:29.000Z | hiro/core/sizable.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | hiro/core/sizable.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | #if defined(Hiro_Sizable)
auto mSizable::allocate() -> pObject* {
return new pSizable(*this);
}
auto mSizable::doSize() const -> void {
if(state.onSize) return state.onSize();
}
auto mSizable::geometry() const -> Geometry {
return state.geometry;
}
auto mSizable::minimumSize() const -> Size {
return signal(minimumSize);
}
auto mSizable::onSize(const function<void ()>& callback) -> type& {
state.onSize = callback;
return *this;
}
auto mSizable::setGeometry(Geometry geometry) -> type& {
state.geometry = geometry;
signal(setGeometry, geometry);
return *this;
}
#endif
| 19.225806 | 67 | 0.692953 | [
"geometry"
] |
b4072441286a44cac3fde97ada5614434dd3a326 | 4,872 | cpp | C++ | cpp/src/cylon/arrow/arrow_partition_kernels.cpp | nirandaperera/cylon | bc9e4dc1285a4a1313577e696ae858437235ace9 | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/arrow/arrow_partition_kernels.cpp | nirandaperera/cylon | bc9e4dc1285a4a1313577e696ae858437235ace9 | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/arrow/arrow_partition_kernels.cpp | nirandaperera/cylon | bc9e4dc1285a4a1313577e696ae858437235ace9 | [
"Apache-2.0"
] | null | null | null | /*
* 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 "arrow_partition_kernels.hpp"
namespace cylon {
std::shared_ptr<ArrowPartitionKernel> GetPartitionKernel(arrow::MemoryPool *pool,
const std::shared_ptr<arrow::DataType> &data_type) {
std::shared_ptr<ArrowPartitionKernel> kernel;
switch (data_type->id()) {
case arrow::Type::UINT8:kernel = std::make_shared<UInt8ArrayHashPartitioner>(pool);
break;
case arrow::Type::INT8:kernel = std::make_shared<Int8ArrayHashPartitioner>(pool);
break;
case arrow::Type::UINT16:kernel = std::make_shared<UInt16ArrayHashPartitioner>(pool);
break;
case arrow::Type::INT16:kernel = std::make_shared<Int16ArrayHashPartitioner>(pool);
break;
case arrow::Type::UINT32:kernel = std::make_shared<UInt32ArrayHashPartitioner>(pool);
break;
case arrow::Type::INT32:kernel = std::make_shared<Int32ArrayHashPartitioner>(pool);
break;
case arrow::Type::UINT64:kernel = std::make_shared<UInt64ArrayHashPartitioner>(pool);
break;
case arrow::Type::INT64:kernel = std::make_shared<Int64ArrayHashPartitioner>(pool);
break;
case arrow::Type::FLOAT:kernel = std::make_shared<FloatArrayHashPartitioner>(pool);
break;
case arrow::Type::DOUBLE:kernel = std::make_shared<DoubleArrayHashPartitioner>(pool);
break;
case arrow::Type::STRING:kernel = std::make_shared<StringHashPartitioner>(pool);
break;
case arrow::Type::BINARY:kernel = std::make_shared<BinaryHashPartitionKernel>(pool);
break;
case arrow::Type::FIXED_SIZE_BINARY:
kernel = std::make_shared<FixedSizeBinaryHashPartitionKernel>(pool);
break;
default:LOG(FATAL) << "Un-known type";
return NULLPTR;
}
return kernel;
}
std::shared_ptr<ArrowPartitionKernel> GetPartitionKernel(arrow::MemoryPool *pool,
const std::shared_ptr<arrow::Array> &values) {
return GetPartitionKernel(pool, values->type());
}
cylon::Status HashPartitionArray(arrow::MemoryPool *pool,
const std::shared_ptr<arrow::Array> &values,
const std::vector<int> &targets,
std::vector<int64_t> *outPartitions,
std::vector<uint32_t> &counts) {
std::shared_ptr<ArrowPartitionKernel> kernel = GetPartitionKernel(pool, values);
kernel->Partition(values, targets, outPartitions, counts);
return cylon::Status::OK();
}
cylon::Status HashPartitionArrays(arrow::MemoryPool *pool,
const std::vector<std::shared_ptr<arrow::Array>> &values,
int64_t length,
const std::vector<int> &targets,
std::vector<int64_t> *outPartitions,
std::vector<uint32_t> &counts) {
std::vector<std::shared_ptr<ArrowPartitionKernel>> hash_kernels;
for (const auto &array : values) {
auto hash_kernel = GetPartitionKernel(pool, array);
if (hash_kernel == NULLPTR) {
LOG(FATAL) << "Un-known type";
return cylon::Status(cylon::NotImplemented, "Not implemented or unsupported data type.");
}
hash_kernels.push_back(hash_kernel);
}
for (int64_t index = 0; index < length; index++) {
int64_t hash_code = 1;
int64_t array_index = 0;
for (const auto &array : values) {
hash_code = 31 * hash_code + hash_kernels[array_index++]->ToHash(array, index);
}
int kX = targets[hash_code % targets.size()];
outPartitions->push_back(kX);
counts[kX]++;
}
return cylon::Status::OK();
}
RowHashingKernel::RowHashingKernel(const std::vector<std::shared_ptr<arrow::Field>> &fields,
arrow::MemoryPool *memory_pool) {
for (auto const &field : fields) {
this->hash_kernels.push_back(std::shared_ptr<ArrowPartitionKernel>(
GetPartitionKernel(memory_pool, field->type())));
}
}
int32_t RowHashingKernel::Hash(const std::shared_ptr<arrow::Table> &table, int64_t row) {
int64_t hash_code = 1;
for (int c = 0; c < table->num_columns(); ++c) {
hash_code = 31 * hash_code + this->hash_kernels[c]->ToHash(table->column(c)->chunk(0), row);
}
return hash_code;
}
} // namespace cylon
| 42 | 99 | 0.651683 | [
"vector"
] |
b40726784d384099cf5a4f248572445bc4b37efb | 585 | cpp | C++ | files/IO/proto_main.cpp | mipt-npm-study/sciprog-python | 09a0d99254fcd559ec8d13bedd5521e98e86b3ce | [
"MIT"
] | 3 | 2021-09-12T20:54:08.000Z | 2021-09-21T14:49:15.000Z | files/IO/proto_main.cpp | mipt-npm-study/sciprog-python | 09a0d99254fcd559ec8d13bedd5521e98e86b3ce | [
"MIT"
] | null | null | null | files/IO/proto_main.cpp | mipt-npm-study/sciprog-python | 09a0d99254fcd559ec8d13bedd5521e98e86b3ce | [
"MIT"
] | 2 | 2021-09-14T13:15:41.000Z | 2021-09-14T15:18:01.000Z |
#include "example.pb.h"
#include <fstream>
using namespace std;
int main(){
auto list = new sciprog::ParticleList();
for (int i = 0; i < 10000; ++i){
auto data = list->add_particle();
data->set_id(i);
data->set_energy(i*3.14);
auto vector = new sciprog::Vector();
vector->set_x(-i/100);
vector->set_y(i/100);
vector->set_z(i*i/10000);
data->set_allocated_momentum_direction(vector);
}
ofstream fout;
fout.open("example.bin");
list->SerializeToOstream(&fout);
fout.close();
return 0;
} | 22.5 | 55 | 0.582906 | [
"vector"
] |
b4089d9e162c3719dde9a9f5a636cf533bfc52b2 | 10,592 | cpp | C++ | miniapps/mtop/seqheat.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | miniapps/mtop/seqheat.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | miniapps/mtop/seqheat.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// ----------------------------------------------------------------
// SeqHeat Miniapp: Gradients of PDE constrained objective function
// ----------------------------------------------------------------
// (Sequential Version)
//
// The following example computes the gradients of a specified objective
// function with respect to parametric fields. The objective function is having
// the following form f(u(\rho)) where u(\rho) is a solution of a specific state
// problem (in the example that is the diffusion equation), and \rho is a
// parametric field discretized by finite elements. The parametric field (also
// called density in topology optimization) controls the coefficients of the
// state equation. For the considered case, the density controls the diffusion
// coefficient within the computational domain.
//
// For more information, the users are referred to:
//
// Hinze, M.; Pinnau, R.; Ulbrich, M. & Ulbrich, S.
// Optimization with PDE Constraints
// Springer Netherlands, 2009
//
// Bendsøe, M. P. & Sigmund, O.
// Topology Optimization - Theory, Methods and Applications
// Springer Verlag, Berlin Heidelberg, 2003
//
// Compile with: make seqheat
//
// Sample runs:
//
// seqheat -m ../../data/star-mixed.mesh
// seqheat --visualization
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "mtop_integrators.hpp"
int main(int argc, char *argv[])
{
const char *mesh_file = "../../data/star.vtk";
int ser_ref_levels = 1;
int order = 2;
bool visualization = false;
double newton_rel_tol = 1e-4;
double newton_abs_tol = 1e-6;
int newton_iter = 10;
int print_level = 0;
mfem::OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use.");
args.AddOption(&ser_ref_levels,
"-rs",
"--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&order,
"-o",
"--order",
"Order (degree) of the finite elements.");
args.AddOption(&visualization,
"-vis",
"--visualization",
"-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&newton_rel_tol,
"-rel",
"--relative-tolerance",
"Relative tolerance for the Newton solve.");
args.AddOption(&newton_abs_tol,
"-abs",
"--absolute-tolerance",
"Absolute tolerance for the Newton solve.");
args.AddOption(&newton_iter,
"-it",
"--newton-iterations",
"Maximum iterations for the Newton solve.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(std::cout);
return 1;
}
args.PrintOptions(std::cout);
// Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral and hexahedral meshes
// with the same code.
mfem::Mesh *mesh = new mfem::Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// Refine the mesh in serial to increase the resolution. In this example
// we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
// a command-line parameter.
for (int lev = 0; lev < ser_ref_levels; lev++)
{
mesh->UniformRefinement();
}
// Diffusion coefficient
mfem::ConstantCoefficient* diffco=new mfem::ConstantCoefficient(1.0);
// Heat source
mfem::ConstantCoefficient* loadco=new mfem::ConstantCoefficient(1.0);
// Define the q-function
mfem::QLinearDiffusion* qfun=new mfem::QLinearDiffusion(*diffco,*loadco,1.0,
1e-7,4.0,0.5);
// Define FE collection and space for the state solution
mfem::H1_FECollection sfec(order, dim);
mfem::FiniteElementSpace* sfes=new mfem::FiniteElementSpace(mesh,&sfec,1);
// Define FE collection and space for the density field
mfem::L2_FECollection pfec(order, dim);
mfem::FiniteElementSpace* pfes=new mfem::FiniteElementSpace(mesh,&pfec,1);
// Define the arrays for the nonlinear form
mfem::Array<mfem::FiniteElementSpace*> asfes;
mfem::Array<mfem::FiniteElementSpace*> apfes;
asfes.Append(sfes);
apfes.Append(pfes);
// Define parametric block nonlinear form using single scalar H1 field
// and L2 scalar density field
mfem::ParametricBNLForm* nf=new mfem::ParametricBNLForm(asfes,apfes);
// Add the parametric integrator
nf->AddDomainIntegrator(new mfem::ParametricLinearDiffusion(*qfun));
// Define true block vectors for state, adjoint, residual
mfem::BlockVector solbv; solbv.Update(nf->GetBlockTrueOffsets()); solbv=0.0;
mfem::BlockVector adjbv; adjbv.Update(nf->GetBlockTrueOffsets()); adjbv=0.0;
mfem::BlockVector resbv; resbv.Update(nf->GetBlockTrueOffsets()); resbv=0.0;
// Define true block vectors for parametric field and gradients
mfem::BlockVector prmbv; prmbv.Update(nf->ParamGetBlockTrueOffsets());
prmbv=0.0;
mfem::BlockVector grdbv; grdbv.Update(nf->ParamGetBlockTrueOffsets());
grdbv=0.0;
// Set the BC for the physics
mfem::Array<mfem::Array<int> *> ess_bdr;
mfem::Array<mfem::Vector*> ess_rhs;
ess_bdr.Append(new mfem::Array<int>(mesh->bdr_attributes.Max()));
ess_rhs.Append(nullptr);
(*ess_bdr[0]) = 1;
nf->SetEssentialBC(ess_bdr,ess_rhs);
delete ess_bdr[0];
// Define the linear solvers
mfem::GMRESSolver *gmres;
gmres = new mfem::GMRESSolver();
gmres->SetAbsTol(newton_abs_tol/10);
gmres->SetRelTol(newton_rel_tol/10);
gmres->SetMaxIter(300);
gmres->SetPrintLevel(print_level);
// Define the Newton solver
mfem::NewtonSolver *ns;
ns = new mfem::NewtonSolver();
ns->iterative_mode = true;
ns->SetSolver(*gmres);
ns->SetOperator(*nf);
ns->SetPrintLevel(print_level);
ns->SetRelTol(newton_rel_tol);
ns->SetAbsTol(newton_abs_tol);
ns->SetMaxIter(newton_iter);
// Solve the problem
// Set the density to 0.5
prmbv=0.5;
nf->SetParamFields(prmbv); // Set the density
// Define the RHS
mfem::Vector b;
solbv=0.0;
// Newton solve
ns->Mult(b, solbv);
// Compute the residual
nf->Mult(solbv,resbv);
std::cout<<"Norm residual="<<resbv.Norml2()<<std::endl;
// Compute the energy of the state system
double energy = nf->GetEnergy(solbv);
std::cout<<"energy ="<< energy<<std::endl;
// Define the block nonlinear form utilized for representing the
// objective. The input is the state array asfes defined earlier.
mfem::BlockNonlinearForm* ob=new mfem::BlockNonlinearForm(asfes);
// Add the integrator for the objective
ob->AddDomainIntegrator(new mfem::DiffusionObjIntegrator());
// Compute the objective
double obj=ob->GetEnergy(solbv);
std::cout<<"Objective ="<<obj<<std::endl;
// Solve the adjoint
{
mfem::BlockVector adjrhs; adjrhs.Update(nf->GetBlockTrueOffsets()); adjrhs=0.0;
// Compute the RHS for the adjoint
ob->Mult(solbv, adjrhs);
// Get the tangent matrix from the state problem
mfem::BlockOperator& A=nf->GetGradient(solbv);
// We do not need to transpose the operator for diffusion
gmres->SetOperator(A.GetBlock(0,0));
// Compute the adjoint solution
gmres->Mult(adjrhs.GetBlock(0), adjbv.GetBlock(0));
}
// Compute gradients
nf->SetAdjointFields(adjbv);
nf->SetStateFields(solbv);
nf->ParamMult(prmbv, grdbv);
// Dump out the data
if (visualization)
{
mfem::ParaViewDataCollection *dacol=new mfem::ParaViewDataCollection("SeqHeat",
mesh);
mfem::GridFunction gfgrd(pfes); gfgrd.SetFromTrueDofs(grdbv.GetBlock(0));
mfem::GridFunction gfdns(pfes); gfdns.SetFromTrueDofs(prmbv.GetBlock(0));
// Define state grid function
mfem::GridFunction gfsol(sfes); gfsol.SetFromTrueDofs(solbv.GetBlock(0));
mfem::GridFunction gfadj(sfes); gfadj.SetFromTrueDofs(adjbv.GetBlock(0));
dacol->SetLevelsOfDetail(order);
dacol->RegisterField("sol", &gfsol);
dacol->RegisterField("adj", &gfadj);
dacol->RegisterField("dns", &gfdns);
dacol->RegisterField("grd", &gfgrd);
dacol->SetTime(1.0);
dacol->SetCycle(1);
dacol->Save();
delete dacol;
}
// FD check
{
// Perturbation vector
mfem::BlockVector prtbv;
mfem::BlockVector tmpbv;
prtbv.Update(nf->ParamGetBlockTrueOffsets());
tmpbv.Update(nf->ParamGetBlockTrueOffsets());
// Generate the perturbation
prtbv.GetBlock(0).Randomize();
prtbv*=1.0;
// Scaling parameter
double lsc=1.0;
// Compute initial objective
double gQoI=ob->GetEnergy(solbv);
double lQoI;
// Norm of the perturbation
double nd=mfem::InnerProduct(prtbv,prtbv);
// Projection of the adjoint gradient on the perturbation
double td=mfem::InnerProduct(prtbv,grdbv);
// Normalize the directional derivative
td=td/nd;
for (int l = 0; l < 10; l++)
{
lsc/=10.0;
// Scale the perturbation
prtbv/=10.0;
// Add the perturbation to the original density
add(prmbv,prtbv,tmpbv);
nf->SetParamFields(tmpbv);
// Solve the physics
ns->Mult(b,solbv);
// Compute the objective
lQoI=ob->GetEnergy(solbv);
// FD approximation
double ld=(lQoI-gQoI)/lsc;
std::cout << "dx=" << lsc << " FD gradient=" << ld/nd
<< " adjoint gradient=" << td
<< " err=" << std::fabs(ld/nd-td) << std::endl;
}
}
delete ob;
delete ns;
delete gmres;
delete nf;
delete pfes;
delete sfes;
delete qfun;
delete loadco;
delete diffco;
delete mesh;
return 0;
}
| 34.501629 | 86 | 0.631798 | [
"mesh",
"vector"
] |
b41b38c6047c336887cc9ac02043209f6e51cd3f | 8,727 | cpp | C++ | lib/src/processMonitor/processMonitor.cpp | xan105/node-processMonitor | 3623bd1f72e1f9ba3e68c9d97480c300e9706ce5 | [
"MIT"
] | null | null | null | lib/src/processMonitor/processMonitor.cpp | xan105/node-processMonitor | 3623bd1f72e1f9ba3e68c9d97480c300e9706ce5 | [
"MIT"
] | 5 | 2020-11-22T15:10:12.000Z | 2022-03-21T10:32:04.000Z | lib/src/processMonitor/processMonitor.cpp | xan105/node-processMonitor | 3623bd1f72e1f9ba3e68c9d97480c300e9706ce5 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2020-2021 Anthony Beaumont
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "stdafx.h" // vs2017 use "pch.h" for vs2019
#include "eventsink.h"
#include "wstring.h"
#include <vector>
typedef void(__stdcall Callback)(char const * event, char const * process, char const * handle, char const * filepath);
//cf: https://docs.microsoft.com/en-us/windows/win32/wmisdk/example--receiving-event-notifications-through-wmi-
class WQL
{
private:
HRESULT hres;
IWbemLocator *pLoc;
IWbemServices *pSvc;
IUnsecuredApartment* pUnsecApp;
EventSink* pSink;
IUnknown* pStubUnk;
IWbemObjectSink* pStubSink;
bool isReady = false;
const _bstr_t WQL_filterWindowsNoise = (
"AND NOT TargetInstance.ExecutablePath LIKE '%Windows\\\\System32%'"
"AND NOT TargetInstance.ExecutablePath LIKE '%Windows\\\\SysWOW64%'"
"AND TargetInstance.Name != 'FileCoAuth.exe'" //OneDrive
);
const _bstr_t WQL_filterUsualProgramLocations = (
"AND NOT TargetInstance.ExecutablePath LIKE '%Program Files%'"
"AND NOT TargetInstance.ExecutablePath LIKE '%Program Files (x86)%'"
"AND NOT TargetInstance.ExecutablePath LIKE '%AppData\\\\Local%'"
"AND NOT TargetInstance.ExecutablePath LIKE '%AppData\\\\Roaming%'"
);
vector<string> explode(const string &delimiter, const string &str)
{
vector<string> arr;
size_t strleng = str.length();
size_t delleng = delimiter.length();
if (delleng == 0)
return arr;//no change
size_t i = 0;
size_t k = 0;
while (i < strleng)
{
size_t j = 0;
while (i + j < strleng && j < delleng && str[i + j] == delimiter[j])
j++;
if (j == delleng)//found delimiter
{
arr.push_back(str.substr(k, i - k));
i += delleng;
k = i;
}
else
{
i++;
}
}
arr.push_back(str.substr(k, i - k));
return arr;
}
public:
WQL() {} //constructor
int init()
{
if (!this->isReady) {
// Step 1: Initialize COM.
this->hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(this->hres))
{
this->isReady = false;
if (this->hres == RPC_E_CHANGED_MODE) {
return 1; //COM library for the calling thread already initialized by 3rd party with different threading model. This lib requires 'COINIT_MULTITHREADED'
}
else {
return 2; //Failed to initialize COM library for the calling thread
}
}
// Step 2: Set general COM security levels
this->hres = CoInitializeSecurity(
NULL,
-1, // COM negotiates service
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if (FAILED(this->hres))
{
CoUninitialize();
this->isReady = false;
return 3; //Failed to initialize security
}
// Step 3: Obtain the initial locator to WMI
this->pLoc = NULL;
this->hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *)&this->pLoc);
if (FAILED(this->hres))
{
CoUninitialize();
this->isReady = false;
return 4; //Failed to create IWbemLocator object
}
// Step 4: Connect to WMI through the IWbemLocator::ConnectServer method
this->pSvc = NULL;
// Connect to the local root\cimv2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
this->hres = this->pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
NULL,
NULL,
0,
NULL,
0,
0,
&this->pSvc
);
if (FAILED(this->hres))
{
this->pLoc->Release();
CoUninitialize();
this->isReady = false;
return 5; //Could not connect to ROOT\\CIMV2 WMI namespace
}
// Step 5: Set security levels on the proxy
this->hres = CoSetProxyBlanket(
this->pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(this->hres))
{
this->pSvc->Release();
this->pLoc->Release();
CoUninitialize();
this->isReady = false;
return 6; //Could not set proxy blanket
}
// Step 6: Receive event notifications
// Use an unsecured apartment for security
this->pUnsecApp = NULL;
this->hres = CoCreateInstance(CLSID_UnsecuredApartment, NULL,
CLSCTX_LOCAL_SERVER, IID_IUnsecuredApartment,
(void**)&this->pUnsecApp);
this->pSink = new EventSink;
pSink->AddRef();
this->pStubUnk = NULL;
pUnsecApp->CreateObjectStub(this->pSink, &this->pStubUnk);
this->pStubSink = NULL;
pStubUnk->QueryInterface(IID_IWbemObjectSink,
(void **)&this->pStubSink);
this->isReady = true;
}
return 0;
}
//WMI QUERY
bool queryAsync_InstanceEvent(bool creation, bool deletion, bool filterWindowsNoise, bool filterUsualProgramLocations, bool whitelist, std::string custom_filter = "")
{
_bstr_t WQL_Query = ("SELECT * ");
if (creation && !deletion) {
WQL_Query = WQL_Query + "FROM __InstanceCreationEvent WITHIN 1 "; //Creation
}
else if (deletion && !creation) {
WQL_Query = WQL_Query + "FROM __InstanceDeletionEvent WITHIN 1 "; //Deletion
}
else {
WQL_Query = WQL_Query + "FROM __InstanceOperationEvent WITHIN 1 "; //Creation + Deletion
}
WQL_Query = WQL_Query + "WHERE TargetInstance ISA 'Win32_Process'";
if (filterWindowsNoise) {
WQL_Query = WQL_Query + this->WQL_filterWindowsNoise;
}
if (filterUsualProgramLocations) {
WQL_Query = WQL_Query + this->WQL_filterUsualProgramLocations;
}
if (custom_filter.length() > 0) {
vector<string> v = this->explode(",", custom_filter);
for (size_t i = 0; i < v.size(); i++) {
if(whitelist) {
if (i == 0) {
WQL_Query = WQL_Query + "AND ( TargetInstance.Name = '" + v[i].c_str() + "'";
}
else {
WQL_Query = WQL_Query + "OR TargetInstance.Name = '" + v[i].c_str() + "'";
}
} else {
WQL_Query = WQL_Query + "AND TargetInstance.Name != '" + v[i].c_str() + "'";
}
}
if (whitelist) WQL_Query = WQL_Query + ")";
}
this->hres = this->pSvc->ExecNotificationQueryAsync(
_bstr_t("WQL"),
WQL_Query,
WBEM_FLAG_SEND_STATUS,
NULL,
this->pStubSink);
if (FAILED(this->hres))
{
this->close();
return false;
}
else
{
return true;
}
}
void cancel()
{
this->hres = this->pSvc->CancelAsyncCall(this->pStubSink);
}
void close()
{
this->pSvc->Release();
this->pLoc->Release();
this->pUnsecApp->Release();
this->pStubUnk->Release();
this->pSink->Release();
this->pStubSink->Release();
CoUninitialize();
this->isReady = false;
}
};
WQL monitor;
Callback* callback;
#define APICALL __declspec(dllexport)
extern "C"
{
APICALL int createEventSink()
{
return monitor.init();
}
APICALL void closeEventSink()
{
monitor.cancel();
monitor.close();
}
APICALL bool getInstanceEvent(bool creation, bool deletion, bool filterWindowsNoise, bool filterUsualProgramLocations, bool whitelist, char const * custom_filter)
{
return monitor.queryAsync_InstanceEvent(creation, deletion, filterWindowsNoise, filterUsualProgramLocations, whitelist, custom_filter);
}
APICALL void setCallback(Callback* callbackPtr) {
callback = callbackPtr;
return;
}
} | 26.525836 | 167 | 0.661739 | [
"object",
"vector",
"model"
] |
b41bbda00926d4299e4db46224165619d606bd97 | 29,531 | cc | C++ | proxy/logging/LogUtils.cc | mingzym/zym4T | 2e5d46250d79def96e0979ebb2a13efc53993e47 | [
"Apache-2.0"
] | 2 | 2019-01-19T02:49:35.000Z | 2019-06-12T09:21:10.000Z | proxy/logging/LogUtils.cc | mingzym/zym4T | 2e5d46250d79def96e0979ebb2a13efc53993e47 | [
"Apache-2.0"
] | null | null | null | proxy/logging/LogUtils.cc | mingzym/zym4T | 2e5d46250d79def96e0979ebb2a13efc53993e47 | [
"Apache-2.0"
] | null | null | null | /** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/***************************************************************************
LogUtils.cc
This file contains a set of utility routines that are used throughout the
logging implementation.
***************************************************************************/
#include "ink_config.h"
#include "ink_unused.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#if (HOST_OS == solaris)
#include <netdb.h>
#else
#include "/usr/include/netdb.h" // need following instead of <netdb.h>
#endif
#include "P_RecProcess.h"
#define LOG_SignalManager REC_SignalManager
// REC_SIGNAL_LOGGING_ERROR is defined in I_RecSignals.h
// REC_SIGNAL_LOGGING_WARNING is defined in I_RecSignals.h
#include "Compatability.h"
#include "LogUtils.h"
#include "LogLimits.h"
#include "LogFormatType.h"
/*-------------------------------------------------------------------------
-------------------------------------------------------------------------*/
LogUtils::LogUtils(DoNotConstruct object)
{
ink_release_assert(!"you can't construct a LogUtils object");
}
/*-------------------------------------------------------------------------
LogUtils::timestamp_to_str
This routine will convert a timestamp (seconds) into a short string,
of the format "%Y%m%d.%Hh%Mm%Ss".
Since the resulting buffer is passed in, this routine is thread-safe.
Return value is the number of characters placed into the array, not
including the NULL.
-------------------------------------------------------------------------*/
int
LogUtils::timestamp_to_str(long timestamp, char *buf, int size)
{
static const char *format_str = "%Y%m%d.%Hh%Mm%Ss";
struct tm res;
struct tm *tms;
tms = ink_localtime_r((const time_t *) ×tamp, &res);
return strftime(buf, size, format_str, tms);
}
/*-------------------------------------------------------------------------
LogUtils::timestamp_to_netscape_str
This routine will convert a timestamp (seconds) into a string compatible
with the Netscape logging formats.
This routine is intended to be called from the (single) logging thread,
and is therefore NOT MULTITHREADED SAFE. There is a single, static,
string buffer that the time string is constructed into and returned.
-------------------------------------------------------------------------*/
char *
LogUtils::timestamp_to_netscape_str(long timestamp)
{
static char timebuf[64]; // NOTE: not MT safe
static char gmtstr[16];
static long last_timestamp = 0;
static char bad_time[] = "Bad timestamp";
// safety check
if (timestamp < 0) {
return bad_time;
}
//
// since we may have many entries per second, lets only do the
// formatting if we actually have a new timestamp.
//
if (timestamp != last_timestamp) {
//
// most of this garbage is simply to find out the offset from GMT,
// taking daylight savings into account.
//
#ifdef NEED_ALTZONE_DEFINED
time_t altzone = timezone;
#endif
struct tm res;
struct tm *tms = ink_localtime_r((const time_t *) ×tamp, &res);
#if (HOST_OS == freebsd) || (HOST_OS == darwin)
long zone = -tms->tm_gmtoff; // double negative!
#else
long zone = (tms->tm_isdst > 0) ? altzone : timezone;
#endif
int offset;
char sign;
if (zone >= 0) {
offset = zone / 60;
sign = '-';
} else {
offset = zone / -60;
sign = '+';
}
int glen = ink_snprintf(gmtstr, 16, "%c%.2d%.2d",
sign, offset / 60, offset % 60);
strftime(timebuf, 64 - glen, "%d/%b/%Y:%H:%M:%S ", tms);
strncat(timebuf, gmtstr, sizeof(timebuf) - strlen(timebuf) - 1);
last_timestamp = timestamp;
}
return timebuf;
}
/*-------------------------------------------------------------------------
LogUtils::timestamp_to_date_str
This routine will convert a timestamp (seconds) into a W3C compatible
date string.
-------------------------------------------------------------------------*/
char *
LogUtils::timestamp_to_date_str(long timestamp)
{
static char timebuf[64]; // NOTE: not MT safe
static long last_timestamp = 0;
static char bad_time[] = "Bad timestamp";
// safety check
if (timestamp < 0) {
return bad_time;
}
//
// since we may have many entries per second, lets only do the
// formatting if we actually have a new timestamp.
//
if (timestamp != last_timestamp) {
struct tm res;
struct tm *tms = ink_localtime_r((const time_t *) ×tamp, &res);
strftime(timebuf, 64, "%Y-%m-%d", tms);
last_timestamp = timestamp;
}
return timebuf;
}
/*-------------------------------------------------------------------------
LogUtils::timestamp_to_time_str
This routine will convert a timestamp (seconds) into a W3C compatible
time string.
-------------------------------------------------------------------------*/
char *
LogUtils::timestamp_to_time_str(long timestamp)
{
static char timebuf[64]; // NOTE: not MT safe
static long last_timestamp = 0;
static char bad_time[] = "Bad timestamp";
// safety check
if (timestamp < 0) {
return bad_time;
}
//
// since we may have many entries per second, lets only do the
// formatting if we actually have a new timestamp.
//
if (timestamp != last_timestamp) {
struct tm res;
struct tm *tms = ink_localtime_r((const time_t *) ×tamp, &res);
strftime(timebuf, 64, "%H:%M:%S", tms);
last_timestamp = timestamp;
}
return timebuf;
}
/*-------------------------------------------------------------------------
LogUtils::ip_from_host
This routine performs a DNS lookup on the given hostname and returns the
associated IP address in the form of a single unsigned int (s_addr). If
the host is not found or some other error occurs, then zero is returned.
-------------------------------------------------------------------------*/
unsigned
LogUtils::ip_from_host(char *host)
{
unsigned ip = 0;
ink_gethostbyname_r_data d;
struct hostent *he = 0;
ink_assert(host != NULL);
he = ink_gethostbyname_r(host, &d);
if (he != NULL) {
ip = ((struct in_addr *) (he->h_addr_list[0]))->s_addr;
}
return ip;
}
/*-------------------------------------------------------------------------
LogUtils::manager_alarm
This routine provides a convenient abstraction for sending the traffic
server manager process an alarm. The logging system can send
LOG_ALARM_N_TYPES different types of alarms, as defined in LogUtils.h.
Subsequent alarms of the same type will override the previous alarm
entry.
-------------------------------------------------------------------------*/
void
LogUtils::manager_alarm(LogUtils::AlarmType alarm_type, char *msg, ...)
{
char msg_buf[LOG_MAX_FORMATTED_LINE];
va_list ap;
ink_assert(alarm_type >= 0 && alarm_type < LogUtils::LOG_ALARM_N_TYPES);
if (msg == NULL) {
snprintf(msg_buf, sizeof(msg_buf), "No Message");
} else {
va_start(ap, msg);
ink_vsnprintf(msg_buf, LOG_MAX_FORMATTED_LINE, msg, ap);
va_end(ap);
}
switch (alarm_type) {
case LogUtils::LOG_ALARM_ERROR:
LOG_SignalManager(REC_SIGNAL_LOGGING_ERROR, msg_buf);
break;
case LogUtils::LOG_ALARM_WARNING:
LOG_SignalManager(REC_SIGNAL_LOGGING_WARNING, msg_buf);
break;
default:
ink_assert(false);
}
}
/*-------------------------------------------------------------------------
LogUtils::strip_trailing_newline
This routine examines the given string buffer to see if the last
character before the trailing NULL is a newline ('\n'). If so, it will
be replaced with a NULL, thus stripping it and reducing the length of
the string by one.
-------------------------------------------------------------------------*/
void
LogUtils::strip_trailing_newline(char *buf)
{
if (buf != NULL) {
int len =::strlen(buf);
if (len > 0) {
if (buf[len - 1] == '\n') {
buf[len - 1] = '\0';
}
}
}
}
/*-------------------------------------------------------------------------
LogUtils::escapify_url
This routine will escapify a URL to remove spaces (and perhaps other ugly
characters) from a URL and replace them with a hex escape sequence.
Since the escapes are larger (multi-byte) than the characters being
replaced, the string returned will be longer than the string passed.
-------------------------------------------------------------------------*/
char *
LogUtils::escapify_url(Arena * arena, char *url, int len_in, int *len_out)
{
// codes_to_escape is a bitmap encoding the codes that should be escaped.
// These are all the codes defined in section 2.4.3 of RFC 2396
// (control, space, delims, and unwise) plus the tilde. In RFC 2396
// the tilde is an "unreserved" character, but we escape it because
// historically this is what the traffic_server has done.
// Note that we leave codes beyond 127 unmodified.
//
static unsigned char codes_to_escape[32] = {
0xFF, 0xFF, 0xFF, 0xFF, // control
0xB4, // space " # %
0x00, 0x00, //
0x0A, // < >
0x00, 0x00, 0x00, //
0x1E, 0x80, // [ \ ] ^ `
0x00, 0x00, //
0x1F, // { | } ~ DEL
0x00, 0x00, 0x00, 0x00, // all non-ascii characters unmodified
0x00, 0x00, 0x00, 0x00, // .
0x00, 0x00, 0x00, 0x00, // .
0x00, 0x00, 0x00, 0x00 // .
};
static char hex_digit[16] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F'
};
if (!url) {
*len_out = 0;
return (NULL);
}
// Count specials in the url, assuming that there won't be any.
//
int count = 0;
char *p = url;
char *in_url_end = url + len_in;
while (p < in_url_end) {
register unsigned char c = *p;
if (codes_to_escape[c / 8] & (1 << (7 - c % 8))) {
count++;
}
p++;
}
if (!count) {
// The common case, no escapes, so just return the source string.
//
*len_out = len_in;
return url;
}
// For each special char found, we'll need an escape string, which is
// three characters long. Count this and allocate the string required.
//
// make sure we take into account the characters we are substituting
// for when we calculate out_len !!! in other words,
// out_len = len_in + 3*count - count
//
int out_len = len_in + 2 * count;
// To play it safe, we null terminate the string we return in case
// a module that expects null-terminated strings calls escapify_url,
// so we allocate an extra byte for the EOS
//
char *new_url = (char *) arena->str_alloc(out_len + 1);
char *from = url;
char *to = new_url;
while (from < in_url_end) {
register unsigned char c = *from;
if (codes_to_escape[c / 8] & (1 << (7 - c % 8))) {
*to++ = '%';
*to++ = hex_digit[c / 16];
*to++ = hex_digit[c % 16];
} else {
*to++ = *from;
}
from++;
}
*to = 0; // null terminate string
*len_out = out_len;
return new_url;
}
/*-------------------------------------------------------------------------
LogUtils::remove_content_type_attributes
HTTP allows content types to have attributes following the main type and
subtype. For example, attributes of text/html might be charset=iso-8859.
The content type attributes are not logged, so this function strips them
from the given buffer, if present.
-------------------------------------------------------------------------*/
void
LogUtils::remove_content_type_attributes(char *type_str, int *type_len)
{
if (!type_str) {
*type_len = 0;
return;
}
// Look for a semicolon and cut out everything after that
//
char *p = (char *) memchr(type_str, ';', *type_len);
if (p) {
*type_len = p - type_str;
}
}
/*-------------------------------------------------------------------------
LogUtils::ip_to_hex_str
This routine simply writes the given IP integer [ip] in the equivalent
hexadecimal string format "xxxxxxxxxx" into the provided buffer [buf] of
size [bufLen].
It returns 1 if the provided buffer is not big enough to hold the
equivalent ip string (and its null terminator), and 0 otherwise.
If the buffer is not big enough, only the ip "segments" that completely
fit into it are written, and the buffer is null terminated.
If a non-null pointer to size_t [numCharsPtr] is given, then the
length of the ip string is written there (this is the same one would
get from calling strlen(buf) after a call to ip_to_str, so the null
string terminator is not counted).
-------------------------------------------------------------------------*/
int
LogUtils::ip_to_hex_str(unsigned ip, char *buf, size_t bufLen, size_t * numCharsPtr)
{
static const char *table = "0123456789abcdef@";
int retVal = 1;
if (buf && bufLen > 0) {
if (bufLen > 8)
bufLen = 8;
for (retVal = 0; retVal < (int) bufLen;) {
buf[retVal++] = (char) table[(ip & 0xf)];
ip >>= 4;
}
if (numCharsPtr) {
*numCharsPtr = (size_t) retVal;
}
retVal = (retVal == 8) ? 0 : 1;
}
return retVal;
};
/*-------------------------------------------------------------------------
LogUtils::timestamp_to_hex_str
This routine simply writes the given timestamp integer [time_t] in the equivalent
hexadecimal string format "xxxxxxxxxx" into the provided buffer [buf] of
size [bufLen].
It returns 1 if the provided buffer is not big enough to hold the
equivalent ip string (and its null terminator), and 0 otherwise.
If the buffer is not big enough, only the ip "segments" that completely
fit into it are written, and the buffer is null terminated.
-------------------------------------------------------------------------*/
int
LogUtils::timestamp_to_hex_str(unsigned ip, char *buf, size_t bufLen, size_t * numCharsPtr)
{
static const char *table = "0123456789abcdef@";
int retVal = 1;
int shift = 28;
if (buf && bufLen > 0) {
if (bufLen > 8)
bufLen = 8;
for (retVal = 0; retVal < (int) bufLen;) {
buf[retVal++] = (char) table[((ip >> shift) & 0xf)];
shift -= 4;
}
if (numCharsPtr) {
*numCharsPtr = (size_t) retVal;
}
retVal = (retVal == 8) ? 0 : 1;
}
return retVal;
};
/*
int
LogUtils::ip_to_str (unsigned ip, char *str, unsigned len)
{
int ret = ink_snprintf (str, len, "%u.%u.%u.%u",
(ip >> 24) & 0xff,
(ip >> 16) & 0xff,
(ip >> 8) & 0xff,
ip & 0xff);
return ((ret <= (int)len)? ret : (int)len);
}
*/
/*-------------------------------------------------------------------------
LogUtils::ip_to_str
This routine simply writes the given IP integer [ip] in the equivalent
string format "aaa.bbb.ccc.ddd" into the provided buffer [buf] of size
[bufLen].
It returns 1 if the provided buffer is not big enough to hold the
equivalent ip string (and its null terminator), and 0 otherwise.
If the buffer is not big enough, only the ip "segments" that completely
fit into it are written, and the buffer is null terminated.
If a non-null pointer to size_t [numCharsPtr] is given, then the
length of the ip string is written there (this is the same one would
get from calling strlen(buf) after a call to ip_to_str, so the null
string terminator is not counted).
-------------------------------------------------------------------------*/
int
LogUtils::ip_to_str(unsigned ip, char *buf, size_t bufLen, size_t * numCharsPtr)
{
static const char *table[] = {
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"01", "11", "21", "31", "41", "51", "61", "71", "81", "91",
"02", "12", "22", "32", "42", "52", "62", "72", "82", "92",
"03", "13", "23", "33", "43", "53", "63", "73", "83", "93",
"04", "14", "24", "34", "44", "54", "64", "74", "84", "94",
"05", "15", "25", "35", "45", "55", "65", "75", "85", "95",
"06", "16", "26", "36", "46", "56", "66", "76", "86", "96",
"07", "17", "27", "37", "47", "57", "67", "77", "87", "97",
"08", "18", "28", "38", "48", "58", "68", "78", "88", "98",
"09", "19", "29", "39", "49", "59", "69", "79", "89", "99",
"001", "101", "201", "301", "401", "501", "601", "701", "801", "901",
"011", "111", "211", "311", "411", "511", "611", "711", "811", "911",
"021", "121", "221", "321", "421", "521", "621", "721", "821", "921",
"031", "131", "231", "331", "431", "531", "631", "731", "831", "931",
"041", "141", "241", "341", "441", "541", "641", "741", "841", "941",
"051", "151", "251", "351", "451", "551", "651", "751", "851", "951",
"061", "161", "261", "361", "461", "561", "661", "761", "861", "961",
"071", "171", "271", "371", "471", "571", "671", "771", "871", "971",
"081", "181", "281", "381", "481", "581", "681", "781", "881", "981",
"091", "191", "291", "391", "491", "591", "691", "791", "891", "991",
"002", "102", "202", "302", "402", "502", "602", "702", "802", "902",
"012", "112", "212", "312", "412", "512", "612", "712", "812", "912",
"022", "122", "222", "322", "422", "522", "622", "722", "822", "922",
"032", "132", "232", "332", "432", "532", "632", "732", "832", "932",
"042", "142", "242", "342", "442", "542", "642", "742", "842", "942",
"052", "152", "252", "352", "452", "552"
};
int retVal = 0;
register unsigned int numChars = 0;
register int s;
register unsigned int n;
register int shft = 24;
const char *d;
for (int i = 0; i < 4; ++i) {
s = (ip >> shft) & 0xff;
d = table[s];
n = (s > 99 ? 4 : (s > 9 ? 3 : 2)); // '.' or '\0' included
if (bufLen >= n) {
switch (n) {
case 4:
buf[numChars++] = d[2];
case 3:
buf[numChars++] = d[1];
default:
buf[numChars++] = d[0];
}
buf[numChars++] = (i < 3 ? '.' : 0);
bufLen -= n;
shft -= 8;
} else {
retVal = 1; // not enough buffer space
buf[numChars - 1] = 0; // null terminate the buffer
break;
}
}
if (numCharsPtr) {
*numCharsPtr = numChars - 1;
}
return retVal;
};
/*-------------------------------------------------------------------------
LogUtils::str_to_ip
This routine converts the string form of an IP address
("aaa.bbb.ccc.ddd") to its equivalent integer form.
-------------------------------------------------------------------------*/
unsigned
LogUtils::str_to_ip(char *ipstr)
{
unsigned ip = 0;
unsigned a, b, c, d;
// coverity[secure_coding]
int ret = sscanf(ipstr, "%u.%u.%u.%u", &a, &b, &c, &d);
if (ret == 4) {
ip = d | (c << 8) | (b << 16) | (a << 24);
}
return ip;
}
/*-------------------------------------------------------------------------
LogUtils::valid_ipstr_format
This routine checks for a string formated as an ip address.
It makes sure that the format is valid, and allows at most three digit
numbers between the dots, but it does not check for an invalid three digit
number (e.g., 111.222.333.444 would return true)
-------------------------------------------------------------------------*/
bool LogUtils::valid_ipstr_format(char *ipstr)
{
ink_assert(ipstr);
char
c;
bool
retVal = true;
bool
lastDot = true;
int
i = 0, numDots = 0;
int
numDigits = 0;
while (c = ipstr[i++], c != 0) {
if (c == '.') {
if (lastDot || (++numDots > 3)) {
retVal = false; // consecutive dots, or more than 3
// or dot at beginning
break;
}
lastDot = true;
numDigits = 0;
} else if (ParseRules::is_digit(c)) {
++numDigits;
if (numDigits > 3) {
retVal = false;
break;
}
lastDot = false;
} else {
retVal = false; // no digit or dot
break;
}
}
// make sure there are no less than three dots and that the last char
// is not a dot
//
return (retVal == true ? (numDots == 3 && !lastDot) : false);
}
// return the seconds remaining until the time of the next roll given
// the current time, the rolling offset, and the rolling interval
//
int
LogUtils::seconds_to_next_roll(time_t time_now, int rolling_offset, int rolling_interval)
{
struct tm lt;
ink_localtime_r((const time_t *) &time_now, <);
int sidl = lt.tm_sec + lt.tm_min * 60 + lt.tm_hour * 3600;
int tr = rolling_offset * 3600;
return ((tr >= sidl ? (tr - sidl) % rolling_interval : (86400 - (sidl - tr)) % rolling_interval));
}
// Converts the ink64 val argument to a null terminated string, returning a
// pointer to the beginning of the string.
//
// The string is stored in the provided buffer if the buffer is large
// enough, otherwise the buffer is not touched, and the function returns NULL.
//
// The argument total_chars returns the number of characters that were
// converted or that would have been converted if the buffer had been large
// enough. total_chars includes the null terminator.
//
// The optional arguments req_width and pad_char allow users to
// specify a requested width of the output string (including the null
// terminator), and a padding character to use to reach that width. Padding
// happens only if the resulting string is shorter than the requested width
// and if there is room in the buffer to accomodate the padding.
//
char *
LogUtils::ink64_to_str(char *buf, unsigned int buf_size, ink64 val,
unsigned int *total_chars, unsigned int req_width, char pad_char)
{
const int local_buf_size = 32;
char local_buf[local_buf_size];
bool using_local_buffer = false;
bool negative = false;
char *out_buf;
if (buf_size < 22) {
// ink64 may not fit in provided buffer, use the local one
out_buf = &local_buf[local_buf_size - 1];
using_local_buffer = true;
} else {
out_buf = &buf[buf_size - 1];
}
unsigned int num_chars = 1; // includes eos
*out_buf-- = 0;
if (val < 0) {
val = -val;
negative = true;
}
if (val < 10) {
*out_buf-- = '0' + (char) val;
++num_chars;
} else {
do {
*out_buf-- = (char) (val % 10) + '0';
val /= 10;
++num_chars;
} while (val);
}
// pad with pad_char if needed
//
if (req_width) {
// add minus sign if padding character is not 0
if (negative && pad_char != '0') {
*out_buf = '-';
++num_chars;
} else {
out_buf++;
}
if (req_width > buf_size)
req_width = buf_size;
unsigned int num_padding = 0;
if (req_width > num_chars) {
num_padding = req_width - num_chars;
switch (num_padding) {
case 3:
*--out_buf = pad_char;
case 2:
*--out_buf = pad_char;
case 1:
*--out_buf = pad_char;
break;
default:
for (unsigned int i = 0; i < num_padding; ++i, *--out_buf = pad_char);
}
num_chars += num_padding;
}
// add minus sign if padding character is 0
if (negative && pad_char == '0') {
if (num_padding) {
*out_buf = '-'; // overwrite padding
} else {
*--out_buf = '-';
++num_chars;
}
}
} else if (negative) {
*out_buf = '-';
++num_chars;
} else {
out_buf++;
}
if (using_local_buffer) {
if (num_chars <= buf_size) {
memcpy(buf, out_buf, num_chars);
out_buf = buf;
} else {
// data does not fit return NULL
out_buf = NULL;
}
}
if (total_chars)
*total_chars = num_chars;
return out_buf;
}
// Formats the incoming timestamp_sec and timestamp_usec into a
// non-null-terminated string of the format "%d.%03d" which is
// 'almost' what squid specifies. squid specifies "%9.%03d", but
// timestamps of less than 9 digits for the seconds value correspond
// to dates before March 1973, so it is not worth dealing with those.
//
// If the provided buffer buf of size buf_size is big enough to hold the
// resulting string, then places the string in buf WITHOUT A
// NULL-TERMINATING CHARACTER, and returns the number of characters written.
//
// If the provided buffer is too small, leaves it untouched and
// returns -(required_buffer_size)
//
int
LogUtils::squid_timestamp_to_buf(char *buf, unsigned int buf_size, long timestamp_sec, long timestamp_usec)
{
int res;
const int tmp_buf_size = 32;
char tmp_buf[tmp_buf_size];
// convert seconds
//
unsigned int num_chars_s;
char *ts_s = LogUtils::ink64_to_str(tmp_buf, tmp_buf_size - 4,
timestamp_sec, &num_chars_s);
ink_debug_assert(ts_s);
// convert milliseconds
//
tmp_buf[tmp_buf_size - 5] = '.';
int ms = timestamp_usec / 1000;
unsigned int num_chars_ms;
char RELEASE_UNUSED *ts_ms = LogUtils::ink64_to_str(&tmp_buf[tmp_buf_size - 4],
4, ms, &num_chars_ms, 4, '0');
ink_debug_assert(ts_ms && num_chars_ms == 4);
unsigned int chars_to_write = num_chars_s + 3; // no eos
if (buf_size >= chars_to_write) {
memcpy(buf, ts_s, chars_to_write);
res = chars_to_write;
} else {
res = -((int) chars_to_write);
}
return res;
}
// Checks if the file pointed to by full_filename either is a regular
// file or a pipe and has write permission, or, if the file does not
// exist, if the path prefix of full_filename names a directory that
// has both execute and write permissions, so there will be no problem
// creating the file. If the size_bytes pointer is not NULL, it returns
// the size of the file through it.
// Also checks the current size limit for the file. If there is a
// limit and has_size_limit is not null, *has_size_limit is set to
// true. If there is no limit and has_size_limit is not null,
// *has_size_limit is set to false. If there is a limit and if the
// current_size_limit_bytes pointer is not null, it returns the limit
// through it.
//
// returns:
// 0 on success
// -1 on system error (no permission, etc.)
// 1 if the file full_filename points to is neither a regular file
// nor a pipe
//
int
LogUtils::file_is_writeable(const char *full_filename,
off_t * size_bytes, bool * has_size_limit, inku64 * current_size_limit_bytes)
{
int ret_val = 0;
int e;
struct stat stat_data;
e = stat(full_filename, &stat_data);
if (e == 0) {
// stat succeeded, check if full_filename points to a regular
// file/fifo and if so, check if file has write permission
//
#ifdef ASCII_PIPE_FORMAT_SUPPORTED
if (!(stat_data.st_mode & S_IFREG || stat_data.st_mode & S_IFIFO)) {
#else
if (!(stat_data.st_mode & S_IFREG)) {
#endif
ret_val = 1;
} else if (!(stat_data.st_mode & S_IWUSR)) {
errno = EACCES;
ret_val = -1;
}
if (size_bytes)
*size_bytes = stat_data.st_size;
} else {
// stat failed
//
if (errno != ENOENT) {
// can't stat file
//
ret_val = -1;
} else {
// file does not exist, check that the prefix is a directory with
// write and execute permissions
char *dir;
char *prefix = 0;
// search for forward or reverse slash in full_filename
// starting from the end
//
const char *slash = strrchr(full_filename, '/');
if (slash) {
size_t prefix_len = slash - full_filename + 1;
prefix = new char[prefix_len + 1];
memcpy(prefix, full_filename, prefix_len);
prefix[prefix_len] = 0;
dir = prefix;
} else {
dir = (char *) "."; // full_filename has no prefix, use .
}
// check if directory is executable and writeable
//
e = access(dir, X_OK | W_OK);
if (e < 0) {
ret_val = -1;
} else {
if (size_bytes)
*size_bytes = 0;
}
if (prefix) {
delete[]prefix;
}
}
}
// check for the current filesize limit
//
if (ret_val == 0) {
struct rlimit limit_data;
e = getrlimit(RLIMIT_FSIZE, &limit_data);
if (e < 0) {
ret_val = -1;
} else {
if (limit_data.rlim_cur != RLIM_INFINITY) {
if (has_size_limit)
*has_size_limit = true;
if (current_size_limit_bytes)
*current_size_limit_bytes = limit_data.rlim_cur;
} else {
if (has_size_limit)
*has_size_limit = false;
}
}
}
return ret_val;
}
| 30.602073 | 107 | 0.567641 | [
"object"
] |
b42872da59988ca4900479d0b1a75155ff1f1c1d | 2,377 | cxx | C++ | Modules/Core/Common/test/itkMetaDataObjectTest.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/Core/Common/test/itkMetaDataObjectTest.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/Core/Common/test/itkMetaDataObjectTest.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkMetaDataObject.h"
#include "itkImage.h"
#include "itkMath.h"
template <typename TMetaData>
int
testMetaData(const TMetaData & value)
{
using MetaDataType = TMetaData;
using MetaDataObjectType = itk::MetaDataObject<MetaDataType>;
typename MetaDataObjectType::Pointer metaDataObject = MetaDataObjectType::New();
metaDataObject->SetMetaDataObjectValue(value);
if (itk::Math::NotExactlyEquals(metaDataObject->GetMetaDataObjectValue(), value))
{
std::cerr << "Set value does not equal original value!" << std::endl;
return EXIT_FAILURE;
}
std::cout << "The metadata's type name is: " << metaDataObject->GetMetaDataObjectTypeName() << std::endl;
std::cout << "The metadata object: " << std::endl;
metaDataObject->Print(std::cout);
std::cout << std::endl << std::endl;
return EXIT_SUCCESS;
}
int
itkMetaDataObjectTest(int, char *[])
{
int result = EXIT_SUCCESS;
result += testMetaData<unsigned char>(24);
result += testMetaData<char>(-24);
result += testMetaData<unsigned short>(24);
result += testMetaData<short>(-24);
result += testMetaData<unsigned int>(24);
result += testMetaData<int>(-24);
result += testMetaData<unsigned long>(24);
result += testMetaData<long>(-24);
result += testMetaData<unsigned long long>(24);
result += testMetaData<long long>(-24);
result += testMetaData<float>(-24);
result += testMetaData<double>(-24);
result += testMetaData<std::string>("I T K");
using ImageType = itk::Image<unsigned short, 3>;
ImageType::Pointer image = nullptr;
result += testMetaData<ImageType::Pointer>(image);
return result;
}
| 32.121622 | 107 | 0.663021 | [
"object"
] |
b42a23e67499ac7e0806f40b77223457496240fb | 14,843 | cpp | C++ | src/bmp24.cpp | ChristianVisintin/libBMPP | b66ffec5cc1c26520ae535d0e88e29e0853afcdb | [
"MIT"
] | 4 | 2021-01-19T06:54:59.000Z | 2022-03-26T10:41:53.000Z | src/bmp24.cpp | ChristianVisintin/libBMPP | b66ffec5cc1c26520ae535d0e88e29e0853afcdb | [
"MIT"
] | 2 | 2020-05-09T05:23:51.000Z | 2020-05-09T14:37:13.000Z | src/bmp24.cpp | ChristianVisintin/libBMPP | b66ffec5cc1c26520ae535d0e88e29e0853afcdb | [
"MIT"
] | 1 | 2022-03-21T03:26:01.000Z | 2022-03-21T03:26:01.000Z | /**
* libBMpp - bmp24.hpp
* Developed by Christian Visintin
*
* MIT License
* Copyright (c) 2019 Christian Visintin
* 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 <bmp24.hpp>
#include <fstream>
#ifdef BMP_DEBUG
#include <iostream>
#include <string>
#endif
#define MIN(a,b) ((a) < (b) ? (a) : (b))
namespace bmp {
/**
* @function Bmp24
* @description Bmp24 class constructor
**/
Bmp24::Bmp24() : Bmp() {
pixelArray.clear();
}
/**
* @function Bmp
* @description Bmp class constructor
* @param size_t width
* @param size_t height
* @param uint8_t default red
* @param uint8_t default green
* @param uint8_t default blue
**/
Bmp24::Bmp24(size_t width, size_t height, uint8_t defaultRed, uint8_t defaultGreen, uint8_t defaultBlue) : Bmp(width, height) {
//Set bits per pixel
header->bitsPerPixel = 24;
//FileSize must be set by child class
size_t nextMultipleOf4 = roundToMultiple(width * (header->bitsPerPixel / 8), 4);
size_t paddingSize = nextMultipleOf4 - (header->width * (header->bitsPerPixel / 8));
size_t rowSize = paddingSize + ((width * header->bitsPerPixel / 8));
size_t dataSize = rowSize * height;
header->fileSize = 54 + dataSize;
//DataSize must be set by child class
header->dataSize = dataSize;
//Create empty image
size_t arraySize = header->width * header->height;
pixelArray.reserve(arraySize);
for (size_t i = 0; i < arraySize; i++) {
pixelArray.push_back(new RGBPixel(defaultRed, defaultGreen, defaultBlue));
}
}
/**
* @function Bmp24
* @description Bmp24 class copy constructor
* @param const Bmp& bmp
*/
Bmp24::Bmp24(const Bmp24& bmp) : Bmp(bmp) {
//Copy pixel array to new bmp
size_t arraySize = bmp.pixelArray.size();
for (size_t i = 0; i < arraySize; i++) {
RGBPixel* copyPixel = reinterpret_cast<RGBPixel*>(bmp.pixelArray.at(i));
pixelArray.push_back(new RGBPixel(copyPixel->getRed(), copyPixel->getGreen(), copyPixel->getBlue()));
}
}
/**
* @function Bmp
* @description Bmp class copy constructor
* @param const Bmp& bmp
*/
Bmp24::Bmp24(Bmp24* bmp) : Bmp(bmp) {
//Copy pixel array to new bmp
size_t arraySize = bmp->pixelArray.size();
for (size_t i = 0; i < arraySize; i++) {
RGBPixel* copyPixel = reinterpret_cast<RGBPixel*>(bmp->pixelArray.at(i));
pixelArray.push_back(new RGBPixel(copyPixel->getRed(), copyPixel->getGreen(), copyPixel->getBlue()));
}
}
/**
* @function ~Bmp24
* @description Bmp24 class destructor
**/
Bmp24::~Bmp24() {
}
/**
* @function decodeBmp
* @description decode Bmp data buffer converting it to header struct and RGBPixel array
* @param uint8_t*
* @param size_t
* @returns bool
**/
bool Bmp24::decodeBmp(uint8_t* bmpData, size_t dataSize) {
//Call superclass decodeBmp to decode header
if (!Bmp::decodeBmp(bmpData, dataSize)) {
return false;
}
//Get data
size_t nextMultipleOf4 = roundToMultiple(header->width * (header->bitsPerPixel / 8), 4);
size_t paddingSize = nextMultipleOf4 - (header->width * (header->bitsPerPixel / 8));
size_t realRowSize = (header->width * (header->bitsPerPixel / 8));
size_t rowPositionCounter = 0;
for (size_t dataPtr = header->dataOffset - 1; dataPtr < header->fileSize - 1;) {
//Store Pixels for each byte NOTE: BMP is BGR
uint8_t blue = bmpData[++dataPtr];
uint8_t green = bmpData[++dataPtr];
uint8_t red = bmpData[++dataPtr];
//Create new pixel
pixelArray.push_back(new RGBPixel(red, green, blue));
rowPositionCounter += 3;
//If row has been parsed, go to next line
if (rowPositionCounter >= realRowSize) {
rowPositionCounter = 0;
dataPtr += paddingSize;
}
}
return true;
}
/**
* @function encodeBmp
* @description: encodes bitmap to buffer
* @param size_t*
* @returns uint8_t*
**/
uint8_t* Bmp24::encodeBmp(size_t& dataSize) {
//Get our fundamental parameters
size_t nextMultipleOf4 = roundToMultiple(header->width * (header->bitsPerPixel / 8), 4);
size_t paddingSize = nextMultipleOf4 - header->width * (header->bitsPerPixel / 8);
size_t realRowSize = (header->width * (header->bitsPerPixel / 8));
//Fill header and get bmpData with fixed size
uint8_t* bmpData = Bmp::encodeBmp(dataSize);
//Return nullptr if needed
if (bmpData == nullptr) {
return nullptr;
}
//Fill data
int pxIndex = -1;
size_t rowPositionCounter = 0;
for (size_t dataPtr = header->dataOffset - 1; dataPtr < dataSize - 1;) {
if (++pxIndex >= static_cast<int>(pixelArray.size())) {
break;
}
//Set pixel
RGBPixel* currPixel = reinterpret_cast<RGBPixel*>(pixelArray.at(pxIndex));
bmpData[++dataPtr] = currPixel->getBlue();
bmpData[++dataPtr] = currPixel->getGreen();
bmpData[++dataPtr] = currPixel->getRed();
//Check if row has to be closed
rowPositionCounter += 3;
if (rowPositionCounter >= realRowSize) {
//Fill row with padding and go on new line
rowPositionCounter = 0;
for (size_t i = 0; i < paddingSize; i++) {
bmpData[++dataPtr] = 0;
}
}
}
return bmpData;
}
/**
* @function readBmp
* @description read a BMP file and decodes it. The decoded Bmp becomes the object
* @param const std::string& bmpFile
* @returns bool
*/
bool Bmp24::readBmp(const std::string& bmpFile) {
std::ifstream iFile;
iFile.open(bmpFile, std::ios::binary | std::ios::ate);
if (!iFile.is_open()) {
return false;
}
std::streamsize size = iFile.tellg();
iFile.seekg(0, std::ios::beg);
char* dataBuffer = new char[size];
if (!iFile.read(dataBuffer, size)) {
delete[] dataBuffer;
return false;
}
iFile.close();
//Decode
bool rc = decodeBmp(reinterpret_cast<uint8_t*>(dataBuffer), size);
delete[] dataBuffer;
return rc;
}
/**
* @function writeBmp
* @description encode BMP write the buffer to a file.
* @param const std::string& bmpFile
* @returns bool
*/
bool Bmp24::writeBmp(const std::string& bmpFile) {
size_t outDataSize;
uint8_t* outBuf = encodeBmp(outDataSize);
if (outBuf == nullptr) {
return false;
}
//Write file
std::ofstream outFile;
outFile.open(bmpFile);
if (!outFile.is_open()) {
delete[] outBuf;
return false;
}
for (size_t i = 0; i < outDataSize; i++) {
outFile << outBuf[i];
}
outFile.close();
delete[] outBuf;
return true;
}
/**
* @function setPixelAt
* @description: replace pixel in a certain position with the provided one
* @param size_t
* @param size_t
* @param uint8_t
* @param uint8_t
* @param uint8_t
* @returns bool
**/
bool Bmp24::setPixelAt(size_t row, size_t column, uint8_t red, uint8_t green, uint8_t blue) {
//Get index, considering that pixels are stored bottom to top
size_t reversedRow = (header->height - 1 - row); // h - 1 - r
size_t index = (header->width * reversedRow) + column;
return setPixelAt(index, red, green, blue);
}
/**
* @function setPixelAt
* @description: replace pixel in a certain position with the provided one
* @param size_t
* @param uint8_t
* @param uint8_t
* @param uint8_t
* @returns bool
**/
bool Bmp24::setPixelAt(size_t index, uint8_t red, uint8_t green, uint8_t blue) {
if (index >= pixelArray.size()) {
return false;
}
RGBPixel* reqPixel = reinterpret_cast<RGBPixel*>(pixelArray.at(index));
reqPixel->setPixel(red, green, blue);
return true;
}
/**
* @function getPixelAt
* @description return pointer to pixel in the provided position
* @param size_t
* @param size_t
* @returns RGBPixel*
**/
RGBPixel* Bmp24::getPixelAt(size_t row, size_t column) {
//Get index, considering that pixels are stored bottom to top
size_t reversedRow = (header->height - 1 - row); // h - 1 - r
size_t index = (header->width * reversedRow) + column;
return getPixelAt(index);
}
/**
* @function getPixelAt
* @description return pointer to pixel in the provided position
* @param int
* @returns RGBPixel*
**/
RGBPixel* Bmp24::getPixelAt(size_t index) {
if (index >= pixelArray.size()) {
return nullptr;
}
return reinterpret_cast<RGBPixel*>(pixelArray.at(index));
}
/**
* @function toGreyScale
* @description: convert bitmap to greyscaleArea; if greyLevels is set, provided amount of greys will be used
* @param int
* @returns bool
**/
bool Bmp24::toGreyScale(int greyLevels /*= 255*/) {
//Convert each pixel to grey
for (auto& pixel : pixelArray) {
RGBPixel* rgbPixel = reinterpret_cast<RGBPixel*>(pixel);
//Get average value (grey for each pixel)
uint8_t red = rgbPixel->getRed();
uint8_t green = rgbPixel->getGreen();
uint8_t blue = rgbPixel->getBlue();
uint8_t greyValue = (red + green + blue) / 3;
//Apply greyLevels
if (greyLevels < 255) {
uint8_t appliedLevel = 255 / greyLevels;
//Fix grey based on levels we have
greyValue = greyValue - (greyValue % appliedLevel);
}
rgbPixel->setPixel(greyValue, greyValue, greyValue);
}
return true;
}
/**
* @function toSepiaTone
* @description: converts image to sepia tone
* @returns bool
**/
bool Bmp24::toSepiaTone() {
//Convert each pixel to sepia
for (auto& pixel : pixelArray) {
RGBPixel* rgbPixel = reinterpret_cast<RGBPixel*>(pixel);
uint8_t red = MIN((rgbPixel->getRed() * 0.393) + (rgbPixel->getGreen() * 0.769) + (rgbPixel->getBlue() * 0.189), 255);
uint8_t green = MIN((rgbPixel->getRed() * 0.349) + (rgbPixel->getGreen() * 0.686) + (rgbPixel->getBlue() * 0.168), 255);
uint8_t blue = MIN((rgbPixel->getRed() * 0.272) + (rgbPixel->getGreen() * 0.534) + (rgbPixel->getBlue() * 0.131), 255);
rgbPixel->setPixel(red, green, blue);
}
return true;
}
/**
* @function invert
* @description invert colors
* @returns bool
**/
bool Bmp24::invert() {
//Convert each pixel to sepia
for (auto& pixel : pixelArray) {
RGBPixel* rgbPixel = reinterpret_cast<RGBPixel*>(pixel);
uint8_t red = 255 - rgbPixel->getRed();
uint8_t green = 255 - rgbPixel->getGreen();
uint8_t blue = 255 - rgbPixel->getBlue();
rgbPixel->setPixel(red, green, blue);
}
return true;
}
/**
* @function resizeArea
* @description resize area (does not scale image), both enlarging or scaling it
* @param size_t width
* @param size_t height
* @param size_t xOffset (optional)
* @param size_t yOffset (optional)
* @returns bool
**/
bool Bmp24::resizeArea(size_t width, size_t height, size_t xOffset /* = 0*/, size_t yOffset /* = 0*/) {
while (header->width != width || header->height != height) {
size_t currWidth = header->width;
size_t currHeight = header->height;
//Resize image in order to match user requests; start with enlarging if necessary
if (width > currWidth || height > currHeight) {
//Pass higher size or current one to enlarge
size_t enlargedWidth = (width > currWidth) ? width : currWidth;
size_t enlargedHeight = (height > currHeight) ? height : currHeight;
//Initialize Pixel lambda
std::function<void(Pixel*&)> initializePixel = [](Pixel*& px) { px = new RGBPixel(255, 255, 255); };
if (!enlargeArea(enlargedWidth, enlargedHeight, initializePixel, xOffset, yOffset)) {
return false;
}
continue;
}
//Also, scale area if necessary
if (width < currWidth || height << currHeight) {
//Pass lower size or current one to scale
size_t scaledWidth = (width < currWidth) ? width : currWidth;
size_t scaledHeight = (height < currHeight) ? height : currHeight;
//Scale image
if (!scaleArea(scaledWidth, scaledHeight, xOffset, yOffset)) {
return false;
}
continue;
}
}
//Return OK
return true;
}
/**
* @function resizeImage
* @description resize image (not only area) applying bilinear image scaling
* @param size_t
* @param size_t
* @returns bool
**/
bool Bmp24::resizeImage(size_t width, size_t height) {
//Apply resizing
size_t prevWidth = header->width;
size_t prevHeight = header->height;
std::vector<Pixel*> resizedArray; //New pixel vector
float xRatio = static_cast<float>(prevWidth - 1) / width;
float yRatio = static_cast<float>(prevHeight - 1) / height;
//Working variables
RGBPixel *px1, *px2, *px3, *px4;
int x, y, index;
float xDiff, yDiff;
uint8_t red, green, blue;
for (size_t row = 0; row < height; row++) {
for (size_t column = 0; column < width; column++) {
x = static_cast<int>(xRatio * column);
y = static_cast<int>(yRatio * row);
xDiff = (xRatio * column) - x;
yDiff = (yRatio * row) - y;
index = ((y * prevWidth) + x);
px1 = reinterpret_cast<RGBPixel*>(pixelArray.at(index));
px2 = reinterpret_cast<RGBPixel*>(pixelArray.at(index + 1));
px3 = reinterpret_cast<RGBPixel*>(pixelArray.at(index + prevWidth));
px4 = reinterpret_cast<RGBPixel*>(pixelArray.at(index + prevWidth + 1));
//Yb = Ab(1-w)(1-h) + Bb(w)(1-h) + Cb(h)(1-w) + Db(wh)
blue = (px1->getBlue() * (1 - xDiff) * (1 - yDiff)) + (px2->getBlue() * (xDiff) * (1 - yDiff)) + (px3->getBlue() * (yDiff) * (1 - xDiff)) + (px4->getBlue() * (xDiff * yDiff));
green = (px1->getGreen() * (1 - xDiff) * (1 - yDiff)) + (px2->getGreen() * (xDiff) * (1 - yDiff)) + (px3->getGreen() * (yDiff) * (1 - xDiff)) + (px4->getGreen() * (xDiff * yDiff));
red = (px1->getRed() * (1 - xDiff) * (1 - yDiff)) + (px2->getRed() * (xDiff) * (1 - yDiff)) + (px3->getRed() * (yDiff) * (1 - xDiff)) + (px4->getRed() * (xDiff * yDiff));
//Instance new pixel
Pixel* resizedPixel = new RGBPixel(red, green, blue);
//Push pixel into array
resizedArray.push_back(resizedPixel);
}
}
//Delete all pixels in previous pixel array
for (auto& pixel : pixelArray) {
RGBPixel* px = reinterpret_cast<RGBPixel*>(pixel);
delete px;
}
pixelArray = resizedArray;
//Change header parameters
return Bmp::resizeImage(width, height);
}
}
| 30.794606 | 186 | 0.664488 | [
"object",
"vector"
] |
b42ccd9863924d5c150fe64163446b27d0903972 | 2,323 | hpp | C++ | include/dish2/algorithm/battleship_nop_out_phenotypically_neutral_instructions.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 29 | 2019-02-04T02:39:52.000Z | 2022-01-28T10:06:26.000Z | include/dish2/algorithm/battleship_nop_out_phenotypically_neutral_instructions.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 95 | 2020-02-22T19:48:14.000Z | 2021-09-14T19:17:53.000Z | include/dish2/algorithm/battleship_nop_out_phenotypically_neutral_instructions.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 6 | 2019-11-19T10:13:09.000Z | 2021-03-25T17:35:32.000Z | #pragma once
#ifndef DISH2_ALGORITHM_BATTLESHIP_NOP_OUT_PHENOTYPICALLY_NEUTRAL_INSTRUCTIONS_HPP_INCLUDE
#define DISH2_ALGORITHM_BATTLESHIP_NOP_OUT_PHENOTYPICALLY_NEUTRAL_INSTRUCTIONS_HPP_INCLUDE
#include <algorithm>
#include <iostream>
#include <tuple>
#include "../../../third-party/Empirical/include/emp/base/vector.hpp"
#include "../../../third-party/signalgp-lite/include/sgpl/morph/nop_out_instructions.hpp"
#include "../debug/log_msg.hpp"
#include "../debug/LogScope.hpp"
#include "../debug/log_tee.hpp"
#include "../debug/make_log_entry_boilerplate.hpp"
#include "../genome/Genome.hpp"
#include "../world/ThreadWorld.hpp"
#include "assess_instructions_for_phenotypic_divergence.hpp"
namespace dish2 {
template< typename Spec >
auto battleship_nop_out_phenotypically_neutral_instructions(
dish2::Genome<Spec> genome, const size_t nop_length=1
) {
const dish2::LogScope guard{ "evaluating instruction-by-instruction" };
dish2::log_msg(
"evaluating ", genome.program.size(), " instructions ",
nop_length, " at a time"
);
using sgpl_spec_t = typename Spec::sgpl_spec_t;
emp::vector< char > should_nop( genome.program.size() );
emp::vector< size_t > divergence_updates( genome.program.size() );
#pragma omp parallel for
for (size_t idx = 0; idx < genome.program.size(); idx += nop_length) {
#ifdef __EMSCRIPTEN__
const dish2::LogScope guard3{
emp::to_string("evaluating instruction ", idx)
};
#endif // #ifdef __EMSCRIPTEN__
const auto res = dish2::assess_instructions_for_phenotypic_divergence<Spec>(
genome, idx, nop_length
);
dish2::log_tee << dish2::make_log_entry_boilerplate();
for (size_t i{}; i < nop_length; ++i) if ( idx + i < should_nop.size() ) {
should_nop[idx + i] = (res == cfg.PHENOTYPIC_DIVERGENCE_N_UPDATES());
divergence_updates[idx + i] = res;
if (i == 0) {
dish2::log_tee << (should_nop[idx + i] ? "x" : "o");
dish2::log_tee << std::flush;
}
}
}
dish2::log_tee << " done" << '\n' << '\n';
genome.program
= sgpl::nop_out_instructions< sgpl_spec_t >( genome.program, should_nop );
return std::tuple{genome, divergence_updates};
}
} // namespace dish2
#endif // #ifndef DISH2_ALGORITHM_BATTLESHIP_NOP_OUT_PHENOTYPICALLY_NEUTRAL_INSTRUCTIONS_HPP_INCLUDE
| 30.565789 | 100 | 0.708997 | [
"vector"
] |
b42e00e2fbd7d0101775eddf99e9387f25130f46 | 5,081 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/base/carry_data.cc | xu-weizhen/mindspore | e55642e40b8ce9abafa8e50865b490f0317b4703 | [
"Apache-2.0"
] | 4 | 2021-01-26T09:14:01.000Z | 2021-01-26T09:17:24.000Z | mindspore/lite/src/runtime/kernel/arm/base/carry_data.cc | xu-weizhen/mindspore | e55642e40b8ce9abafa8e50865b490f0317b4703 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/base/carry_data.cc | xu-weizhen/mindspore | e55642e40b8ce9abafa8e50865b490f0317b4703 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 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 "src/runtime/kernel/arm/base/carry_data.h"
#include "include/errorcode.h"
#include "src/tensorlist.h"
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
namespace mindspore::kernel {
int CarryDataKernel::MoveData(std::vector<lite::Tensor *>::iterator dst_begin,
std::vector<lite::Tensor *>::iterator dst_end,
std::vector<lite::Tensor *>::iterator src_begin,
std::vector<lite::Tensor *>::iterator src_limit) {
for (auto dst_iter = dst_begin, src_iter = src_begin; dst_iter != dst_end; dst_iter++, src_iter++) {
if (src_iter == src_limit) {
MS_LOG(ERROR) << "out of range of input tensor";
return RET_ERROR;
}
auto *dst_tensor = *dst_iter;
auto *src_tensor = *src_iter;
if (dst_tensor == nullptr || src_tensor == nullptr) {
MS_LOG(ERROR) << "input tensor or output tensor of merge is nullptr";
return RET_ERROR;
}
lite::STATUS ret;
if (src_tensor->data_type() == kObjectTypeTensorType && dst_tensor->data_type() == kObjectTypeTensorType) {
ret = MoveTensorLiteData(reinterpret_cast<lite::TensorList *>(dst_tensor),
reinterpret_cast<lite::TensorList *>(src_tensor));
} else {
ret = MoveTensorData(dst_tensor, src_tensor);
}
if (ret != RET_OK) {
MS_LOG(ERROR) << "Move data failed : " << ret;
return ret;
}
}
return RET_OK;
}
int CarryDataKernel::MoveTensorData(lite::Tensor *dst_tensor, lite::Tensor *src_tensor) {
if (dst_tensor->data_type() != src_tensor->data_type() || dst_tensor->format() != src_tensor->format() ||
!(dst_tensor->shape() == src_tensor->shape() || (dst_tensor->shape().empty() && src_tensor->shape().empty()))) {
MS_LOG(ERROR) << "input tensor and output tensor is incompatible";
return RET_ERROR;
}
if (src_tensor->root_tensor() == nullptr) {
if (src_tensor->IsConst() || src_tensor->IsGraphInput() || src_tensor->ref_count() > 1) {
auto dst_data = dst_tensor->MutableData();
if (dst_data == nullptr) {
MS_LOG(ERROR) << "data of dst tensor is nullptr";
return RET_ERROR;
}
auto src_data = src_tensor->data_c();
MS_ASSERT(src_data != nullptr);
memcpy(dst_data, src_data, dst_tensor->Size());
} else {
dst_tensor->FreeData();
dst_tensor->set_data(src_tensor->data_c());
src_tensor->set_data(nullptr);
}
} else {
auto ret = dst_tensor->set_root_tensor(src_tensor->root_tensor());
if (ret != RET_OK) {
MS_LOG(ERROR) << "Set root tensor for tensor(" << dst_tensor->tensor_name() << ") failed";
return ret;
}
}
return RET_OK;
}
int CarryDataKernel::MoveTensorLiteData(lite::TensorList *dst_tensor, lite::TensorList *src_tensor) {
// shape may change, because tensors.size() can be change in RunGraph
if (dst_tensor->data_type() != src_tensor->data_type() || dst_tensor->format() != src_tensor->format()) {
MS_LOG(ERROR) << "input tensorlist and output tensorlist data_type or format is incompatible";
return RET_ERROR;
}
if (dst_tensor->element_shape() != src_tensor->element_shape()) {
MS_LOG(ERROR) << "input tensorlist and output tensorlist element shape is incompatible";
return RET_ERROR;
}
auto update_data_type = kTypeUnknown;
auto dst_tensor_data_type = dst_tensor->tensors_data_type();
auto src_tensor_data_type = src_tensor->tensors_data_type();
if (dst_tensor_data_type != src_tensor_data_type) {
if (src_tensor_data_type != kTypeUnknown && dst_tensor_data_type != kTypeUnknown) {
MS_LOG(ERROR) << "input tensorlist and output tensorlist is incompatible";
return RET_ERROR;
}
update_data_type = dst_tensor_data_type != kTypeUnknown ? dst_tensor_data_type : src_tensor_data_type;
}
if (update_data_type != kTypeUnknown) {
src_tensor->set_tensors_data_type(update_data_type);
dst_tensor->set_tensors_data_type(update_data_type);
}
if (src_tensor->root_tensor() == nullptr) {
dst_tensor->CopyTensorList(*src_tensor, false);
src_tensor->set_tensors({});
} else {
dst_tensor->set_shape(src_tensor->shape());
auto ret = dst_tensor->set_root_tensor(src_tensor->root_tensor());
if (ret != RET_OK) {
MS_LOG(ERROR) << "Set root tensor for tensor(" << dst_tensor->tensor_name() << ") failed";
return ret;
}
}
return RET_OK;
}
} // namespace mindspore::kernel
| 40.975806 | 118 | 0.671718 | [
"shape",
"vector"
] |
b430ba67ec1517ffca4917b0326962eb38984c1e | 39,137 | cc | C++ | horovod/common/controller.cc | Infi-zc/horovod | 94cd8561a21d449fc8c80c8fef422025b84dfc22 | [
"Apache-2.0"
] | 5,089 | 2017-08-10T20:44:50.000Z | 2019-02-12T00:45:34.000Z | horovod/common/controller.cc | Infi-zc/horovod | 94cd8561a21d449fc8c80c8fef422025b84dfc22 | [
"Apache-2.0"
] | 669 | 2017-08-11T21:33:41.000Z | 2019-02-12T01:02:17.000Z | horovod/common/controller.cc | Infi-zc/horovod | 94cd8561a21d449fc8c80c8fef422025b84dfc22 | [
"Apache-2.0"
] | 706 | 2017-08-11T00:30:43.000Z | 2019-02-11T12:00:34.000Z | // Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
// Modifications copyright Microsoft
// Modifications copyright (C) 2020, NVIDIA CORPORATION. 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 "controller.h"
#include <atomic>
#include <map>
#include <queue>
#include <set>
#include <unordered_set>
#include "global_state.h"
#include "logging.h"
#include "operations.h"
#if HAVE_CUDA
#include "ops/cuda/cuda_kernels.h"
#endif
namespace horovod {
namespace common {
void Controller::SynchronizeParameters() {
ParameterManager::Params param;
if (is_coordinator_) {
param = parameter_manager_.GetParams();
}
void* buffer = (void*)(¶m);
size_t param_size = sizeof(param);
Bcast(buffer, param_size, 0, Communicator::GLOBAL);
if (!is_coordinator_) {
parameter_manager_.SetParams(param);
}
parameter_manager_.Reset();
}
Controller::Controller(ResponseCache& response_cache, TensorQueue& tensor_queue,
Timeline& timeline, ParameterManager& parameter_manager,
GroupTable& group_table,
TimelineController& timeline_controller)
: stall_inspector_(response_cache), tensor_queue_(tensor_queue),
timeline_(timeline), timeline_controller_(timeline_controller),
response_cache_(response_cache), parameter_manager_(parameter_manager),
group_table_(group_table) {}
void Controller::Initialize() {
response_cache_.clear();
// Initialize concrete implementations.
DoInitialization();
is_initialized_ = true;
}
ResponseList Controller::ComputeResponseList(bool this_process_requested_shutdown,
HorovodGlobalState& state,
ProcessSet& process_set) {
assert(IsInitialized());
// Update cache capacity if autotuning is active.
if (parameter_manager_.IsAutoTuning()) {
response_cache_.set_capacity((int)parameter_manager_.CacheEnabled() *
cache_capacity_);
}
// Copy the data structures out from parameters.
// However, don't keep the lock for the rest of the loop, so that
// enqueued stream callbacks can continue.
CacheCoordinator cache_coordinator(response_cache_.num_active_bits());
// message queue used only in this cycle
std::deque<Request> message_queue_tmp;
tensor_queue_.PopMessagesFromQueue(message_queue_tmp);
for (auto& message : message_queue_tmp) {
if (message.request_type() == Request::JOIN) {
process_set.joined = true;
cache_coordinator.set_uncached_in_queue(true);
continue;
}
// Never cache a barrier request, when all ranks return ready for this message, barrier will be released.
if(message.request_type() == Request::BARRIER) {
cache_coordinator.set_uncached_in_queue(true);
continue;
}
// Keep track of cache hits
if (response_cache_.capacity() > 0) {
auto cache_ = response_cache_.cached(message);
if (cache_ == ResponseCache::CacheState::HIT) {
uint32_t cache_bit = response_cache_.peek_cache_bit(message);
cache_coordinator.record_hit(cache_bit);
// Record initial time cached tensor is encountered in queue.
stall_inspector_.RecordCachedTensorStart(message.tensor_name());
} else {
if (cache_ == ResponseCache::CacheState::INVALID) {
uint32_t cache_bit = response_cache_.peek_cache_bit(message);
cache_coordinator.record_invalid_bit(cache_bit);
}
cache_coordinator.set_uncached_in_queue(true);
// Remove timing entry if uncached or marked invalid.
stall_inspector_.RemoveCachedTensor(message.tensor_name());
}
}
}
if (process_set.joined && response_cache_.capacity() > 0) {
for (uint32_t bit : response_cache_.list_all_bits()) {
cache_coordinator.record_hit(bit);
}
}
// Flag indicating that the background thread should shut down.
bool should_shut_down = this_process_requested_shutdown;
// Check for stalled tensors.
if (stall_inspector_.ShouldPerformCheck()) {
if (is_coordinator_) {
should_shut_down |=
stall_inspector_.CheckForStalledTensors(global_ranks_);
}
if (response_cache_.capacity() > 0) {
stall_inspector_.InvalidateStalledCachedTensors(cache_coordinator);
}
stall_inspector_.UpdateCheckTime();
}
cache_coordinator.set_should_shut_down(should_shut_down);
if (response_cache_.capacity() > 0) {
// Obtain common cache hits and cache invalidations across workers. Also,
// determine if any worker has uncached messages in queue or requests
// a shutdown. This function removes any invalid cache entries, if they
// exist.
CoordinateCacheAndState(cache_coordinator);
// Remove uncommon cached tensors from queue and replace to state
// queue for next cycle. Skip adding common cached tensors to
// queue as they are handled separately.
std::deque<Request> messages_to_replace;
size_t num_messages = message_queue_tmp.size();
for (size_t i = 0; i < num_messages; ++i) {
auto& message = message_queue_tmp.front();
if (response_cache_.cached(message) == ResponseCache::CacheState::HIT) {
uint32_t cache_bit = response_cache_.peek_cache_bit(message);
if (cache_coordinator.cache_hits().find(cache_bit) ==
cache_coordinator.cache_hits().end()) {
// Try to process again in next cycle.
messages_to_replace.push_back(std::move(message));
} else {
// Remove timing entry for messages being handled this cycle.
stall_inspector_.RemoveCachedTensor(message.tensor_name());
}
} else {
// Remove timing entry for messages being handled this cycle.
stall_inspector_.RemoveCachedTensor(message.tensor_name());
message_queue_tmp.push_back(std::move(message));
}
message_queue_tmp.pop_front();
}
tensor_queue_.PushMessagesToQueue(messages_to_replace);
}
if (!message_queue_tmp.empty()) {
LOG(TRACE, rank_) << "Sent " << message_queue_tmp.size()
<< " messages to coordinator.";
}
ResponseList response_list;
response_list.set_shutdown(cache_coordinator.should_shut_down());
bool need_communication = true;
if (response_cache_.capacity() > 0 &&
!cache_coordinator.uncached_in_queue()) {
// if cache is enabled and no uncached new message coming in, no need for
// additional communications
need_communication = false;
// If no messages to send, we can simply return an empty response list;
if (cache_coordinator.cache_hits().empty()) {
return response_list;
}
// otherwise we need to add cached messages to response list.
}
if (!need_communication) {
// If all messages in queue have responses in cache, use fast path with
// no additional coordination.
// If group fusion is disabled, fuse tensors in groups separately
if (state.disable_group_fusion && !group_table_.empty()) {
// Note: need group order to be based on position in cache for global consistency
std::vector<int> common_ready_groups;
std::unordered_set<int> processed;
for (auto bit : cache_coordinator.cache_hits()) {
const auto& tensor_name = response_cache_.peek_response(bit).tensor_names()[0];
int group_id = group_table_.GetGroupIDFromTensorName(tensor_name);
if (group_id != NULL_GROUP_ID && processed.find(group_id) == processed.end()) {
common_ready_groups.push_back(group_id);
processed.insert(group_id);
}
}
for (auto id : common_ready_groups) {
std::deque<Response> responses;
for (const auto &tensor_name : group_table_.GetGroupTensorNames(id)) {
auto bit = response_cache_.peek_cache_bit(tensor_name);
responses.push_back(response_cache_.get_response(bit));
// Erase cache hit to avoid processing a second time.
cache_coordinator.erase_hit(bit);
}
FuseResponses(responses, state, response_list);
}
}
std::deque<Response> responses;
// Convert cache hits to responses. Populate so that least
// recently used responses get priority. All workers call the code
// here so we use the get method here to consistently update the cache
// order.
for (auto bit : cache_coordinator.cache_hits()) {
responses.push_back(response_cache_.get_response(bit));
}
// Fuse responses as normal.
FuseResponses(responses, state, response_list);
response_list.set_shutdown(cache_coordinator.should_shut_down());
} else {
// There are uncached messages coming in, need communication to figure out
// whether those are ready to be reduced.
// Collect all tensors that are ready to be reduced. Record them in the
// tensor count table (rank zero) or send them to rank zero to be
// recorded (everyone else).
std::vector<std::string> ready_to_reduce;
if (is_coordinator_) {
LOG(TRACE) << "Adding messages from process-set rank 0";
while (!message_queue_tmp.empty()) {
// Pop the first available message
Request message = message_queue_tmp.front();
message_queue_tmp.pop_front();
if (message.request_type() == Request::JOIN) {
process_set.joined_size++;
process_set.last_joined_rank = global_ranks_[rank_];
continue;
}
bool reduce = IncrementTensorCount(message, process_set.joined_size);
stall_inspector_.RecordUncachedTensorStart(
message.tensor_name(), message.request_rank(), size_);
if (reduce) {
ready_to_reduce.push_back(message.tensor_name());
}
}
// Receive ready tensors from other ranks
std::vector<RequestList> ready_list;
RecvReadyTensors(ready_to_reduce, ready_list);
// Process messages.
for (int i = 1; i < size_; ++i) {
LOG(TRACE) << "Adding messages from process-set rank " << i;
auto received_message_list = ready_list[i];
for (auto& received_message : received_message_list.requests()) {
auto& received_name = received_message.tensor_name();
if (received_message.request_type() == Request::JOIN) {
process_set.joined_size++;
process_set.last_joined_rank = global_ranks_[i];
continue;
}
bool reduce =
IncrementTensorCount(received_message, process_set.joined_size);
stall_inspector_.RecordUncachedTensorStart(
received_message.tensor_name(), received_message.request_rank(),
size_);
if (reduce) {
ready_to_reduce.push_back(received_name);
}
}
if (received_message_list.shutdown()) {
// Received SHUTDOWN request from one of the workers.
should_shut_down = true;
}
}
// Check if tensors from previous ticks are ready to reduce after Joins.
if (process_set.joined_size > 0) {
for (auto& table_iter : message_table_) {
int count = (int)table_iter.second.size();
if (count == (size_ - process_set.joined_size) &&
std::find(ready_to_reduce.begin(), ready_to_reduce.end(),
table_iter.first) == ready_to_reduce.end()) {
timeline_.NegotiateEnd(table_iter.first);
ready_to_reduce.push_back(table_iter.first);
}
}
}
// Fuse tensors in groups before processing others.
if (state.disable_group_fusion && !group_table_.empty()) {
// Extract set of common groups from coordinator tensor list and cache hits.
std::vector<int> common_ready_groups;
std::unordered_set<int> processed;
for (const auto& tensor_name : ready_to_reduce) {
int group_id = group_table_.GetGroupIDFromTensorName(tensor_name);
if (group_id != NULL_GROUP_ID && processed.find(group_id) == processed.end()) {
common_ready_groups.push_back(group_id);
processed.insert(group_id);
// Leaving name in list, to be skipped later.
}
}
if (response_cache_.capacity() > 0) {
for (auto bit : cache_coordinator.cache_hits()) {
const auto& tensor_name = response_cache_.peek_response(bit).tensor_names()[0];
int group_id = group_table_.GetGroupIDFromTensorName(tensor_name);
if (group_id != NULL_GROUP_ID && processed.find(group_id) == processed.end()) {
common_ready_groups.push_back(group_id);
processed.insert(group_id);
}
}
}
// For each ready group, form and fuse response lists independently
for (auto id : common_ready_groups) {
std::deque<Response> responses;
for (const auto &tensor_name : group_table_.GetGroupTensorNames(id)) {
if (message_table_.find(tensor_name) != message_table_.end()) {
// Uncached message
Response response =
ConstructResponse(tensor_name, process_set.joined_size);
responses.push_back(std::move(response));
} else {
// Cached message
auto bit = response_cache_.peek_cache_bit(tensor_name);
responses.push_back(response_cache_.get_response(bit));
// Erase cache hit to avoid processing a second time.
cache_coordinator.erase_hit(bit);
}
}
FuseResponses(responses, state, response_list);
}
}
// At this point, rank zero should have a fully updated tensor count
// table and should know all the tensors that need to be reduced or
// gathered, and everyone else should have sent all their information
// to rank zero. We can now do reductions and gathers; rank zero will
// choose which ones and in what order, and will notify the other ranks
// before doing each reduction.
std::deque<Response> responses;
if (response_cache_.capacity() > 0) {
// Prepopulate response list with cached responses. Populate so that
// least recently used responses get priority. Since only the
// coordinator rank calls this code, use peek instead of get here to
// preserve cache order across workers.
// No need to do this when all ranks did Join.
if (process_set.joined_size < size_) {
for (auto bit : cache_coordinator.cache_hits()) {
responses.push_back(response_cache_.peek_response(bit));
}
}
}
for (auto& tensor_name : ready_to_reduce) {
// Skip tensors in group that were handled earlier.
if (state.disable_group_fusion &&
!group_table_.empty() &&
group_table_.GetGroupIDFromTensorName(tensor_name) != NULL_GROUP_ID) {
continue;
}
Response response =
ConstructResponse(tensor_name, process_set.joined_size);
responses.push_back(std::move(response));
}
if (process_set.joined_size == size_) {
// All ranks did Join(). Send the response, reset joined_size and
// last_joined_rank.
Response join_response;
join_response.set_response_type(Response::JOIN);
join_response.add_tensor_name(JOIN_TENSOR_NAME);
join_response.set_last_joined_rank(process_set.last_joined_rank);
responses.push_back(std::move(join_response));
process_set.joined_size = 0;
process_set.last_joined_rank = -1;
}
FuseResponses(responses, state, response_list);
response_list.set_shutdown(should_shut_down);
// Broadcast final results to other ranks.
SendFinalTensors(response_list);
} else {
RequestList message_list;
message_list.set_shutdown(should_shut_down);
while (!message_queue_tmp.empty()) {
message_list.add_request(message_queue_tmp.front());
message_queue_tmp.pop_front();
}
// Send ready tensors to rank zero
SendReadyTensors(message_list);
// Receive final tensors to be processed from rank zero
RecvFinalTensors(response_list);
}
}
if (!response_list.responses().empty()) {
std::string tensors_ready;
for (const auto& r : response_list.responses()) {
tensors_ready += r.tensor_names_string() + "; ";
}
LOG(TRACE) << "Sending ready responses as " << tensors_ready;
}
// If need_communication is false, meaning no uncached message coming in,
// thus no need to update cache.
if (need_communication && response_cache_.capacity() > 0) {
// All workers add supported responses to cache. This updates the cache
// order consistently across workers.
for (auto& response : response_list.responses()) {
if ((response.response_type() == Response::ResponseType::ALLREDUCE ||
response.response_type() == Response::ResponseType::ALLGATHER ||
response.response_type() == Response::ResponseType::ADASUM ||
response.response_type() == Response::ResponseType::ALLTOALL) &&
(int)response.devices().size() == size_) {
response_cache_.put(response, tensor_queue_, process_set.joined);
}
}
}
// Reassign cache bits based on current cache order.
response_cache_.update_cache_bits();
return response_list;
}
int64_t Controller::TensorFusionThresholdBytes() {
int64_t proposed_fusion_threshold =
parameter_manager_.TensorFusionThresholdBytes();
// If the cluster is homogeneous,
// adjust buffer size to make sure it is divisible by local_size to improve
// performance for operations that perform local reductions by default such as Adasum.
if (is_homogeneous_) {
// Assume the worst-case data type float64, since if it is divisible with
// float64, it will be divisible for other types too.
// Ensuring that fusion buffer can hold a number of elements divisible by
// FUSION_BUFFER_ATOMIC_UNIT for performance
int double_size = GetTypeSize(HOROVOD_FLOAT64);
int64_t div = (int64_t)local_size_ * (int64_t)double_size * FUSION_BUFFER_ATOMIC_UNIT;
return ((proposed_fusion_threshold + div - 1) / div) * div;
}
return proposed_fusion_threshold;
}
Response Controller::ConstructResponse(const std::string& name, int joined_size) {
bool error = false;
auto it = message_table_.find(name);
assert(it != message_table_.end());
std::vector<Request>& requests = it->second;
assert(!requests.empty());
std::ostringstream error_message_stream;
// Check that all data types of tensors being processed
// are identical.
auto data_type = requests[0].tensor_type();
for (unsigned int i = 1; i < requests.size(); ++i) {
auto request_type = requests[i].tensor_type();
if (data_type != request_type) {
error = true;
error_message_stream << "Mismatched data types: One rank had type "
<< DataType_Name(data_type)
<< ", but another rank had type "
<< DataType_Name(request_type) << ".";
break;
}
}
// Check that all requested operations are the same
auto message_type = requests[0].request_type();
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
auto request_type = requests[i].request_type();
if (message_type != request_type) {
error = true;
error_message_stream << "Mismatched operations: One rank did an "
<< Request::RequestType_Name(message_type)
<< ", but another rank did an "
<< Request::RequestType_Name(request_type) << ".";
break;
}
}
// If we are doing an allreduce, broadcast, or reducescatter check that all
// tensor shapes are identical.
if (message_type == Request::ALLREDUCE ||
message_type == Request::ADASUM ||
message_type == Request::BROADCAST ||
message_type == Request::REDUCESCATTER) {
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(dim);
}
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
TensorShape request_shape;
for (auto dim : requests[i].tensor_shape()) {
request_shape.AddDim(dim);
}
if (tensor_shape != request_shape) {
error = true;
error_message_stream
<< "Mismatched " << Request::RequestType_Name(message_type)
<< " tensor shapes: One rank sent a tensor of shape "
<< tensor_shape.DebugString()
<< ", but another rank sent a tensor of shape "
<< request_shape.DebugString() << ".";
break;
}
}
}
// If we are doing an allreduce, check that prescaling and postscaling factors
// are identical across ranks.
double prescale_factor;
double postscale_factor;
if (message_type == Request::ALLREDUCE ||
message_type == Request::ADASUM) {
prescale_factor = requests[0].prescale_factor();
postscale_factor = requests[0].postscale_factor();
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
double request_prescale_factor = requests[i].prescale_factor();
double request_postscale_factor = requests[i].postscale_factor();
if (prescale_factor != request_prescale_factor ||
postscale_factor != request_postscale_factor) {
error = true;
error_message_stream
<< "Mismatched prescale and/or postscale factors: "
<< "One rank sent factors (" << prescale_factor
<< ", " << postscale_factor << "), but another rank "
<< "sent factors (" << request_prescale_factor
<< ", " << request_postscale_factor << ").";
break;
}
}
}
std::vector<int64_t> tensor_sizes;
if (message_type == Request::ALLGATHER ||
message_type == Request::ALLTOALL) {
if (joined_size > 0) {
error = true;
if (message_type == Request::ALLGATHER) {
error_message_stream << "Allgather is not supported with Join at this time. "
<< "Specify sparse_to_dense=True if using DistributedOptimizer";
} else if (message_type == Request::ALLTOALL) {
error_message_stream << "Alltoall is not supported with Join at this time.";
}
}
// If we are doing an allgather/alltoall, make sure all but the first dimension are
// the same. The first dimension may be different and the output tensor is
// the sum of the first dimension. Collect the sizes by rank for allgather only.
tensor_sizes.resize(requests.size());
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(dim);
}
if (tensor_shape.dims() == 0) {
error = true;
error_message_stream << "Process-set rank zero tried to "
<< Request::RequestType_Name(message_type)
<< " a rank-zero tensor.";
} else {
tensor_sizes[requests[0].request_rank()] = tensor_shape.dim_size(0);
}
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
TensorShape request_shape;
for (auto dim : requests[i].tensor_shape()) {
request_shape.AddDim(dim);
}
if (tensor_shape.dims() != request_shape.dims()) {
error = true;
error_message_stream
<< "Mismatched " << Request::RequestType_Name(message_type)
<< " tensor shapes: One rank sent a tensor of rank "
<< tensor_shape.dims()
<< ", but another rank sent a tensor of rank "
<< request_shape.dims() << ".";
break;
}
bool dim_mismatch = false;
for (int dim = 1; dim < tensor_shape.dims(); ++dim) {
if (tensor_shape.dim_size(dim) != request_shape.dim_size(dim)) {
error = true;
error_message_stream
<< "Mismatched " << Request::RequestType_Name(message_type)
<< " tensor shapes: One rank sent a tensor with dimension " << dim
<< " equal to " << tensor_shape.dim_size(dim)
<< ", but another rank sent a tensor with dimension " << dim
<< " equal to " << request_shape.dim_size(dim) << ".";
dim_mismatch = true;
break;
}
}
if (dim_mismatch) {
break;
}
// Collect first dimension sizes for allgather to use for fusion and allgather op.
if (message_type == Request::ALLGATHER) {
tensor_sizes[requests[i].request_rank()] = request_shape.dim_size(0);
}
}
}
if (message_type == Request::REDUCESCATTER) {
if (joined_size > 0) {
error = true;
error_message_stream << "Reducescatter is not supported with Join at this time.";
}
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(dim);
}
tensor_sizes.push_back(tensor_shape.num_elements());
}
if (message_type == Request::ALLREDUCE || message_type == Request::ADASUM) {
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(dim);
}
tensor_sizes.push_back(tensor_shape.num_elements());
}
if (message_type == Request::BROADCAST) {
if (joined_size > 0) {
error = true;
error_message_stream << "Broadcast is not supported with Join at this time.";
}
// If we are doing a broadcast, check that all root ranks are identical.
int first_root_rank = requests[0].root_rank();
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
int this_root_rank = requests[i].root_rank();
if (first_root_rank != this_root_rank) {
int first_global_root_rank = GetGlobalRanks()[first_root_rank];
int this_global_root_rank = GetGlobalRanks()[this_root_rank];
error = true;
error_message_stream << "Mismatched "
<< Request::RequestType_Name(message_type)
<< " root ranks: One rank specified root rank "
<< first_global_root_rank
<< ", but another rank specified root rank "
<< this_global_root_rank << ".";
break;
}
}
}
bool first_device_is_cpu = requests[0].device() == CPU_DEVICE_ID;
for (unsigned int i = 1; i < requests.size(); ++i) {
if (error) {
break;
}
bool this_device_is_cpu = requests[i].device() == CPU_DEVICE_ID;
if (first_device_is_cpu != this_device_is_cpu) {
error = true;
error_message_stream
<< "Mismatched " << Request::RequestType_Name(message_type)
<< " CPU/GPU device selection: One rank specified device "
<< (first_device_is_cpu ? "CPU" : "GPU")
<< ", but another rank specified device "
<< (this_device_is_cpu ? "CPU" : "GPU") << ".";
break;
}
}
std::vector<int32_t> devices(requests.size());
for (auto& request : requests) {
devices[request.request_rank()] = request.device();
}
Response response;
response.add_tensor_name(name);
if (error) {
std::string error_message = error_message_stream.str();
response.set_response_type(Response::ERROR);
response.set_error_message(error_message);
} else if (message_type == Request::ALLGATHER) {
response.set_response_type(Response::ALLGATHER);
for (auto dim : tensor_sizes) {
response.add_tensor_size(dim);
}
} else if (message_type == Request::ALLREDUCE) {
response.set_response_type(Response::ALLREDUCE);
for (auto dim : tensor_sizes) {
response.add_tensor_size(dim);
}
response.set_tensor_type(data_type);
response.set_prescale_factor(prescale_factor);
response.set_postscale_factor(postscale_factor);
} else if (message_type == Request::BROADCAST) {
response.set_response_type(Response::BROADCAST);
} else if (message_type == Request::ALLTOALL) {
response.set_response_type(Response::ALLTOALL);
} else if (message_type == Request::REDUCESCATTER) {
response.set_response_type(Response::REDUCESCATTER);
for (auto dim : tensor_sizes) {
response.add_tensor_size(dim);
}
response.set_tensor_type(data_type);
} else if (message_type == Request::ADASUM) {
response.set_response_type(Response::ADASUM);
for (auto dim : tensor_sizes) {
response.add_tensor_size(dim);
}
response.set_tensor_type(data_type);
response.set_prescale_factor(prescale_factor);
response.set_postscale_factor(postscale_factor);
} else if (message_type == Request::BARRIER) {
response.set_response_type(Response::BARRIER);
}
response.set_devices(devices);
// Clear all queued up requests for this name. They are now taken care of
// by the constructed response.
message_table_.erase(it);
stall_inspector_.RemoveUncachedTensor(name);
return response;
}
void Controller::CoordinateCacheAndState(CacheCoordinator& cache_coordinator) {
// Sync cache and state information across workers.
cache_coordinator.sync(shared_from_this(),
timeline_controller_.TimelineEnabled());
// If invalid cache entries exist, erase associated entries.
if (!cache_coordinator.invalid_bits().empty()) {
for (auto bit : cache_coordinator.invalid_bits()) {
response_cache_.erase_response(bit);
}
}
if (timeline_controller_.TimelineEnabled()) {
// Start/continue negotiation phase on timeline bit entries.
for (auto bit : cache_coordinator.timeline_bits()) {
auto& response = response_cache_.peek_response(bit);
timeline_.NegotiateStart(response.tensor_names()[0],
(Request::RequestType)response.response_type());
}
// End negotiation phase for synced cache hit set entries.
for (auto bit : cache_coordinator.cache_hits()) {
auto& response = response_cache_.peek_response(bit);
timeline_.NegotiateEnd(response.tensor_names()[0]);
}
}
}
void Controller::FuseResponses(std::deque<Response>& responses,
HorovodGlobalState& state,
ResponseList& response_list) {
while (!responses.empty()) {
auto response = responses.front();
assert(response.tensor_names().size() == 1);
responses.pop_front();
int64_t tensor_size = 0;
if (response.response_type() == Response::ResponseType::ALLREDUCE ||
response.response_type() == Response::ResponseType::ADASUM ||
response.response_type() == Response::ResponseType::REDUCESCATTER) {
// Attempt to add more responses to this fused response.
tensor_size = response.tensor_sizes()[0] * GetTypeSize(response.tensor_type());
#if HAVE_CUDA
if (state.batch_d2d_memcopies) {
// Add 16 byte pad for batched memcpy op
tensor_size = BATCHED_D2D_PADDING * ((tensor_size + BATCHED_D2D_PADDING - 1) / BATCHED_D2D_PADDING);
}
#endif
std::deque<Response> skipped_responses;
int64_t skipped_size = 0;
while (!responses.empty()) {
auto& new_response = responses.front();
assert(new_response.tensor_names().size() == 1);
int64_t new_tensor_size = new_response.tensor_sizes().empty()
? 0
: new_response.tensor_sizes()[0] *
GetTypeSize(new_response.tensor_type());
#if HAVE_CUDA
if (state.batch_d2d_memcopies) {
// Add 16 byte pad for batched memcpy op
new_tensor_size = BATCHED_D2D_PADDING * ((new_tensor_size + BATCHED_D2D_PADDING - 1) / BATCHED_D2D_PADDING);
}
#endif
if (response.response_type() == new_response.response_type() &&
response.devices() == new_response.devices() &&
response.tensor_type() == new_response.tensor_type() &&
tensor_size + new_tensor_size <= TensorFusionThresholdBytes() &&
response.prescale_factor() == new_response.prescale_factor() &&
response.postscale_factor() == new_response.postscale_factor()) {
// These tensors will fuse together well.
tensor_size += new_tensor_size;
response.add_tensor_name(std::move(new_response.tensor_names()[0]));
response.add_tensor_size(new_response.tensor_sizes()[0]);
responses.pop_front();
} else {
// In general, don't try to fuse additional tensors since they are
// usually computed in order of requests and skipping tensors may
// mean that the batch will have to wait longer while skipped
// tensors could be reduced at that time. However, mixed-precision
// training may yield requests of various dtype in a mixed-up
// sequence causing breakups in fusion. To counter this some look
// ahead is allowed.
skipped_size += new_tensor_size;
if (tensor_size + skipped_size <= TensorFusionThresholdBytes()) {
// Skip response and look ahead for more to fuse.
skipped_responses.push_back(std::move(new_response));
responses.pop_front();
} else {
break;
}
}
}
// Replace any skipped responses.
while (!skipped_responses.empty()) {
responses.push_front(std::move(skipped_responses.back()));
skipped_responses.pop_back();
}
} else if (response.response_type() == Response::ResponseType::ALLGATHER) {
// Attempt to add more responses to this fused response.
const auto& entry =
tensor_queue_.GetTensorEntry(response.tensor_names()[0]);
// This is size of first dimension.
int64_t total_byte_size_of_output =
TotalByteSizeOfAllgatherOutput(response.tensor_sizes(), entry);
std::deque<Response> skipped_responses;
int64_t skipped_size = 0;
while (!responses.empty()) {
auto& new_response = responses.front();
if (new_response.response_type() == Response::ResponseType::BARRIER ||
new_response.response_type() == Response::ResponseType::JOIN) {
break;
}
assert(new_response.tensor_names().size() == 1);
const auto& new_entry =
tensor_queue_.GetTensorEntry(new_response.tensor_names()[0]);
int64_t new_total_byte_size_of_output = TotalByteSizeOfAllgatherOutput(
new_response.tensor_sizes(), new_entry);
if (response.response_type() == new_response.response_type() &&
response.devices() == new_response.devices() &&
entry.tensor->dtype() == new_entry.tensor->dtype() &&
total_byte_size_of_output + new_total_byte_size_of_output <=
TensorFusionThresholdBytes()) {
// These tensors will fuse together well.
total_byte_size_of_output += new_total_byte_size_of_output;
response.add_allgather_response(new_response);
responses.pop_front();
} else {
// In general, don't try to fuse additional tensors since they are
// usually computed in order of requests and skipping tensors may
// mean that the batch will have to wait longer while skipped
// tensors could be reduced at that time. However, mixed-precision
// training may yield requests of various dtype in a mixed-up
// sequence causing breakups in fusion. To counter this some look
// ahead is allowed.
skipped_size += new_total_byte_size_of_output;
if (total_byte_size_of_output + skipped_size <=
TensorFusionThresholdBytes()) {
// Skip response and look ahead for more to fuse.
skipped_responses.push_back(std::move(new_response));
responses.pop_front();
} else {
break;
}
}
}
// Replace any skipped responses.
while (!skipped_responses.empty()) {
responses.push_front(std::move(skipped_responses.back()));
skipped_responses.pop_back();
}
}
response_list.add_response(std::move(response));
LOG(TRACE) << "Created response of size " << tensor_size;
}
}
int64_t Controller::TotalByteSizeOfAllgatherOutput(
const std::vector<int64_t>& tensor_sizes, const TensorTableEntry& entry) {
int64_t total_dimension_size = 0;
for (auto sz : tensor_sizes) {
total_dimension_size += sz;
}
// Every tensor participating in Allgather operation may have
// different first dimension size, but the rest of dimensions are same
// for all tensors. Here we get shape of tensor sliced by first
// dimension. Allgather output will have shape of: (sum of first
// dimension of every tensor) x (tensor slice shape).
int64_t total_count_of_output_entries = total_dimension_size;
for (int i = 1; i < entry.tensor->shape().dims(); ++i) {
total_count_of_output_entries *= entry.tensor->shape().dim_size(i);
}
int element_size = GetTypeSize(entry.tensor->dtype());
int64_t total_byte_size_of_output =
total_count_of_output_entries * element_size;
return total_byte_size_of_output;
}
int Controller::GetLocalSizeAtCrossRank(int i) {
return local_sizes_for_cross_rank_[i];
}
bool Controller::IncrementTensorCount(const Request& msg, int joined_size) {
auto& name = msg.tensor_name();
auto table_iter = message_table_.find(name);
if (table_iter == message_table_.end()) {
std::vector<Request> messages = {msg};
messages.reserve(static_cast<unsigned long>(size_));
message_table_.emplace(name, std::move(messages));
table_iter = message_table_.find(name);
timeline_.NegotiateStart(name, msg.request_type());
} else {
std::vector<Request>& messages = table_iter->second;
messages.push_back(msg);
}
timeline_.NegotiateRankReady(name, msg.request_rank());
std::vector<Request>& messages = table_iter->second;
int count = (int)messages.size();
bool ready_to_reduce = count == (size_ - joined_size);
if (ready_to_reduce) {
timeline_.NegotiateEnd(name);
}
return ready_to_reduce;
}
} // namespace common
} // namespace horovod
| 38.145224 | 118 | 0.650254 | [
"shape",
"vector"
] |
b43372e88bc5a7d49e55fe5300d9ed33b8ab3ad6 | 3,009 | cpp | C++ | DearPyGui/src/core/AppItems/containers/mvMenu.cpp | czhmisaka/DearPyGui | a10b6cb8446aa17d3b3255214ca6b535111ec835 | [
"MIT"
] | 1 | 2021-02-09T07:03:52.000Z | 2021-02-09T07:03:52.000Z | DearPyGui/src/core/AppItems/containers/mvMenu.cpp | czhmisaka/DearPyGui | a10b6cb8446aa17d3b3255214ca6b535111ec835 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/containers/mvMenu.cpp | czhmisaka/DearPyGui | a10b6cb8446aa17d3b3255214ca6b535111ec835 | [
"MIT"
] | null | null | null | #pragma once
#include "mvMenu.h"
#include "mvApp.h"
namespace Marvel {
void mvMenu::InsertParser(std::map<std::string, mvPythonParser>* parsers)
{
parsers->insert({ "add_menu", mvPythonParser({
{mvPythonDataType::String, "name"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "label", "", "''"},
{mvPythonDataType::Bool, "show", "Attempt to render", "True"},
{mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"},
{mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"},
{mvPythonDataType::Bool, "enabled", "", "True"},
}, "Adds a menu to an existing menu bar. Must be followed by a call to end.", "None", "Containers") });
}
mvMenu::mvMenu(const std::string& name)
: mvBoolPtrBase(name, false, name)
{
m_description.container = true;
}
void mvMenu::draw()
{
auto styleManager = m_styleManager.getScopedStyleManager();
ScopedID id;
mvImGuiThemeScope scope(this);
// create menu and see if its selected
if (ImGui::BeginMenu(m_label.c_str(), m_core_config.enabled))
{
// set other menus's value false on same level
for (auto sibling : m_parent->m_children)
{
// ensure sibling
if (sibling->getType() == mvAppItemType::Menu)
*((mvMenu*)sibling.get())->m_value = false;
}
// set current menu value true
*m_value = true;
//we do this so that the children dont get the theme
scope.cleanup();
for (auto& item : m_children)
{
// skip item if it's not shown
if (!item->m_core_config.show)
continue;
// set item width
if (item->m_core_config.width != 0)
ImGui::SetNextItemWidth((float)item->m_core_config.width);
item->draw();
item->getState().update();
}
registerWindowFocusing();
ImGui::EndMenu();
}
}
#ifndef MV_CPP
void mvMenu::setExtraConfigDict(PyObject* dict)
{
if (dict == nullptr)
return;
if (PyObject* item = PyDict_GetItemString(dict, "enabled")) m_core_config.enabled = ToBool(item);
}
void mvMenu::getExtraConfigDict(PyObject* dict)
{
if (dict == nullptr)
return;
PyDict_SetItemString(dict, "enabled", ToPyBool(m_core_config.enabled));
}
PyObject* add_menu(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
const char* label = "";
int show = true;
const char* parent = "";
const char* before = "";
int enabled = true;
if (!(*mvApp::GetApp()->getParsers())["add_menu"].parse(args, kwargs, __FUNCTION__, &name,
&label, &show, &parent, &before, &enabled))
return ToPyBool(false);
auto item = CreateRef<mvMenu>(name);
item->checkConfigDict(kwargs);
item->setConfigDict(kwargs);
item->setExtraConfigDict(kwargs);
if (mvApp::GetApp()->getItemRegistry().addItemWithRuntimeChecks(item, parent, before))
{
mvApp::GetApp()->getItemRegistry().pushParent(item);
if (!show)
item->hide();
}
return GetPyNone();
}
#endif
} | 24.266129 | 135 | 0.661682 | [
"render"
] |
b433bc18acc9dadb06b82d89ad8088f78825c2dc | 8,433 | hpp | C++ | cuarma/traits/size.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | cuarma/traits/size.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | cuarma/traits/size.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | #pragma once
/* =========================================================================
Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang.
-----------------
cuarma - COE of Peking University, Shaoqiang Tang.
-----------------
Author Email yangxianpku@pku.edu.cn
Code Repo https://github.com/yangxianpku/cuarma
License: MIT (X11) License
============================================================================= */
/** @file cuarma/traits/size.hpp
* @encoding:UTF-8 文档编码
@brief Generic size and resize functionality for different vector and matrix types
*/
#include <string>
#include <fstream>
#include <sstream>
#include "cuarma/forwards.h"
#include "cuarma/meta/result_of.hpp"
#include "cuarma/meta/predicate.hpp"
#ifdef CUARMA_WITH_UBLAS
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#endif
#include <vector>
#include <map>
namespace cuarma
{
namespace traits
{
//
// Resize: Change the size of vectors and matrices
//
/** @brief Generic resize routine for resizing a matrix (cuarma, uBLAS, etc.) to a new size/dimension */
template<typename MatrixType>
void resize(MatrixType & matrix, arma_size_t rows, arma_size_t cols)
{
matrix.resize(rows, cols);
}
/** @brief Generic resize routine for resizing a vector (cuarma, uBLAS, etc.) to a new size */
template<typename VectorType>
void resize(VectorType & vec, arma_size_t new_size)
{
vec.resize(new_size);
}
/** \cond */
#ifdef CUARMA_WITH_UBLAS
//ublas needs separate treatment:
template<typename ScalarType>
void resize(boost::numeric::ublas::compressed_matrix<ScalarType> & matrix,
arma_size_t rows,
arma_size_t cols)
{
matrix.resize(rows, cols, false); //Note: omitting third parameter leads to compile time error (not implemented in ublas <= 1.42)
}
#endif
//
// size1: No. of rows for matrices
//
/** @brief Generic routine for obtaining the number of rows of a matrix (cuarma, uBLAS, etc.) */
template<typename MatrixType>
arma_size_t
size1(MatrixType const & mat) { return mat.size1(); }
/** \cond */
template<typename RowType>
arma_size_t
size1(std::vector< RowType > const & mat) { return mat.size(); }
//
// size2: No. of columns for matrices
//
/** @brief Generic routine for obtaining the number of columns of a matrix (cuarma, uBLAS, etc.) */
template<typename MatrixType>
typename result_of::size_type<MatrixType>::type
size2(MatrixType const & mat) { return mat.size2(); }
/** \cond */
template<typename RowType>
arma_size_t
size2(std::vector< RowType > const & mat) { return mat[0].size(); }
//
// size: Returns the length of vectors
//
/** @brief Generic routine for obtaining the size of a vector (cuarma, uBLAS, etc.) */
template<typename VectorType>
arma_size_t size(VectorType const & vec)
{
return vec.size();
}
/** \cond */
template<typename SparseMatrixType, typename VectorType>
arma_size_t size(vector_expression<const SparseMatrixType, const VectorType, op_prod> const & proxy)
{
return size1(proxy.lhs());
}
template<typename NumericT>
arma_size_t size(vector_expression<const matrix_base<NumericT>, const vector_base<NumericT>, op_prod> const & proxy) //matrix-vector product
{
return proxy.lhs().size1();
}
template<typename NumericT, typename LhsT, typename RhsT, typename OpT>
arma_size_t size(vector_expression<const matrix_base<NumericT>, const vector_expression<LhsT, RhsT, OpT>, op_prod> const & proxy) //matrix-vector product
{
return proxy.lhs().size1();
}
template<typename NumericT>
arma_size_t size(vector_expression<const matrix_expression<const matrix_base<NumericT>, const matrix_base<NumericT>, op_trans>,
const vector_base<NumericT>,
op_prod> const & proxy) //transposed matrix-vector product
{
return proxy.lhs().lhs().size2();
}
template<typename LHS, typename RHS, typename OP>
arma_size_t size(vector_expression<LHS, RHS, OP> const & proxy)
{
return size(proxy.lhs());
}
template<typename LHS, typename RHS>
arma_size_t size(vector_expression<LHS, const vector_tuple<RHS>, op_inner_prod> const & proxy)
{
return proxy.rhs().const_size();
}
template<typename LhsT, typename RhsT, typename OpT, typename VectorT>
arma_size_t size(vector_expression<const matrix_expression<const LhsT, const RhsT, OpT>,
VectorT,
op_prod> const & proxy)
{
return size1(proxy.lhs());
}
template<typename LhsT, typename RhsT, typename OpT, typename NumericT>
arma_size_t size(vector_expression<const matrix_expression<const LhsT, const RhsT, OpT>,
const vector_base<NumericT>,
op_prod> const & proxy)
{
return size1(proxy.lhs());
}
template<typename LhsT1, typename RhsT1, typename OpT1,
typename LhsT2, typename RhsT2, typename OpT2>
arma_size_t size(vector_expression<const matrix_expression<const LhsT1, const RhsT1, OpT1>,
const vector_expression<const LhsT2, const RhsT2, OpT2>,
op_prod> const & proxy)
{
return size1(proxy.lhs());
}
template<typename NumericT>
arma_size_t size(vector_expression<const matrix_base<NumericT>,
const matrix_base<NumericT>,
op_row_sum> const & proxy)
{
return size1(proxy.lhs());
}
template<typename LhsT, typename RhsT, typename OpT>
arma_size_t size(vector_expression<const matrix_expression<const LhsT, const RhsT, OpT>,
const matrix_expression<const LhsT, const RhsT, OpT>,
op_row_sum> const & proxy)
{
return size1(proxy.lhs());
}
template<typename NumericT>
arma_size_t size(vector_expression<const matrix_base<NumericT>,
const matrix_base<NumericT>,
op_col_sum> const & proxy)
{
return size2(proxy.lhs());
}
template<typename LhsT, typename RhsT, typename OpT>
arma_size_t size(vector_expression<const matrix_expression<const LhsT, const RhsT, OpT>,
const matrix_expression<const LhsT, const RhsT, OpT>,
op_col_sum> const & proxy)
{
return size2(proxy.lhs());
}
/** \endcond */
//
// internal_size: Returns the internal (padded) length of vectors
//
/** @brief Helper routine for obtaining the buffer length of a cuarma vector */
template<typename NumericT>
arma_size_t internal_size(vector_base<NumericT> const & vec)
{
return vec.internal_size();
}
//
// internal_size1: No. of internal (padded) rows for matrices
//
/** @brief Helper routine for obtaining the internal number of entries per row of a cuarma matrix */
template<typename NumericT>
arma_size_t internal_size1(matrix_base<NumericT> const & mat) { return mat.internal_size1(); }
//
// internal_size2: No. of internal (padded) columns for matrices
//
/** @brief Helper routine for obtaining the internal number of entries per column of a cuarma matrix */
template<typename NumericT>
arma_size_t internal_size2(matrix_base<NumericT> const & mat) { return mat.internal_size2(); }
/** @brief Helper routine for obtaining the internal number of entries per row of a cuarma matrix */
template<typename NumericT>
arma_size_t ld(matrix_base<NumericT> const & mat)
{
if (mat.row_major())
return mat.internal_size2();
return mat.internal_size1();
}
template<typename NumericT>
arma_size_t nld(matrix_base<NumericT> const & mat)
{
if (mat.row_major())
return mat.stride2();
return mat.stride1();
}
template<typename LHS>
arma_size_t size(vector_expression<LHS, const int, op_matrix_diag> const & proxy)
{
int k = proxy.rhs();
int A_size1 = static_cast<int>(size1(proxy.lhs()));
int A_size2 = static_cast<int>(size2(proxy.lhs()));
int row_depth = std::min(A_size1, A_size1 + k);
int col_depth = std::min(A_size2, A_size2 - k);
return arma_size_t(std::min(row_depth, col_depth));
}
template<typename LHS>
arma_size_t size(vector_expression<LHS, const unsigned int, op_row> const & proxy)
{
return size2(proxy.lhs());
}
template<typename LHS>
arma_size_t size(vector_expression<LHS, const unsigned int, op_column> const & proxy)
{
return size1(proxy.lhs());
}
} //namespace traits
} //namespace cuarma | 30.665455 | 154 | 0.675323 | [
"vector"
] |
b434b15e912fc4aee0aedb9770144fedb7628e61 | 1,779 | cc | C++ | DetectorDescription/DDCMS/src/DDCompactView.cc | jeongsumin/cmssw | 54acaec3dc59abda01c018920077db98db976746 | [
"Apache-2.0"
] | null | null | null | DetectorDescription/DDCMS/src/DDCompactView.cc | jeongsumin/cmssw | 54acaec3dc59abda01c018920077db98db976746 | [
"Apache-2.0"
] | null | null | null | DetectorDescription/DDCMS/src/DDCompactView.cc | jeongsumin/cmssw | 54acaec3dc59abda01c018920077db98db976746 | [
"Apache-2.0"
] | null | null | null | #include "DetectorDescription/DDCMS/interface/DDCompactView.h"
#include "FWCore/Utilities/interface/Exception.h"
#include <DD4hep/Filter.h>
#include <cmath>
#include "tbb/concurrent_vector.h"
template <>
std::vector<int> cms::DDCompactView::getVector<int>(const std::string& key) const {
std::vector<int> result;
const auto& vmap = this->detector()->vectors();
for (auto const& it : vmap) {
if (dd4hep::dd::noNamespace(it.first) == key) {
std::transform(
it.second.begin(), it.second.end(), std::back_inserter(result), [](int n) -> int { return (int)n; });
return result;
}
}
return result;
}
template <>
std::vector<double> cms::DDCompactView::getVector<double>(const std::string& key) const {
const auto& vmap = this->detector()->vectors();
for (auto const& it : vmap) {
if (dd4hep::dd::noNamespace(it.first) == key) {
return it.second;
}
}
return std::vector<double>();
}
template <>
std::vector<double> const& cms::DDCompactView::get<std::vector<double>>(const std::string& key) const {
const auto& vmap = this->detector()->vectors();
for (auto const& it : vmap) {
if (dd4hep::dd::noNamespace(it.first) == key) {
return it.second;
}
}
throw cms::Exception("DDError") << "no vector<double> with name " << key;
}
template <>
tbb::concurrent_vector<double> const& cms::DDCompactView::get<tbb::concurrent_vector<double>>(
const std::string& name, const std::string& key) const {
const auto& spec = specpars().specPar(name);
if (spec != nullptr) {
auto const& nitem = spec->numpars.find(key);
if (nitem != end(spec->numpars)) {
return nitem->second;
}
}
throw cms::Exception("DDError") << "no SpecPar with name " << name << " and vector<double> key " << key;
}
| 31.767857 | 111 | 0.645306 | [
"vector",
"transform"
] |
b434bf13438e43d3bacef4cc8c5065536f3e6e7c | 2,536 | cpp | C++ | libraries/ArduinoJson/test/JsonArray/set.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | null | null | null | libraries/ArduinoJson/test/JsonArray/set.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | 1 | 2020-01-09T07:07:44.000Z | 2020-01-09T07:07:44.000Z | libraries/ArduinoJson/test/JsonArray/set.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | null | null | null | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
using namespace Catch::Matchers;
TEST_CASE("JsonArray::set()") {
DynamicJsonDocument doc;
JsonArray _array = doc.to<JsonArray>();
_array.add(0);
SECTION("int") {
_array.set(0, 123);
REQUIRE(123 == _array[0].as<int>());
REQUIRE(_array[0].is<int>());
REQUIRE_FALSE(_array[0].is<bool>());
}
SECTION("double") {
_array.set(0, 123.45);
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(_array[0].is<double>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("bool") {
_array.set(0, true);
REQUIRE(true == _array[0].as<bool>());
REQUIRE(_array[0].is<bool>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("const char*") {
_array.set(0, "hello");
REQUIRE_THAT(_array[0].as<const char*>(), Equals("hello"));
REQUIRE(_array[0].is<const char*>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("nested array") {
DynamicJsonDocument doc2;
JsonArray arr = doc2.to<JsonArray>();
_array.set(0, arr);
REQUIRE(arr == _array[0].as<JsonArray>());
REQUIRE(_array[0].is<JsonArray>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("nested object") {
DynamicJsonDocument doc2;
JsonObject obj = doc2.to<JsonObject>();
_array.set(0, obj);
REQUIRE(obj == _array[0].as<JsonObject>());
REQUIRE(_array[0].is<JsonObject>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("array subscript") {
DynamicJsonDocument doc2;
JsonArray arr = doc2.to<JsonArray>();
arr.add("hello");
_array.set(0, arr[0]);
REQUIRE_THAT(_array[0].as<char*>(), Equals("hello"));
}
SECTION("object subscript") {
DynamicJsonDocument doc2;
JsonObject obj = doc2.to<JsonObject>();
obj["x"] = "hello";
_array.set(0, obj["x"]);
REQUIRE_THAT(_array[0].as<char*>(), Equals("hello"));
}
SECTION("should not duplicate const char*") {
_array.set(0, "world");
const size_t expectedSize = JSON_ARRAY_SIZE(1);
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate char*") {
_array.set(0, const_cast<char*>("world"));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6;
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate std::string") {
_array.set(0, std::string("world"));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6;
REQUIRE(expectedSize == doc.memoryUsage());
}
}
| 24.621359 | 63 | 0.623817 | [
"object"
] |
b43ab6cb95dbc1be6f46d865127477ce9a371879 | 6,209 | cpp | C++ | src/editor-graph.cpp | adct-the-experimenter/timeline-track-editor | f8282da358384b6349272bb242f0bdba8cee1e7e | [
"BSD-3-Clause"
] | 6 | 2019-05-28T03:04:02.000Z | 2021-07-02T18:38:39.000Z | src/editor-graph.cpp | adct-the-experimenter/timeline-track-editor | f8282da358384b6349272bb242f0bdba8cee1e7e | [
"BSD-3-Clause"
] | 5 | 2019-06-24T18:08:28.000Z | 2019-08-26T02:25:34.000Z | src/editor-graph.cpp | adct-the-experimenter/timeline-track-editor | f8282da358384b6349272bb242f0bdba8cee1e7e | [
"BSD-3-Clause"
] | null | null | null | #include "editor-graph.h"
EditorGraph::EditorGraph(wxWindow* parent) : wxPanel(parent)
{
}
void EditorGraph::SetReferenceToTimeTickVector(std::vector <int> *thisVector){timeTickVectorPtr = thisVector;}
int EditorGraph::GetVerticalGraphValueAtThisTime(double& thisTime, bool& legitValue)
{
//check if there is already a point at that time value
if ( map_time.find(thisTime) == map_time.end() )
{
//if not found, do nothing
legitValue = false;
return 0;
}
else
{
//if found
//get iterator to vector from time map
std::unordered_map<double,wxPoint>::const_iterator got = map_time.find (thisTime);
wxPoint point = got->second;
legitValue = true;
return (int)(point).y;
}
}
template <typename T>
void EditorGraph::render(wxDC& dc,std::vector <T> *verticalAxisVector)
{
DrawHorizontalAxis(dc);
DrawVerticalAxis(dc,verticalAxisVector);
DrawCurrentPointsOnGraph(dc);
}
template void EditorGraph::render<double>( wxDC& , std::vector<double>*);
void EditorGraph::DrawHorizontalAxis(wxDC& dc)
{
wxFont font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT);
dc.SetFont(font);
int step = (int) round( TRACK_WIDTH / (TIME_TICK_NUM-1) );
int offset = TRACK_WIDTH / (TIME_TICK_NUM - 1);
dc.SetPen(wxPen(wxColour(90, 80, 60)));
for ( int i=1; i <= (int)timeTickVectorPtr->size(); i++ )
{
dc.DrawLine(i*step - offset, 1, i*step - offset , 10);
//skip drawing the zero tick maker because it is mixes with text of vertical axis
if(i != 1)
{
dc.DrawText( wxString::Format( wxT("%ds"), (int)timeTickVectorPtr->at(i-1) ) , i*step - offset, 10);
}
}
}
template <typename T>
void EditorGraph::DrawVerticalAxis(wxDC& dc,std::vector <T> *verticalAxisVector)
{
wxFont font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT);
dc.SetFont(font);
int step = (int) round( TRACK_HEIGHT / (verticalAxisVector->size()) );
dc.SetPen(wxPen(wxColour(90, 80, 60)));
for ( size_t i=1; i <= verticalAxisVector->size(); i++ )
{
dc.DrawLine(1, i*step, 10, i*step);
//start at end to draw positive numbers on top
dc.DrawText( wxString::Format( wxT("%d"), (int)verticalAxisVector->at(verticalAxisVector->size() - i) ) , 0, (i*step) - 10);
}
}
template void EditorGraph::DrawVerticalAxis<double>( wxDC& , std::vector<double>*);
template <typename T>
void EditorGraph::mouseDownLeftClick(T& vertStart, T& vertEnd, T& vertRes,
double& time, int& relMouseY, bool& legitValues)
{
EditorGraph::PlacePointByMouse(vertStart,vertEnd,vertRes,time,relMouseY,legitValues);
}
template void EditorGraph::mouseDownLeftClick<double>( double& vertStart, double& vertEnd, double& vertRes,
double& time, int& relMouseY, bool& legitValues);
void EditorGraph::mouseDownRightClick(double& time,bool& legitValue)
{
EditorGraph::RemovePointByMouse(time,legitValue);
}
template <typename T>
void EditorGraph::PlacePointByMouse(T& vertStart, T& vertEnd, T& vertRes,
double& time, int& relMouseY, bool& legitValues)
{
//get graphical coordinates of where mouse left clicked relative to track panel
int mouseX = wxGetMousePosition().x - this->GetScreenPosition().x;
int mouseY = wxGetMousePosition().y - this->GetScreenPosition().y;
//convert mouse x to time value
double thisTime = mouseX * ((double)TIME_END_VALUE / (double)TRACK_WIDTH);
//make time value a multiple of timer resolution
thisTime = round (thisTime / (double(TIME_RESOLUTION) / 1000)) * (double(TIME_RESOLUTION) / 1000);
//std::cout << "add time:" << thisTime << std::endl;
legitValues = false;
//check if there is already a point at that time value
if ( map_time.find(thisTime) == map_time.end() )
{
//make mouseY a multiple of vertical resolution in pixels
//convert to value, divide by resolution, round result, multiply by resolution, convert back to pixel value
mouseY = round(mouseY * ( (vertEnd - vertStart) / double(TRACK_HEIGHT) ) * ( 1 / vertRes) ) * vertRes * ( double(TRACK_HEIGHT) / (vertEnd - vertStart) );
//std::cout << "mouseY is " << mouseY << "at time " << thisTime << " in place point by mouse.";
//if not found
//put into vector of graph points
//graph_points.push_back( wxPoint(mouseX,mouseY) );
//put into time map
//the iterator to element pushed back is actually the one before end iterator due to vectors having an extra element
//to carry out data operations!
//std::vector<wxPoint>::iterator it = graph_points.end()-1;
map_time.emplace(thisTime, wxPoint(mouseX,mouseY));
//save time and mouse y to input variables
time = thisTime;
relMouseY = mouseY;
legitValues = true;
}
}
template void EditorGraph::PlacePointByMouse<double>(double& vertStart, double& vertEnd, double& vertRes,
double& time, int& relMouseY, bool& legitValues);
void EditorGraph::RemovePointByMouse(double& time,bool& legitValue)
{
//get graphical coordinates of where mouse left clicked relative to track panel
int mouseX = wxGetMousePosition().x - this->GetScreenPosition().x;
//convert mouse x to time value
double thisTime = mouseX * ((double)TIME_END_VALUE / (double)TRACK_WIDTH);
//make time value a multiple of timer resolution
thisTime = round (thisTime / (double(TIME_RESOLUTION) / 1000)) * (double(TIME_RESOLUTION) / 1000);
//std::cout << "remove time:" << thisTime << std::endl;
//check if there is already a point at that time value
if ( map_time.find(thisTime) == map_time.end() )
{
//if not found, do nothing
legitValue = false;
}
else
{
//if found, remove the point
//save time point info
legitValue = true;
time = thisTime;
//get iterator to vector from time map
//std::unordered_map<double,wxPoint>::const_iterator got = map_time.find (thisTime);
//wxPoint point = got->second;
//remove point from vector of graph points
//graph_points.erase(it);
//remove from time map
map_time.erase(thisTime);
}
}
void EditorGraph::DrawCurrentPointsOnGraph(wxDC& dc)
{
// draw a circle
dc.SetBrush(*wxBLACK_BRUSH);
//for(size_t i=0; i < graph_points.size(); i++)
//{
// dc.DrawCircle( graph_points.at(i), 2 );
//}
for ( auto it = map_time.begin(); it != map_time.end(); ++it )
{
dc.DrawCircle( it->second, 2 );
}
}
| 31.358586 | 155 | 0.698824 | [
"render",
"vector"
] |
b43b4f55d8454a387c6518b099c6d3c48ca00570 | 2,909 | cpp | C++ | src/ClingInterpreterModule.cpp | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 13 | 2019-09-24T06:45:54.000Z | 2020-10-22T10:04:33.000Z | src/ClingInterpreterModule.cpp | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 65 | 2019-09-20T07:25:22.000Z | 2020-10-14T14:31:52.000Z | src/ClingInterpreterModule.cpp | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 22 | 2019-09-25T10:11:57.000Z | 2020-10-12T10:40:14.000Z | #include "ClingInterpreterModule.hpp"
/// \todo use boost outcome for error reporting
#include <iostream>
#include <exception>
#if defined(CLING_IS_ON)
// __has_include is currently supported by GCC and Clang. However GCC 4.9 may have issues and
// returns 1 for 'defined( __has_include )', while '__has_include' is actually not supported:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63662
#if __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
namespace cling_utils {
std::vector<std::string>
InterpreterModule::extra_args;
InterpreterModule::InterpreterModule(const std::string &id)
: id_(id)
{
createInterpreter();
}
InterpreterModule::~InterpreterModule() {}
void InterpreterModule::processCode(const std::string& code) {
cling::Interpreter::CompilationResult interpRes;
cling::Value res; // Will hold the result of the expression evaluation.
interpRes = interpreter_->process(code.c_str(), &res);
if(interpRes
!= cling::Interpreter::Interpreter::kSuccess) {
/// \todo use boost outcome for error reporting
std::cerr << "ERROR while running code\n" << code.substr(0, 100) << std::endl;
std::terminate();
}
}
void add_default_cling_args(std::vector<std::string> &args) {
args.push_back("EmbedCling");
args.push_back("-I.");
args.push_back("-I../");
args.push_back("--std=c++17");
args.push_back("-I../cling-build/build/lib/clang/5.0.0/include");
args.push_back("-I../cling-build/src/include/");
args.push_back("-I../cling-build/build/include/");
args.push_back("-I../cling-build/src/tools/clang/include/");
args.push_back("-I../cling-build/build/tools/clang/include/");
args.push_back("-I../cling-build/src/tools/cling/include/");
// https://stackoverflow.com/a/30877725
args.push_back("-DBOOST_SYSTEM_NO_DEPRECATED");
args.push_back("-DBOOST_ERROR_CODE_HEADER_ONLY");
for(const auto& it: InterpreterModule::extra_args) {
args.push_back(it);
}
}
void InterpreterModule::createInterpreter() {
std::vector<std::string> args;
add_default_cling_args(args);
std::vector< const char* > interp_args;
{
std::vector< std::string >::const_iterator iarg;
for( iarg = args.begin() ; iarg != args.end() ; ++iarg ) {
interp_args.push_back(iarg->c_str());
}
}
interpreter_ = std::make_unique<cling::Interpreter>(
interp_args.size(), &(interp_args[0]), LLVMDIR/*, {}, false*/);
interpreter_->AddIncludePath(".");
interpreter_->AddIncludePath("../");
interpreter_->enableDynamicLookup(true);
metaProcessor_ = std::make_unique<cling::MetaProcessor>(*interpreter_, llvm::outs());
interpreter_->process("#define CLING_IS_ON 1");
}
} // namespace cling_utils
#endif // CLING_IS_ON
| 31.619565 | 93 | 0.687865 | [
"vector"
] |
b43c05345b5ec2f69e34cabb7a40ad431a5c1a11 | 6,666 | hpp | C++ | src/core/thread/address_resolver.hpp | jjzhang166/openthread | e68e38b8e85fe4eeb3810727cd3583b5f87a4e70 | [
"BSD-3-Clause"
] | 1 | 2021-05-21T05:03:00.000Z | 2021-05-21T05:03:00.000Z | src/core/thread/address_resolver.hpp | leslieguyo/openthread | 6e7f8534e038a131173b57f9cf899351e8242413 | [
"BSD-3-Clause"
] | null | null | null | src/core/thread/address_resolver.hpp | leslieguyo/openthread | 6e7f8534e038a131173b57f9cf899351e8242413 | [
"BSD-3-Clause"
] | 1 | 2021-05-21T05:03:01.000Z | 2021-05-21T05:03:01.000Z | /*
* Copyright (c) 2016, Nest Labs, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 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.
*/
/**
* @file
* This file includes definitions for Thread EID-to-RLOC mapping and caching.
*/
#ifndef ADDRESS_RESOLVER_HPP_
#define ADDRESS_RESOLVER_HPP_
#include <openthread-core-config.h>
#include <openthread-types.h>
#include <coap/coap_server.hpp>
#include <common/timer.hpp>
#include <mac/mac.hpp>
#include <net/icmp6.hpp>
#include <net/udp6.hpp>
namespace Thread {
class MeshForwarder;
class ThreadLastTransactionTimeTlv;
class ThreadMeshLocalEidTlv;
class ThreadNetif;
class ThreadTargetTlv;
/**
* @addtogroup core-arp
*
* @brief
* This module includes definitions for Thread EID-to-RLOC mapping and caching.
*
* @{
*/
/**
* This class implements the EID-to-RLOC mapping and caching.
*
*/
class AddressResolver
{
public:
/**
* This constructor initializes the object.
*
*/
explicit AddressResolver(ThreadNetif &aThreadNetif);
/**
* This method clears the EID-to-RLOC cache.
*
*/
void Clear(void);
/**
* This method removes a Router ID from the EID-to-RLOC cache.
*
* @param[in] aRouterId The Router ID.
*
*/
void Remove(uint8_t aRouterId);
/**
* This method returns the RLOC16 for a given EID, or initiates an Address Query if the mapping is not known.
*
* @param[in] aEid A reference to the EID.
* @param[out] aRloc16 The RLOC16 corresponding to @p aEid.
*
* @retval kTheradError_None Successfully provided the RLOC16.
* @retval kThreadError_AddressQuery Initiated an Address Query.
*
*/
ThreadError Resolve(const Ip6::Address &aEid, Mac::ShortAddress &aRloc16);
private:
enum
{
kCacheEntries = OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES,
kStateUpdatePeriod = 1000u, ///< State update period in milliseconds.
};
/**
* Thread Protocol Parameters and Constants
*
*/
enum
{
kAddressQueryTimeout = 3, ///< ADDRESS_QUERY_TIMEOUT (seconds)
kAddressQueryInitialRetryDelay = 15, ///< ADDRESS_QUERY_INITIAL_RETRY_DELAY (seconds)
kAddressQueryMaxRetryDelay = 480, ///< ADDRESS_QUERY_MAX_RETRY_DELAY (seconds)
};
struct Cache
{
Ip6::Address mTarget;
uint8_t mMeshLocalIid[Ip6::Address::kInterfaceIdentifierSize];
Mac::ShortAddress mRloc16;
uint16_t mRetryTimeout;
uint8_t mTimeout;
uint8_t mFailures;
enum State
{
kStateInvalid,
kStateQuery,
kStateCached,
};
State mState;
};
ThreadError SendAddressQuery(const Ip6::Address &aEid);
ThreadError SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid,
const Ip6::Address *aDestination);
void SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv, const ThreadMeshLocalEidTlv &aMlEidTlv,
const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv,
const Ip6::Address &aDestination);
void SendAddressNotificationResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo);
static void HandleUdpReceive(void *aContext, otMessage aMessage, const otMessageInfo *aMessageInfo);
static void HandleAddressError(void *aContext, Coap::Header &aHeader,
Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
static void HandleAddressQuery(void *aContext, Coap::Header &aHeader,
Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
static void HandleAddressNotification(void *aContext, Coap::Header &aHeader,
Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void HandleAddressNotification(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
static void HandleDstUnreach(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo,
const Ip6::IcmpHeader &aIcmpHeader);
void HandleDstUnreach(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const Ip6::IcmpHeader &aIcmpHeader);
static void HandleTimer(void *aContext);
void HandleTimer(void);
Coap::Resource mAddressError;
Coap::Resource mAddressQuery;
Coap::Resource mAddressNotification;
Cache mCache[kCacheEntries];
uint16_t mCoapMessageId;
uint8_t mCoapToken[2];
Ip6::IcmpHandler mIcmpHandler;
Ip6::UdpSocket mSocket;
Timer mTimer;
MeshForwarder &mMeshForwarder;
Coap::Server &mCoapServer;
Mle::MleRouter &mMle;
Ip6::Netif &mNetif;
};
/**
* @}
*/
} // namespace Thread
#endif // ADDRESS_RESOLVER_HPP_
| 35.269841 | 119 | 0.681818 | [
"object"
] |
b43cc7509532b8f4ec578f88ee192eae18f0ce3a | 15,395 | cc | C++ | Rpi/Nav/NavSimple.cc | Kronos3/vo-cmpe460 | 0de7ace458a58cb580b3a79462b515d6313440a2 | [
"MIT"
] | null | null | null | Rpi/Nav/NavSimple.cc | Kronos3/vo-cmpe460 | 0de7ace458a58cb580b3a79462b515d6313440a2 | [
"MIT"
] | null | null | null | Rpi/Nav/NavSimple.cc | Kronos3/vo-cmpe460 | 0de7ace458a58cb580b3a79462b515d6313440a2 | [
"MIT"
] | null | null | null | #include "NavAlgorithm.h"
#include "Assert.hpp"
#include "opencv2/imgproc.hpp"
namespace Rpi
{
NavSimple::NavSimple(CarController* car)
: NavAlgorithm(car)
{
}
bool NavSimple::process(CamFrame* frame, cv::Mat &image)
{
F32 left, right;
EdgesFound edges;
// EdgesFound edges = find_edges(image, left, right,
// m_car->params().simple.row,
// m_car->params().simple.cutoff);
F32 turning = 0;
char edge_mnemonic = '?';
switch (edges)
{
case NONE_FOUND:
// Stop the car
return false;
case LEFT_FOUND:
turning = 1 * (1 - left);
edge_mnemonic = 'L';
break;
case RIGHT_FOUND:
turning = -1 * (1 - right);
edge_mnemonic = 'R';
break;
case BOTH_FOUND:
edge_mnemonic = 'B';
if (left < right)
{
turning = 1 * (1 - left);
}
else
{
turning = -1 * (1 - right);
}
break;
default:
FW_ASSERT(0 && "Invalid edge case found", edges);
}
// F32 turning_factor = m_car->params().simple.turning * turning;
F32 turning_factor = 0 * turning;
std::ostringstream ss;
ss << "Edges: " << edge_mnemonic << "\n"
<< "Left: " << left << "\n"
<< "Right: " << right << "\n"
<< "Turn: " << turning_factor;
draw_information(image, ss.str());
// Send the commands to the car
m_car->steer(turning_factor);
m_car->throttle(0, 0); // TODO(tumbar) remove
return true;
}
NavSimplePid::NavSimplePid(CarController* car)
: NavPid(car)
{
}
void draw_full_line(cv::Mat& img,
cv::Point2f p1,
cv::Point2f p2,
const cv::Scalar &color)
{
cv::Point2f p, q;
// Check if the line is a vertical line because vertical lines don't have slope
if (p1.x != p2.x)
{
p.x = 0;
q.x = (F32)img.cols;
// Slope equation (y1 - y2) / (x1 - x2)
F32 m = (p1.y - p2.y) / (p1.x - p2.x);
// Line equation: y = mx + b
F32 b = p1.y - (m * p1.x);
p.y = m * p.x + b;
q.y = m * q.x + b;
}
else
{
p.x = q.x = p2.x;
p.y = 0;
q.y = (F32)img.rows;
}
cv::line(img, p, q, color, 1);
}
struct ParametricSpline
{
bool set(const std::vector<cv::Point> &points)
{
F64 last_t = 0;
for (size_t i = 1; i < points.size(); i++)
{
F64 dx = points[i].x - points[i - 1].x;
F64 dy = points[i].y - points[i - 1].y;
// dt = ds
// parameter is length of curve
// F64 gradient = std::sqrt((dx * dx) + (dy * dy));
// if (gradient < 0.01)
// {
// // Points are too close together
// continue;
// }
t.push_back(last_t + 1);
x.push_back(points[i].x);
y.push_back(points[i].y);
last_t += 1;
}
if (t.size() <= 3)
{
return false;
}
// setup splines for x and y coordinate
sx.set_points(t, x);
sy.set_points(t, y);
return true;
}
bool get_center(F64 t_,
const std::vector<cv::Point> &other_track,
cv::Point ¢er,
cv::Mat &image_diagnostic) const
{
// Pick a line
// Find p0 and p1
// We are solving for a line perpendicular to the tangent
cv::Point2d p0(sx(t_), sy(t_));
cv::Point2d p1 = p0 + cv::Point2d(sy.deriv(1, t_), sx.deriv(1, t_));
draw_full_line(image_diagnostic, p0, p1, cv::Scalar(255, 255, 255));
// Move through every pair on the other_track
// and find the line segment that will intersect the
for (U32 i = 0; i < other_track.size() - 1; i++)
{
cv::Point2d solution;
if (linear_solver(p0, p1,
other_track.at(i),
other_track.at(i + 1),
solution))
{
// Now the midpoint between this solution and p0
// is the center of the track
center = 0.5 * (p0 + solution);
return true;
}
}
return false;
}
const tk::spline& getx() const { return sx; }
const tk::spline& gety() const { return sy; }
cv::Point operator()(F32 t_)
{
return {(I32)sx(t_), (I32)sy(t_)};
}
F64 dx(F32 t_)
{
return sx.deriv(1, t_);
}
static bool linear_solver(
cv::Point2d A, cv::Point2d B,
cv::Point2d C, cv::Point2d D,
cv::Point2d &solution)
{
F64 a = B.y - A.y;
F64 b = A.x - B.x;
F64 c = a * (A.x) + b * (A.y);
// Line CD represented as a2x + b2y = c2
F64 a1 = D.y - C.y;
F64 b1 = C.x - D.x;
F64 c1 = a1 * (C.x) + b1 * (C.y);
F64 det = a * b1 - a1 * b;
if (det == 0)
{
// Lines are parallel
return false;
}
else
{
F64 x_sol = (b1 * c - b * c1) / det;
F64 y_sol = (a * c1 - a1 * c) / det;
solution = cv::Point2d(x_sol, y_sol);
return true;
}
}
std::vector<F64> t;
std::vector<F64> x;
std::vector<F64> y;
tk::spline sx;
tk::spline sy;
};
bool NavSimplePid::process(CamFrame* frame, cv::Mat &image)
{
// Nav doesn't care about the dimensions of the image,
// we can operate on the Vision pipeline's size
cv::resize(image, m_resized,
cv::Size(image.cols / 8, image.rows / 8),
0, 0, cv::INTER_NEAREST // same as Vis
);
F32 row = m_car->params().scan.row;
I32 center = m_resized.cols / 2;
I32 left, right;
I32 row_pix = (I32) (row * (F32) m_resized.rows);
cv::Point center_pnt = cv::Point(center, row_pix);
EdgesFound edges = find_edges(m_resized, center_pnt, left, right);
F64 actual;
switch(edges)
{
case NONE_FOUND:
right = m_resized.cols;
left = 0;
break;
case LEFT_FOUND:
right = m_resized.cols;
cv::drawMarker(m_resized, cv::Point(left, row_pix),
cv::Scalar(155, 155, 155), cv::MARKER_CROSS, 5, 1);
break;
case RIGHT_FOUND:
cv::drawMarker(m_resized, cv::Point(right, row_pix),
cv::Scalar(155, 155, 155), cv::MARKER_CROSS, 5, 1);
left = 0;
break;
case BOTH_FOUND:
cv::drawMarker(m_resized, cv::Point(left, row_pix),
cv::Scalar(155, 155, 155), cv::MARKER_CROSS, 5, 1);
cv::drawMarker(m_resized, cv::Point(right, row_pix),
cv::Scalar(155, 155, 155), cv::MARKER_CROSS, 5, 1);
break;
}
actual = (right + left) / 2.0;
#if 0
std::vector<cv::Point> center_line;
for (U32 i = 0; i < left_line.size(); i++)
{
center_line.push_back(0.5 * (left_line.at(i) + right_line.at(i)));
}
// Low pass the center line
for (U32 i = 1; i < center_line.size() - 1; i++)
{
center_line[i] =
0.25 * center_line[i - 1] +
0.5 * center_line[i] +
0.25 * center_line[i + 1];
cv::drawMarker(m_resized, center_line[i], cv::Scalar(255, 255, 255),
cv::MARKER_SQUARE, 5);
}
cv::Point steering_point = center_line.at(2);
cv::drawMarker(m_resized, steering_point, cv::Scalar(255, 255, 255),
cv::MARKER_TRIANGLE_UP, 10);
F64 actual = (F64)steering_point.x / m_resized.cols;
#endif
#if 0
std::vector<cv::Point> center_points;
for (U32 i = 0; i < FW_MIN(left_line.size(), right_line.size()); i++)
{
cv::Point center_point = 0.5 * (left_line[i] + right_line[i]);
center_points.push_back(center_point);
cv::drawMarker(m_resized, center_point, cv::Scalar(255, 255, 255),
cv::MARKER_CROSS, 5);
}
F64 actual;
ParametricSpline center_spline;
if (center_spline.set(center_points))
{
cv::Point steering_point = center_spline(m_car->params().pid.steering_t);
cv::drawMarker(m_resized, steering_point,
cv::Scalar(255, 255, 255),
cv::MARKER_TRIANGLE_UP);
// center_spline.draw_heading(m_car->params().pid.steering_t, m_resized);
// actual = center_spline.dx(m_car->params().pid.steering_t);
steering_point = center
}
else
{
actual = 0.0;
}
#endif
F64 desired = m_resized.cols / 2.0;
F64 error = desired - actual;
F64 steering = pid(error);
F64 throttle = (1.0 - error) * m_car->params().pid.t;
std::ostringstream ss;
ss << "Desired: " << desired << "\n"
<< "Actual: " << actual << "\n"
<< "Error: " << error << "\n"
<< "Turn: " << steering << "\n"
<< "Throttle: " << throttle << "\n";
cv::resize(m_resized, image,
cv::Size(image.cols, image.rows),
0, 0, cv::INTER_NEAREST // same as Vis
);
draw_information(image, ss.str());
m_car->steer((F32) steering);
// m_car->throttle((F32) throttle,
// (F32) throttle);
// TODO(tumbar) Dynamic throttle
m_car->throttle(m_car->params().pid.t,
m_car->params().pid.t);
return true;
}
template<typename T>
void smooth_bad(std::vector<T> &line, U32 iter_n)
{
// Continuously smooth the line
std::vector<T> buffer = line;
std::vector<T>* current = &line;
std::vector<T>* average = &buffer;
for (U32 iter = 0; iter < iter_n; iter++)
{
for (U32 i = 1; i < line.size(); i++)
{
T p1 = current->at(i);
T p0 = current->at(i);
(*average)[i] = 0.5 * (p1 + p0);
}
// Swap the two buffers
std::vector<T>* tmp = current;
current = average;
average = tmp;
}
// line should not have bad points anymore
}
void remove_bad(std::vector<cv::Point> &line,
F32 derivative_tolerance)
{
// Discontinuities are defined as points whose derivatives
// don't match approaching from both sides
// Matching is defined as under some threshold
U32 size_last;
do
{
size_last = line.size();
for (U32 i = 1; i < line.size() - 1; i++)
{
// We are only concerned with dx because
// we are scanning at a constant dy
F64 top_d = cv::norm(line[i + 1] - line[i]);
F64 bottom_d = cv::norm(line[i - 1] - line[i]);
if (top_d > derivative_tolerance
&& bottom_d > derivative_tolerance)
{
// The current point is a bad point
line.erase(line.begin() + i);
}
}
} while (line.size() != size_last && line.size() > 3);
// First and last points are usually bad
if (line.size() >= 3)
{
line.erase(line.begin());
line.erase(line.end() - 1);
}
}
void refine_edges(
cv::Mat &image,
std::vector<cv::Point> &line)
{
for (auto &p: line)
{
// Search around this point for the nearest edge
I32 i;
for (i = 0; i < 30; i++)
{
U8 left_search = image.at<U8>(p.y, p.x - i);
U8 right_search = image.at<U8>(p.y, p.x + i);
if (left_search > 150)
{
p = cv::Point(p.x - i, p.y);
break;
}
else if (right_search > 150)
{
p = cv::Point(p.x + i, p.y);
break;
}
}
}
}
void NavSimplePid::find_track_edges(cv::Mat &image,
std::vector<cv::Point> &left_line,
std::vector<cv::Point> &right_line) const
{
// Scan the image by moving up along the frame and scanning for edges
U32 max_pts = 30;
left_line.clear();
right_line.clear();
left_line.reserve(max_pts);
right_line.reserve(max_pts);
// Find the track
F32 row = m_car->params().scan.row;
I32 center = image.cols / 2;
I32 left, right;
I32 row_pix = (I32) (row * (F32) image.rows);
cv::Point center_pnt = cv::Point(center, row_pix);
EdgesFound edges = find_edges(image, center_pnt, left, right);
if (edges != BOTH_FOUND)
{
return;
}
// Draw the track lines
cv::Point ls(left, row_pix);
cv::Point rs(right, row_pix);
cv::Point lp;
cv::Point rp;
U32 i = 0;
I32 rc = THETA_DIVISIONS / 4;
I32 lc = THETA_DIVISIONS / 4;
while (trace_line(image, ls,
lp, m_car->params().scan.step,
lc) &&
trace_line(image, rs,
rp, m_car->params().scan.step,
rc) &&
i++ < max_pts)
{
left_line.push_back(lp);
right_line.push_back(rp);
ls = lp;
rs = rp;
}
for (const auto &l: left_line)
{
cv::drawMarker(image, l, cv::Scalar(155, 155, 155),
cv::MARKER_CROSS, 5);
}
for (const auto &r: right_line)
{
cv::drawMarker(image, r, cv::Scalar(155, 155, 155),
cv::MARKER_DIAMOND, 5);
}
}
} | 30.606362 | 87 | 0.43683 | [
"vector"
] |
b43e5cb85a43e3b7168ecbb0e0295b0daa067476 | 32,194 | cpp | C++ | reference/aga_bayrate/db.cpp | flovo/goratings | 50b5443b73daae64306e256205eabee8f4815c65 | [
"MIT"
] | 13 | 2020-07-02T16:43:12.000Z | 2021-12-12T00:12:48.000Z | reference/aga_bayrate/db.cpp | flovo/goratings | 50b5443b73daae64306e256205eabee8f4815c65 | [
"MIT"
] | 13 | 2020-07-05T10:06:42.000Z | 2022-02-27T10:03:24.000Z | reference/aga_bayrate/db.cpp | flovo/goratings | 50b5443b73daae64306e256205eabee8f4815c65 | [
"MIT"
] | 2 | 2020-07-04T11:19:37.000Z | 2021-01-15T16:46:32.000Z | /*************************************************************************************
Copyright 2010 Philip Waldron
This file is part of BayRate.
BayRate 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.
BayRate 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
***************************************************************************************/
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include <assert.h>
#include <mysql++/mysql++.h>
#include <ctime>
#include <boost/date_time/gregorian/gregorian.hpp>
#include "db.h"
#include "db_passwords.h"
#include "collection.h"
#include "player.h"
#include "game.h"
using namespace std;
//using namespace boost::gregorian;
databaseConnection::databaseConnection() {
onlyone = false;
showagagd = false;
showallratedplayers = false;
showmembersdb = false;
showratingsdb = false;
showtournamentlist = false;
}
databaseConnection::~databaseConnection() {
db.disconnect();
ratingsdb.disconnect();
membersdb.disconnect();
}
void databaseConnection::onlyOne (bool b) {
onlyone = b;
}
void databaseConnection::showAGAGD (bool b) {
showagagd = b;
}
void databaseConnection::syncShowAllRatedPlayers (bool b) {
showallratedplayers = b;
}
void databaseConnection::showMembersDB (bool b) {
showmembersdb = b;
}
void databaseConnection::showRatingsDB (bool b) {
showratingsdb = b;
}
void databaseConnection::showTournamentList (bool b) {
showtournamentlist = b;
}
/****************************************************************
makeConnection ()
Establish a connection to the ratings server(s).
*****************************************************************/
bool databaseConnection::makeConnection() {
db = mysqlpp::Connection(false);
// return db.connect("database", "host", "user", "password") &&
// ratingsdb.connect("database", "host", "user", "password");
return db.connect(usgo_agagd_database, usgo_agagd_server, usgo_agagd_user, usgo_agagd_password)
&& ratingsdb.connect(ratings_database, ratings_server, ratings_user, ratings_password)
&& membersdb.connect(members_database, members_server, members_user, members_password);
// return db.connect("usgo_agagd", "localhost", "root", "Burcan**") && ratingsdb.connect("usgo", "localhost", "root", "Burcan**");
}
// Set exclude flags on any games for which player rank data is bogus
// Bogus ranks are anything that isn't a kyu/dan indicator
// Blank ranks will be dealt with later
void databaseConnection::excludeBogusGameData() {
mysqlpp::Query query(&db, false);
query.exec("UPDATE games SET exclude = 1 WHERE NOT (rank_1 LIKE '%k%' OR rank_1 LIKE '%K%' OR rank_1 LIKE '%d%' OR rank_1 LIKE '%D%')");
query.exec("UPDATE games SET exclude = 1 WHERE NOT (rank_2 LIKE '%k%' OR rank_2 LIKE '%K%' OR rank_2 LIKE '%d%' OR rank_2 LIKE '%D%')");
query.exec("UPDATE games SET exclude = 1 WHERE (rank_1 = '0k' OR rank_1 = '0K' OR rank_1 = '0d' OR rank_1 = '0D')");
query.exec("UPDATE games SET exclude = 1 WHERE (rank_2 = '0k' OR rank_2 = '0K' OR rank_2 = '0d' OR rank_2 = '0D')");
query.exec("UPDATE games SET exclude = 1 WHERE handicap>9");
query.exec("UPDATE games SET exclude = 1 WHERE handicap>=2 and komi>=10");
query.exec("UPDATE games SET exclude = 1 WHERE handicap>=2 and komi<=-10");
query.exec("UPDATE games SET exclude = 1 WHERE (handicap=0 or handicap=1) and komi<=-20");
query.exec("UPDATE games SET exclude = 1 WHERE (handicap=0 or handicap=1) and komi<=-20");
query.exec("UPDATE games SET exclude = 1 WHERE (game_date < '1900-01-01')");
query.exec("UPDATE games SET exclude = 1 WHERE pin_player_1 = 0 or pin_player_2 = 0");
}
/****************************************************************
bool databaseConnection::getMostRecentRatedGameDate(boost::gregorian::date &tournamentCascadeDate)
****************************************************************/
bool databaseConnection::getMostRecentRatedGameDate(boost::gregorian::date &tournamentCascadeDate) {
mysqlpp::Query query = db.query("SELECT MAX(Game_Date) AS date FROM games WHERE Rated = 1");
cout << query.str() << endl;
cout << endl;
mysqlpp::StoreQueryResult res = query.store();
if (!res)
return false;
mysqlpp::Date tempDate = res[0]["date"];
// Check if the response was NULL. The date gets converted to 0000-00-00 if it is.
if (tempDate == mysqlpp::Date("0000-00-00")) {
return true;
}
tournamentCascadeDate = boost::gregorian::date(boost::gregorian::from_simple_string(tempDate.str()));
return true;
}
/****************************************************************
bool databaseConnection::getTournamentUpdateList (vector<string> &tournamentUpdateList, date &tournamentCascadeDate)
Get the list of tournaments that need (re)rating. List of
tournament codes is placed in parameter TournamentUpdateList.
Date of first tournament that need rerating placed in parameter
tournamentCascadeDate.
Returns true if the operation was successful
*****************************************************************/
bool databaseConnection::getTournamentUpdateList(vector<string> &tournamentUpdateList, boost::gregorian::date &tournamentCascadeDate) {
mysqlpp::Query query = db.query("SELECT MIN(Game_Date) AS date FROM games WHERE Game_Date > '1950-01-01' AND NOT (Online OR Exclude OR Rated)");
if (showtournamentlist) {
cout << "getTournamentUpdateList: AGAGD: " << query.str() << endl;
cout << endl;
}
mysqlpp::StoreQueryResult res = query.store();
if (!res)
return false;
mysqlpp::Date tempDate = res[0]["date"];
// Check if the response was NULL. The date gets converted to 0000-00-00 if it is.
if (tempDate == mysqlpp::Date("0000-00-00")) {
return true;
}
tournamentCascadeDate = boost::gregorian::date(boost::gregorian::from_simple_string(tempDate.str()));
mysqlpp::Query query2 = db.query("SELECT DISTINCT t.Tournament_Code, t.Tournament_Date FROM tournaments t, games g WHERE t.Tournament_Date >= %0q AND t.Tournament_Code = g.Tournament_Code AND NOT (g.Online OR g.Exclude) ORDER BY Tournament_Date");
if (showtournamentlist) {
cout << "getTournamentUpdateList: AGAGD: " << query2.str(tempDate) << endl;
cout << endl;
}
query2.parse();
res = query2.store(tempDate);
for (size_t i=0; i<res.num_rows(); i++) {
tournamentUpdateList.push_back(static_cast<string>(res[i]["Tournament_Code"]));
if (showtournamentlist)
cout << res[i]["Tournament_Code"] << endl;
}
cout << endl;
return true;
}
/****************************************************************
bool getTDList ()
Gets the last valid TDList prior to the date given by parameter
tournamentCascadeDate. Data placed into map parameter TdList.
USES "ratings" table
Returns true if the operation is successful
*****************************************************************/
bool databaseConnection::getTDList(boost::gregorian::date &tournamentCascadeDate, map<int, tdListEntry> &tdList, mysqlpp::Query &query, bool verbose_getTDList) {
tdListEntry entry;
if (verbose_getTDList) {
cout << "databaseConnection::getTDList: " << query.str() << endl;
cout << endl;
}
query.parse();
mysqlpp::StoreQueryResult res = query.store(mysqlpp::Date(boost::gregorian::to_iso_extended_string(tournamentCascadeDate)));
for (size_t i=0; i<res.num_rows(); ++i) {
entry.id = res[i]["pin_player"];
entry.rating = res[i]["rating"];
entry.rating_ante = res[i]["rating"];
entry.sigma = res[i]["sigma"];
entry.sigma_ante = res[i]["sigma"];
entry.name = string(res[i]["name"]);
mysqlpp::Date tempDate = res[i]["elab_date"];
if (tempDate == mysqlpp::Date("0000-00-00")) {
entry.lastRatingDate = boost::gregorian::date(1900, 1, 1);
}
else {
entry.lastRatingDate = boost::gregorian::date(boost::gregorian::from_simple_string(tempDate.str()));
}
entry.ratingUpdated = false;
tdList[entry.id] = entry;
if (verbose_getTDList)
cout << res.num_rows() << ':' << i+1 << '\t' << entry.id << '\t' << entry.rating << '\t'
<< entry.sigma << '\t' << entry.name << endl;
}
return true;
}
/****************************************************************
bool getTDListAsOfDate ()
Gets the TDList as of the date given by parameter tournamentCascadeDate.
Data placed into map parameter TdList.
Returns true if the operation is successful
*****************************************************************/
bool databaseConnection::getTDListAsOfDate(boost::gregorian::date &tournamentCascadeDate, map<int, tdListEntry> &tdList, bool verbose_getTDList) {
tdListEntry entry;
mysqlpp::Query query = db.query("SELECT CONCAT(players.name, ' ', players.last_name) AS name, x.pin_player, x.rating, x.sigma, x.elab_date FROM ratings x, players, (SELECT MAX(elab_date) AS maxdate, pin_player FROM ratings WHERE elab_date <= %0q GROUP BY pin_player) AS maxresults WHERE x.pin_player = maxresults.pin_player AND x.elab_date = maxresults.maxdate AND x.pin_player = players.pin_player AND x.pin_player != 0");
return databaseConnection::getTDList(tournamentCascadeDate, tdList, query, verbose_getTDList);
}
/****************************************************************
bool getTDListCurrent ()
Gets the current TDList. Data placed into map parameter TdList.
Returns true if the operation is successful
*****************************************************************/
bool databaseConnection::getTDListCurrent(map<int, tdListEntry> &tdList, bool verbose_getTDList) {
boost::gregorian::date tournamentCascadeDate = boost::gregorian::date(boost::gregorian::max_date_time);
tdListEntry entry;
mysqlpp::Query query = db.query("SELECT CONCAT(players.name, ' ', players.last_name) AS name, x.pin_player, x.rating, x.sigma, x.elab_date FROM ratings x, players, (SELECT MAX(elab_date) AS maxdate, pin_player FROM ratings WHERE elab_date <= %0q GROUP BY pin_player) AS maxresults WHERE x.pin_player = maxresults.pin_player AND x.elab_date = maxresults.maxdate AND x.pin_player = players.pin_player AND x.pin_player != 0");
return databaseConnection::getTDList(tournamentCascadeDate, tdList, query, verbose_getTDList);
}
/****************************************************************
bool getTDListPrior ()
Gets the last valid TDList PRIOR to the date given by parameter
tournamentCascadeDate. Data placed into map parameter TdList.
Returns true if the operation is successful
*****************************************************************/
bool databaseConnection::getTDListPrior(boost::gregorian::date &tournamentCascadeDate, map<int, tdListEntry> &tdList, bool verbose_getTDList) {
tdListEntry entry;
mysqlpp::Query query = db.query("SELECT CONCAT(players.name, ' ', players.last_name) AS name, x.pin_player, x.rating, x.sigma, x.elab_date FROM ratings x, players, (SELECT MAX(elab_date) AS maxdate, pin_player FROM ratings WHERE elab_date < %0q GROUP BY pin_player) AS maxresults WHERE x.pin_player = maxresults.pin_player AND x.elab_date = maxresults.maxdate AND x.pin_player = players.pin_player AND x.pin_player != 0");
return databaseConnection::getTDList(tournamentCascadeDate, tdList, query, verbose_getTDList);
}
/****************************************************************
bool getPlayerList ()
Gets the last valid TDList prior to the date given by parameter
tournamentCascadeDate. Data placed into map parameter TdList.
Does NOT use "ratings" table;
Returns true if the operation is successful
*****************************************************************/
bool databaseConnection::getPlayerList(boost::gregorian::date &tournamentCascadeDate, map<int, tdListEntry> &tdList, bool verbose_getTDList) {
tdListEntry entry;
mysqlpp::Query query = db.query("SELECT CONCAT(players.name, ' ', players.last_name) AS name, players.pin_player, players.rating, players.sigma, players.elab_date FROM players WHERE players.rating IS NOT NULL AND players.sigma IS NOT NULL");
if (verbose_getTDList) {
cout << "databaseConnection::getPlayerList: " << query.str() << endl;
cout << endl;
}
query.parse();
mysqlpp::StoreQueryResult res = query.store();
if (!res)
return false;
for (size_t i=0; i<res.num_rows(); ++i) {
entry.id = res[i]["pin_player"];
entry.rating = res[i]["rating"];
entry.sigma = res[i]["sigma"];
entry.name = string(res[i]["name"]);
mysqlpp::Date tempDate = res[i]["elab_date"];
if (tempDate == mysqlpp::Date("0000-00-00")) {
entry.lastRatingDate = boost::gregorian::date(1900, 1, 1);
}
else {
entry.lastRatingDate = boost::gregorian::date(boost::gregorian::from_simple_string(tempDate.str()));
}
entry.ratingUpdated = false;
tdList[entry.id] = entry;
if (verbose_getTDList)
cout << res.num_rows() << ':' << i+1 << '\t' << entry.id << '\t' << entry.rating << '\t'
<< entry.sigma << '\t' << entry.name << endl;
}
return true;
}
/****************************************************************
bool getTournamentInfo (string &tournamentCode, collection &c)
Gets players and games from tournament indexed by parameters
tournamentCode, and place the information in parameter collection.
Returns true if operation is successful.
*****************************************************************/
bool databaseConnection::getTournamentInfo (string &tournamentCode, collection &c) {
player p;
game g;
stringstream ss(stringstream::in | stringstream::out);
int rankPartNumber;
char rankPartKyuDan;
std::string test;
mysqlpp::Query dateQuery = db.query("SELECT Tournament_Date, Tournament_Descr FROM tournaments WHERE tournament_code=%0q LIMIT 1");
dateQuery.parse();
mysqlpp::StoreQueryResult dateResult = dateQuery.store(tournamentCode);
mysqlpp::Date tempDate = dateResult[0]["Tournament_Date"];
if (tempDate == mysqlpp::Date("0000-00-00")) {
return false;
}
c.tournamentCode = tournamentCode;
dateResult[0]["Tournament_Descr"].to_string(c.tournamentName);
c.tournamentDate = boost::gregorian::date(boost::gregorian::from_simple_string(tempDate.str()));
cout << c.tournamentCode << '\t' << c.tournamentDate << '\t' << c.tournamentName << endl;
mysqlpp::Query gameQuery = db.query("SELECT pin_player_1, rank_1, color_1, pin_player_2, rank_2, color_2, handicap, komi, result FROM games WHERE Tournament_Code=%0q AND NOT (Online OR Exclude)");
gameQuery.parse();
mysqlpp::StoreQueryResult gameRes=gameQuery.store(tournamentCode);
for (size_t i=0; i<gameRes.num_rows(); i++) {
// Process and locally store the game information
if (string(gameRes[i]["color_1"]) == string("W")) {
g.white = gameRes[i]["pin_player_1"];
g.black = gameRes[i]["pin_player_2"];
}
else if (string(gameRes[i]["color_1"]) == string("B")) {
g.white = gameRes[i]["pin_player_2"];
g.black = gameRes[i]["pin_player_1"];
}
else {
cout << "Fatal error: unknown player colour " << gameRes[i]["color_1"] << endl;
exit (1);
}
if (string(gameRes[i]["result"]) == string("W")) {
g.whiteWins = true;
}
else if (string(gameRes[i]["result"]) == string("B")) {
g.whiteWins = false;
}
else {
cout << "Fatal error: unknown game result " << gameRes[i]["result"] << endl;
exit (1);
}
g.handicap = gameRes[i]["handicap"];
g.komi = gameRes[i]["komi"];
c.gameList.push_back(g);
// Process and locally store the player information
p.id = gameRes[i]["pin_player_1"];
if (c.playerHash.find(p.id) == c.playerHash.end()) {
ss.str(string(gameRes[i]["rank_1"]));
ss >> rankPartNumber >> rankPartKyuDan;
if ( (rankPartKyuDan == 'k') || (rankPartKyuDan == 'K') ) {
p.seed = -(rankPartNumber+0.5);
}
else if ( (rankPartKyuDan == 'd') || (rankPartKyuDan == 'd') ) {
p.seed = rankPartNumber+0.5;
}
else {
cout << "Fatal error: player " << gameRes[i]["pin_player_1"] << " unknown rank format: " << gameRes[i]["rank_1"] << endl;
exit(1);
}
c.playerHash[p.id] = p;
}
p.id = gameRes[i]["pin_player_2"];
if (c.playerHash.find(p.id) == c.playerHash.end()) {
ss.str(string(gameRes[i]["rank_2"]));
ss >> rankPartNumber >> rankPartKyuDan;
if ( (rankPartKyuDan == 'k') || (rankPartKyuDan == 'K') ) {
p.seed = -(rankPartNumber+0.5);
}
else if ( (rankPartKyuDan == 'd') || (rankPartKyuDan == 'd') ) {
p.seed = rankPartNumber+0.5;
}
else {
cout << "Fatal error: player " << gameRes[i]["pin_player_2"] << " unknown rank format: " << gameRes[i]["rank_2"] << endl;
exit(1);
}
c.playerHash[p.id] = p;
}
}
return true;
}
bool databaseConnection::updateAGAGD(collection &c, map<int, player>::iterator &playerIt, bool commit) {
// mysqlpp::Query query1 = db.query("INSERT INTO ratings (pin_player, rating, sigma, elab_date) VALUES (%0q, %1q, %2q, %3q) ON DUPLICATE KEY UPDATE rating=%4q, sigma=%5q");
mysqlpp::Query query1 = db.query("INSERT INTO ratings (pin_player, rating, sigma, elab_date, tournament_code) VALUES (%0q, %1q, %2q, %3q, %4q) ON DUPLICATE KEY UPDATE rating=%5q, sigma=%6q, tournament_code=%7q");
query1.parse();
if (showagagd) {
cout << "updateAGAGD: " << query1.str(playerIt->second.id, playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate), c.tournamentCode, playerIt->second.rating, playerIt->second.sigma, c.tournamentCode) << ";" << endl;
}
if (commit) {
query1.execute(playerIt->second.id, playerIt->second.rating,
playerIt->second.sigma, to_iso_extended_string(c.tournamentDate),
c.tournamentCode, playerIt->second.rating, playerIt->second.sigma,
c.tournamentCode);
if (query1.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query1.error() <<endl;
return false;
}
}
mysqlpp::Query query2 = db.query("UPDATE players SET rating=%0q, sigma=%1q, elab_date=%2q, Last_Appearance=%3q WHERE pin_player=%4q");
query2.parse();
if (showagagd) {
cout << "updateAGAGD: " << query2.str(playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate), c.tournamentCode, playerIt->second.id) << ";" << endl;
}
if (commit) { // and not onlyone) { // XXX
query2.execute(playerIt->second.rating, playerIt->second.sigma,
to_iso_extended_string(c.tournamentDate), c.tournamentCode, playerIt->second.id);
if (query2.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query2.error() <<endl;
return false;
}
}
return true;
}
bool databaseConnection::updateRatings(collection &c, map<int, player>::iterator &playerIt, bool commit) {
mysqlpp::Query query5 = ratingsdb.query("INSERT INTO ratings (ID, Rating, Sigma, Date) VALUES (%0q, %1q, %2q, UNIX_TIMESTAMP(%3q)) ON DUPLICATE KEY UPDATE rating=%4q, sigma=%5q, date=UNIX_TIMESTAMP(%6q)");
query5.parse();
if (showratingsdb) {
cout << "updateRatings: " << query5.str(playerIt->second.id, playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate), playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate)) << ";" << endl;
}
if (commit) {
query5.execute(playerIt->second.id, playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate),
playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate));
if (query5.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query5.error() << endl;
return false;
}
}
return true;
}
bool databaseConnection::updateMembers(collection &c, map<int, player>::iterator &playerIt, bool commit) {
/*
mysqlpp::Query query5 = membersdb.query("INSERT INTO ratings (ID, Rating, Sigma, Date) VALUES (%0q, %1q, %2q, UNIX_TIMESTAMP(%3q)) ON DUPLICATE KEY UPDATE rating=%4q, sigma=%5q, date=UNIX_TIMESTAMP(%6q)");
*/
mysqlpp::Query query5 = membersdb.query("UPDATE ratings SET rating=%0q, sigma=%1q, date=UNIX_TIMESTAMP(%2q) WHERE ID=%3q");
query5.parse();
if (showmembersdb) {
/*
cout << "updateMembers: " << query5.str(playerIt->second.id, playerIt->second.rating, playerIt->second.sigma,
to_iso_extended_string(c.tournamentDate), playerIt->second.rating,
playerIt->second.sigma, to_iso_extended_string(c.tournamentDate)) << endl;
*/
cout << "updateMembers: " << query5.str(playerIt->second.rating, playerIt->second.sigma, to_iso_extended_string(c.tournamentDate), playerIt->second.id) << ";" << endl;
}
if (commit) { // and not onlyone) { // XXX
/*
query5.execute(playerIt->second.id, playerIt->second.rating, playerIt->second.sigma,
to_iso_extended_string(c.tournamentDate), playerIt->second.rating,
playerIt->second.sigma, to_iso_extended_string(c.tournamentDate));
*/
query5.execute(playerIt->second.rating, playerIt->second.sigma,
to_iso_extended_string(c.tournamentDate), playerIt->second.id);
if (query5.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query5.error() << endl;
return false;
}
}
return true;
}
/****************************************************************
void syncNewRatings (collection &c)
Pushes new ratings onto the various ratings databases and updates
appropriate indexes.
*****************************************************************/
void databaseConnection::syncNewRatings (collection &c, bool commit) {
map<int, player>::iterator playerIt = c.playerHash.begin();
mysqlpp::Transaction trans_agagd(db);
mysqlpp::Transaction trans_ratings(ratingsdb);
mysqlpp::Transaction trans_members(membersdb);
for (playerIt = c.playerHash.begin(); playerIt != c.playerHash.end(); playerIt++) {
cout << "Updating records for ID: " << playerIt->second.id << endl;
if ( updateAGAGD(c, playerIt, commit) == false ) { // commit or &commit ?
trans_agagd.rollback();
exit(1);
}
if ( updateRatings(c, playerIt, commit) == false ) { // commit or &commit ?
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
if ( updateMembers(c, playerIt, commit) == false ) { // commit or &commit ?
trans_members.rollback();
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
if (showagagd or showratingsdb or showmembersdb)
cout << endl;
}
// Finish updating AGAGD
mysqlpp::Query query2 = db.query("UPDATE games SET elab_date = %0q, Rated = 1 WHERE tournament_code=%1q AND Online=0");
query2.parse();
// Update the elab_dates for tournaments
mysqlpp::Query tournaments_query = db.query("UPDATE tournaments SET elab_date = %0q, Status = 1 WHERE tournament_code=%1q");
tournaments_query.parse();
if (showagagd) {
cout << "syncNewRatings: AGAGD Games: " << query2.str(to_iso_extended_string(c.tournamentDate), c.tournamentCode) << ";" << endl;
cout << "syncNewRatings: AGAGD Tournaments: " << tournaments_query.str(to_iso_extended_string(c.tournamentDate), c.tournamentCode) << ";" << endl;
}
if (commit) {
query2.execute(to_iso_extended_string(c.tournamentDate), c.tournamentCode);
if (query2.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query2.error() << endl;
trans_agagd.rollback();
exit(1);
}
tournaments_query.execute(to_iso_extended_string(c.tournamentDate), c.tournamentCode);
if (tournaments_query.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< tournaments_query.error() << endl;
trans_agagd.rollback();
exit(1);
}
}
cout << endl;
// Finish updating Ratings
tm d_tm = to_tm(c.tournamentDate);
mysqlpp::Query query6 = ratingsdb.query("INSERT INTO ratings_tourneys (Year, Month, Day, Label) VALUES (%0q, %1q, %2q, %3q)");
query6.parse();
if (showratingsdb) {
cout << "syncNewRatings: Ratings DB: " << query6.str(1900+d_tm.tm_year, 1+d_tm.tm_mon, d_tm.tm_mday, c.tournamentName) << ";" << endl;
}
if (commit) {
query6.execute(1900+d_tm.tm_year, 1+d_tm.tm_mon, d_tm.tm_mday, c.tournamentName);
if (query6.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query6.error() << endl;
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
}
mysqlpp::Query query7 = ratingsdb.query("INSERT INTO ratings_log (Name, User, Date, Seq, Extra) VALUES ('RatingsUpdate', 0, NOW(), 0, 'Bayrate Update')");
query7.parse();
if (showratingsdb) {
cout << "syncNewRatings: Ratings DB: " << query7.str() << ";" << endl;
}
if (commit) {
query7.execute();
if (query7.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query7.error() << endl;
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
}
cout << endl;
// Finish updating Members
mysqlpp::Query query6a = membersdb.query("INSERT INTO ratings_tourneys (Year, Month, Day, Label) VALUES (%0q, %1q, %2q, %3q)");
query6a.parse();
if (showmembersdb) {
cout << "syncNewRatings: Members DB: " << query6.str(1900+d_tm.tm_year, 1+d_tm.tm_mon, d_tm.tm_mday, c.tournamentName) << ";" << endl;
}
if (commit) {
query6a.execute(1900+d_tm.tm_year, 1+d_tm.tm_mon, d_tm.tm_mday, c.tournamentName);
if (query6a.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query6a.error() << endl;
trans_members.rollback();
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
}
mysqlpp::Query query7a = membersdb.query("INSERT INTO ratings_log (Name, User, Date, Seq, Extra) VALUES ('RatingsUpdate', 0, NOW(), 0, 'Bayrate Update')");
query7a.parse();
if (showmembersdb) {
cout << "syncNewRatings: Members DB: " << query7.str() << ";" << endl;
}
if (commit) {
query7a.execute();
if (query7a.errnum() != 0) {
cerr << "Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< query7a.error() << endl;
trans_members.rollback();
trans_ratings.rollback();
trans_agagd.rollback();
exit(1);
}
}
cout << endl;
trans_members.commit();
trans_ratings.commit();
trans_agagd.commit();
return;
}
/****************************************************************
void syncDBs (map<int, tdListEntry> &tdList)
Pushes new ratings onto the various ratings databases and updates
appropriate indexes.
*****************************************************************/
void databaseConnection::syncDBs (map<int, tdListEntry> &tdList, bool commit) {
bool show = false;
mysqlpp::Query agagdquery = db.query("SELECT rating, sigma, Elab_Date AS date FROM players WHERE Pin_Player = %0q");
agagdquery.parse();
mysqlpp::Query ratingsdbquery = ratingsdb.query("SELECT rating, sigma, FROM_UNIXTIME(date, '%Y-%m-%d') AS date FROM ratings WHERE ID = %0q");
ratingsdbquery.parse();
mysqlpp::Query membersdbquery = membersdb.query("SELECT rating, sigma, FROM_UNIXTIME(date, '%Y-%m-%d') AS date FROM ratings WHERE ID = %0q");
membersdbquery.parse();
mysqlpp::Query update = db.query("UPDATE players SET rating = %0q, sigma = %1q, Elab_Date = %2q WHERE Pin_Player = %3q");
update.parse();
for (map<int, tdListEntry>::iterator tdListIt = tdList.begin(); tdListIt != tdList.end(); tdListIt++) {
// Get data from the AGAGD
mysqlpp::StoreQueryResult agagd_res = agagdquery.store(tdListIt->second.id);
if (!agagd_res) {
cerr << "mysqlpp::StoreQueryResult() failed: " << agagdquery.errnum()
<< " : " << agagdquery.error() << endl;
exit(-1);
}
double agagd_rating = 0;
if (strcmp((const char*)agagd_res[0]["rating"], "NULL") == 0)
agagd_rating = 0;
else
agagd_rating = agagd_res[0]["rating"];
double agagd_sigma = 0;
if (strcmp((const char*)agagd_res[0]["sigma"], "NULL") == 0)
agagd_sigma = 0;
else
agagd_sigma = agagd_res[0]["sigma"];
// string agagd_date = agagd_res[0]["date"];
// Get data from the ratings database
mysqlpp::StoreQueryResult ratings_res = ratingsdbquery.store(tdListIt->second.id);
if (!ratings_res) {
cerr << "mysqlpp::StoreQueryResult() failed: " << ratingsdbquery.errnum()
<< " : " << ratingsdbquery.error() << endl;
exit(-1);
}
double ratings_rating = ratings_res[0]["rating"];
double ratings_sigma = ratings_res[0]["sigma"];
// string ratings_date = ratings_res[0]["date"]; Grrr....const_reference splat!#$*(!
if (ratings_rating == 0 or ratings_sigma == 0)
continue;
// Get data from the members database
mysqlpp::StoreQueryResult members_res = membersdbquery.store(tdListIt->second.id);
if (!members_res) {
cerr << "mysqlpp::StoreQueryResult() failed: " << membersdbquery.errnum()
<< " : " << membersdbquery.error() <<endl;
exit(-1);
}
double members_rating = members_res[0]["rating"];
double members_sigma = members_res[0]["sigma"];
mysqlpp::Date md = members_res[0]["date"];
string members_date = md.str();
if (ratings_rating != members_rating or ratings_sigma != members_sigma or ratings_res[0]["date"] != members_res[0]["date"]) {
cout << "Update Members to match Ratings: " << tdListIt->second.id
<< "\tratings_date: " << ratings_res[0]["date"] << "\tmembers_date: " << members_res[0]["date"] << endl;
exit(-1);
}
// value obtained by iteration. this value prevents certain ineffective database updates
// SIGMA: precision: 1e-05, difference: 1e-05
// Update AGAGD to match Ratings: 6
// 6 r: 5.009620 r:0.391880 2007-07-01 m: 5.009620 m:0.391880 5.009620 0.391870
// AGAGD: UPDATE players SET rating = 5.00962, sigma = 0.39188000000000001, Elab_Date = '2007-07-01' WHERE Pin_Player = 6
double precision = 0.000010000000001;
// #ifdef REPORT_PRECISION
if ( (fabs(ratings_rating) - fabs(agagd_rating)) > precision )
cout << setprecision(10) << "RATING: precision: " << precision << ", difference: "
<< (fabs(ratings_rating) - fabs(agagd_rating)) << endl;
if ( (fabs(ratings_sigma) - fabs(agagd_sigma)) > precision )
cout << setprecision(10) << "SIGMA: precision: " << precision << ", difference: "
<< (fabs(ratings_sigma) - fabs(agagd_sigma)) << endl;
// #endif
if ( (fabs(ratings_rating) - fabs(agagd_rating)) > precision or
(fabs(ratings_sigma) - fabs(agagd_sigma)) > precision) {
cout << "Update AGAGD to match Ratings: " << tdListIt->second.id << endl;
cout << fixed << setprecision(6) << tdListIt->second.id
<< "\tr:" << setw(10) << ratings_rating << "\tr:" << ratings_sigma << '\t' << members_date << '\t'
<< "\tm:" << setw(10) << members_rating << "\tm:" << members_sigma << '\t'
<< setw(10) << agagd_rating << '\t' << agagd_sigma << endl;
cout << "AGAGD: " << update.str(ratings_rating, ratings_sigma, ratings_res[0]["date"], tdListIt->second.id) << endl;
cout << endl;
show = false;
cout << "commit: " << commit << endl;
if (commit) {
mysqlpp::Transaction trans_update(db);
// update.execute(ratings_rating, ratings_sigma, ratings_res[0]["date"], tdListIt->second.id);
update.execute(ratings_rating, ratings_sigma, ratings_res[0]["date"], tdListIt->second.id);
if (update.errnum() != 0) {
cerr << "update Query failure in db.cpp. Rolling back transaction and exiting program due to: "
<< update.error() << endl;
trans_update.rollback();
exit(1);
}
trans_update.commit();
}
// cerr << update.error() << endl;
// exit(0);
}
// if (tdListIt->second.id > 1620)
// break;
}
}
| 38.975787 | 424 | 0.654283 | [
"vector"
] |
b440958427e23b8e68e38d7f94f58a831cd373db | 418 | hpp | C++ | src/parser/cpp/headers/formatter.hpp | cgabriel5/nodecliac | 221e0dc88f7a3174f7426037d0d08b4f98a7af0e | [
"MIT"
] | 5 | 2020-01-22T23:15:46.000Z | 2020-05-22T04:33:00.000Z | src/parser/cpp/headers/formatter.hpp | cgabriel5/nodecliac | 221e0dc88f7a3174f7426037d0d08b4f98a7af0e | [
"MIT"
] | 4 | 2020-04-13T00:00:21.000Z | 2022-02-14T04:42:25.000Z | src/parser/cpp/headers/formatter.hpp | cgabriel5/nodecliac | 221e0dc88f7a3174f7426037d0d08b4f98a7af0e | [
"MIT"
] | null | null | null | #ifndef FORMATTER_HPP
#define FORMATTER_HPP
#include "./structs.hpp"
#include <tuple>
#include <string>
#include <vector>
#include <map>
using namespace std;
tuple <string, string, string, string, string, string, map<string, string>, string>
formatter(StateParse &S,
vector<vector<Token>> &BRANCHES,
vector<vector<vector<int>>> &cchains,
map<int, vector<Flag>> &flags,
vector<vector<int>> &settings);
#endif
| 19.904762 | 83 | 0.727273 | [
"vector"
] |
b44413a69fe34df06ac10219c705f7b00acd6e0a | 5,685 | hxx | C++ | Modules/IO/TransformBase/include/itkTransformFileWriter.hxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 3 | 2019-11-19T09:47:25.000Z | 2022-02-24T00:32:31.000Z | Modules/IO/TransformBase/include/itkTransformFileWriter.hxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 1 | 2019-03-18T14:19:49.000Z | 2020-01-11T13:54:33.000Z | Modules/IO/TransformBase/include/itkTransformFileWriter.hxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 1 | 2022-02-24T00:32:36.000Z | 2022-02-24T00:32:36.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkTransformFileWriter_hxx
#define itkTransformFileWriter_hxx
#include "itkTransformFileWriter.h"
#include "itkTransformFactoryBase.h"
#include "itkTransformIOFactory.h"
#include "itkCompositeTransformIOHelper.h"
namespace itk
{
template<typename TParametersValueType>
TransformFileWriterTemplate<TParametersValueType>
::TransformFileWriterTemplate() :
m_FileName(""),
m_AppendMode(false)
{
TransformFactoryBase::RegisterDefaultTransforms();
}
template<typename TParametersValueType>
TransformFileWriterTemplate<TParametersValueType>
::~TransformFileWriterTemplate()
{
}
/** Set the writer to append to the specified file */
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::SetAppendOn()
{
this->SetAppendMode(true);
}
/** Set the writer to overwrite the specified file - This is the
* default mode. */
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::SetAppendOff()
{
this->SetAppendMode(false);
}
/** Set the writer mode (append/overwrite). */
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::SetAppendMode(bool mode)
{
this->m_AppendMode = mode;
}
/** Get the writer mode. */
template<typename TParametersValueType>
bool TransformFileWriterTemplate<TParametersValueType>
::GetAppendMode()
{
return ( this->m_AppendMode );
}
template<>
void
TransformFileWriterTemplate<double>
::PushBackTransformList(const Object *transObj);
template<>
void
TransformFileWriterTemplate<float>
::PushBackTransformList(const Object *transObj);
/** Set the input transform and reinitialize the list of transforms */
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::SetInput(const Object *transform)
{
m_TransformList.clear();
this->PushBackTransformList(transform);
}
template<typename TParametersValueType>
const typename TransformFileWriterTemplate<TParametersValueType>::TransformType *
TransformFileWriterTemplate<TParametersValueType>
::GetInput()
{
ConstTransformPointer res = *(m_TransformList.begin());
return res.GetPointer();
}
/** Add a transform to be written */
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::AddTransform(const Object *transform)
{
/* Check for a CompositeTransform.
* The convention is that there should be one, and it should
* be the first transform in the file
*/
const std::string transformName = transform->GetNameOfClass();
if( transformName.find("CompositeTransform") != std::string::npos )
{
if(this->m_TransformList.size() > 0)
{
itkExceptionMacro("Can only write a transform of type CompositeTransform "
"as the first transform in the file.");
}
}
this->PushBackTransformList(transform);
}
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::Update()
{
if ( m_FileName == "" )
{
itkExceptionMacro ("No file name given");
}
if( m_TransformIO.IsNull() )
{
typedef TransformIOFactoryTemplate<TParametersValueType> TransformFactoryIOType;
m_TransformIO = TransformFactoryIOType::CreateTransformIO( m_FileName.c_str(), WriteMode );
if ( m_TransformIO.IsNull() )
{
std::ostringstream msg;
msg << "Could not create Transform IO object for writing file " << this->GetFileName() << std::endl;
std::list< LightObject::Pointer > allobjects = ObjectFactoryBase::CreateAllInstance("itkTransformIOBaseTemplate");
if (allobjects.size() > 0)
{
msg << " Tried to create one of the following:" << std::endl;
for ( std::list< LightObject::Pointer >::iterator i = allobjects.begin();
i != allobjects.end(); ++i )
{
const Object *obj = dynamic_cast<Object*>(i->GetPointer());
msg << " " << obj->GetNameOfClass() << std::endl;
}
msg << " You probably failed to set a file suffix, or" << std::endl;
msg << " set the suffix to an unsupported type." << std::endl;
}
else
{
msg << " There are no registered Transform IO factories." << std::endl;
msg << " Please visit https://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem." << std::endl;
}
itkExceptionMacro( << msg.str().c_str() );
}
}
m_TransformIO->SetAppendMode(this->m_AppendMode);
m_TransformIO->SetFileName(this->m_FileName);
m_TransformIO->SetTransformList(this->m_TransformList);
m_TransformIO->Write();
}
template<typename TParametersValueType>
void TransformFileWriterTemplate<TParametersValueType>
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "FileName: " << m_FileName << std::endl;
}
} // namespace itk
#endif
| 30.079365 | 122 | 0.704134 | [
"object",
"transform"
] |
b4470ea0faf739626f7e17eb66942a4a569377e8 | 1,427 | hpp | C++ | src/lib/scheduler/operator_task.hpp | mrks-test/hyrise | 71480199f504cf9cffc86582cdac68dbb2ea4952 | [
"MIT"
] | null | null | null | src/lib/scheduler/operator_task.hpp | mrks-test/hyrise | 71480199f504cf9cffc86582cdac68dbb2ea4952 | [
"MIT"
] | null | null | null | src/lib/scheduler/operator_task.hpp | mrks-test/hyrise | 71480199f504cf9cffc86582cdac68dbb2ea4952 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <unordered_map>
#include <vector>
#include "scheduler/abstract_task.hpp"
namespace opossum {
class AbstractOperator;
/**
* Makes an AbstractOperator scheduleable
*/
class OperatorTask : public AbstractTask {
public:
// We don't like abbreviations, but "operator" is a keyword
OperatorTask(std::shared_ptr<AbstractOperator> op, SchedulePriority priority = SchedulePriority::Default,
bool stealable = true);
/**
* Create tasks recursively from result operator and set task dependencies automatically.
*/
static std::vector<std::shared_ptr<AbstractTask>> make_tasks_from_operator(
const std::shared_ptr<AbstractOperator>& op);
const std::shared_ptr<AbstractOperator>& get_operator() const;
std::string description() const override;
protected:
void _on_execute() override;
/**
* Create tasks recursively. Called by `make_tasks_from_operator`. Returns the root of the subtree that was added.
* @param task_by_op Cache to avoid creating duplicate Tasks for diamond shapes
*/
static std::shared_ptr<AbstractTask> _add_tasks_from_operator(
const std::shared_ptr<AbstractOperator>& op, std::vector<std::shared_ptr<AbstractTask>>& tasks,
std::unordered_map<std::shared_ptr<AbstractOperator>, std::shared_ptr<AbstractTask>>& task_by_op);
private:
std::shared_ptr<AbstractOperator> _op;
};
} // namespace opossum
| 30.361702 | 116 | 0.746321 | [
"vector"
] |
b4477a4bb88eced29abe5c0393f4c09f9da2cb8f | 10,175 | cc | C++ | src/developer/forensics/feedback_data/tests/inspect_data_budget_unittest.cc | dahliaOS/fuchsia-pi4 | 5b534fccefd918b5f03205393c1fe5fddf8031d0 | [
"BSD-2-Clause"
] | 3 | 2021-09-02T07:21:06.000Z | 2022-03-12T03:20:10.000Z | src/developer/forensics/feedback_data/tests/inspect_data_budget_unittest.cc | dahliaOS/fuchsia-pi4 | 5b534fccefd918b5f03205393c1fe5fddf8031d0 | [
"BSD-2-Clause"
] | null | null | null | src/developer/forensics/feedback_data/tests/inspect_data_budget_unittest.cc | dahliaOS/fuchsia-pi4 | 5b534fccefd918b5f03205393c1fe5fddf8031d0 | [
"BSD-2-Clause"
] | 2 | 2022-02-25T12:22:49.000Z | 2022-03-12T03:20:10.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/forensics/feedback_data/inspect_data_budget.h"
#include <algorithm>
#include <optional>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/developer/forensics/testing/stubs/cobalt_logger_factory.h"
#include "src/developer/forensics/testing/unit_test_fixture.h"
#include "src/developer/forensics/utils/cobalt/logger.h"
#include "src/developer/forensics/utils/cobalt/metrics.h"
#include "src/lib/files/file.h"
#include "src/lib/files/path.h"
#include "src/lib/files/scoped_temp_dir.h"
namespace forensics {
namespace feedback_data {
namespace {
constexpr size_t kKilobytes = 1024u;
constexpr size_t kMegabytes = 1048576u;
constexpr size_t kGigabytes = 1073741824u;
using inspect::testing::ChildrenMatch;
using inspect::testing::NameMatches;
using inspect::testing::NodeMatches;
using inspect::testing::PropertyList;
using inspect::testing::StringIs;
using inspect::testing::UintArrayIs;
using inspect::testing::UintIs;
using testing::AllOf;
using testing::IsEmpty;
using testing::UnorderedElementsAre;
using testing::UnorderedElementsAreArray;
class InspectDataBudgetTest : public UnitTestFixture {
public:
void SetUp() override {
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>());
cobalt_ = std::make_unique<cobalt::Logger>(dispatcher(), services());
}
void MakeUnlimitedBudget() {
inspect_node_manager_ = std::make_unique<InspectNodeManager>(&InspectRoot());
inspect_data_budget_ = std::make_unique<InspectDataBudget>(
"non-existent_path", inspect_node_manager_.get(), cobalt_.get());
}
void MakeLimitedBudget() {
inspect_node_manager_ = std::make_unique<InspectNodeManager>(&InspectRoot());
std::string limit_data_flag_path = files::JoinPath(tmp_dir_.path(), "limit_inspect_data");
files::WriteFile(limit_data_flag_path, " ");
inspect_data_budget_ = std::make_unique<InspectDataBudget>(
limit_data_flag_path.c_str(), inspect_node_manager_.get(), cobalt_.get());
}
void CalcBudget(size_t zip_file_bytes) {
std::map<std::string, ArchiveFileStats> file_size_stats;
// The Inspect file must exists or else the inspect budget is disabled.
file_size_stats["inspect.json"] = {0, 0};
file_size_stats["other"] = {0, zip_file_bytes};
inspect_data_budget_->UpdateBudget(file_size_stats);
}
void CalcBudget(const std::map<std::string, ArchiveFileStats>& file_size_stats) {
inspect_data_budget_->UpdateBudget(file_size_stats);
}
std::optional<size_t> GetSizeInBytes() { return inspect_data_budget_->SizeInBytes(); }
private:
std::unique_ptr<InspectNodeManager> inspect_node_manager_;
files::ScopedTempDir tmp_dir_;
std::unique_ptr<InspectDataBudget> inspect_data_budget_;
std::unique_ptr<cobalt::Logger> cobalt_;
};
TEST_F(InspectDataBudgetTest, TestUnlimitedBudget) {
MakeUnlimitedBudget();
ASSERT_FALSE(GetSizeInBytes());
// setting a budget should not do anything.
CalcBudget(1 * kMegabytes);
ASSERT_FALSE(GetSizeInBytes());
}
TEST_F(InspectDataBudgetTest, TestLimitedBudget) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
}
TEST_F(InspectDataBudgetTest, TestForCrash_MissingSizeStats) {
MakeLimitedBudget();
std::map<std::string, ArchiveFileStats> file_size_stats;
CalcBudget(file_size_stats);
}
TEST_F(InspectDataBudgetTest, TestSizeBudget_Maintain) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
size_t initial_budget = GetSizeInBytes().value();
CalcBudget(2 * kMegabytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), initial_budget);
}
TEST_F(InspectDataBudgetTest, TestSizeBudget_UpperLimit) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
size_t initial_budget = GetSizeInBytes().value();
CalcBudget(724 * kKilobytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), initial_budget);
}
TEST_F(InspectDataBudgetTest, TestSizeBudget_LowerLimit) {
// Arrive at the lower limit by making the zip size 2 GB twice (this should reduce the initial
// budget at most by 2^16 times).
MakeLimitedBudget();
CalcBudget(2 * kGigabytes);
CalcBudget(2 * kGigabytes);
ASSERT_TRUE(GetSizeInBytes());
size_t lower_limit = GetSizeInBytes().value();
CalcBudget(kGigabytes);
ASSERT_TRUE(GetSizeInBytes());
size_t new_budget = GetSizeInBytes().value();
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(lower_limit, new_budget);
}
TEST_F(InspectDataBudgetTest, TestSizeBudget_Reduce_Increase) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
size_t initial_budget = GetSizeInBytes().value();
size_t budget = (initial_budget * 1024) / 1500;
CalcBudget(3000 * kKilobytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), budget);
// Note: Make sure that the geometric mean of the last zip size and the new zip size > 2MB.
// Otherwise the resulting budget might be lower than our calculated value due to upper limit
// restrictions.
budget = (budget * 1024) / 800;
CalcBudget(1600 * kKilobytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), budget);
}
TEST_F(InspectDataBudgetTest, TestInspectBudget_BudgetDisabled) {
MakeUnlimitedBudget();
const auto node = AllOf(
NodeMatches(AllOf(NameMatches("inspect_budget"), PropertyList(UnorderedElementsAreArray({
StringIs("is_budget_enabled", "false"),
})))),
ChildrenMatch(IsEmpty()));
EXPECT_THAT(InspectTree(), ChildrenMatch(UnorderedElementsAre(AllOf(node))));
}
TEST_F(InspectDataBudgetTest, TestInspectBudget_BudgetEnabled) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
size_t initial_budget = GetSizeInBytes().value();
CalcBudget(1 * kMegabytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), initial_budget);
const auto budget =
AllOf(NodeMatches(AllOf(NameMatches("last_ten_input_budget_previous_snapshot_size_bytes"),
PropertyList(UnorderedElementsAreArray({
UintArrayIs("0", std::vector<uint64_t>{20971520u, 1048576u}),
})))),
ChildrenMatch(IsEmpty()));
const auto node = AllOf(NodeMatches(AllOf(NameMatches("inspect_budget"),
PropertyList(UnorderedElementsAreArray({
UintIs("min_input_budget_bytes", 4194304u),
UintIs("max_input_budget_bytes", 20971520u),
UintIs("target_snapshot_size_bytes", 2097152u),
StringIs("is_budget_enabled", "true"),
})))),
ChildrenMatch(UnorderedElementsAre(budget)));
EXPECT_THAT(InspectTree(), ChildrenMatch(UnorderedElementsAre(AllOf(node))));
}
TEST_F(InspectDataBudgetTest, TestInspectBudget_MaxEntries) {
MakeLimitedBudget();
// zip_size = min(floor(budget * 0.2), 3MB) + 512KB
for (int i = 0; i < 12; i++) {
const size_t budget = GetSizeInBytes().value();
const float compression_ratio = 0.2;
const size_t zip_size =
std::min<size_t>(std::floor(budget * compression_ratio), 3 * kMegabytes) + 512 * kKilobytes;
CalcBudget(zip_size);
}
const auto budget =
AllOf(NodeMatches(AllOf(NameMatches("last_ten_input_budget_previous_snapshot_size_bytes"),
PropertyList(UnorderedElementsAreArray({
UintArrayIs("2", std::vector<uint64_t>{8036989u, 2245028u}),
UintArrayIs("3", std::vector<uint64_t>{7906790u, 2131685u}),
UintArrayIs("4", std::vector<uint64_t>{7874894u, 2105646u}),
UintArrayIs("5", std::vector<uint64_t>{7866963u, 2099266u}),
UintArrayIs("6", std::vector<uint64_t>{7864982u, 2097680u}),
UintArrayIs("7", std::vector<uint64_t>{7864486u, 2097284u}),
UintArrayIs("8", std::vector<uint64_t>{7864362u, 2097185u}),
UintArrayIs("9", std::vector<uint64_t>{7864331u, 2097160u}),
UintArrayIs("10", std::vector<uint64_t>{7864323u, 2097154u}),
UintArrayIs("11", std::vector<uint64_t>{7864323u, 2097152u}),
})))),
ChildrenMatch(IsEmpty()));
const auto node = AllOf(NodeMatches(AllOf(NameMatches("inspect_budget"),
PropertyList(UnorderedElementsAreArray({
UintIs("min_input_budget_bytes", 4194304u),
UintIs("max_input_budget_bytes", 20971520u),
UintIs("target_snapshot_size_bytes", 2097152u),
StringIs("is_budget_enabled", "true"),
})))),
ChildrenMatch(UnorderedElementsAre(budget)));
EXPECT_THAT(InspectTree(), ChildrenMatch(UnorderedElementsAre(AllOf(node))));
}
TEST_F(InspectDataBudgetTest, TestCobalt_BudgetEnabled) {
MakeLimitedBudget();
ASSERT_TRUE(GetSizeInBytes());
size_t initial_budget = GetSizeInBytes().value();
CalcBudget(1 * kMegabytes);
ASSERT_TRUE(GetSizeInBytes());
ASSERT_EQ(GetSizeInBytes().value(), initial_budget);
RunLoopUntilIdle();
EXPECT_THAT(ReceivedCobaltEvents(),
UnorderedElementsAreArray({
cobalt::Event(cobalt::EventType::kMultidimensionalEvent,
cobalt::kInspectBudgetMetricId, {}, 20971520),
}));
}
} // namespace
} // namespace feedback_data
} // namespace forensics
| 38.396226 | 100 | 0.661032 | [
"vector"
] |
b44dabb4bce96eed6d19c9b61339fb1b24ea4d4c | 7,560 | cpp | C++ | library/src/blas1/rocblas_dot.cpp | ntrost57/rocBLAS | a03ecf96be5bfdd11945bc409c92bab593eef899 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_dot.cpp | ntrost57/rocBLAS | a03ecf96be5bfdd11945bc409c92bab593eef899 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_dot.cpp | ntrost57/rocBLAS | a03ecf96be5bfdd11945bc409c92bab593eef899 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2016 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include <hip/hip_runtime.h>
#include "rocblas.h"
#include "status.h"
#include "definitions.h"
#include "reduction.h"
#include "rocblas_unique_ptr.hpp"
#include "handle.h"
#include "logging.h"
#include "utility.h"
namespace {
// HIP support up to 1024 threads/work itemes per thread block/work group
// setting to 256
constexpr int NB = 256;
template <typename T>
__global__ void dot_kernel_part1(
rocblas_int n, const T* x, rocblas_int incx, const T* y, rocblas_int incy, T* workspace)
{
ssize_t tx = hipThreadIdx_x;
ssize_t tid = hipBlockIdx_x * hipBlockDim_x + tx;
T sum = 0;
for(rocblas_int i = tid; i < n; i += hipGridDim_x * hipBlockDim_x)
{
sum += y[i * incy] * x[i * incx];
}
__shared__ T tmp[NB];
tmp[tx] = sum;
rocblas_sum_reduce<NB>(tx, tmp);
if(tx == 0)
workspace[hipBlockIdx_x] = tmp[0];
}
// assume workspace has already been allocated, recommened for repeated calling of dot product
// routine
template <typename T>
rocblas_status rocblas_dot_workspace(rocblas_handle __restrict__ handle,
rocblas_int n,
const T* x,
rocblas_int incx,
const T* y,
rocblas_int incy,
T* result,
T* workspace)
{
// At least two kernels are needed to finish the reduction
// kernel 1 write partial result per thread block in workspace, number of partial result is NB
// kernel 2 gather all the partial result in workspace and finish the final reduction. number of
// threads (NB) loop blocks
dim3 grid(NB);
dim3 threads(NB);
if(incx < 0)
x -= ssize_t(incx) * (n - 1);
if(incy < 0)
y -= ssize_t(incy) * (n - 1);
hipLaunchKernelGGL(
dot_kernel_part1, grid, threads, 0, handle->rocblas_stream, n, x, incx, y, incy, workspace);
hipLaunchKernelGGL((rocblas_reduction_kernel_part2<NB>),
1,
threads,
0,
handle->rocblas_stream,
NB,
workspace,
handle->pointer_mode != rocblas_pointer_mode_device ? workspace : result);
if(handle->pointer_mode != rocblas_pointer_mode_device)
RETURN_IF_HIP_ERROR(hipMemcpy(result, workspace, sizeof(*result), hipMemcpyDeviceToHost));
return rocblas_status_success;
}
template <typename>
constexpr char rocblas_dot_name[] = "unknown";
template <>
constexpr char rocblas_dot_name<float>[] = "rocblas_sdot";
template <>
constexpr char rocblas_dot_name<double>[] = "rocblas_ddot";
template <>
constexpr char rocblas_dot_name<rocblas_float_complex>[] = "rocblas_cdot";
template <>
constexpr char rocblas_dot_name<rocblas_double_complex>[] = "rocblas_zdot";
/* ============================================================================================ */
/*! \brief BLAS Level 1 API
\details
dot(u) perform dot product of vector x and y
result = x * y;
dotc perform dot product of complex vector x and complex y
result = conjugate (x) * y;
@param[in]
handle rocblas_handle.
handle to the rocblas library context queue.
@param[in]
n rocblas_int.
@param[in]
x pointer storing vector x on the GPU.
@param[in]
incx rocblas_int
specifies the increment for the elements of y.
@param[inout]
result
store the dot product. either on the host CPU or device GPU.
return is 0 if n <= 0.
********************************************************************/
// allocate workspace inside this API
template <typename T>
rocblas_status rocblas_dot(rocblas_handle handle,
rocblas_int n,
const T* x,
rocblas_int incx,
const T* y,
rocblas_int incy,
T* result)
{
if(!handle)
return rocblas_status_invalid_handle;
auto layer_mode = handle->layer_mode;
if(layer_mode & rocblas_layer_mode_log_trace)
log_trace(handle, rocblas_dot_name<T>, n, x, incx, y, incy);
if(layer_mode & rocblas_layer_mode_log_bench)
log_bench(handle,
"./rocblas-bench -f dot -r",
rocblas_precision_string<T>,
"-n",
n,
"--incx",
incx,
"--incy",
incy);
if(layer_mode & rocblas_layer_mode_log_profile)
log_profile(handle, rocblas_dot_name<T>, "N", n, "incx", incx, "incy", incy);
if(!x || !y || !result)
return rocblas_status_invalid_pointer;
/*
* Quick return if possible.
*/
if(n <= 0)
{
if(rocblas_pointer_mode_device == handle->pointer_mode)
RETURN_IF_HIP_ERROR(hipMemset(result, 0, sizeof(*result)));
else
*result = 0;
return rocblas_status_success;
}
void* workspace = handle->get_dot();
if(!workspace)
return rocblas_status_memory_error;
auto status =
rocblas_dot_workspace<T>(handle, n, x, incx, y, incy, result, (T*)workspace);
return status;
}
} // namespace
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" {
rocblas_status rocblas_sdot(rocblas_handle handle,
rocblas_int n,
const float* x,
rocblas_int incx,
const float* y,
rocblas_int incy,
float* result)
{
return rocblas_dot(handle, n, x, incx, y, incy, result);
}
rocblas_status rocblas_ddot(rocblas_handle handle,
rocblas_int n,
const double* x,
rocblas_int incx,
const double* y,
rocblas_int incy,
double* result)
{
return rocblas_dot(handle, n, x, incx, y, incy, result);
}
#if 0 // complex not supported
rocblas_status rocblas_cdotu(rocblas_handle handle,
rocblas_int n,
const rocblas_float_complex* x,
rocblas_int incx,
const rocblas_float_complex* y,
rocblas_int incy,
rocblas_float_complex* result)
{
return rocblas_dot(handle, n, x, incx, y, incy, result);
}
rocblas_status rocblas_zdotu(rocblas_handle handle,
rocblas_int n,
const rocblas_double_complex* x,
rocblas_int incx,
const rocblas_double_complex* y,
rocblas_int incy,
rocblas_double_complex* result)
{
return rocblas_dot(handle, n, x, incx, y, incy, result);
}
#endif
} // extern "C"
| 30.983607 | 100 | 0.514418 | [
"vector"
] |
b44dd31131c7c4e516a84366f222c74d1638d57d | 2,168 | cpp | C++ | 3rdParty/boost/1.71.0/libs/intrusive/example/doc_auto_unlink.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/boost/1.71.0/libs/intrusive/example/doc_auto_unlink.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/boost/1.71.0/libs/intrusive/example/doc_auto_unlink.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2013
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_auto_unlink_code
#include <boost/intrusive/list.hpp>
#include <cassert>
using namespace boost::intrusive;
typedef list_base_hook<link_mode<auto_unlink> > auto_unlink_hook;
class MyClass : public auto_unlink_hook
//This hook removes the node in the destructor
{
int int_;
public:
MyClass(int i = 0) : int_(i) {}
int get_int() { return int_; }
void unlink() { auto_unlink_hook::unlink(); }
bool is_linked() { return auto_unlink_hook::is_linked(); }
};
//Define a list that will store values using the base hook
//The list can't have constant-time size!
typedef list< MyClass, constant_time_size<false> > List;
int main()
{
//Create the list
List l;
{
//Create myclass and check it's linked
MyClass myclass;
assert(myclass.is_linked() == false);
//Insert the object
l.push_back(myclass);
//Check that we have inserted the object
assert(l.empty() == false);
assert(&l.front() == &myclass);
assert(myclass.is_linked() == true);
//Now myclass' destructor will unlink it
//automatically
}
//Check auto-unlink has been executed
assert(l.empty() == true);
{
//Now test the unlink() function
//Create myclass and check it's linked
MyClass myclass;
assert(myclass.is_linked() == false);
//Insert the object
l.push_back(myclass);
//Check that we have inserted the object
assert(l.empty() == false);
assert(&l.front() == &myclass);
assert(myclass.is_linked() == true);
//Now unlink the node
myclass.unlink();
//Check auto-unlink has been executed
assert(l.empty() == true);
}
return 0;
}
//]
| 25.809524 | 77 | 0.589022 | [
"object"
] |
b44efe20087af195893f2fad0308554b97b0d748 | 3,896 | cpp | C++ | src/qt/generatecodedialog.cpp | RIC-DeKon/riecoin | 7986f9f69264ed64ca19b273bd0e0b87fc71c8f4 | [
"MIT"
] | null | null | null | src/qt/generatecodedialog.cpp | RIC-DeKon/riecoin | 7986f9f69264ed64ca19b273bd0e0b87fc71c8f4 | [
"MIT"
] | null | null | null | src/qt/generatecodedialog.cpp | RIC-DeKon/riecoin | 7986f9f69264ed64ca19b273bd0e0b87fc71c8f4 | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2021 The Riecoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/generatecodedialog.h>
#include <qt/forms/ui_generatecodedialog.h>
#include <qt/addressbookpage.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/platformstyle.h>
#include <qt/walletmodel.h>
#include <key_io.h>
#include <wallet/wallet.h>
#include <vector>
#include <QClipboard>
#include <QTimer>
GenerateCodeDialog::GenerateCodeDialog(const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::GenerateCodeDialog), model(nullptr), platformStyle(_platformStyle)
{
ui->setupUi(this);
ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(":/icons/address-book"));
ui->code->setWordWrapMode(QTextOption::WrapAnywhere);
ui->copyCodeButton->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy"));
GUIUtil::setupAddressWidget(ui->addressIn, this);
GUIUtil::handleCloseWindowShortcut(this);
this->show();
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &GenerateCodeDialog::refresh);
timer->setInterval(MODEL_UPDATE_DELAY);
timer->start();
}
GenerateCodeDialog::~GenerateCodeDialog()
{
delete ui;
}
void GenerateCodeDialog::setModel(WalletModel *_model)
{
this->model = _model;
}
void GenerateCodeDialog::on_addressBookButton_clicked()
{
if (model && model->getAddressTableModel())
{
model->refresh(false);
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
ui->addressIn->setText(dlg.getReturnValue());
}
}
if (!model)
return;
}
void GenerateCodeDialog::on_copyCodeButton_clicked()
{
GUIUtil::setClipboard(ui->code->toPlainText());
}
constexpr uint64_t codeRefreshInterval(60ULL);
void GenerateCodeDialog::refresh()
{
ui->codeQr->setQR("INVALID", "INVALID");
CTxDestination destination = DecodeDestination(ui->addressIn->text().toStdString());
if (!IsValidDestination(destination)) {
ui->statusLabel->setText(tr("Please enter a valid Bech32 address."));
ui->code->setText(QString::fromStdString("-"));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid()) {
ui->statusLabel->setText(tr("Wallet unlock was cancelled."));
return;
}
const uint64_t timestamp(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());
const std::string& timestampStr(std::to_string(timestamp - (timestamp % codeRefreshInterval)));
std::string signature;
SigningResult res = model->wallet().signMessage(MessageSignatureFormat::SIMPLE, timestampStr, destination, signature);
QString error;
switch (res) {
case SigningResult::OK:
error = tr("No error");
break;
case SigningResult::PRIVATE_KEY_NOT_AVAILABLE:
error = tr("Private key for the entered address is not available.");
break;
case SigningResult::SIGNING_FAILED:
error = tr("Message signing failed.");
break;
// no default case, so the compiler can warn about missing cases
}
if (res != SigningResult::OK) {
ui->statusLabel->setText(error);
ui->code->setText(QString::fromStdString("-"));
}
else {
ui->statusLabel->setText(tr(("Valid for " + std::to_string(codeRefreshInterval - (timestamp % codeRefreshInterval)) + " s").c_str()));
ui->code->setText(QString::fromStdString(signature));
ui->codeQr->setQR(QString::fromStdString(signature), "Riecoin Authentication Code");
}
}
| 33.586207 | 189 | 0.683522 | [
"vector",
"model"
] |
b453c2dfcedb318dab46061ef2a5179244765fa7 | 17,636 | cpp | C++ | src/day19.cpp | michaeladler/aoc-2021 | 4321d2b1ded7f93ac6c90d80f8d4f6d2b23eb45b | [
"Apache-2.0"
] | null | null | null | src/day19.cpp | michaeladler/aoc-2021 | 4321d2b1ded7f93ac6c90d80f8d4f6d2b23eb45b | [
"Apache-2.0"
] | null | null | null | src/day19.cpp | michaeladler/aoc-2021 | 4321d2b1ded7f93ac6c90d80f8d4f6d2b23eb45b | [
"Apache-2.0"
] | null | null | null | // Took some inspiration from:
// * https://github.com/Praful/advent_of_code/blob/main/2021/src/day19.jl
// * https://github.com/taddeus/advent-of-code/blob/master/2021/19_beacon.py
// * https://github.com/Jellycious/aoc-2021/blob/main/src/days/day19.rs
#include "day19.h"
#define MAX_SCANNERS 32
#define MAX_POINTS 32
#define OVERLAP_BOUND 12
// // The threshold for number of overlapping probes was 12, this constitutes to binomial(n,2) = n*(n-1)/2 edges.
#define EDGE_THRESHOLD 66
using my_int = int32_t;
enum Rotation {
IDENTITY,
ROTZ,
ROTX,
SPECIAL_ONE,
SPECIAL_TWO,
};
#define ROTATION_COUNT 24
// clang-format off
// https://www.euclideanspace.com/maths/algebra/matrix/transforms/examples/index.htm
constexpr Rotation ALL_ROTATIONS[ROTATION_COUNT] = {
IDENTITY,
ROTZ, ROTZ, ROTZ,
ROTX,
ROTZ, ROTZ, ROTZ,
ROTX,
ROTZ, ROTZ, ROTZ,
SPECIAL_ONE,
ROTZ, ROTZ, ROTZ,
ROTX,
ROTZ, ROTZ, ROTZ,
SPECIAL_TWO,
ROTZ, ROTZ, ROTZ,
};
// clang-format on
struct Point3D {
my_int x, y, z;
Point3D operator-(const Point3D& other) const {
return {.x = x - other.x, .y = y - other.y, .z = z - other.z};
}
void operator+=(const Point3D& other) {
x += other.x;
y += other.y;
z += other.z;
}
Point3D operator+(const Point3D& other) const {
return {.x = x + other.x, .y = y + other.y, .z = z + other.z};
}
inline int64_t dist(const Point3D& other) const {
auto dx = (other.x - x);
auto dy = other.y - y;
auto dz = other.z - z;
return dx * dx + dy * dy + dz * dz;
}
inline int64_t manhattan_dist(const Point3D& other) const {
return std::abs(other.x - x) + std::abs(other.y - y) + std::abs(other.z - z);
}
bool operator==(const Point3D& other) const {
return x == other.x && y == other.y && z == other.z;
}
Point3D rotx() {
return {.x = x, .y = -z, .z = y};
}
Point3D rotz() {
return {.x = -y, .y = x, .z = z};
}
Point3D special1() {
/* heading = 180 degrees
* attitude = 0
* bank = 90 degrees
*
* -1 0 0
* 0 0 -1
* 0 -1 0
*/
return {.x = -x, .y = -z, .z = -y};
}
Point3D special2() {
return {.x = x, .y = z, .z = -y};
}
};
template <>
struct fmt::formatter<Point3D> : formatter<string_view> {
template <typename FormatContext>
auto format(const Point3D& p, FormatContext& ctx) -> decltype(ctx.out()) {
// ctx.out() is an output iterator to write to.
return format_to(
ctx.out(),
"x={}, y={}, z={}",
p.x, p.y, p.z);
}
};
MAKE_HASHABLE(Point3D, t.x, t.y, t.z)
struct Scanner {
std::optional<Point3D> m_location;
Point3D m_points[MAX_POINTS];
size_t m_count = 0;
std::vector<int64_t> m_distances;
std::unordered_map<int64_t, std::pair<size_t, size_t>> m_distance_to_points;
uint8_t m_rot_idx = 0;
void add_point(my_int x, my_int y, my_int z) {
assert(m_count < MAX_POINTS);
m_points[m_count++] = {.x = x, .y = y, .z = z};
}
void compute_distances() {
m_distances.reserve(m_count * m_count);
m_distance_to_points.reserve(m_count * m_count);
for (size_t i = 0; i < m_count; i++) {
for (size_t j = i + 1; j < m_count; j++) {
int64_t dist = m_points[i].dist(m_points[j]);
m_distances.push_back(dist);
m_distance_to_points[dist] = std::make_pair(i, j);
}
}
std::sort(m_distances.begin(), m_distances.end());
}
void rotate() {
m_rot_idx++;
assert(m_rot_idx < ROTATION_COUNT);
switch (ALL_ROTATIONS[m_rot_idx]) {
case IDENTITY:
break;
case ROTZ:
for (size_t i = 0; i < m_count; i++) m_points[i] = m_points[i].rotz();
break;
case ROTX:
for (size_t i = 0; i < m_count; i++) m_points[i] = m_points[i].rotx();
break;
case SPECIAL_ONE:
for (size_t i = 0; i < m_count; i++) m_points[i] = m_points[i].special1();
break;
case SPECIAL_TWO:
for (size_t i = 0; i < m_count; i++) m_points[i] = m_points[i].special2();
break;
}
}
};
struct OverlapResult {
size_t first, second; // index into scanners array
int64_t common_distance;
};
static std::optional<Point3D> scanner_location(const std::pair<Point3D, Point3D>& beacon_pair1,
const std::pair<Point3D, Point3D>& beacon_pair2) {
{
auto loc1 = beacon_pair1.first - beacon_pair2.first;
auto loc2 = beacon_pair1.second - beacon_pair2.second;
if (loc1 == loc2) return loc1;
}
{
auto loc1 = beacon_pair1.first - beacon_pair2.second;
auto loc2 = beacon_pair1.second - beacon_pair2.first;
if (loc1 == loc2) return loc1;
}
std::optional<Point3D> result;
return result;
}
using parse::input_t;
parse::output_t day19(input_t in) {
long part1, part2;
size_t scanner_count;
Scanner scanners[MAX_SCANNERS];
scanners[0].m_location = {0, 0, 0};
{
int scanner_idx = -1;
while (in.len > 4) {
if (*(in.s + 4) == 's') { // start new scanner
scanner_idx++;
parse::seek_next_line(in);
continue;
}
auto x = static_cast<my_int>(parse::number(in));
in.s++, in.len--; // skip comma
auto y = static_cast<my_int>(parse::number(in));
in.s++, in.len--; // skip comma
auto z = static_cast<my_int>(parse::number(in));
scanners[scanner_idx].add_point(x, y, z);
parse::seek_next_line(in);
while (in.len && *in.s == '\n') { in.s++, in.len--; };
}
scanner_count = scanner_idx + 1;
}
DEBUG("Parsed {} scanners", scanner_count);
/*
* Step 1: For each scanner, compute the distance between any two beacons.
*/
for (size_t alpha = 0; alpha < scanner_count; alpha++) {
scanners[alpha].compute_distances();
}
/*
* Step 2: Find overlapping scanners.
* This function does not guarantee that two scanners overlap, but there is strong evidence
* that two scanners might overlap. If a scanner is not in the result then it does definitely not
* overlap with `s1`.
*/
std::vector<OverlapResult> overlapping_scanners;
overlapping_scanners.reserve(MAX_SCANNERS * (MAX_SCANNERS - 1));
for (size_t alpha = 0; alpha < scanner_count; alpha++) {
auto n = scanners[alpha].m_distances.size();
for (size_t beta = alpha + 1; beta < scanner_count; beta++) {
auto m = scanners[beta].m_distances.size();
uint64_t common_count = 0;
size_t i = 0, j = 0;
std::vector<int64_t> common_distances;
common_distances.reserve(MAX_POINTS * MAX_POINTS);
while (i < n && j < m) {
if (scanners[alpha].m_distances[i] == scanners[beta].m_distances[j]) {
common_count++;
common_distances.push_back(scanners[alpha].m_distances[i]);
i++;
j++;
} else if (scanners[alpha].m_distances[i] > scanners[beta].m_distances[j]) {
j++;
} else {
i++;
}
}
if (common_count >= EDGE_THRESHOLD) {
OverlapResult result = {.first = alpha, .second = beta, .common_distance = common_distances[0]};
overlapping_scanners.push_back(result);
}
}
}
/* Step 3: For each of these overlapping scanners (s1 and s2, say), use a pair of beacons to find the correct rotation of
* beacons in s2 so that they align to beacons in s1. As part of finding the rotation, the location of the scanner
* (relative to the first scanner) pops out.
*/
std::unordered_set<Point3D> unique_beacons;
unique_beacons.reserve(MAX_SCANNERS * MAX_POINTS);
for (size_t i = 0; i < scanners[0].m_count; i++) unique_beacons.insert(scanners[0].m_points[i]);
size_t processed = 1;
while (processed < scanner_count) {
for (const auto& overlap_result : overlapping_scanners) {
size_t i = overlap_result.first;
size_t j = overlap_result.second;
if (scanners[i].m_location.has_value() && scanners[j].m_location.has_value()) continue;
if (!scanners[i].m_location.has_value() && !scanners[j].m_location.has_value()) continue;
if (!scanners[i].m_location.has_value()) {
auto old = i;
i = j;
j = old;
}
DEBUG("Using scanner {} at location {} to align scanner {}", i, *scanners[i].m_location, j);
DEBUG("Common distances: {}", overlap_result.common_distances);
// i is processed, j is not processed
assert(scanners[i].m_location.has_value());
assert(!scanners[j].m_location.has_value());
assert(scanners[j].m_rot_idx == 0);
auto s1_indices = scanners[i].m_distance_to_points[overlap_result.common_distance];
std::pair<Point3D, Point3D> s1_beacons = std::make_pair(
scanners[i].m_points[s1_indices.first],
scanners[i].m_points[s1_indices.second]);
DEBUG("s1_beacons: {}", s1_beacons);
auto s2_indices = scanners[j].m_distance_to_points[overlap_result.common_distance];
std ::pair<Point3D, Point3D> s2_beacons = std::make_pair(
scanners[j].m_points[s2_indices.first],
scanners[j].m_points[s2_indices.second]);
DEBUG("s2_beacons: {}", s2_beacons);
// find orientation of s2
for (uint8_t rot_idx = 0; rot_idx < ROTATION_COUNT; rot_idx++) {
switch (ALL_ROTATIONS[rot_idx]) {
case IDENTITY:
break;
case ROTZ:
s2_beacons.first = s2_beacons.first.rotz();
s2_beacons.second = s2_beacons.second.rotz();
break;
case ROTX:
s2_beacons.first = s2_beacons.first.rotx();
s2_beacons.second = s2_beacons.second.rotx();
break;
case SPECIAL_ONE:
s2_beacons.first = s2_beacons.first.special1();
s2_beacons.second = s2_beacons.second.special1();
break;
case SPECIAL_TWO:
s2_beacons.first = s2_beacons.first.special2();
s2_beacons.second = s2_beacons.second.special2();
break;
}
DEBUG("rotate2: {}", s2_beacons);
std::optional<Point3D> maybe_location = scanner_location(s1_beacons, s2_beacons);
if (maybe_location.has_value()) {
Point3D location = maybe_location.value();
DEBUG("Scanner {} has location {}", j, location);
// We need to adjust the location so that it is relative to
// the first scanner (ie scanners[1]), which is
// what scanner[id1] has been aligned to.
location += scanners[i].m_location.value();
scanners[j].m_location = location;
for (uint8_t rot_counter = 0; rot_counter < rot_idx; rot_counter++) {
scanners[j].rotate();
}
for (size_t k = 0; k < scanners[j].m_count; k++) {
unique_beacons.insert(scanners[j].m_points[k] + location);
}
processed++;
break;
}
}
DEBUG("processed: {}", processed);
}
}
part1 = unique_beacons.size();
part2 = std::numeric_limits<long>().min();
for (size_t i = 0; i < scanner_count; i++) {
for (size_t j = 0; j < scanner_count; j++) {
auto dist = scanners[i].m_location->manhattan_dist(*scanners[j].m_location);
if (dist > part2) part2 = dist;
}
}
return {part1, part2};
}
#ifdef IS_MAIN
int main() {
input_t in = parse::load_input("input/day19.txt");
auto output = day19(in);
fmt::print("Part 1: {}\nPart 2: {}\n", output.answer[0], output.answer[1]);
return 0;
}
#endif // IS_MAIN
#ifdef IS_TEST
#include <doctest/doctest.h>
using std::make_tuple;
TEST_CASE("day19: examples") {
auto test_cases = {
make_tuple(
"--- scanner 0 ---\n"
"404,-588,-901\n"
"528,-643,409\n"
"-838,591,734\n"
"390,-675,-793\n"
"-537,-823,-458\n"
"-485,-357,347\n"
"-345,-311,381\n"
"-661,-816,-575\n"
"-876,649,763\n"
"-618,-824,-621\n"
"553,345,-567\n"
"474,580,667\n"
"-447,-329,318\n"
"-584,868,-557\n"
"544,-627,-890\n"
"564,392,-477\n"
"455,729,728\n"
"-892,524,684\n"
"-689,845,-530\n"
"423,-701,434\n"
"7,-33,-71\n"
"630,319,-379\n"
"443,580,662\n"
"-789,900,-551\n"
"459,-707,401\n"
"\n"
"--- scanner 1 ---\n"
"686,422,578\n"
"605,423,415\n"
"515,917,-361\n"
"-336,658,858\n"
"95,138,22\n"
"-476,619,847\n"
"-340,-569,-846\n"
"567,-361,727\n"
"-460,603,-452\n"
"669,-402,600\n"
"729,430,532\n"
"-500,-761,534\n"
"-322,571,750\n"
"-466,-666,-811\n"
"-429,-592,574\n"
"-355,545,-477\n"
"703,-491,-529\n"
"-328,-685,520\n"
"413,935,-424\n"
"-391,539,-444\n"
"586,-435,557\n"
"-364,-763,-893\n"
"807,-499,-711\n"
"755,-354,-619\n"
"553,889,-390\n"
"\n"
"--- scanner 2 ---\n"
"649,640,665\n"
"682,-795,504\n"
"-784,533,-524\n"
"-644,584,-595\n"
"-588,-843,648\n"
"-30,6,44\n"
"-674,560,763\n"
"500,723,-460\n"
"609,671,-379\n"
"-555,-800,653\n"
"-675,-892,-343\n"
"697,-426,-610\n"
"578,704,681\n"
"493,664,-388\n"
"-671,-858,530\n"
"-667,343,800\n"
"571,-461,-707\n"
"-138,-166,112\n"
"-889,563,-600\n"
"646,-828,498\n"
"640,759,510\n"
"-630,509,768\n"
"-681,-892,-333\n"
"673,-379,-804\n"
"-742,-814,-386\n"
"577,-820,562\n"
"\n"
"--- scanner 3 ---\n"
"-589,542,597\n"
"605,-692,669\n"
"-500,565,-823\n"
"-660,373,557\n"
"-458,-679,-417\n"
"-488,449,543\n"
"-626,468,-788\n"
"338,-750,-386\n"
"528,-832,-391\n"
"562,-778,733\n"
"-938,-730,414\n"
"543,643,-506\n"
"-524,371,-870\n"
"407,773,750\n"
"-104,29,83\n"
"378,-903,-323\n"
"-778,-728,485\n"
"426,699,580\n"
"-438,-605,-362\n"
"-469,-447,-387\n"
"509,732,623\n"
"647,635,-688\n"
"-868,-804,481\n"
"614,-800,639\n"
"595,780,-596\n"
"\n"
"--- scanner 4 ---\n"
"727,592,562\n"
"-293,-554,779\n"
"441,611,-461\n"
"-714,465,-776\n"
"-743,427,-804\n"
"-660,-479,-426\n"
"832,-632,460\n"
"927,-485,-438\n"
"408,393,-506\n"
"466,436,-512\n"
"110,16,151\n"
"-258,-428,682\n"
"-393,719,612\n"
"-211,-452,876\n"
"808,-476,-593\n"
"-575,615,604\n"
"-485,667,467\n"
"-680,325,-822\n"
"-627,-443,-432\n"
"872,-547,-609\n"
"833,512,582\n"
"807,604,487\n"
"839,-516,451\n"
"891,-625,532\n"
"-652,-548,-490\n"
"30,-46,-14",
79, 3621),
};
for (auto& tc : test_cases) {
auto first = std::string(std::get<0>(tc));
input_t in = {&first[0], static_cast<ssize_t>(first.length())};
auto output = day19(in);
CHECK_EQ(std::get<1>(tc), std::strtol(output.answer[0].c_str(), NULL, 10));
CHECK_EQ(std::get<2>(tc), std::strtol(output.answer[1].c_str(), NULL, 10));
}
}
TEST_CASE("day19, part 1 & part 2") {
input_t in = parse::load_input("input/day19.txt");
auto output = day19(in);
CHECK_EQ(365, std::strtol(output.answer[0].c_str(), NULL, 10));
CHECK_EQ(11060, std::strtol(output.answer[1].c_str(), NULL, 10));
}
#endif // IS_TEST
| 33.338374 | 125 | 0.496428 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.