hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d7827ef6aaed40723c3bf8aba84df5e6b037875 | 986 | cpp | C++ | src/Score.cpp | Pyr0x1/Memory | e73f68554b1707bccd984e9d3725e597aee7c82a | [
"MIT"
] | 1 | 2016-01-15T04:45:26.000Z | 2016-01-15T04:45:26.000Z | src/Score.cpp | Pyr0x1/Memory | e73f68554b1707bccd984e9d3725e597aee7c82a | [
"MIT"
] | null | null | null | src/Score.cpp | Pyr0x1/Memory | e73f68554b1707bccd984e9d3725e597aee7c82a | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include "Score.h"
Score::Score (std::string fontPath, SDL_Color fontColor, int size) {
this->font = TTF_OpenFont (fontPath.c_str(), size);
if(!this->font)
printf("TTF_OpenFont: %s\n", TTF_GetError());
this->color = fontColor;
this->value = 0;
}
void Score::write (SDL_Renderer* renderer, SDL_Point position) {
std::ostringstream oStream;
oStream << this->value;
std::string valueStr = oStream.str ();
this->surface = TTF_RenderText_Solid (this->font, valueStr.c_str (), this->color);
this->texture = SDL_CreateTextureFromSurface (renderer, this->surface);
SDL_Rect destRect = {position.x, position.y, this->surface->w, this->surface->h};
SDL_RenderCopy (renderer, this->texture, NULL, &destRect);
SDL_FreeSurface (this->surface);
return ;
}
void Score::increase () {
this->value++;
}
void Score::reset () {
this->value = 0;
}
Score::~Score () {
TTF_CloseFont (this->font);
SDL_DestroyTexture (this->texture);
}
| 20.541667 | 83 | 0.691684 | Pyr0x1 |
4d7efa0da1d3e666c546b9ac7a3b9361d9965cb9 | 19,300 | hpp | C++ | src/projects/lja/multi_graph.hpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | src/projects/lja/multi_graph.hpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | src/projects/lja/multi_graph.hpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <sequences/sequence.hpp>
#include <unordered_set>
#include <unordered_map>
#include <experimental/filesystem>
#include <fstream>
#include <common/string_utils.hpp>
#include <sequences/contigs.hpp>
namespace multigraph {
class Edge;
struct Vertex {
Sequence seq;
int id;
std::vector<Edge *> outgoing;
Vertex *rc = nullptr;
explicit Vertex(const Sequence &seq, int id) : seq(seq), id(id) {
outgoing.reserve(4);
}
bool isCanonical() const {
return seq <= !seq;
}
size_t inDeg() const {
return rc->outgoing.size();
}
size_t outDeg() const {
return outgoing.size();
}
};
struct Edge {
private:
Sequence seq;
int id;
size_t sz;
bool canonical;
public:
Vertex *start = nullptr;
Vertex *end = nullptr;
Edge *rc = nullptr;
explicit Edge(const Sequence &seq, int id = 0) : seq(seq), id(id), sz(seq.size()), canonical(seq <= !seq) {
}
Sequence getSeq() const {
if(seq.empty())
return start->seq + end->seq.Subseq(sz);
return seq;
}
int getId() const {
return id;
}
size_t size() const {
return sz;
}
size_t overlap() const {
VERIFY(start->seq.size() + end->seq.size() > sz);
return start->seq.size() + end->seq.size() - sz;
}
bool isCanonical() const {
VERIFY(canonical == (id > 0));
return canonical;
}
};
struct MultiGraph {
int maxVId = 0;
int maxEId = 0;
std::vector<Vertex *> vertices;
std::vector<Edge *> edges;
MultiGraph() = default;
MultiGraph(MultiGraph &&other) = default;
MultiGraph &operator=(MultiGraph &&other) = default;
MultiGraph(const MultiGraph &) = delete;
MultiGraph &LoadGFA(const std::experimental::filesystem::path &gfa_file, bool int_ids) {
std::ifstream is;
is.open(gfa_file);
std::unordered_map<std::string, Vertex*> vmap;
for( std::string line; getline(is, line); ) {
std::vector<std::string> tokens = ::split(line);
if(tokens[0] == "S") {
std::string name = tokens[1];
Vertex &newV = int_ids ? addVertex(Sequence(tokens[2]), std::stoi(name)) : addVertex(Sequence(tokens[2]));
VERIFY(vmap.find(name) == vmap.end());
vmap[name] = &newV;
} else if(tokens[0] == "L") {
Vertex *v1 = vmap[tokens[1]];
Vertex *v2 = vmap[tokens[3]];
if(tokens[2] == "-")
v1 = v1->rc;
if(tokens[4] == "-")
v2 = v2->rc;
size_t overlap = std::stoull(tokens[5].substr(0, tokens[5].size() - 1));
if(v1->seq.Subseq(v1->seq.size() - overlap) != v2->seq.Subseq(0, overlap)) {
v1 = v1->rc;
}
VERIFY(v1->seq.Subseq(v1->seq.size() - overlap) == v2->seq.Subseq(0, overlap));
addEdge(*v1, *v2, v1->seq + v2->seq.Subseq(overlap));
}
}
is.close();
return *this;
}
MultiGraph DBG() const {
MultiGraph dbg;
std::unordered_map<Edge *, Vertex *> emap;
for(Vertex * v : vertices) {
if(v->outDeg() == 0 || emap.find(v->outgoing[0]) != emap.end()) {
continue;
}
Vertex *newv = &dbg.addVertex(v->seq.Subseq(v->seq.size() - v->outgoing[0]->overlap()));
for(Edge * edge : v->outgoing) {
Vertex * right = edge->end;
for(Edge * edge1 : right->rc->outgoing) {
emap[edge1] = newv->rc;
emap[edge1->rc] = newv;
}
}
}
for(Vertex * v : vertices) {
if(!(v->seq <= !v->seq))
continue;
Vertex * start = nullptr;
Vertex * end = nullptr;
if(v->inDeg() == 0) {
start = &dbg.addVertex(v->seq.Subseq(0, 4001));
} else {
start = emap[v->rc->outgoing[0]]->rc;
}
if(v->outDeg() == 0) {
end = &dbg.addVertex(v->seq.Subseq(v->seq.size() - 4001));
} else {
end = emap[v->outgoing[0]];
}
dbg.addEdge(*start, *end, v->seq, v->id);
}
return std::move(dbg);
}
~MultiGraph() {
for(Vertex * &v : vertices) {
delete v;
v = nullptr;
}
for(Edge * &e : edges) {
delete e;
e = nullptr;
}
}
MultiGraph DeleteEdges(const std::unordered_set<Edge *> &to_delete) const {
MultiGraph mg;
std::unordered_map<Vertex *, Vertex *> vmap;
std::unordered_set<Edge *> visited;
for(Vertex * v : vertices) {
if(vmap.find(v) != vmap.end())
continue;
vmap[v] = &mg.addVertex(v->seq, v->id);
vmap[v->rc] = vmap[v]->rc;
}
for(Edge * edge : edges) {
if(!edge->isCanonical() || to_delete.find(edge) != to_delete.end())
continue;
mg.addEdge(*vmap[edge->start], *vmap[edge->end], edge->getSeq(), edge->getId());
}
return std::move(mg);
}
MultiGraph BulgeSubgraph() const {
std::unordered_set<Vertex *> good;
std::unordered_set<Edge *> to_delete;
size_t sz = 0;
for(Vertex *v : vertices) {
if(v->outDeg() != 2) {
continue;
}
if(v->outgoing[0]->end == v->outgoing[1]->end) {
good.emplace(v);
good.emplace(v->rc);
}
}
size_t bulges = 0;
for(Vertex *v : vertices) {
if(v->outDeg() != 2) {
continue;
}
if(to_delete.find(v->outgoing[0]) != to_delete.end() ||
to_delete.find(v->outgoing[1]) != to_delete.end()) {
continue;
}
Edge * todel = nullptr;
if(v->outgoing[0]->end == v->outgoing[1]->end) {
todel = v->outgoing[0];
bulges++;
sz += v->outgoing[0]->size();
} else {
if((good.find(v) == good.end() || v->outgoing[0]->size() < 1000000) && v->outgoing[0]->end->outDeg() == 0) {
todel = v->outgoing[0];
} else if((good.find(v) == good.end() || v->outgoing[0]->size() < 1000000) && v->outgoing[1]->end->outDeg() == 0) {
todel = v->outgoing[1];
} else if(good.find(v->outgoing[0]->end)== good.end()) {
todel = v->outgoing[0];
} else if(good.find(v->outgoing[1]->end)== good.end()) {
todel = v->outgoing[1];
}
}
if(todel != nullptr) {
to_delete.emplace(todel);
to_delete.emplace(todel->rc);
sz += todel->size();
}
}
std::cout << "Deleting " << sz << " " << to_delete.size() / 2 << std::endl;
std::cout << "Bulges " << bulges << std::endl;
return DeleteEdges(to_delete);
}
void checkConsistency() const {
std::unordered_set<Edge const *> eset;
std::unordered_set<Vertex const *> vset;
for(Edge const * edge: edges) {
eset.emplace(edge);
VERIFY(edge->rc->start == edge->end->rc);
VERIFY(edge->rc->rc == edge);
}
for(Edge const *edge : edges) {
VERIFY(eset.find(edge->rc) != eset.end());
}
for(Vertex const * v: vertices) {
vset.emplace(v);
VERIFY(v->rc->rc == v);
for(Edge *edge : v->outgoing) {
VERIFY(eset.find(edge) != eset.end());
VERIFY(edge->start == v);
}
}
for(Vertex const *v : vertices) {
VERIFY(vset.find(v->rc) != vset.end());
}
}
Vertex &addVertex(const Sequence &seq, int id = 0) {
if(id == 0) {
id = maxVId + 1;
}
maxVId = std::max(std::abs(id), maxVId);
vertices.emplace_back(new Vertex(seq, id));
Vertex *res = vertices.back();
Vertex *rc = res;
if(seq != !seq) {
vertices.emplace_back(new Vertex(!seq, -id));
rc = vertices.back();
}
res->rc = rc;
rc->rc = res;
return *res;
}
Edge &addEdge(Vertex &from, Vertex &to, const Sequence &seq, int id = 0) {
if(id == 0) {
id = maxEId + 1;
}
maxEId = std::max(std::abs(id), maxEId);
if(!(seq <= !seq)) {
id = -id;
}
edges.emplace_back(new Edge(seq, id));
Edge *res = edges.back();
res->start = &from;
res->end = &to;
res->start->outgoing.emplace_back(res);
if(seq != !seq) {
edges.emplace_back(new Edge(!seq, -id));
Edge *rc = edges.back();
rc->start = to.rc;
rc->end = from.rc;
res->rc = rc;
rc->rc = res;
res->rc->start->outgoing.emplace_back(res->rc);
} else {
res->rc = res;
}
return *res;
}
std::vector<Edge *> uniquePathForward(Edge &edge) {
std::vector<Edge *> res = {&edge};
Vertex *cur = edge.end;
while(cur != edge.start && cur->inDeg() == 1 && cur->outDeg() == 1) {
res.emplace_back(cur->outgoing[0]);
cur = res.back()->end;
}
return std::move(res);
}
std::vector<Edge *> uniquePath(Edge &edge) {
std::vector<Edge *> path = uniquePathForward(*edge.rc);
return uniquePathForward(*path.back()->rc);
}
MultiGraph Merge() {
MultiGraph res;
std::unordered_set<Edge *> used;
std::unordered_map<Vertex *, Vertex *> old_to_new;
for(Edge *edge : edges) {
if(used.find(edge) != used.end())
continue;
std::vector<Edge *> unique = uniquePath(*edge);
for(Edge *e : unique) {
used.emplace(e);
used.emplace(e->rc);
}
Vertex *old_start = unique.front()->start;
Vertex *old_end = unique.back()->end;
Vertex *new_start = nullptr;
Vertex *new_end = nullptr;
if(old_to_new.find(old_start) == old_to_new.end()) {
old_to_new[old_start] = &res.addVertex(old_start->seq);
old_to_new[old_start->rc] = old_to_new[old_start]->rc;
}
new_start = old_to_new[old_start];
if(old_to_new.find(old_end) == old_to_new.end()) {
old_to_new[old_end] = &res.addVertex(old_end->seq);
old_to_new[old_end->rc] = old_to_new[old_end]->rc;
}
new_end = old_to_new[old_end];
Sequence new_seq;
if(unique.size() == 1) {
new_seq = unique[0]->getSeq();
} else {
SequenceBuilder sb;
sb.append(old_start->seq);
for(Edge *e : unique) {
sb.append(e->getSeq().Subseq(e->start->seq.size()));
}
new_seq = sb.BuildSequence();
}
res.addEdge(*new_start, *new_end, new_seq);
}
for(Vertex *vertex : vertices) {
if(vertex->inDeg() == 0 && vertex->outDeg() == 0 && vertex->seq <= !vertex->seq) {
res.addVertex(vertex->seq);
}
}
res.checkConsistency();
return std::move(res);
}
std::vector<Contig> getEdges(bool cut_overlaps) {
std::unordered_map<Vertex *, size_t> cut;
for(Vertex *v : vertices) {
if(v->seq <= !v->seq) {
if(v->outDeg() == 1) {
cut[v] = 0;
} else {
cut[v] = 1;
}
cut[v->rc] = 1 - cut[v];
}
}
std::vector<Contig> res;
size_t cnt = 1;
for(Edge *edge : edges) {
if(edge->isCanonical()) {
size_t cut_left = edge->start->seq.size() * cut[edge->start];
size_t cut_right = edge->end->seq.size() * (1 - cut[edge->end]);
if(!cut_overlaps) {
cut_left = 0;
cut_right = 0;
}
if(cut_left + cut_right >= edge->size()) {
continue;
}
res.emplace_back(edge->getSeq().Subseq(cut_left, edge->size() - cut_right), itos(edge->getId()));
cnt++;
}
}
return std::move(res);
}
void printEdges(const std::experimental::filesystem::path &f, bool cut_overlaps) {
std::ofstream os;
os.open(f);
for(const Contig &contig : getEdges(cut_overlaps)) {
os << ">" << contig.id << "\n" << contig.seq << "\n";
}
os.close();
}
void printDot(const std::experimental::filesystem::path &f) {
std::ofstream os;
os.open(f);
os << "digraph {\nnodesep = 0.5;\n";
for(Vertex *vertex : vertices) {
os << vertex->id << " [label=\"" << vertex->seq.size() << "\" style=filled fillcolor=\"white\"]\n";
}
std::unordered_map<Edge *, std::string> eids;
for (Edge *edge : edges) {
os << "\"" << edge->start->id << "\" -> \"" << edge->end->id <<
"\" [label=\"" << edge->getId() << "(" << edge->size() << ")\" color = \"black\"]\n" ;
}
os << "}\n";
os.close();
}
void printEdgeGFA(const std::experimental::filesystem::path &f, const std::vector<Vertex *> &component) const {
std::ofstream os;
os.open(f);
os << "H\tVN:Z:1.0" << std::endl;
std::unordered_map<Edge *, std::string> eids;
for(Vertex *v : component)
for (Edge *edge : v->outgoing) {
if (edge->isCanonical()) {
eids[edge] = itos(edge->getId());
eids[edge->rc] = itos(edge->getId());
os << "S\t" << eids[edge] << "\t" << edge->getSeq() << "\n";
}
}
for (Vertex *vertex : component) {
if(!vertex->isCanonical())
continue;
for (Edge *out_edge : vertex->outgoing) {
std::string outid = eids[out_edge];
bool outsign = out_edge->isCanonical();
for (Edge *inc_edge : vertex->rc->outgoing) {
std::string incid = eids[inc_edge];
bool incsign = inc_edge->rc->isCanonical();
os << "L\t" << incid << "\t" << (incsign ? "+" : "-") << "\t" << outid << "\t"
<< (outsign ? "+" : "-") << "\t" << vertex->seq.size() << "M" << "\n";
}
}
}
os.close();
}
void printEdgeGFA(const std::experimental::filesystem::path &f) const {
printEdgeGFA(f, vertices);
}
void printVertexGFA(const std::experimental::filesystem::path &f, const std::vector<Vertex *> &component) const {
std::ofstream os;
os.open(f);
os << "H\tVN:Z:1.0" << std::endl;
size_t cnt = 1;
std::unordered_map<Vertex *, std::string> vids;
for(Vertex *v : component)
if(v->seq <= !v->seq) {
vids[v] = itos(v->id);
vids[v->rc] = itos(v->id);
os << "S\t" << vids[v] << "\t" << v->seq << "\n";
cnt++;
}
for(Vertex *v : component)
for (Edge *edge : v->outgoing) {
if (edge->isCanonical()) {
bool incsign = v->seq <= !v->seq;
bool outsign = edge->end->seq <= !edge->end->seq;
os << "L\t" << vids[v] << "\t" << (incsign ? "+" : "-") << "\t"
<< vids[edge->end] << "\t" << (outsign ? "+" : "-") << "\t"
<< (v->seq.size() + edge->end->seq.size() - edge->size()) << "M" << "\n";
}
}
os.close();
}
void printVertexGFA(const std::experimental::filesystem::path &f) const {
printVertexGFA(f, vertices);
}
std::vector<std::vector<Vertex *>> split() const {
std::vector<std::vector<Vertex *>> res;
std::unordered_set<Vertex *> visited;
for(Vertex *v : vertices) {
if(visited.find(v) != visited.end())
continue;
std::vector<Vertex *> stack = {v};
res.emplace_back(std::vector<Vertex *>());
while(!stack.empty()) {
Vertex *p = stack.back();
stack.pop_back();
if(visited.find(p) != visited.end())
continue;
visited.emplace(p);
visited.emplace(p->rc);
res.back().emplace_back(p);
res.back().emplace_back(p->rc);
for(Edge *e : p->outgoing)
stack.emplace_back(e->end);
for(Edge *e : p->rc->outgoing)
stack.emplace_back(e->end);
}
}
return std::move(res);
}
};
}
| 38.067061 | 135 | 0.412642 | fedarko |
4d7f0085ce495c58f5b980a403b741030b0fab38 | 274 | cpp | C++ | src/unit_tests/main.cpp | tyrbedarf/LumixEngine | 0ec51d724abcc06f297c3e189282763a630f7eb5 | [
"MIT"
] | 3 | 2021-05-27T10:43:33.000Z | 2021-05-27T10:44:02.000Z | src/unit_tests/main.cpp | tyrbedarf/LumixEngine | 0ec51d724abcc06f297c3e189282763a630f7eb5 | [
"MIT"
] | null | null | null | src/unit_tests/main.cpp | tyrbedarf/LumixEngine | 0ec51d724abcc06f297c3e189282763a630f7eb5 | [
"MIT"
] | 3 | 2021-05-27T10:44:15.000Z | 2021-11-18T09:20:10.000Z | #include "engine/lumix.h"
#include "engine/debug/floating_points.h"
#include "unit_tests/suite/unit_test_app.h"
int main(int argc, const char * argv[])
{
Lumix::enableFloatingPointTraps(true);
Lumix::UnitTest::App app;
app.init();
app.run(argc, argv);
app.exit();
}
| 18.266667 | 43 | 0.715328 | tyrbedarf |
4d8118e6f98fdefb970263985e8e6be4cbdd5f19 | 396 | hpp | C++ | est/include/est/est_io_cb.hpp | dungeonsnd/lite-libs | 38f84bd1cf6f1a43836f43e57fcd1d22b18d706b | [
"FSFAP"
] | null | null | null | est/include/est/est_io_cb.hpp | dungeonsnd/lite-libs | 38f84bd1cf6f1a43836f43e57fcd1d22b18d706b | [
"FSFAP"
] | null | null | null | est/include/est/est_io_cb.hpp | dungeonsnd/lite-libs | 38f84bd1cf6f1a43836f43e57fcd1d22b18d706b | [
"FSFAP"
] | null | null | null | #ifndef _HEADER_FILE_EST_IO_CB_HPP_
#define _HEADER_FILE_EST_IO_CB_HPP_
typedef void (*est_funcIocb) (bufferevent *bev, void *arg);
typedef void (*est_funcErrorcb) (bufferevent *bev,short event, void *arg);
typedef void (*est_funcTimecb) (int fd,short event, void *arg);
typedef void (*est_funcAcceptcb) (evutil_socket_t listener, short event, void *arg);
#endif // _HEADER_FILE_EST_IO_CB_HPP_
| 39.6 | 84 | 0.790404 | dungeonsnd |
4d871ec0231e6e547b55a7c9b30da5c58d55674f | 3,125 | cc | C++ | CodeChef/SNACKDOWN/16/Pre-Elimination A/Problem F/F.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | CodeChef/SNACKDOWN/16/Pre-Elimination A/Problem F/F.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | CodeChef/SNACKDOWN/16/Pre-Elimination A/Problem F/F.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foreach(it, v) for(__typeof((v).begin()) it=(v).begin(); it != (v).end(); ++it)
#define meta __FUNCTION__,__LINE__
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
using namespace std;
const long double PI = 3.1415926535897932384626433832795;
template<typename S, typename T>
ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;}
template<typename T>
ostream& operator<<(ostream& out,vector<T> const& v){
int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
typedef long long ll;
typedef pair<int,int> pii;
const int N = 100100;
const ll MOD = 1e9 + 7;
int a[N];
ll s[N];
ll getAtZ(ll x, ll y, ll z, ll vx, ll vy, int cur, int m){
int jump = m - cur;
if(x << jump == z) return vx;
if(y << jump == z) return vy;
jump--;
x <<= 1;
y <<= 1;
ll mid = x+1;
ll vm = (vx + vy) % MOD;
if(z <= (mid << jump))
return getAtZ(x, mid, z, vx, vm, cur+1, m);
else
return getAtZ(mid, y, z, vm, vy, cur+1, m);
}
ll getSum(ll l, ll r, int cnt, ll px, ll py, ll vx, ll vy){
if(cnt == 0){
// tr(meta, l, r, cnt, px, py, vx, vy);
if(l) return (s[r] - s[l-1] + MOD) % MOD;
return s[r];
}
ll ret = 0;
if(r % 2){
ll v1 = getAtZ(px, py, l, vx, vy, 0, cnt);
ll v2 = getAtZ(px, py, r-1, vx, vy, 0, cnt);
ll v3 = getAtZ(px, py, r, vx, vy, 0, cnt);
ret = getSum(l/2, r/2, cnt-1, px, py, vx, vy) * 3 % MOD;
ret = (ret - v1 + MOD) % MOD;
ret = (ret - v2 + MOD) % MOD;
ret = (ret + v3) % MOD;
}
else{
ll v1 = getAtZ(px, py, l, vx, vy, 0, cnt);
ll v2 = getAtZ(px, py, r, vx, vy, 0, cnt);
ret = getSum(l/2, r/2, cnt-1, px, py, vx, vy) * 3 % MOD;
ret = (ret - v1 + MOD) % MOD;
ret = (ret - v2 + MOD) % MOD;
}
// tr(meta, l, r, cnt, px, py, vx, vy, "returning", ret);
return ret;
}
int n, m;
ll get(ll x){
if(x < 0) return 0;
ll lo = 0, hi = n, mid;
while(lo+1 < hi){
mid = (lo + hi) >> 1;
ll pos = mid << m;
if(pos <= x) lo = mid;
else hi = mid;
}
ll l = lo, r = lo+1;
ll sm = s[l];
for(int i = 0; i < m; i++){
sm = ((sm * 3) % MOD - a[0] - a[l] + MOD) % MOD;
}
ll ret = sm;
if((l << m) == x) return ret;
// tr(meta, x, l, l << m, ret);
ret = ret + getSum((l << m), x, m, l, r, a[l], a[r]) % MOD;
ret = (ret - a[l] + MOD) % MOD;
assert(ret >= 0 and ret < MOD);
return ret;
}
void solve(){
ll x, y;
scanf("%d%d%lld%lld", &n, &m, &x, &y);
x--, y--;
for(int i = 0; i < n; i++){
sd(a[i]);
}
s[0] = a[0];
for(int i = 1; i < n; i++){
s[i] = s[i-1] + a[i] % MOD;
}
ll ans = (get(y) - get(x-1) + MOD) % MOD;
printf("%lld\n", ans);
}
int main(){
int t;
sd(t);
while(t--) solve();
return 0;
}
| 21.258503 | 97 | 0.52608 | VastoLorde95 |
4d902c774febb89d40c247919b0b3fb95f63f778 | 584 | cpp | C++ | BOJ_CPP/22477.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/22477.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/22477.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int n, m;
cin >> n;
string s;
map<string, int> mp;
for (int i = 0; i < n; ++i) {
cin >> s;
mp[s] = 1;
}
cin >> m;
bool flag = 1;
for (int i = 0; i < m; ++i) {
cin >> s;
if (mp.count(s)) {
cout << (flag ? "Opened by " : "Closed by ");
flag = !flag;
} else {
cout << "Unknown ";
}
cout << s << "\n";
}
return 0;
} | 20.137931 | 63 | 0.409247 | tnsgh9603 |
4d94f198f30b3eafebb4779688b9ef5713d30f9a | 406 | cpp | C++ | luogu/c++/P5727.cpp | Crabtime/cpp-project | 1d79aab95be18d704e431efc5eff94d11e6096d3 | [
"CC0-1.0"
] | 1 | 2020-08-09T01:35:17.000Z | 2020-08-09T01:35:17.000Z | luogu/c++/P5727.cpp | Crabtime/cpp-project | 1d79aab95be18d704e431efc5eff94d11e6096d3 | [
"CC0-1.0"
] | null | null | null | luogu/c++/P5727.cpp | Crabtime/cpp-project | 1d79aab95be18d704e431efc5eff94d11e6096d3 | [
"CC0-1.0"
] | null | null | null | #include<iostream>
#pragma GCC optimize(3)
using namespace std;
void bingbao(long long n)
{
if (n == 1)
{
std:: cout << 1 << ' ';
return;
}
if (n%2 == 0)
{
bingbao(n/2);
}
else
{
bingbao(n*3+1);
}
std:: cout << n << ' ';
}
int main()
{
long long n;
std:: cin >> n;
bingbao(n);
return 0;
} | 14 | 32 | 0.399015 | Crabtime |
4d97a8916b1bf346f3c89869d6f1819a06d42ab7 | 648 | hh | C++ | include/ThreadRun.hh | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | null | null | null | include/ThreadRun.hh | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | null | null | null | include/ThreadRun.hh | phirippu/instrument-simulation | 0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8 | [
"CC-BY-4.0"
] | 1 | 2021-03-08T16:01:14.000Z | 2021-03-08T16:01:14.000Z | //
// Created by phil on 5/17/18.
//
#ifndef THREADRUN_HH
#define THREADRUN_HH
#include <G4Run.hh>
#include <map>
#include <G4ToolsAnalysisManager.hh>
#include "SensitiveDetector.hh"
#include "DetectorConstruction.hh"
class ThreadRun : public G4Run {
public:
explicit ThreadRun(const G4String &rootFileName);
~ThreadRun() override;
void RecordEvent(const G4Event *) override;
void Merge(const G4Run *) override;
G4ToolsAnalysisManager *analysisManager = nullptr;
private:
std::vector<SensitiveDetector *> sdCollection;
const DetectorConstruction *dConstruction;
G4int iNtupleIdx;
};
#endif //THREADRUN_HH
| 18.514286 | 54 | 0.736111 | phirippu |
4d99cffcb437d087031789496c36ba21685621ea | 5,851 | cc | C++ | jjOpenCLBasic.cc | ied206/NPKICracker | 72052835fd97286525051036d6148a55bf594f72 | [
"MIT"
] | 10 | 2015-12-05T02:56:04.000Z | 2020-05-28T02:41:32.000Z | jjOpenCLBasic.cc | ied206/NPKICracker | 72052835fd97286525051036d6148a55bf594f72 | [
"MIT"
] | null | null | null | jjOpenCLBasic.cc | ied206/NPKICracker | 72052835fd97286525051036d6148a55bf594f72 | [
"MIT"
] | 4 | 2015-11-27T13:23:51.000Z | 2021-07-22T08:32:48.000Z | #include "jjOpenCLBasic.hpp"
cl_context createContext()
{
cl_int errNum;
JJ_CL_PLATFORMS platformsInformations;
cl_context context = NULL;
errNum = jjOpenCLPlatformInitialize(&platformsInformations, true);
cl_context_properties contextProperties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)platformsInformations.platforms[0].platformID,
0
};
context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, NULL, NULL, &errNum);
if(errNum != CL_SUCCESS)
{
cout << "This system has no OpenCL available GPU device" << endl;
context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
if(errNum != CL_SUCCESS)
{
cout << "This system has no OpenCL available CPU device" << endl;
cout << "This system isn't available to run this application" << endl;
exit(1);
}
else{
cout << "Application find OpenCL CPU device. Runnig on it...\n\n" << endl;
}
}
else{
cout << "Application find OpenCL GPU device. Running on it...\n\n" << endl;
}
return context;
}
cl_command_queue createCommandqueue(cl_context context, cl_device_id* device)
{
cl_int errNum;
cl_device_id* devices;
cl_command_queue commandQueue = NULL;
size_t deviceBufferSize = -1;
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &deviceBufferSize);
if(errNum != CL_SUCCESS)
{
cerr << "Failed to call clGetContextInfo(..., CL_CONTEXT_DEVICES, ...)" << endl;
exit(1);
}
if(deviceBufferSize <= 0)
{
cerr << "No available device" << endl;
exit(1);
}
devices = new cl_device_id[deviceBufferSize / sizeof(cl_device_id)];
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, deviceBufferSize, devices, NULL);
if(errNum != CL_SUCCESS)
{
cerr << "Failed to get device id" << endl;
exit(1);
}
commandQueue = clCreateCommandQueue(context, devices[0], 0, NULL);
if(commandQueue == NULL)
{
cerr << "Failed to create command queue for device 0" << endl;
exit(1);
}
*device = devices[0];
delete [] devices;
return commandQueue;
}
cl_program CreateProgram(cl_context context, cl_device_id device, const char* filename)
{
cl_int errNum;
cl_program program;
ifstream kernelFile(filename, ios::in);
ostringstream oss;
if(!kernelFile.is_open())
{
cerr << "kernel file " << filename << " isn't available to open." << endl;
exit(1);
}
oss << kernelFile.rdbuf();
string srcStdStr = oss.str();
const char* srcStr = srcStdStr.c_str();
program = clCreateProgramWithSource(context, 1, (const char**)&srcStr, NULL, &errNum);
if((errNum != CL_SUCCESS) || program == NULL)
{
cerr << "Failed to create OpenCL Program" << endl;
exit(1);
}
errNum = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if(errNum != CL_SUCCESS)
{
char *buildLog;
size_t errLength;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, (size_t)NULL, NULL, &errLength);
buildLog = (char*)malloc(sizeof(char) * (errLength + 1));
errNum = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(char)*errLength, buildLog, NULL);
cerr << "OpenCL kernel build Error! Errors are here:\nclGetProgramBuildInfo return errorcode: " << errNum << " is";
switch(errNum){
case CL_INVALID_DEVICE: cerr << "CL_INVALID_DEVICE. Device is not valid with this program object." << endl; break;
case CL_INVALID_VALUE: cerr << "CL_INVALID_VALUE. Parameter to clBuildProgram was wrong." << endl
<< "If pfn_notify is NULL and user_data is not NULL, this can happen." << endl
<< "device_list is NULL and num_devices is greater than 0, or device_list is not NULL and num_devices is zero, this can also happen" << endl;break;
case CL_INVALID_PROGRAM: cerr << "CL_INVALID_PROGRAM. Program object is not valid" << endl; break;
case CL_INVALID_BINARY: cerr << "CL_INVALID_BINARY. Given device_list is not matching binary given to clCreateProgramWithBinary, this can happen" << endl; break;
case CL_INVALID_BUILD_OPTIONS: cerr << "CL_INVALID_BUILD_OPTIONS. Build option string given to clBuildProgram's options argument is wrong." << endl; break;
case CL_INVALID_OPERATION: cerr << "CL_INVALID_OPERATION. Previous clBuildProgram call has not ended or kernel object is attatching to program object." << endl; break;
case CL_COMPILER_NOT_AVAILABLE: cerr <<"CL_COMPILER_NOT_AVAILABLE" << endl; break;
case CL_OUT_OF_RESOURCES: cerr << "CL_OUT_OF_RESOURCES" << endl; break;
case CL_OUT_OF_HOST_MEMORY: cerr << "CL_OUT_OF_HOST_MEMORY" << endl; break;
default: break;
}
cerr << endl;
cerr << buildLog << endl;
free(buildLog);
clReleaseProgram(program);
exit(1);
}
cout << "OpenCL program successfully built" << endl;
return program;
}
cl_kernel CreateKernel(cl_program program, const char* kernel_name)
{
cl_int errNum;
cl_kernel kernel = NULL;
kernel = clCreateKernel(program, kernel_name, &errNum);
if(errNum != CL_SUCCESS){
cerr << "Error code is this: " << errNum << endl;
switch(errNum){
case CL_INVALID_PROGRAM: cerr << "CL_INVALID_PROGRAM. Program object given first argument to CreateKernel is wrong." << endl; break;
case CL_INVALID_PROGRAM_EXECUTABLE: cerr << "CL_INVALID_PROGRAM_EXECUTABLE." << endl; break;
case CL_INVALID_KERNEL: cerr << "CL_INVALID_KERNEL_NAME. Kernel name given second argument CreateKernel is wrong." << endl; break;
case CL_INVALID_KERNEL_DEFINITION: cerr << "CL_INVALID_KERNEL_DEFINITION. Kernel source code is not suitable for this OpenCL device" << endl; break;
case CL_INVALID_VALUE: cerr << "CL_INVALID_VALUE. Are you sure you have not given NULL as second argument to CreateKernel?" << endl; break;
case CL_OUT_OF_HOST_MEMORY: cerr << "CL_OUT_OF_HOST_MEMORY. There is no suitable memory for kernel memory allocation" << endl; break;
default: break;
}
exit(1);
}
cout << "OpenCL kernel successfully built" << endl;
return kernel;
} | 39.802721 | 170 | 0.727055 | ied206 |
4d9b94c441c12910416148b948cea09e639df2a9 | 2,572 | cpp | C++ | src/Algorithm/bellman_ford.cpp | petuzk/PAMSI-2 | 473e7e57823a01de3464c0cac9f795f024c1c9bf | [
"MIT"
] | null | null | null | src/Algorithm/bellman_ford.cpp | petuzk/PAMSI-2 | 473e7e57823a01de3464c0cac9f795f024c1c9bf | [
"MIT"
] | null | null | null | src/Algorithm/bellman_ford.cpp | petuzk/PAMSI-2 | 473e7e57823a01de3464c0cac9f795f024c1c9bf | [
"MIT"
] | null | null | null | #include "inc/Algorithm/bellman_ford.hpp"
template <typename VIT, typename EIT>
void bellman_ford(const IVGraph<VIT, EIT>& graph, IVGraph<VIT, EIT>& tree, const Vertex<VIT>* start, EIT zero_cost, EIT max_cost) {
// Pobierz tablicę wierzchołków
const auto graph_vertices = graph.vertices();
std::size_t num_vertices = graph_vertices.size();
// Zaalokuj pamięć dla nowych krawędzi i wierzchołków
tree.preallocateForVertices(num_vertices);
tree.preallocateForEdges(num_vertices - 1);
// Utwórz tablicę wierzchołków specjalnych
BFVertex<VIT, EIT>* vertices = new BFVertex<VIT, EIT>[num_vertices];
// Dodaj wszystkie wierzchołki do drzewa i zainicjalizuj tablicę
for (std::size_t i = 0; i < num_vertices; i++) {
const Vertex<VIT>* gv = graph_vertices[i];
const Vertex<VIT>* tv = tree.insertVertex(gv->getItem());
vertices[i] = {
tv, nullptr,
gv == start ? zero_cost : max_cost // w. początkowy ma wagę 0, pozostałe - "nieskończoność"
};
}
// Pobierz tablicę krawędzi
const auto graph_edges = graph.edges();
std::size_t num_edges = graph_edges.size();
// Utwórz tablicę krawędzi specjalnych
BFEdge<VIT, EIT>* edges = new BFEdge<VIT, EIT>[num_edges];
// Dodaj krawędzie grafu do tablicy
for (std::size_t i = 0; i < num_edges; i++) {
const Edge<VIT, EIT>* ge = graph_edges[i];
edges[i] = {
vertices + dynamic_cast<const IndexableVertex<VIT, EIT>*>(ge->getV())->getIndex(),
vertices + dynamic_cast<const IndexableVertex<VIT, EIT>*>(ge->getW())->getIndex(),
ge->getItem()
};
}
// Wykonaj relaksację krawędzi
for (std::size_t i = 1; i < num_vertices; i++) {
for (std::size_t j = 0; j < num_edges; j++) {
BFEdge<VIT, EIT>& e = edges[j];
BFVertex<VIT, EIT>* min_v = e.v;
BFVertex<VIT, EIT>* max_v = e.w;
// Wybierz min_v i max_v
if (max_v->cost < min_v->cost) {
min_v = e.w;
max_v = e.v;
}
// Jeśli waga wierzchołka min_v nie jest "nieskończonością"
if (min_v->cost != max_cost) {
EIT new_cost = min_v->cost + e.cost;
// Jeśli nowa droga jest krótsza
if (new_cost < max_v->cost) {
// Zaktualizuj max_v
max_v->cost = new_cost;
max_v->predecessor = min_v;
}
}
}
}
// Zapisz krawędzie do drzewa
for (std::size_t i = 0; i < num_vertices; i++) {
const BFVertex<VIT, EIT>& v = vertices[i];
if (v.predecessor)
tree.insertEdge(v.tree_vertex, v.predecessor->tree_vertex, v.cost - v.predecessor->cost);
}
delete[] edges;
delete[] vertices;
}
template void bellman_ford(const IVGraph<int, int>&, IVGraph<int, int>&, const Vertex<int>*, int, int); | 30.987952 | 131 | 0.670684 | petuzk |
4da00025d02c6016049b4ae806c28fd07ea05119 | 1,139 | cpp | C++ | src/mesh.cpp | mfirmin/c5sc | 66b06061bf0f1a53c435f4109cd7fa636466c353 | [
"MIT"
] | 1 | 2015-01-05T07:49:33.000Z | 2015-01-05T07:49:33.000Z | src/mesh.cpp | mfirmin/c5sc | 66b06061bf0f1a53c435f4109cd7fa636466c353 | [
"MIT"
] | null | null | null | src/mesh.cpp | mfirmin/c5sc | 66b06061bf0f1a53c435f4109cd7fa636466c353 | [
"MIT"
] | null | null | null |
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/multi/geometries/multi_point.hpp>
#include <iostream>
#include <vector>
#include "mesh.h"
#include "component.h"
#include "vertex.h"
void Mesh::createHull(int c_num)
{
using boost::geometry::append;
using boost::geometry::make;
using boost::geometry::model::d2::point_xy;
boost::geometry::model::multi_point<point_xy<dReal> > pointset;
for (int i = 0; i < components.at(c_num)->faces.size(); i++)
{
for (std::vector<int>::iterator vertIter = components.at(c_num)->faces.at(i)->vertices.begin(); vertIter != components.at(c_num)->faces.at(i)->vertices.end(); vertIter++)
{
append(pointset, make<point_xy<dReal> >(vertexPalette.at(*vertIter)->pos.x, vertexPalette.at(*vertIter)->pos.y));
}
}
boost::geometry::model::multi_point<point_xy<dReal> > hull;
boost::geometry::convex_hull(pointset, hull);
for (std::vector<point_xy<dReal> >::size_type i = 0; i < hull.size(); i++)
{
components.at(c_num)->hull.push_back(std::make_pair(boost::geometry::get<0>(hull[i]), boost::geometry::get<1>(hull[i])));
}
}
| 27.780488 | 172 | 0.697981 | mfirmin |
4da1d3528ae1af961618792d29711b3ad89f55ff | 2,352 | cpp | C++ | src/algos/tree.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | 5 | 2016-03-17T07:02:11.000Z | 2021-12-12T14:43:58.000Z | src/algos/tree.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | null | null | null | src/algos/tree.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | 3 | 2015-10-29T15:21:01.000Z | 2020-11-25T09:41:21.000Z | /*
* tree.cpp
*
* Created on: 17.09.2013
* Author: Ralph
*/
#include "tree.h"
#include <QDebug>
Tree::Tree( int id, float value ) :
m_id( id ),
m_value( value ),
m_texturePosition( QVector3D( 0, 0, 0 ) ),
m_parent( 0 )
{
QColor color1( 255, 0, 0 );
QColor color2( 128, 128, 128 );
m_colors.push_back( color1 );
m_colors.push_back( color2 );
m_colors.push_back( color2 );
m_colors.push_back( color2 );
}
Tree::~Tree()
{
}
Tree* Tree::getParent()
{
return m_parent;
}
void Tree::setParent( Tree* parent )
{
m_parent = parent;
}
void Tree::addChild( Tree* child )
{
m_children.push_back( child );
}
QList<Tree*> Tree::getChildren()
{
return m_children;
}
QColor Tree::getColor( int id )
{
return m_colors[id];
}
void Tree::setColor( int id, QColor& color, bool propagateUp, bool propagateDown )
{
m_colors[id] = color;
if ( propagateUp && m_parent )
{
m_parent->setColor( id, color, true, false );
}
if ( propagateDown )
{
for ( int i = 0; i < m_children.size(); ++i )
{
m_children[i]->setColor( id, color, false, true );
}
}
}
void Tree::setColor( int id, int colorId, QColor& color )
{
if ( id == m_id )
{
m_colors[colorId] = color;
for ( int i = 0; i < m_children.size(); ++i )
{
m_children[i]->setColor( m_children[i]->getId(), colorId, color );
}
}
else
{
for ( int i = 0; i < m_children.size(); ++i )
{
m_children[i]->setColor( id, colorId, color );
}
}
}
int Tree::getId()
{
return m_id;
}
float Tree::getValue()
{
return m_value;
}
void Tree::setValue( float value )
{
m_value = value;
}
int Tree::getNumLeaves()
{
int numLeaves = 0;
if ( m_children.size() > 0 )
{
for ( int i = 0; i < m_children.size(); ++i )
{
numLeaves += m_children[i]->getNumLeaves();
}
}
else
{
numLeaves = 1;
}
return numLeaves;
}
QVector3D Tree::getTexturePosition()
{
return m_texturePosition;
}
void Tree::setTexturePosition( QVector3D value )
{
m_texturePosition = value;
}
| 17.684211 | 83 | 0.520833 | mhough |
4da20923bcfa8a49967d6d80ae93d584b57e07d4 | 3,425 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Permissions.FileIOPermission/CPP/remarks.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Permissions.FileIOPermission/CPP/remarks.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Permissions.FileIOPermission/CPP/remarks.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
using namespace System;
using namespace System::Security;
using namespace System::Security::Permissions;
int main()
{
try
{
FileIOPermission^ fileIOPerm1;
fileIOPerm1 = gcnew FileIOPermission(PermissionState::Unrestricted);
// Tests for: SetPathList(FileIOPermissionAccess,String)
// Test the Read list
fileIOPerm1->SetPathList(FileIOPermissionAccess::Read, "C:\\documents");
Console::WriteLine("Read access before SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Read))
{
Console::WriteLine("\t" + path);
}
//<Snippet12>
fileIOPerm1->SetPathList(FileIOPermissionAccess::Read, "C:\\temp");
//</Snippet12>
Console::WriteLine("Read access after SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Read))
{
Console::WriteLine("\t" + path);
}
// Test the Write list
fileIOPerm1->SetPathList(FileIOPermissionAccess::Write, "C:\\temp");
Console::WriteLine("Write access before SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Write))
{
Console::WriteLine("\t" + path);
}
//<Snippet13>
fileIOPerm1->SetPathList(FileIOPermissionAccess::Write, "C:\\documents");
//</Snippet13>
Console::WriteLine("Write access after SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Write))
{
Console::WriteLine("\t" + path);
}
// Tests for: SetPathList(FileIOPermissionAccess,String[])
// Test the Read list
fileIOPerm1->SetPathList(FileIOPermissionAccess::Read, gcnew array<String^> {"C:\\pictures", "C:\\music"});
Console::WriteLine("Read access before SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Read))
{
Console::WriteLine("\t" + path);
}
//<Snippet14>
fileIOPerm1->SetPathList(FileIOPermissionAccess::Read, gcnew array<String^> {"C:\\temp", "C:\\Documents"});
//</Snippet14>
Console::WriteLine("Read access after SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Read))
{
Console::WriteLine("\t" + path);
}
// Test the Write list
fileIOPerm1->SetPathList(FileIOPermissionAccess::Write, gcnew array<String^> {"C:\\temp", "C:\\Documents"});
Console::WriteLine("Write access before SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Write))
{
Console::WriteLine("\t" + path);
}
//<Snippet15>
fileIOPerm1->SetPathList(FileIOPermissionAccess::Write, gcnew array<String^> {"C:\\pictures", "C:\\music"});
//</Snippet15>
Console::WriteLine("Write access after SetPathList = ");
for each (String^ path in fileIOPerm1->GetPathList(FileIOPermissionAccess::Write))
{
Console::WriteLine("\t" + path);
}
}
catch (Exception^ ex)
{
Console::WriteLine(ex->Message);
}
} | 36.052632 | 117 | 0.597372 | hamarb123 |
4da2ad46b72c9c6a89fba8cbf75af5eca1e0d36a | 566 | hxx | C++ | Legolas/Matrix/tst/ArbitraryPrecision/APFloat.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/tst/ArbitraryPrecision/APFloat.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/tst/ArbitraryPrecision/APFloat.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | /**
* project DESCARTES
*
* @file APFloat.hxx
*
* @author Laurent PLAGNE
* @date june 2004 - january 2005
*
* @par Modifications
* - author date object
*
* (c) Copyright EDF R&D - CEA 2001-2005
*/
#ifndef __LEGOLAS_APFLOAT_HXX__
#define __LEGOLAS_APFLOAT_HXX__
#include "apfloat.h"
#include "apcplx.h"
template <int PRECISION>
class APFloat : public apfloat
{
public:
APFloat( void ):apfloat(0,PRECISION){};
template <class SOURCE>
APFloat(const SOURCE & source):apfloat(source){
(*this).prec(PRECISION);
};
};
#endif
| 15.722222 | 49 | 0.660777 | LaurentPlagne |
4da474db05c2e6b20c92184ccd98bc28b6686d82 | 415 | hpp | C++ | Etaler/Algorithms/Anomaly.hpp | mewpull/Etaler | fcc88a96ec05af34d7c1717beef0e35671015152 | [
"BSD-3-Clause"
] | 1 | 2020-04-19T17:23:49.000Z | 2020-04-19T17:23:49.000Z | Etaler/Algorithms/Anomaly.hpp | mewpull/Etaler | fcc88a96ec05af34d7c1717beef0e35671015152 | [
"BSD-3-Clause"
] | null | null | null | Etaler/Algorithms/Anomaly.hpp | mewpull/Etaler | fcc88a96ec05af34d7c1717beef0e35671015152 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <Etaler/Core/Tensor.hpp>
namespace et
{
static float anomaly(const Tensor& pred, const Tensor& real)
{
et_assert(real.dtype() == DType::Bool);
et_assert(pred.dtype() == DType::Bool);
et_assert(real.shape() == pred.shape());
Tensor should_predict = sum(real);
Tensor not_predicted = sum(!pred && real).cast(DType::Float);
return (not_predicted/should_predict).toHost<float>()[0];
}
} | 21.842105 | 62 | 0.703614 | mewpull |
4da85f9f4aeae3f72f131919678d630c30d6e6cf | 6,408 | cpp | C++ | QP/v5.4.2/qpcpp/examples/win32/comp_qm/alarm.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/win32/comp_qm/alarm.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/win32/comp_qm/alarm.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | //****************************************************************************
// Model: comp.qm
// File: ./alarm.cpp
//
// This code has been generated by QM tool (see state-machine.com/qm).
// DO NOT EDIT THIS FILE MANUALLY. All your changes will be lost.
//
// This program is open source 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.
//
// 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.
//****************************************************************************
//${.::alarm.cpp} ............................................................
#include "qpcpp.h"
#include "bsp.h"
#include "alarm.h"
#include "clock.h"
Q_DEFINE_THIS_FILE
// Alarm component --------------------
//${Components::Alarm} .......................................................
//${Components::Alarm::Alarm} ................................................
Alarm::Alarm()
: QMsm(Q_STATE_CAST(&Alarm::initial))
{}
//${Components::Alarm::SM} ...................................................
QP::QState Alarm::initial(Alarm * const me, QP::QEvt const * const e) {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&off_s,
{
Q_ACTION_CAST(&off_e), // entry
Q_ACTION_CAST(0) // zero terminator
}
};
// ${Components::Alarm::SM::initial}
me->m_alarm_time = 12U*60U;
(void)e; // unused parameter
return QM_TRAN_INIT(&tatbl_);
}
//${Components::Alarm::SM::off} ..............................................
QP::QMState const Alarm::off_s = {
static_cast<QP::QMState const *>(0), // superstate (top)
Q_STATE_CAST(&off),
Q_ACTION_CAST(&off_e),
Q_ACTION_CAST(&off_x),
Q_ACTION_CAST(0) // no intitial tran.
};
// ${Components::Alarm::SM::off}
QP::QState Alarm::off_e(Alarm * const me) {
// while in the off state, the alarm is kept in decimal format
me->m_alarm_time = (me->m_alarm_time/60)*100 + me->m_alarm_time%60;
BSP_showTime24H("*** Alarm OFF ", me->m_alarm_time, 100U);
return QM_ENTRY(&off_s);
}
// ${Components::Alarm::SM::off}
QP::QState Alarm::off_x(Alarm * const me) {
// upon exit, the alarm is converted to binary format
me->m_alarm_time = (me->m_alarm_time/100U)*60U + me->m_alarm_time%100U;
return QM_EXIT(&off_s);
}
// ${Components::Alarm::SM::off}
QP::QState Alarm::off(Alarm * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${Components::Alarm::SM::off::ALARM_ON}
case ALARM_ON_SIG: {
// ${Components::Alarm::SM::off::ALARM_ON::[alarminrange?]}
if ((me->m_alarm_time / 100U < 24U)
&& (me->m_alarm_time % 100U < 60U))
{
static struct {
QP::QMState const *target;
QP::QActionHandler act[3];
} const tatbl_ = { // transition-action table
&on_s,
{
Q_ACTION_CAST(&off_x), // exit
Q_ACTION_CAST(&on_e), // entry
Q_ACTION_CAST(0) // zero terminator
}
};
status_ = QM_TRAN(&tatbl_);
}
// ${Components::Alarm::SM::off::ALARM_ON::[else]}
else {
me->m_alarm_time = 0U;
BSP_showTime24H("*** Alarm reset", me->m_alarm_time, 100U);
status_ = QM_HANDLED();
}
break;
}
// ${Components::Alarm::SM::off::ALARM_SET}
case ALARM_SET_SIG: {
// while setting, the alarm is kept in decimal format
me->m_alarm_time =
(10U * me->m_alarm_time + Q_EVT_CAST(SetEvt)->digit) % 10000U;
BSP_showTime24H("*** Alarm reset ", me->m_alarm_time, 100U);
status_ = QM_HANDLED();
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
return status_;
}
//${Components::Alarm::SM::on} ...............................................
QP::QMState const Alarm::on_s = {
static_cast<QP::QMState const *>(0), // superstate (top)
Q_STATE_CAST(&on),
Q_ACTION_CAST(&on_e),
Q_ACTION_CAST(0), // no exit action
Q_ACTION_CAST(0) // no intitial tran.
};
// ${Components::Alarm::SM::on}
QP::QState Alarm::on_e(Alarm * const me) {
BSP_showTime24H("*** Alarm ON ", me->m_alarm_time, 60U);
return QM_ENTRY(&on_s);
}
// ${Components::Alarm::SM::on}
QP::QState Alarm::on(Alarm * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${Components::Alarm::SM::on::ALARM_OFF}
case ALARM_OFF_SIG: {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&off_s,
{
Q_ACTION_CAST(&off_e), // entry
Q_ACTION_CAST(0) // zero terminator
}
};
status_ = QM_TRAN(&tatbl_);
break;
}
// ${Components::Alarm::SM::on::ALARM_SET}
case ALARM_SET_SIG: {
BSP_showMsg("*** Cannot set Alarm when it is ON");
status_ = QM_HANDLED();
break;
}
// ${Components::Alarm::SM::on::TIME}
case TIME_SIG: {
// ${Components::Alarm::SM::on::TIME::[Q_EVT_CAST(TimeEvt)->current_ti~}
if (Q_EVT_CAST(TimeEvt)->current_time == me->m_alarm_time) {
BSP_showMsg("ALARM!!!");
// asynchronously post the event to the container AO
APP_alarmClock->POST(Q_NEW(QEvt, ALARM_SIG), this);
status_ = QM_HANDLED();
}
else {
status_ = QM_UNHANDLED();
}
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
(void)me; // avoid compiler warning in case 'me' is not used
return status_;
}
| 35.798883 | 84 | 0.50515 | hyller |
4dad07d32ef5afd291098b79cbf7d4e087488044 | 747 | hpp | C++ | test/data-tests/include/common.hpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 4,526 | 2015-01-01T15:31:00.000Z | 2022-03-31T17:33:49.000Z | test/data-tests/include/common.hpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 4,497 | 2015-01-01T15:29:12.000Z | 2022-03-31T19:19:35.000Z | test/data-tests/include/common.hpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 3,023 | 2015-01-01T18:40:53.000Z | 2022-03-30T13:30:46.000Z | #ifndef COMMON_HPP
#define COMMON_HPP
#include <osmium/index/map/dummy.hpp>
#include <osmium/index/map/sparse_mem_array.hpp>
#include <osmium/geom/wkt.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/io/xml_input.hpp>
#include <osmium/visitor.hpp>
using index_neg_type = osmium::index::map::Dummy<osmium::unsigned_object_id_type, osmium::Location>;
using index_pos_type = osmium::index::map::SparseMemArray<osmium::unsigned_object_id_type, osmium::Location>;
using location_handler_type = osmium::handler::NodeLocationsForWays<index_pos_type, index_neg_type>;
#include "check_basics_handler.hpp"
#include "check_wkt_handler.hpp"
#include "testdata-testcases.hpp"
#endif // COMMON_HPP
| 32.478261 | 109 | 0.803213 | zhaitianduo |
4dae1d24938f250fb960ddb05d89a72f274f2652 | 5,755 | cpp | C++ | src/FeedController.cpp | JadedCtrl/rifen | eddbc45d987abe6524715a25ed56e09e8c349300 | [
"MIT"
] | 4 | 2021-03-22T06:38:33.000Z | 2021-03-23T04:57:44.000Z | src/FeedController.cpp | JadedCtrl/rifen | eddbc45d987abe6524715a25ed56e09e8c349300 | [
"MIT"
] | 12 | 2021-02-25T22:13:36.000Z | 2021-05-03T01:21:50.000Z | src/FeedController.cpp | JadedCtrl/rifen | eddbc45d987abe6524715a25ed56e09e8c349300 | [
"MIT"
] | 1 | 2021-10-11T06:40:06.000Z | 2021-10-11T06:40:06.000Z | /*
* Copyright 2020, Jaidyn Levesque <[email protected]>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "FeedController.h"
#include <iostream>
#include <Catalog.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Message.h>
#include <MessageRunner.h>
#include <Notification.h>
#include <StringList.h>
#include "Daemon.h"
#include "Entry.h"
#include "Preferences.h"
#include "SourceManager.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "FeedController"
FeedController::FeedController()
:
fEnqueuedTotal(0),
fMainThread(find_thread(NULL)),
fDownloadThread(0),
fParseThread(0),
fDownloadQueue(new BObjectList<Feed>()),
fMessageRunner(new BMessageRunner(be_app, BMessage(kControllerCheck), 50000, -1))
{
fDownloadThread = spawn_thread(_DownloadLoop, "here, eat this",
B_NORMAL_PRIORITY, &fMainThread);
fParseThread = spawn_thread(_ParseLoop, "oki tnx nomnomnom",
B_NORMAL_PRIORITY, &fMainThread);
resume_thread(fDownloadThread);
resume_thread(fParseThread);
}
FeedController::~FeedController()
{
kill_thread(fDownloadThread);
kill_thread(fParseThread);
}
void
FeedController::MessageReceived(BMessage* msg)
{
switch (msg->what)
{
case kEnqueueFeed:
{
int i = 0;
BString feedID;
BString feedSource;
ssize_t size = sizeof(Feed);
while (msg->HasString("feed_identifiers", i)) {
msg->FindString("feed_identifiers", i, &feedID);
msg->FindString("feed_sources", i, &feedSource);
Feed* feed = SourceManager::GetFeed(feedID.String(),
feedSource.String());
fDownloadQueue->AddItem(feed);
_SendProgress();
i++;
}
fMessageRunner->SetCount(-1);
break;
}
case kUpdateSubscribed:
{
BObjectList<Feed> list = SourceManager::Feeds();
fDownloadQueue->AddList(&list);
_SendProgress();
break;
}
case kClearQueue:
{
fDownloadQueue->MakeEmpty();
break;
}
case kControllerCheck:
{
_ProcessQueueItem();
_ReceiveStatus();
break;
}
}
}
void
FeedController::_SendProgress()
{
int32 dqCount = fDownloadQueue->CountItems();
if (fEnqueuedTotal < dqCount)
fEnqueuedTotal = dqCount;
BMessage progress(kProgress);
progress.AddInt32("total", fEnqueuedTotal);
progress.AddInt32("current", fEnqueuedTotal - dqCount);
be_app->MessageReceived(&progress);
if (dqCount == 0)
fEnqueuedTotal = 0;
}
void
FeedController::_ProcessQueueItem()
{
if (has_data(fDownloadThread) && !fDownloadQueue->IsEmpty()) {
Feed* feed = fDownloadQueue->ItemAt(0);
fDownloadQueue->RemoveItemAt(0);
send_data(fDownloadThread, 0, (void*)feed, sizeof(Feed));
BMessage downloadInit = BMessage(kDownloadStart);
downloadInit.AddString("feed_name", feed->Title());
downloadInit.AddString("feed_url", feed->Url().UrlString());
((App*)be_app)->MessageReceived(&downloadInit);
}
}
void
FeedController::_ReceiveStatus()
{
thread_id sender;
while (has_data(find_thread(NULL))) {
Feed* feedBuffer = (Feed*)malloc(sizeof(Feed));
int32 code = receive_data(&sender, (void*)feedBuffer, sizeof(Feed));
switch (code)
{
case kDownloadComplete:
{
BMessage complete = BMessage(kDownloadComplete);
complete.AddString("feed_name", feedBuffer->Title());
complete.AddString("feed_url", feedBuffer->Url().UrlString());
((App*)be_app)->MessageReceived(&complete);
send_data(fParseThread, 0, (void*)feedBuffer, sizeof(Feed));
break;
}
case kDownloadFail:
{
BMessage failure = BMessage(kDownloadFail);
failure.AddString("feed_name", feedBuffer->Title());
failure.AddString("feed_url",
feedBuffer->Url().UrlString());
((App*)be_app)->MessageReceived(&failure);
_SendProgress();
break;
}
case kParseFail:
{
BMessage failure = BMessage(kParseFail);
failure.AddString("feed_name", feedBuffer->Title());
failure.AddString("feed_url", feedBuffer->Url().UrlString());
((App*)be_app)->MessageReceived(&failure);
_SendProgress();
break;
}
// If parse was successful, the code is the amount of new entries
default:
BMessage complete = BMessage(kParseComplete);
complete.AddString("feed_name", feedBuffer->Title());
complete.AddString("feed_url", feedBuffer->Url().UrlString());
complete.AddInt32("entry_count", code);
((App*)be_app)->MessageReceived(&complete);
_SendProgress();
break;
}
free(feedBuffer);
}
}
int32
FeedController::_DownloadLoop(void* data)
{
thread_id main = *((thread_id*)data);
thread_id sender;
while (true) {
Feed* feedBuffer = (Feed*)malloc(sizeof(Feed));
receive_data(&sender, (void*)feedBuffer, sizeof(Feed));
std::cout << B_TRANSLATE("Downloading feed from ")
<< feedBuffer->Url().UrlString() << "…\n";
if (SourceManager::Fetch(feedBuffer)) {
send_data(main, kDownloadComplete, (void*)feedBuffer, sizeof(Feed));
}
else {
send_data(main, kDownloadFail, (void*)feedBuffer, sizeof(Feed));
}
free(feedBuffer);
}
return 0;
}
int32
FeedController::_ParseLoop(void* data)
{
thread_id main = *((thread_id*)data);
thread_id sender;
while (true) {
Feed* feedBuffer = (Feed*)malloc(sizeof(Feed));
receive_data(&sender, (void*)feedBuffer, sizeof(Feed));
BObjectList<Entry> entries;
int32 entriesCount = 0;
BString feedTitle;
BUrl feedUrl = feedBuffer->Url();
SourceManager::Parse(feedBuffer);
entries = feedBuffer->NewEntries();
entriesCount = entries.CountItems();
feedTitle = feedBuffer->Title();
for (int i = 0; i < entriesCount; i++)
entries.ItemAt(i)->Filetize(((App*)be_app)->fPreferences->EntryDir());
entries.MakeEmpty();
SourceManager::EditFeed(feedBuffer);
send_data(main, entriesCount, (void*)feedBuffer, sizeof(Feed));
free(feedBuffer);
}
return 0;
}
| 23.205645 | 82 | 0.699913 | JadedCtrl |
4db0b6eeb82823b53363ac6c2a5cd5b8bce8c6d4 | 4,859 | cpp | C++ | toonz/sources/stdfx/igs_perlin_noise.cpp | wofogen/tahoma2d | ce5a89a7b1027b2c1769accb91184a2ee6442b4d | [
"BSD-3-Clause"
] | 36 | 2020-05-18T22:26:35.000Z | 2022-02-19T00:09:25.000Z | toonz/sources/stdfx/igs_perlin_noise.cpp | LibrePhone/opentoonz | cb95a29db4c47ab1f36a6e85a039c4c9c901f88a | [
"BSD-3-Clause"
] | 22 | 2017-03-16T18:52:36.000Z | 2019-09-09T06:02:53.000Z | toonz/sources/stdfx/igs_perlin_noise.cpp | LibrePhone/opentoonz | cb95a29db4c47ab1f36a6e85a039c4c9c901f88a | [
"BSD-3-Clause"
] | 9 | 2019-05-27T02:48:16.000Z | 2022-03-29T12:32:04.000Z | #include <cmath> // pow()
#include "iwa_noise1234.h"
namespace {
double perlin_noise_3d_(const double x, const double y, const double z,
const int octaves_start // 0<=
,
const int octaves_end // 0<=
,
const double persistence // Not 0
// 1/4 or 1/2 or 1/sqrt(3) or 1/sqrt(2) or 1 or ...
) {
double total = 0;
Noise1234 pn;
for (int ii = octaves_start; ii <= octaves_end; ++ii) {
const double frequency = pow(2.0, ii); // 1,2,4,8...
const double amplitude = pow(persistence, ii);
total += pn.noise(x * frequency, y * frequency, z * frequency) * amplitude;
}
return total;
}
double perlin_noise_minmax_(const int octaves_start // 0<=
,
const int octaves_end // 0<=
,
const double persistence // Not 0
// 1/4 or 1/2 or 1/sqrt(3) or 1/sqrt(2) or 1 or ...
) {
double total = 0;
for (int ii = octaves_start; ii <= octaves_end; ++ii) {
total += pow(persistence, ii);
}
return total;
}
}
//--------------------------------------------------------------------
#include <stdexcept> // std::domain_error(-)
#include <limits> // std::numeric_limits
#include "igs_ifx_common.h" /* igs::image::rgba */
#include "igs_perlin_noise.h"
namespace {
template <class T>
void change_(T *image_array, const int height // pixel
,
const int width // pixel
,
const int channels, const bool alpha_rendering_sw,
const double a11 // geometry of 2D affine transformation
,
const double a12, const double a13, const double a21,
const double a22, const double a23, const double zz,
const int octaves_start // 0<=
,
const int octaves_end // 0<=
,
const double persistence // Not 0
) {
const int max_div = std::numeric_limits<T>::max();
const int max_div_2 = max_div / 2;
// 255 / 2 --> 127
// 65535 / 2 --> 32767
// const double max_mul = static_cast<double>(max_div_2+0.999999);
// const double max_off = static_cast<double>(max_div_2+1);
const double max_mul = static_cast<double>(max_div_2 + 0.499999);
const double max_off = static_cast<double>(max_div_2 + 1.5);
/*
-1 .............. 0 ......... 1
x127+0.499999
------------------------------------------
-127+0.499999 ... 0 ......... 127+0.499999
+127+1.5 ... 127+1.5 ... 127+1.5
------------------------------------------
1.000001 ........ 127+1.5 ... 255.999999
integer
------------------------------------------
1 ............... 128 ....... 255
*/
const double maxi =
perlin_noise_minmax_(octaves_start, octaves_end, persistence);
using namespace igs::image::rgba;
T *image_crnt = image_array;
for (int yy = 0; yy < height; ++yy) {
for (int xx = 0; xx < width; ++xx, image_crnt += channels) {
const T val = static_cast<T>(
perlin_noise_3d_(xx * a11 + yy * a12 + a13, xx * a21 + yy * a22 + a23,
zz, octaves_start, octaves_end, persistence) /
maxi * max_mul +
max_off);
for (int zz = 0; zz < channels; ++zz) {
if (!alpha_rendering_sw && (alp == zz)) {
image_crnt[zz] = static_cast<T>(max_div);
} else {
image_crnt[zz] = val;
}
}
}
}
}
}
// #include "igs_geometry2d.h"
void igs::perlin_noise::change(
unsigned char *image_array, const int height // pixel
,
const int width // pixel
,
const int channels, const int bits, const bool alpha_rendering_sw,
const double a11 // geometry of 2D affine transformation
,
const double a12, const double a13, const double a21, const double a22,
const double a23, const double zz, const int octaves_start // 0...
,
const int octaves_end // 0...
,
const double persistence // not 0
) {
// igs::geometry2d::affine af(a11 , a12 , a13 , a21 , a22 , a23);
// igs::geometry2d::translate();
if (std::numeric_limits<unsigned char>::digits == bits) {
change_(image_array, height, width, channels, alpha_rendering_sw, a11, a12,
a13, a21, a22, a23, zz, octaves_start, octaves_end, persistence);
} else if (std::numeric_limits<unsigned short>::digits == bits) {
change_(reinterpret_cast<unsigned short *>(image_array), height, width,
channels, alpha_rendering_sw, a11, a12, a13, a21, a22, a23, zz,
octaves_start, octaves_end, persistence);
} else {
throw std::domain_error("Bad bits,Not uchar/ushort");
}
}
| 36.810606 | 80 | 0.529739 | wofogen |
4db6989b183d07f065f757f7901cdeda556dacae | 97 | hpp | C++ | Vega/Source/Vega/Vendor/Imgui.hpp | killdaNME/RyZen7m-3000apu | a5d2ce7966f2c9e5cc7f64d9d5bfaa5986cd7b48 | [
"MIT"
] | 1 | 2020-12-13T15:31:53.000Z | 2020-12-13T15:31:53.000Z | Vega/Source/Vega/Vendor/Imgui.hpp | killdaNME/RyZen7m-3000apu | a5d2ce7966f2c9e5cc7f64d9d5bfaa5986cd7b48 | [
"MIT"
] | null | null | null | Vega/Source/Vega/Vendor/Imgui.hpp | killdaNME/RyZen7m-3000apu | a5d2ce7966f2c9e5cc7f64d9d5bfaa5986cd7b48 | [
"MIT"
] | null | null | null | #include <imgui.h>
#include <examples/imgui_impl_glfw.h>
#include <examples/imgui_impl_opengl3.h> | 32.333333 | 40 | 0.804124 | killdaNME |
4dbaab39ff1bdd4141f38cbb132cabba06db39ec | 1,468 | cpp | C++ | src/game/server/tf/bot/behavior/tf_bot_dead.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/server/tf/bot/behavior/tf_bot_dead.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/server/tf/bot/behavior/tf_bot_dead.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
// tf_bot_dead.cpp
// Push up daisies
// Michael Booth, May 2009
#include "cbase.h"
#include "tf_player.h"
#include "tf_gamerules.h"
#include "bot/tf_bot.h"
#include "bot/behavior/tf_bot_dead.h"
#include "bot/behavior/tf_bot_behavior.h"
#include "nav_mesh.h"
//---------------------------------------------------------------------------------------------
ActionResult< CTFBot > CTFBotDead::OnStart( CTFBot *me, Action< CTFBot > *priorAction )
{
m_deadTimer.Start();
return Continue();
}
//---------------------------------------------------------------------------------------------
ActionResult< CTFBot > CTFBotDead::Update( CTFBot *me, float interval )
{
if ( me->IsAlive() )
{
// how did this happen?
return ChangeTo( new CTFBotMainAction, "This should not happen!" );
}
if ( m_deadTimer.IsGreaterThen( 5.0f ) )
{
if ( me->HasAttribute( CTFBot::REMOVE_ON_DEATH ) )
{
// remove dead bots
engine->ServerCommand( UTIL_VarArgs( "kickid %d\n", me->GetUserID() ) );
}
else if ( me->HasAttribute( CTFBot::BECOME_SPECTATOR_ON_DEATH ) )
{
me->ChangeTeam( TEAM_SPECTATOR, false, true );
return Done();
}
}
#ifdef TF_RAID_MODE
if ( TFGameRules()->IsRaidMode() && me->GetTeamNumber() == TF_TEAM_RED )
{
// dead defenders go to spectator for recycling
me->ChangeTeam( TEAM_SPECTATOR, false, true );
}
#endif // TF_RAID_MODE
return Continue();
}
| 24.881356 | 95 | 0.586512 | cstom4994 |
4dbc0c2ce513bc772629df94d9f629a56438e820 | 5,865 | hpp | C++ | src/_cmsis_rtos/memorypool.hpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | 11 | 2015-10-06T21:00:30.000Z | 2021-07-27T05:54:44.000Z | src/_cmsis_rtos/memorypool.hpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | null | null | null | src/_cmsis_rtos/memorypool.hpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | 1 | 2015-10-03T03:51:28.000Z | 2015-10-03T03:51:28.000Z | /*******************************************************************************
WEOS - Wrapper for embedded operating systems
Copyright (c) 2013-2016, Manuel Freiberger
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#ifndef WEOS_CMSIS_RTOS_MEMORYPOOL_HPP
#define WEOS_CMSIS_RTOS_MEMORYPOOL_HPP
#ifndef WEOS_CONFIG_HPP
#error "Do not include this file directly."
#endif // WEOS_CONFIG_HPP
#include "_core.hpp"
#include "../memorypool.hpp"
#include "../atomic.hpp"
WEOS_BEGIN_NAMESPACE
//! A shared memory pool.
//! A shared_memory_pool is a thread-safe alternative to the memory_pool.
//! Like its non-threaded counterpart, it holds the memory for up to
//! (\p TNumElem) elements of type \p TElement internally and does not
//! allocate them on the heap.
template <typename TElement, std::size_t TNumElem>
class shared_memory_pool
{
public:
//! The type of the elements in this pool.
typedef TElement element_type;
private:
static_assert(TNumElem > 0, "The number of elements must be non-zero.");
// Every chunk has to be aligned such that it can contain either a
// void* or an element_type.
static const std::size_t chunk_align =
alignment_of<void*>::value > alignment_of<element_type>::value
? alignment_of<void*>::value
: alignment_of<element_type>::value;
// The chunk size has to be large enough to store a void* or an element.
static const std::size_t chunk_size =
sizeof(void*) > sizeof(element_type)
? sizeof(void*)
: sizeof(element_type);
// One chunk must be large enough for a void* or an element_type and it
// must be aligned to the stricter of both. Furthermore, the alignment
// must be a multiple of the size. The aligned_storage<> takes care
// of this.
typedef typename aligned_storage<chunk_size, chunk_align>::type chunk_type;
// The control block of a memory box. Defined as OS_BM in
// ${CMSIS-RTOS}/SRC/rt_TypeDef.h.
static_assert(osCMSIS_RTX <= ((4<<16) | 80), "Check the layout of OS_BM.");
struct ControlBlock
{
void* free;
void* end;
std::uint32_t chunkSize;
};
public:
//! Constructs a shared memory pool.
shared_memory_pool() noexcept
{
m_controlBlock.free = weos_detail::FreeList(
&m_chunks[0], sizeof(chunk_type), TNumElem).first();
m_controlBlock.end = &m_chunks[TNumElem];
m_controlBlock.chunkSize = sizeof(chunk_type);
}
shared_memory_pool(const shared_memory_pool&) = delete;
shared_memory_pool& operator=(const shared_memory_pool&) = delete;
//! Returns the number of pool elements.
//! Returns the number of elements for which the pool provides memory.
std::size_t capacity() const noexcept
{
return TNumElem;
}
//! Checks if the memory pool is empty.
//!
//! Returns \p true, if the memory pool is empty.
bool empty() const noexcept
{
// TODO: what memory order to use here?
atomic_thread_fence(memory_order_seq_cst);
return m_controlBlock.free == 0;
}
//! Allocates a chunk from the pool.
//! Allocates one chunk from the memory pool and returns a pointer to it.
//! If the pool is already empty, a null-pointer is returned.
//!
//! \note This method may be called in an interrupt context.
//!
//! \sa free()
void* try_allocate() noexcept
{
return osPoolAlloc(static_cast<osPoolId>(
static_cast<void*>(&m_controlBlock)));
}
//! Frees a chunk of memory.
//! Frees a \p chunk of memory which must have been allocated through
//! this pool.
//!
//! \note This method may be called in an interrupt context.
//!
//! \sa try_allocate()
void free(void* chunk) noexcept
{
osStatus ret = osPoolFree(static_cast<osPoolId>(
static_cast<void*>(&m_controlBlock)),
chunk);
WEOS_ASSERT(ret == osOK);
}
private:
//! The pool's control block. Note: It is important that the control
//! block is placed before the chunk array. osPoolFree() makes a boundary
//! check of the chunk to be freed, which involves the control block.
ControlBlock m_controlBlock;
//! The memory chunks for the elements and the free-list pointers.
chunk_type m_chunks[TNumElem];
};
WEOS_END_NAMESPACE
#endif // WEOS_CMSIS_RTOS_MEMORYPOOL_HPP
| 36.886792 | 86 | 0.665644 | ombre5733 |
4dbd800d25a8dd4bc28e1185068f0870dde9120c | 1,033 | cpp | C++ | src/engine/mt/asmjs/task.cpp | unrealeg4825/Test-engine | 12ce46dbbfd9c738e015a2d549df46c7bb4ffad0 | [
"MIT"
] | 3 | 2021-05-27T10:43:33.000Z | 2021-05-27T10:44:02.000Z | src/engine/mt/asmjs/task.cpp | unrealeg4825/Test-engine | 12ce46dbbfd9c738e015a2d549df46c7bb4ffad0 | [
"MIT"
] | null | null | null | src/engine/mt/asmjs/task.cpp | unrealeg4825/Test-engine | 12ce46dbbfd9c738e015a2d549df46c7bb4ffad0 | [
"MIT"
] | 3 | 2021-05-27T10:44:15.000Z | 2021-11-18T09:20:10.000Z | #include "engine/lumix.h"
#include "engine/iallocator.h"
#include "engine/mt/task.h"
#include "engine/mt/thread.h"
#include "engine/profiler.h"
#if !LUMIX_SINGLE_THREAD()
namespace Lumix
{
namespace MT
{
struct TaskImpl
{
IAllocator& allocator;
};
Task::Task(IAllocator& allocator)
{
m_implementation = LUMIX_NEW(allocator, TaskImpl) {allocator};
}
Task::~Task()
{
LUMIX_DELETE(m_implementation->allocator, m_implementation);
}
bool Task::create(const char* name)
{
ASSERT(false);
return false;
}
bool Task::destroy()
{
ASSERT(false);
return false;
}
void Task::setAffinityMask(uint32 affinity_mask)
{
ASSERT(false);
}
uint32 Task::getAffinityMask() const
{
ASSERT(false);
return 0;
}
bool Task::isRunning() const
{
return false;
}
bool Task::isFinished() const
{
return false;
}
bool Task::isForceExit() const
{
return false;
}
IAllocator& Task::getAllocator()
{
return m_implementation->allocator;
}
void Task::forceExit(bool wait)
{
ASSERT(false);
}
} // namespace MT
} // namespace Lumix
#endif
| 12.297619 | 63 | 0.713456 | unrealeg4825 |
4dc0304f7b8e101917ccb84d856e3b3aeb88e361 | 4,406 | cpp | C++ | AudioKit/Common/Internals/CoreAudio/Apple Code/ParameterRamper.cpp | ethi1989/AudioKit | 97acc8da6dfb75408b2276998073de7a4511d480 | [
"MIT"
] | 206 | 2020-10-28T12:47:49.000Z | 2022-03-26T14:09:30.000Z | AudioKit/Common/Internals/CoreAudio/Apple Code/ParameterRamper.cpp | ethi1989/AudioKit | 97acc8da6dfb75408b2276998073de7a4511d480 | [
"MIT"
] | 7 | 2020-10-29T10:29:23.000Z | 2021-08-07T00:22:03.000Z | AudioKit/Common/Internals/CoreAudio/Apple Code/ParameterRamper.cpp | ethi1989/AudioKit | 97acc8da6dfb75408b2276998073de7a4511d480 | [
"MIT"
] | 30 | 2020-10-28T16:11:40.000Z | 2021-12-28T01:15:23.000Z | //
// ParameterRamper.cpp
// AudioKit
//
// Utility class to manage DSP parameters which can change value smoothly (be ramped) while rendering, without introducing clicks or other distortion into the signal.
//
// Originally based on Apple sample code, but significantly altered by Aurelius Prochazka
//
// Copyright © 2020 AudioKit. All rights reserved.
//
#import <cstdint>
#include "ParameterRamper.hpp"
#import <AudioToolbox/AUAudioUnit.h>
#import <libkern/OSAtomic.h>
#import <stdatomic.h>
#include <math.h>
struct ParameterRamper::InternalData {
float clampLow, clampHigh;
float uiValue;
float taper = 1;
float skew = 0;
uint32_t offset = 0;
float startingPoint;
float goal;
uint32_t duration;
uint32_t samplesRemaining;
volatile atomic_int changeCounter = 0;
int32_t updateCounter = 0;
};
ParameterRamper::ParameterRamper(float value) : data(new InternalData)
{
setImmediate(value);
}
ParameterRamper::~ParameterRamper()
{
delete data;
}
void ParameterRamper::setImmediate(float value)
{
// only to be called from the render thread or when resources are not allocated.
data->goal = data->uiValue = data->startingPoint = value;
data->samplesRemaining = 0;
}
void ParameterRamper::init()
{
/*
Call this from the kernel init.
Updates the internal value from the UI value.
*/
setImmediate(data->uiValue);
}
void ParameterRamper::reset()
{
data->changeCounter = data->updateCounter = 0;
}
void ParameterRamper::setTaper(float taper)
{
data->taper = taper;
atomic_fetch_add(&data->changeCounter, 1);
}
float ParameterRamper::getTaper() const
{
return data->taper;
}
void ParameterRamper::setSkew(float skew)
{
if (skew > 1) {
skew = 1.0;
}
if (skew < 0) {
skew = 0.0;
}
data->skew = skew;
atomic_fetch_add(&data->changeCounter, 1);
}
float ParameterRamper::getSkew() const
{
return data->skew;
}
void ParameterRamper::setOffset(uint32_t offset)
{
if (offset < 0) {
offset = 0;
}
data->offset = offset;
atomic_fetch_add(&data->changeCounter, 1);
}
uint32_t ParameterRamper::getOffset() const
{
return data->offset;
}
void ParameterRamper::setUIValue(float value)
{
data->uiValue = value;
atomic_fetch_add(&data->changeCounter, 1);
}
float ParameterRamper::getUIValue() const
{
return data->uiValue;
}
void ParameterRamper::dezipperCheck(uint32_t rampDuration)
{
// check to see if the UI has changed and if so, start a ramp to dezipper it.
int32_t changeCounterSnapshot = data->changeCounter;
if (data->updateCounter != changeCounterSnapshot) {
data->updateCounter = changeCounterSnapshot;
startRamp(data->uiValue, rampDuration);
}
}
void ParameterRamper::startRamp(float newGoal, uint32_t duration)
{
if (duration == 0) {
setImmediate(newGoal);
} else {
data->startingPoint = data->uiValue;
data->duration = duration;
data->samplesRemaining = duration - data->offset;
data->goal = data->uiValue = newGoal;
}
}
float ParameterRamper::get() const
{
float x = float(data->duration - data->samplesRemaining) / float(data->duration);
float taper1 = data->startingPoint + (data->goal - data->startingPoint) * pow(x, abs(data->taper));
float absxm1 = abs(float(data->duration - data->samplesRemaining) / float(data->duration) - 1.0);
float taper2 = data->startingPoint + (data->goal - data->startingPoint) * (1.0 - pow(absxm1, 1.0 / abs(data->taper)));
return taper1 * (1.0 - data->skew) + taper2 * data->skew;
}
void ParameterRamper::step()
{
// Do this in each inner loop iteration after getting the value.
if (data->samplesRemaining != 0) {
--data->samplesRemaining;
}
}
float ParameterRamper::getAndStep()
{
// Combines get and step. Saves a multiply-add when not ramping.
if (data->samplesRemaining != 0) {
float value = get();
--data->samplesRemaining;
return value;
} else {
return data->goal;
}
}
void ParameterRamper::stepBy(uint32_t n)
{
/*
When a parameter does not participate in the current inner loop, you
will want to advance it after the end of the loop.
*/
if (n >= data->samplesRemaining) {
data->samplesRemaining = 0;
} else {
data->samplesRemaining -= n;
}
}
| 23.816216 | 166 | 0.666364 | ethi1989 |
4dc31fa2013a4e4f26d845ffc650475ae5c17a75 | 971 | hpp | C++ | include/RED4ext/Types/generated/move/SecureFootingResult.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/move/SecureFootingResult.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/move/SecureFootingResult.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/Vector4.hpp>
#include <RED4ext/Types/generated/move/SecureFootingFailureReason.hpp>
#include <RED4ext/Types/generated/move/SecureFootingFailureType.hpp>
namespace RED4ext
{
namespace move {
struct SecureFootingResult
{
static constexpr const char* NAME = "moveSecureFootingResult";
static constexpr const char* ALIAS = "SecureFootingResult";
Vector4 slidingDirection; // 00
Vector4 normalDirection; // 10
Vector4 lowestLocalPosition; // 20
float staticGroundFactor; // 30
move::SecureFootingFailureReason reason; // 34
move::SecureFootingFailureType type; // 38
uint8_t unk3C[0x40 - 0x3C]; // 3C
};
RED4EXT_ASSERT_SIZE(SecureFootingResult, 0x40);
} // namespace move
using SecureFootingResult = move::SecureFootingResult;
} // namespace RED4ext
| 30.34375 | 70 | 0.763131 | Cyberpunk-Extended-Development-Team |
4dc84041d81d3b9596b1329997eea6ca6c632c99 | 836 | cpp | C++ | solutions/286.walls-and-gates.290509829.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/286.walls-and-gates.290509829.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/286.walls-and-gates.290509829.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
class Solution {
public:
void wallsAndGates(vector<vector<int>> &rooms) {
int n = rooms.size();
if (!n)
return;
int m = rooms[0].size();
int INF = 2147483647;
queue<pair<int, int>> q;
int dist = 1;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (rooms[i][j] == 0)
q.emplace(i, j);
}
while (q.size()) {
int _t = q.size();
while (_t--) {
auto p = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int i = p.first + dx[k];
int j = p.second + dy[k];
if (i >= 0 && j >= 0 && i < n && j < m && rooms[i][j] == INF) {
rooms[i][j] = dist;
q.emplace(i, j);
}
}
}
dist++;
}
}
};
| 19.904762 | 73 | 0.379187 | satu0king |
4dc9e8d23f7f7057ceed6069c74b022b4f460758 | 7,726 | cc | C++ | arcane/src/arcane/parallel/VariableParallelOperationBase.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 16 | 2021-09-20T12:37:01.000Z | 2022-03-18T09:19:14.000Z | arcane/src/arcane/parallel/VariableParallelOperationBase.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 66 | 2021-09-17T13:49:39.000Z | 2022-03-30T16:24:07.000Z | arcane/src/arcane/parallel/VariableParallelOperationBase.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 11 | 2021-09-27T16:48:55.000Z | 2022-03-23T19:06:56.000Z | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* VariableParallelOperationBase.cc (C) 2000-2021 */
/* */
/* Classe de base des opérations parallèles sur des variables. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/parallel/VariableParallelOperationBase.h"
#include "arcane/utils/FatalErrorException.h"
#include "arcane/utils/ScopedPtr.h"
#include "arcane/IParallelMng.h"
#include "arcane/ISerializer.h"
#include "arcane/ISerializeMessage.h"
#include "arcane/IParallelExchanger.h"
#include "arcane/ISubDomain.h"
#include "arcane/IVariable.h"
#include "arcane/IItemFamily.h"
#include "arcane/ItemInternal.h"
#include "arcane/ItemGroup.h"
#include "arcane/ParallelMngUtils.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Arcane::Parallel
{
namespace
{
const Int64 SERIALIZE_MAGIC_NUMBER = 0x4cf92789;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
VariableParallelOperationBase::
VariableParallelOperationBase(IParallelMng* pm)
: TraceAccessor(pm->traceMng())
, m_parallel_mng(pm)
, m_item_family(nullptr)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void VariableParallelOperationBase::
setItemFamily(IItemFamily* family)
{
if (m_item_family)
ARCANE_FATAL("family already set");
m_item_family = family;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
IItemFamily* VariableParallelOperationBase::
itemFamily()
{
return m_item_family;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void VariableParallelOperationBase::
addVariable(IVariable* variable)
{
if (!m_item_family)
ARCANE_FATAL("family not set. call setItemFamily()");
if (variable->itemGroup().itemFamily()!=m_item_family)
ARCANE_FATAL("variable->itemFamily() and itemFamily() differ");
m_variables.add(variable);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void VariableParallelOperationBase::
applyOperation(IDataOperation* operation)
{
if (m_variables.empty())
return;
bool is_debug_print = false;
#ifdef ARCANE_DEBUG
is_debug_print = true;
#endif
IParallelMng* pm = m_parallel_mng;
Integer nb_rank = pm->commSize();
m_items_to_send.clear();
m_items_to_send.resize(nb_rank);
_buildItemsToSend();
UniqueArray<ISerializeMessage*> m_messages;
m_messages.reserve(nb_rank);
auto exchanger {ParallelMngUtils::createExchangerRef(pm)};
for( Integer i=0; i<nb_rank; ++i )
if (!m_items_to_send[i].empty())
exchanger->addSender(i);
bool no_exchange = exchanger->initializeCommunicationsMessages();
if (no_exchange)
return;
// Génère les infos pour chaque processeur à qui on va envoyer des entités
for( Integer i=0, is=exchanger->nbSender(); i<is; ++i ){
ISerializeMessage* comm = exchanger->messageToSend(i);
Int32 dest_sub_domain = comm->destination().value();
ConstArrayView<ItemInternal*> dest_items_internal = m_items_to_send[dest_sub_domain];
Integer nb_item = dest_items_internal.size();
debug() << "Number of items to serialize: " << nb_item << " subdomain=" << dest_sub_domain;
UniqueArray<Int32> dest_items_local_id(nb_item);
UniqueArray<Int64> dest_items_unique_id(nb_item);
for( Integer z=0; z<nb_item; ++z ){
ItemInternal* item = dest_items_internal[z];
dest_items_local_id[z] = item->localId();
dest_items_unique_id[z] = item->uniqueId().asInt64();
}
ISerializer* sbuf = comm->serializer();
// Réserve la mémoire pour la sérialisation
sbuf->setMode(ISerializer::ModeReserve);
// Réserve pour le magic number
sbuf->reserve(DT_Int64,1);
// Réserve pour la liste uniqueId() des entités transférées
sbuf->reserve(DT_Int64,1);
sbuf->reserveSpan(dest_items_unique_id);
// Réserve pour chaque variable
for( VariableList::Enumerator i_var(m_variables); ++i_var; ){
IVariable* var = *i_var;
debug(Trace::High) << "Serialize variable (reserve)" << var->name();
var->serialize(sbuf,dest_items_local_id);
}
sbuf->allocateBuffer();
// Sérialise les infos
sbuf->setMode(ISerializer::ModePut);
// Sérialise le magic number
sbuf->putInt64(SERIALIZE_MAGIC_NUMBER);
// Sérialise la liste des uniqueId() des entités transférées
sbuf->putInt64(nb_item);
sbuf->putSpan(dest_items_unique_id);
for( VariableList::Enumerator i_var(m_variables); ++i_var; ){
IVariable* var = *i_var;
debug(Trace::High) << "Serialise variable (put)" << var->name();
var->serialize(sbuf,dest_items_local_id);
}
}
exchanger->processExchange();
{
debug() << "VariableParallelOperationBase::readVariables()";
UniqueArray<Int64> items_unique_id;
UniqueArray<Int32> items_local_id;
// Récupère les infos pour les variables et les remplit
for( Integer i=0, n=exchanger->nbReceiver(); i<n; ++i ){
ISerializeMessage* comm = exchanger->messageToReceive(i);
ISerializer* sbuf = comm->serializer();
// Désérialize les variables
{
// Sérialise le magic number
Int64 magic_number = sbuf->getInt64();
if (magic_number!=SERIALIZE_MAGIC_NUMBER)
ARCANE_FATAL("Bad magic number actual={0} expected={1}. This is probably due to incoherent messaging",
magic_number,SERIALIZE_MAGIC_NUMBER);
// Récupère la liste des uniqueId() des entités transférées
Int64 nb_item = sbuf->getInt64();
items_unique_id.resize(nb_item);
sbuf->getSpan(items_unique_id);
items_local_id.resize(nb_item);
debug(Trace::High) << "Receiving " << nb_item << " items from " << comm->destination().value();
if (is_debug_print){
for( Integer iz=0; iz<nb_item; ++iz )
debug(Trace::Highest) << "Receiving uid=" << items_unique_id[iz];
}
itemFamily()->itemsUniqueIdToLocalId(items_local_id,items_unique_id);
for( VariableList::Enumerator ivar(m_variables); ++ivar; ){
IVariable* var = *ivar;
var->serialize(sbuf,items_local_id,operation);
}
}
}
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // End namespace Arcane::Parallel
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 34.959276 | 112 | 0.533653 | cedricga91 |
4dcae401a0a9fd9e61c47e7b21e73ed4a66fe5a0 | 496 | cpp | C++ | ambiguity-resolution2.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | 1 | 2021-04-27T18:23:05.000Z | 2021-04-27T18:23:05.000Z | ambiguity-resolution2.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | null | null | null | ambiguity-resolution2.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class base
{
public:
void greet()
{
cout<<"hello"<<endl;
}
};
class derived: public base
{
public:
void greet() //this function will be overwritten after creation of the object of derived class
{
cout<<"Namaste"<<endl;
}
};
int main()
{
derived a;
a.greet(); //here greet of derived class will be invoked
base b;
b.greet(); //here greet of base class will be invoked
return 0;
} | 16.533333 | 99 | 0.59879 | rsds8540 |
4dcb9316f4240fe4d35e9519ce700a08ccbf8bb9 | 64,874 | cpp | C++ | DiscImageCreator/outputScsiCmdLog.cpp | tungol/DiscImageCreator | 0dbe5e86402848c56fa2aca7c993eabdaed2e0bb | [
"Apache-2.0"
] | null | null | null | DiscImageCreator/outputScsiCmdLog.cpp | tungol/DiscImageCreator | 0dbe5e86402848c56fa2aca7c993eabdaed2e0bb | [
"Apache-2.0"
] | null | null | null | DiscImageCreator/outputScsiCmdLog.cpp | tungol/DiscImageCreator | 0dbe5e86402848c56fa2aca7c993eabdaed2e0bb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2011-2018 sarami
*
* 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 "struct.h"
#include "convert.h"
#include "output.h"
#include "outputScsiCmdLog.h"
#include "set.h"
VOID OutputInquiry(
PINQUIRYDATA pInquiry
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(InquiryData)
"\t DeviceType: ");
switch (pInquiry->DeviceType) {
case DIRECT_ACCESS_DEVICE:
OutputDriveLogA("DirectAccessDevice (Floppy etc)\n");
break;
case READ_ONLY_DIRECT_ACCESS_DEVICE:
OutputDriveLogA("ReadOnlyDirectAccessDevice (CD/DVD etc)\n");
break;
case OPTICAL_DEVICE:
OutputDriveLogA("OpticalDisk\n");
break;
default:
OutputDriveLogA("OtherDevice\n");
break;
}
OutputDriveLogA(
"\t DeviceTypeQualifier: ");
switch (pInquiry->DeviceTypeQualifier) {
case DEVICE_QUALIFIER_ACTIVE:
OutputDriveLogA("Active\n");
break;
case DEVICE_QUALIFIER_NOT_ACTIVE:
OutputDriveLogA("NotActive\n");
break;
case DEVICE_QUALIFIER_NOT_SUPPORTED:
OutputDriveLogA("NotSupported\n");
break;
default:
OutputDriveLogA("\n");
break;
}
OutputDriveLogA(
"\t DeviceTypeModifier: %u\n"
"\t RemovableMedia: %s\n"
"\t Versions: %u\n"
"\t ResponseDataFormat: %u\n"
"\t HiSupport: %s\n"
"\t NormACA: %s\n"
"\t TerminateTask: %s\n"
"\t AERC: %s\n"
"\t AdditionalLength: %u\n"
"\t MediumChanger: %s\n"
"\t MultiPort: %s\n"
"\t EnclosureServices: %s\n"
"\t SoftReset: %s\n"
"\t CommandQueue: %s\n"
"\t LinkedCommands: %s\n"
"\t RelativeAddressing: %s\n",
pInquiry->DeviceTypeModifier,
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->RemovableMedia),
pInquiry->Versions,
pInquiry->ResponseDataFormat,
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->HiSupport),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->NormACA),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->TerminateTask),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->AERC),
pInquiry->AdditionalLength,
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->MediumChanger),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->MultiPort),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->EnclosureServices),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->SoftReset),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->CommandQueue),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->LinkedCommands),
BOOLEAN_TO_STRING_YES_NO_A(pInquiry->RelativeAddressing));
OutputDriveLogA(
"\t VendorId: %.8s\n"
"\t ProductId: %.16s\n"
"\tProductRevisionLevel: %.4s\n"
"\t VendorSpecific: %.20s\n",
pInquiry->VendorId,
pInquiry->ProductId,
pInquiry->ProductRevisionLevel,
pInquiry->VendorSpecific);
}
VOID OutputGetConfigurationHeader(
PGET_CONFIGURATION_HEADER pConfigHeader
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(GetConfiguration)
"\t DataLength: %ld\n"
"\tCurrentProfile: "
, MAKELONG(MAKEWORD(pConfigHeader->DataLength[3], pConfigHeader->DataLength[2]),
MAKEWORD(pConfigHeader->DataLength[1], pConfigHeader->DataLength[0])));
OutputGetConfigurationFeatureProfileType(
MAKEWORD(pConfigHeader->CurrentProfile[1], pConfigHeader->CurrentProfile[0]));
OutputDriveLogA("\n");
}
VOID OutputGetConfigurationFeatureProfileType(
WORD wFeatureProfileType
) {
switch (wFeatureProfileType) {
case ProfileInvalid:
OutputDriveLogA("Invalid");
break;
case ProfileNonRemovableDisk:
OutputDriveLogA("NonRemovableDisk");
break;
case ProfileRemovableDisk:
OutputDriveLogA("RemovableDisk");
break;
case ProfileMOErasable:
OutputDriveLogA("MOErasable");
break;
case ProfileMOWriteOnce:
OutputDriveLogA("MOWriteOnce");
break;
case ProfileAS_MO:
OutputDriveLogA("AS_MO");
break;
case ProfileCdrom:
OutputDriveLogA("CD-ROM");
break;
case ProfileCdRecordable:
OutputDriveLogA("CD-R");
break;
case ProfileCdRewritable:
OutputDriveLogA("CD-RW");
break;
case ProfileDvdRom:
OutputDriveLogA("DVD-ROM");
break;
case ProfileDvdRecordable:
OutputDriveLogA("DVD-R");
break;
case ProfileDvdRam:
OutputDriveLogA("DVD-RAM");
break;
case ProfileDvdRewritable:
OutputDriveLogA("DVD-RW");
break;
case ProfileDvdRWSequential:
OutputDriveLogA("DVD-RW Sequential");
break;
case ProfileDvdDashRDualLayer:
OutputDriveLogA("DVD-R DL");
break;
case ProfileDvdDashRLayerJump:
OutputDriveLogA("DVD-R Layer Jump");
break;
case ProfileDvdPlusRW:
OutputDriveLogA("DVD+RW");
break;
case ProfileDvdPlusR:
OutputDriveLogA("DVD+R");
break;
case ProfileDDCdrom:
OutputDriveLogA("DDCD-ROM");
break;
case ProfileDDCdRecordable:
OutputDriveLogA("DDCD-R");
break;
case ProfileDDCdRewritable:
OutputDriveLogA("DDCD-RW");
break;
case ProfileDvdPlusRWDualLayer:
OutputDriveLogA("DVD+RW DL");
break;
case ProfileDvdPlusRDualLayer:
OutputDriveLogA("DVD+R DL");
break;
case ProfileBDRom:
OutputDriveLogA("BD-ROM");
break;
case ProfileBDRSequentialWritable:
OutputDriveLogA("BD-R Sequential Writable");
break;
case ProfileBDRRandomWritable:
OutputDriveLogA("BD-R Random Writable");
break;
case ProfileBDRewritable:
OutputDriveLogA("BD-R");
break;
case ProfileHDDVDRom:
OutputDriveLogA("HD DVD-ROM");
break;
case ProfileHDDVDRecordable:
OutputDriveLogA("HD DVD-R");
break;
case ProfileHDDVDRam:
OutputDriveLogA("HD DVD-RAM");
break;
case ProfileHDDVDRewritable:
OutputDriveLogA("HD-DVD-RW");
break;
case ProfileHDDVDRDualLayer:
OutputDriveLogA("HD-DVD-R DL");
break;
case ProfileHDDVDRWDualLayer:
OutputDriveLogA("HD-DVD-RW DL");
break;
case ProfileNonStandard:
OutputDriveLogA("NonStandard");
break;
default:
OutputDriveLogA("Reserved [%#x]", wFeatureProfileType);
break;
}
}
VOID OutputGetConfigurationFeatureProfileList(
PFEATURE_DATA_PROFILE_LIST pList
) {
OutputDriveLogA("\tFeatureProfileList\n");
for (UINT i = 0; i < pList->Header.AdditionalLength / sizeof(FEATURE_DATA_PROFILE_LIST_EX); i++) {
OutputDriveLogA("\t\t");
OutputGetConfigurationFeatureProfileType(
MAKEWORD(pList->Profiles[i].ProfileNumber[1], pList->Profiles[i].ProfileNumber[0]));
OutputDriveLogA("\n");
}
}
VOID OutputGetConfigurationFeatureCore(
PFEATURE_DATA_CORE pCore
) {
OutputDriveLogA(
"\tFeatureCore\n"
"\t\tPhysicalInterface: ");
LONG lVal = MAKELONG(
MAKEWORD(pCore->PhysicalInterface[3], pCore->PhysicalInterface[2]),
MAKEWORD(pCore->PhysicalInterface[1], pCore->PhysicalInterface[0]));
switch (lVal) {
case 0:
OutputDriveLogA("Unspecified\n");
break;
case 1:
OutputDriveLogA("SCSI Family\n");
break;
case 2:
OutputDriveLogA("ATAPI\n");
break;
case 3:
OutputDriveLogA("IEEE 1394 - 1995\n");
break;
case 4:
OutputDriveLogA("IEEE 1394A\n");
break;
case 5:
OutputDriveLogA("Fibre Channel\n");
break;
case 6:
OutputDriveLogA("IEEE 1394B\n");
break;
case 7:
OutputDriveLogA("Serial ATAPI\n");
break;
case 8:
OutputDriveLogA("USB (both 1.1 and 2.0)\n");
break;
case 0xffff:
OutputDriveLogA("Vendor Unique\n");
break;
default:
OutputDriveLogA("Reserved: %08ld\n", lVal);
break;
}
OutputDriveLogA(
"\t\t DeviceBusyEvent: %s\n"
"\t\t INQUIRY2: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pCore->DeviceBusyEvent),
BOOLEAN_TO_STRING_YES_NO_A(pCore->INQUIRY2));
}
VOID OutputGetConfigurationFeatureMorphing(
PFEATURE_DATA_MORPHING pMorphing
) {
OutputDriveLogA(
"\tFeatureMorphing\n"
"\t\tAsynchronous: %s\n"
"\t\t OCEvent: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pMorphing->Asynchronous),
BOOLEAN_TO_STRING_YES_NO_A(pMorphing->OCEvent));
}
VOID OutputGetConfigurationFeatureRemovableMedium(
PFEATURE_DATA_REMOVABLE_MEDIUM pRemovableMedium
) {
OutputDriveLogA(
"\tFeatureRemovableMedium\n"
"\t\t Lockable: %s\n"
"\t\tDefaultToPrevent: %s\n"
"\t\t Eject: %s\n"
"\t\tLoadingMechanism: ",
BOOLEAN_TO_STRING_YES_NO_A(pRemovableMedium->Lockable),
BOOLEAN_TO_STRING_YES_NO_A(pRemovableMedium->DefaultToPrevent),
BOOLEAN_TO_STRING_YES_NO_A(pRemovableMedium->Eject));
switch (pRemovableMedium->LoadingMechanism) {
case 0:
OutputDriveLogA("Caddy/Slot type loading mechanism\n");
break;
case 1:
OutputDriveLogA("Tray type loading mechanism\n");
break;
case 2:
OutputDriveLogA("Pop-up type loading mechanism\n");
break;
case 4:
OutputDriveLogA(
"Embedded changer with individually changeable discs\n");
break;
case 5:
OutputDriveLogA(
"Embedded changer using a magazine mechanism\n");
break;
default:
OutputDriveLogA(
"Reserved: %08d\n", pRemovableMedium->LoadingMechanism);
break;
}
}
VOID OutputGetConfigurationFeatureWriteProtect(
PFEATURE_DATA_WRITE_PROTECT pWriteProtect
) {
OutputDriveLogA(
"\tFeatureWriteProtect\n"
"\t\t SupportsSWPPBit: %s\n"
"\t\tSupportsPersistentWriteProtect: %s\n"
"\t\t WriteInhibitDCB: %s\n"
"\t\t DiscWriteProtectPAC: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pWriteProtect->SupportsSWPPBit),
BOOLEAN_TO_STRING_YES_NO_A(pWriteProtect->SupportsPersistentWriteProtect),
BOOLEAN_TO_STRING_YES_NO_A(pWriteProtect->WriteInhibitDCB),
BOOLEAN_TO_STRING_YES_NO_A(pWriteProtect->DiscWriteProtectPAC));
}
VOID OutputGetConfigurationFeatureRandomReadable(
PFEATURE_DATA_RANDOM_READABLE pRandomReadable
) {
OutputDriveLogA(
"\tFeatureRandomReadable\n"
"\t\t LogicalBlockSize: %lu\n"
"\t\t Blocking: %u\n"
"\t\tErrorRecoveryPagePresent: %s\n",
MAKELONG(MAKEWORD(pRandomReadable->LogicalBlockSize[3], pRandomReadable->LogicalBlockSize[2]),
MAKEWORD(pRandomReadable->LogicalBlockSize[1], pRandomReadable->LogicalBlockSize[0])),
MAKEWORD(pRandomReadable->Blocking[1], pRandomReadable->Blocking[0]),
BOOLEAN_TO_STRING_YES_NO_A(pRandomReadable->ErrorRecoveryPagePresent));
}
VOID OutputGetConfigurationFeatureMultiRead(
PFEATURE_DATA_MULTI_READ pMultiRead
) {
OutputDriveLogA(
"\tFeatureMultiRead\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pMultiRead->Header.Current,
pMultiRead->Header.Persistent,
pMultiRead->Header.Version);
}
VOID OutputGetConfigurationFeatureCdRead(
PFEATURE_DATA_CD_READ pCDRead
) {
OutputDriveLogA(
"\tFeatureCdRead\n"
"\t\t CDText: %s\n"
"\t\t C2ErrorData: %s\n"
"\t\tDigitalAudioPlay: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pCDRead->CDText),
BOOLEAN_TO_STRING_YES_NO_A(pCDRead->C2ErrorData),
BOOLEAN_TO_STRING_YES_NO_A(pCDRead->DigitalAudioPlay));
}
VOID OutputGetConfigurationFeatureDvdRead(
PFEATURE_DATA_DVD_READ pDVDRead
) {
OutputDriveLogA(
"\tFeatureDvdRead\n"
"\t\t Multi110: %s\n"
"\t\t DualDashR: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDRead->Multi110),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRead->DualDashR));
}
VOID OutputGetConfigurationFeatureRandomWritable(
PFEATURE_DATA_RANDOM_WRITABLE pRandomWritable
) {
OutputDriveLogA(
"\tFeatureRandomWritable\n"
"\t\t LastLBA: %lu\n"
"\t\t LogicalBlockSize: %lu\n"
"\t\t Blocking: %u\n"
"\t\tErrorRecoveryPagePresent: %s\n",
MAKELONG(MAKEWORD(pRandomWritable->LastLBA[3], pRandomWritable->LastLBA[2]),
MAKEWORD(pRandomWritable->LastLBA[1], pRandomWritable->LastLBA[0])),
MAKELONG(MAKEWORD(pRandomWritable->LogicalBlockSize[3], pRandomWritable->LogicalBlockSize[2]),
MAKEWORD(pRandomWritable->LogicalBlockSize[1], pRandomWritable->LogicalBlockSize[0])),
MAKEWORD(pRandomWritable->Blocking[1], pRandomWritable->Blocking[0]),
BOOLEAN_TO_STRING_YES_NO_A(pRandomWritable->ErrorRecoveryPagePresent));
}
VOID OutputGetConfigurationFeatureIncrementalStreamingWritable(
PFEATURE_DATA_INCREMENTAL_STREAMING_WRITABLE pIncremental
) {
OutputDriveLogA(
"\tFeatureIncrementalStreamingWritable\n"
"\t\t DataTypeSupported: %u\n"
"\t\t BufferUnderrunFree: %s\n"
"\t\t AddressModeReservation: %s\n"
"\t\tTrackRessourceInformation: %s\n"
"\t\t NumberOfLinkSizes: %u\n",
MAKEWORD(pIncremental->DataTypeSupported[1], pIncremental->DataTypeSupported[0]),
BOOLEAN_TO_STRING_YES_NO_A(pIncremental->BufferUnderrunFree),
BOOLEAN_TO_STRING_YES_NO_A(pIncremental->AddressModeReservation),
BOOLEAN_TO_STRING_YES_NO_A(pIncremental->TrackRessourceInformation),
pIncremental->NumberOfLinkSizes);
for (INT i = 0; i < pIncremental->NumberOfLinkSizes; i++) {
OutputDriveLogA(
"\t\tLinkSize%u: %u\n", i, pIncremental->LinkSize[i]);
}
}
VOID OutputGetConfigurationFeatureSectorErasable(
PFEATURE_DATA_SECTOR_ERASABLE pSectorErasable
) {
OutputDriveLogA(
"\tFeatureSectorErasable\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pSectorErasable->Header.Current,
pSectorErasable->Header.Persistent,
pSectorErasable->Header.Version);
}
VOID OutputGetConfigurationFeatureFormattable(
PFEATURE_DATA_FORMATTABLE pFormattable
) {
OutputDriveLogA(
"\tFeatureFormattable\n"
"\t\t FullCertification: %s\n"
"\t\tQuickCertification: %s\n"
"\t\tSpareAreaExpansion: %s\n"
"\t\tRENoSpareAllocated: %s\n"
"\t\t RRandomWritable: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pFormattable->FullCertification),
BOOLEAN_TO_STRING_YES_NO_A(pFormattable->QuickCertification),
BOOLEAN_TO_STRING_YES_NO_A(pFormattable->SpareAreaExpansion),
BOOLEAN_TO_STRING_YES_NO_A(pFormattable->RENoSpareAllocated),
BOOLEAN_TO_STRING_YES_NO_A(pFormattable->RRandomWritable));
}
VOID OutputGetConfigurationFeatureDefectManagement(
PFEATURE_DATA_DEFECT_MANAGEMENT pDefect
) {
OutputDriveLogA(
"\tFeatureDefectManagement\n"
"\t\tSupplimentalSpareArea: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDefect->SupplimentalSpareArea));
}
VOID OutputGetConfigurationFeatureWriteOnce(
PFEATURE_DATA_WRITE_ONCE pWriteOnce
) {
OutputDriveLogA(
"\tFeatureWriteOnce\n"
"\t\t LogicalBlockSize: %lu\n"
"\t\t Blocking: %u\n"
"\t\tErrorRecoveryPagePresent: %s\n",
MAKELONG(MAKEWORD(pWriteOnce->LogicalBlockSize[3], pWriteOnce->LogicalBlockSize[2]),
MAKEWORD(pWriteOnce->LogicalBlockSize[1], pWriteOnce->LogicalBlockSize[0])),
MAKEWORD(pWriteOnce->Blocking[1], pWriteOnce->Blocking[0]),
BOOLEAN_TO_STRING_YES_NO_A(pWriteOnce->ErrorRecoveryPagePresent));
}
VOID OutputGetConfigurationFeatureRestrictedOverwrite(
PFEATURE_DATA_RESTRICTED_OVERWRITE pRestricted
) {
OutputDriveLogA(
"\tFeatureRestrictedOverwrite\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pRestricted->Header.Current,
pRestricted->Header.Persistent,
pRestricted->Header.Version);
}
VOID OutputGetConfigurationFeatureCdrwCAVWrite(
PFEATURE_DATA_CDRW_CAV_WRITE pCDRW
) {
OutputDriveLogA(
"\tFeatureCdrwCAVWrite\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pCDRW->Header.Current,
pCDRW->Header.Persistent,
pCDRW->Header.Version);
}
VOID OutputGetConfigurationFeatureMrw(
PFEATURE_DATA_MRW pMrw
) {
OutputDriveLogA(
"\tFeatureMrw\n"
"\t\t Write: %s\n"
"\t\t DvdPlusRead: %s\n"
"\t\tDvdPlusWrite: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pMrw->Write),
BOOLEAN_TO_STRING_YES_NO_A(pMrw->DvdPlusRead),
BOOLEAN_TO_STRING_YES_NO_A(pMrw->DvdPlusWrite));
}
VOID OutputGetConfigurationFeatureEnhancedDefectReporting(
PFEATURE_ENHANCED_DEFECT_REPORTING pEnhanced
) {
OutputDriveLogA(
"\tFeatureEnhancedDefectReporting\n"
"\t\t DRTDMSupported: %s\n"
"\t\tNumberOfDBICacheZones: %u\n"
"\t\t NumberOfEntries: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pEnhanced->DRTDMSupported),
pEnhanced->NumberOfDBICacheZones,
MAKEWORD(pEnhanced->NumberOfEntries[1], pEnhanced->NumberOfEntries[0]));
}
VOID OutputGetConfigurationFeatureDvdPlusRW(
PFEATURE_DATA_DVD_PLUS_RW pDVDPLUSRW
) {
OutputDriveLogA(
"\tFeatureDvdPlusRW\n"
"\t\t Write: %s\n"
"\t\t CloseOnly: %s\n"
"\t\tQuickStart: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDPLUSRW->Write),
BOOLEAN_TO_STRING_YES_NO_A(pDVDPLUSRW->CloseOnly),
BOOLEAN_TO_STRING_YES_NO_A(pDVDPLUSRW->QuickStart));
}
VOID OutputGetConfigurationFeatureDvdPlusR(
PFEATURE_DATA_DVD_PLUS_R pDVDPLUSR
) {
OutputDriveLogA(
"\tFeatureDvdPlusR\n"
"\t\tWrite: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDPLUSR->Write));
}
VOID OutputGetConfigurationFeatureRigidRestrictedOverwrite(
PFEATURE_DATA_DVD_RW_RESTRICTED_OVERWRITE pDVDRWRestricted
) {
OutputDriveLogA(
"\tFeatureRigidRestrictedOverwrite\n"
"\t\t Blank: %s\n"
"\t\t Intermediate: %s\n"
"\t\t DefectStatusDataRead: %s\n"
"\t\tDefectStatusDataGenerate: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDRWRestricted->Blank),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRWRestricted->Intermediate),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRWRestricted->DefectStatusDataRead),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRWRestricted->DefectStatusDataGenerate));
}
VOID OutputGetConfigurationFeatureCdTrackAtOnce(
PFEATURE_DATA_CD_TRACK_AT_ONCE pCDTrackAtOnce
) {
OutputDriveLogA(
"\tFeatureCdTrackAtOnce\n"
"\t\tRWSubchannelsRecordable: %s\n"
"\t\t CdRewritable: %s\n"
"\t\t TestWriteOk: %s\n"
"\t\t RWSubchannelPackedOk: %s\n"
"\t\t RWSubchannelRawOk: %s\n"
"\t\t BufferUnderrunFree: %s\n"
"\t\t DataTypeSupported: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->RWSubchannelsRecordable),
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->CdRewritable),
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->TestWriteOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->RWSubchannelPackedOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->RWSubchannelRawOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDTrackAtOnce->BufferUnderrunFree),
MAKEWORD(pCDTrackAtOnce->DataTypeSupported[1], pCDTrackAtOnce->DataTypeSupported[0]));
}
VOID OutputGetConfigurationFeatureCdMastering(
PFEATURE_DATA_CD_MASTERING pCDMastering
) {
OutputDriveLogA(
"\tFeatureCdMastering\n"
"\t\tRWSubchannelsRecordable: %s\n"
"\t\t CdRewritable: %s\n"
"\t\t TestWriteOk: %s\n"
"\t\t RRawRecordingOk: %s\n"
"\t\t RawMultiSessionOk: %s\n"
"\t\t SessionAtOnceOk: %s\n"
"\t\t BufferUnderrunFree: %s\n"
"\t\t MaximumCueSheetLength: %lu\n",
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->RWSubchannelsRecordable),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->CdRewritable),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->TestWriteOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->RawRecordingOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->RawMultiSessionOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->SessionAtOnceOk),
BOOLEAN_TO_STRING_YES_NO_A(pCDMastering->BufferUnderrunFree),
MAKELONG(MAKEWORD(0, pCDMastering->MaximumCueSheetLength[2]),
MAKEWORD(pCDMastering->MaximumCueSheetLength[1], pCDMastering->MaximumCueSheetLength[0])));
}
VOID OutputGetConfigurationFeatureDvdRecordableWrite(
PFEATURE_DATA_DVD_RECORDABLE_WRITE pDVDRecordable
) {
OutputDriveLogA(
"\tFeatureDvdRecordableWrite\n"
"\t\t DVD_RW: %s\n"
"\t\t TestWrite: %s\n"
"\t\t RDualLayer: %s\n"
"\t\tBufferUnderrunFree: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDRecordable->DVD_RW),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRecordable->TestWrite),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRecordable->RDualLayer),
BOOLEAN_TO_STRING_YES_NO_A(pDVDRecordable->BufferUnderrunFree));
}
VOID OutputGetConfigurationFeatureLayerJumpRecording(
PFEATURE_DATA_LAYER_JUMP_RECORDING pLayerJumpRec
) {
OutputDriveLogA(
"\tFeatureLayerJumpRecording\n"
"\t\tNumberOfLinkSizes: %u\n",
pLayerJumpRec->NumberOfLinkSizes);
for (INT i = 0; i < pLayerJumpRec->NumberOfLinkSizes; i++) {
OutputDriveLogA(
"\t\tLinkSize %u: %u\n", i, pLayerJumpRec->LinkSizes[i]);
}
}
VOID OutputGetConfigurationFeatureCDRWMediaWriteSupport(
PFEATURE_CD_RW_MEDIA_WRITE_SUPPORT pCDRWMediaWrite
) {
OutputDriveLogA(
"\tFeatureCDRWMediaWriteSupport\n"
"\t\tSubtype 0: %s\n"
"\t\tSubtype 1: %s\n"
"\t\tSubtype 2: %s\n"
"\t\tSubtype 3: %s\n"
"\t\tSubtype 4: %s\n"
"\t\tSubtype 5: %s\n"
"\t\tSubtype 6: %s\n"
"\t\tSubtype 7: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype0),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype1),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype2),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype3),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype4),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype5),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype6),
BOOLEAN_TO_STRING_YES_NO_A(pCDRWMediaWrite->CDRWMediaSubtypeSupport.Subtype7));
}
VOID OutputGetConfigurationFeatureDvdPlusRWDualLayer(
PFEATURE_DATA_DVD_PLUS_RW_DUAL_LAYER pDVDPlusRWDL
) {
OutputDriveLogA(
"\tFeatureDvdPlusRWDualLayer\n"
"\t\t Write: %s\n"
"\t\t CloseOnly: %s\n"
"\t\tQuickStart: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDPlusRWDL->Write),
BOOLEAN_TO_STRING_YES_NO_A(pDVDPlusRWDL->CloseOnly),
BOOLEAN_TO_STRING_YES_NO_A(pDVDPlusRWDL->QuickStart));
}
VOID OutputGetConfigurationFeatureDvdPlusRDualLayer(
PFEATURE_DATA_DVD_PLUS_R_DUAL_LAYER pDVDPlusRDL
) {
OutputDriveLogA(
"\tFeatureDvdPlusRDualLayer\n"
"\t\tWrite: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pDVDPlusRDL->Write));
}
VOID OutputGetConfigurationFeatureHybridDisc(
PFEATURE_HYBRID_DISC pHybridDisc
) {
OutputDriveLogA(
"\tFeatureHybridDisc\n"
"\t\tResetImmunity: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pHybridDisc->ResetImmunity));
}
VOID OutputGetConfigurationFeaturePowerManagement(
PFEATURE_DATA_POWER_MANAGEMENT pPower
) {
OutputDriveLogA(
"\tFeaturePowerManagement\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pPower->Header.Current,
pPower->Header.Persistent,
pPower->Header.Version);
}
VOID OutputGetConfigurationFeatureSMART(
PFEATURE_DATA_SMART pSmart
) {
OutputDriveLogA(
"\tFeatureSMART\n"
"\t\tFaultFailureReportingPagePresent: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pSmart->FaultFailureReportingPagePresent));
}
VOID OutputGetConfigurationFeatureEmbeddedChanger(
PFEATURE_DATA_EMBEDDED_CHANGER pEmbedded
) {
OutputDriveLogA(
"\tFeatureEmbeddedChanger\n"
"\t\tSupportsDiscPresent: %s\n"
"\t\t SideChangeCapable: %s\n"
"\t\t HighestSlotNumber: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pEmbedded->SupportsDiscPresent),
BOOLEAN_TO_STRING_YES_NO_A(pEmbedded->SideChangeCapable),
pEmbedded->HighestSlotNumber);
}
VOID OutputGetConfigurationFeatureCDAudioAnalogPlay(
PFEATURE_DATA_CD_AUDIO_ANALOG_PLAY pCDAudio
) {
OutputDriveLogA(
"\tFeatureCDAudioAnalogPlay\n"
"\t\t SeperateVolume: %s\n"
"\t\tSeperateChannelMute: %s\n"
"\t\t ScanSupported: %s\n"
"\t\tNumerOfVolumeLevels: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pCDAudio->SeperateVolume),
BOOLEAN_TO_STRING_YES_NO_A(pCDAudio->SeperateChannelMute),
BOOLEAN_TO_STRING_YES_NO_A(pCDAudio->ScanSupported),
MAKEWORD(pCDAudio->NumerOfVolumeLevels[1], pCDAudio->NumerOfVolumeLevels[0]));
}
VOID OutputGetConfigurationFeatureMicrocodeUpgrade(
PFEATURE_DATA_MICROCODE_UPDATE pMicrocode
) {
OutputDriveLogA(
"\tFeatureMicrocodeUpgrade\n"
"\t\tM5: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pMicrocode->M5));
}
VOID OutputGetConfigurationFeatureTimeout(
PFEATURE_DATA_TIMEOUT pTimeOut
) {
OutputDriveLogA(
"\tFeatureTimeout\n"
"\t\t Group3: %s\n"
"\t\tUnitLength: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pTimeOut->Group3),
MAKEWORD(pTimeOut->UnitLength[1], pTimeOut->UnitLength[0]));
}
VOID OutputGetConfigurationFeatureDvdCSS(
PFEATURE_DATA_DVD_CSS pDVDCss
) {
OutputDriveLogA(
"\tFeatureDvdCSS\n"
"\t\tCssVersion: %u\n",
pDVDCss->CssVersion);
}
VOID OutputGetConfigurationFeatureRealTimeStreaming(
PFEATURE_DATA_REAL_TIME_STREAMING pRealTimeStreaming
) {
OutputDriveLogA(
"\tFeatureRealTimeStreaming\n"
"\t\t StreamRecording: %s\n"
"\t\t WriteSpeedInGetPerf: %s\n"
"\t\t WriteSpeedInMP2A: %s\n"
"\t\t SetCDSpeed: %s\n"
"\t\tReadBufferCapacityBlock: %s\n",
BOOLEAN_TO_STRING_YES_NO_A(pRealTimeStreaming->StreamRecording),
BOOLEAN_TO_STRING_YES_NO_A(pRealTimeStreaming->WriteSpeedInGetPerf),
BOOLEAN_TO_STRING_YES_NO_A(pRealTimeStreaming->WriteSpeedInMP2A),
BOOLEAN_TO_STRING_YES_NO_A(pRealTimeStreaming->SetCDSpeed),
BOOLEAN_TO_STRING_YES_NO_A(pRealTimeStreaming->ReadBufferCapacityBlock));
}
VOID OutputGetConfigurationFeatureLogicalUnitSerialNumber(
PFEATURE_DATA_LOGICAL_UNIT_SERIAL_NUMBER pLogical
) {
OutputDriveLogA(
"\tFeatureLogicalUnitSerialNumber\n"
"\t\tSerialNumber: ");
for (INT i = 0; i < pLogical->Header.AdditionalLength; i++) {
OutputDriveLogA("%c", pLogical->SerialNumber[i]);
}
OutputDriveLogA("\n");
}
VOID OutputGetConfigurationFeatureMediaSerialNumber(
PFEATURE_MEDIA_SERIAL_NUMBER pMediaSerialNumber
) {
OutputDriveLogA(
"\tFeatureMediaSerialNumber\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pMediaSerialNumber->Header.Current,
pMediaSerialNumber->Header.Persistent,
pMediaSerialNumber->Header.Version);
}
VOID OutputGetConfigurationFeatureDiscControlBlocks(
PFEATURE_DATA_DISC_CONTROL_BLOCKS pDiscCtrlBlk
) {
OutputDriveLogA("\tFeatureDiscControlBlocks\n");
for (INT i = 0; i < pDiscCtrlBlk->Header.AdditionalLength; i++) {
OutputDriveLogA(
"\t\tContentDescriptor %02u: %08ld\n", i,
MAKELONG(
MAKEWORD(pDiscCtrlBlk->Data[i].ContentDescriptor[3], pDiscCtrlBlk->Data[i].ContentDescriptor[2]),
MAKEWORD(pDiscCtrlBlk->Data[i].ContentDescriptor[1], pDiscCtrlBlk->Data[i].ContentDescriptor[0])));
}
}
VOID OutputGetConfigurationFeatureDvdCPRM(
PFEATURE_DATA_DVD_CPRM pDVDCprm
) {
OutputDriveLogA(
"\tFeatureDvdCPRM\n"
"\t\tCPRMVersion: %u\n",
pDVDCprm->CPRMVersion);
}
VOID OutputGetConfigurationFeatureFirmwareDate(
PFEATURE_DATA_FIRMWARE_DATE pFirmwareDate
) {
OutputDriveLogA(
"\tFeatureFirmwareDate: %.4s-%.2s-%.2s %.2s:%.2s:%.2s\n"
, pFirmwareDate->Year, pFirmwareDate->Month, pFirmwareDate->Day
, pFirmwareDate->Hour, pFirmwareDate->Minute, pFirmwareDate->Seconds);
}
VOID OutputGetConfigurationFeatureAACS(
PFEATURE_DATA_AACS pAACS
) {
OutputDriveLogA(
"\tFeatureAACS\n"
"\t\tBindingNonceGeneration: %s\n"
"\t\tBindingNonceBlockCount: %u\n"
"\t\t NumberOfAGIDs: %u\n"
"\t\t AACSVersion: %u\n",
BOOLEAN_TO_STRING_YES_NO_A(pAACS->BindingNonceGeneration),
pAACS->BindingNonceBlockCount,
pAACS->NumberOfAGIDs,
pAACS->AACSVersion);
}
VOID OutputGetConfigurationFeatureVCPS(
PFEATURE_VCPS pVcps
) {
OutputDriveLogA(
"\tFeatureVCPS\n"
"\t\t Current: %u\n"
"\t\tPersistent: %u\n"
"\t\t Version: %u\n",
pVcps->Header.Current,
pVcps->Header.Persistent,
pVcps->Header.Version);
}
VOID OutputGetConfigurationFeatureReserved(
PFEATURE_DATA_RESERVED pReserved
) {
OutputDriveLogA(
"\tReserved (FeatureCode[%#04x])\n"
"\t\tData: ", MAKEWORD(pReserved->Header.FeatureCode[1], pReserved->Header.FeatureCode[0]));
for (INT i = 0; i < pReserved->Header.AdditionalLength; i++) {
OutputDriveLogA("%02x", pReserved->Data[i]);
}
OutputDriveLogA("\n");
}
VOID OutputGetConfigurationFeatureVendorSpecific(
PFEATURE_DATA_VENDOR_SPECIFIC pVendorSpecific
) {
OutputDriveLogA(
"\tVendorSpecific (FeatureCode[%#04x])\n"
"\t\tVendorSpecificData: ",
MAKEWORD(pVendorSpecific->Header.FeatureCode[1], pVendorSpecific->Header.FeatureCode[0]));
for (INT i = 0; i < pVendorSpecific->Header.AdditionalLength; i++) {
OutputDriveLogA("%02x", pVendorSpecific->VendorSpecificData[i]);
}
OutputDriveLogA("\n");
}
VOID OutputGetConfigurationFeatureNumber(
PDEVICE pDevice,
LPBYTE lpConf,
DWORD dwAllLen
) {
DWORD n = 0;
while (n < dwAllLen) {
WORD wCode = MAKEWORD(lpConf[n + 1], lpConf[n]);
switch (wCode) {
case FeatureProfileList:
OutputGetConfigurationFeatureProfileList((PFEATURE_DATA_PROFILE_LIST)&lpConf[n]);
break;
case FeatureCore:
OutputGetConfigurationFeatureCore((PFEATURE_DATA_CORE)&lpConf[n]);
break;
case FeatureMorphing:
OutputGetConfigurationFeatureMorphing((PFEATURE_DATA_MORPHING)&lpConf[n]);
break;
case FeatureRemovableMedium:
OutputGetConfigurationFeatureRemovableMedium((PFEATURE_DATA_REMOVABLE_MEDIUM)&lpConf[n]);
break;
case FeatureWriteProtect:
OutputGetConfigurationFeatureWriteProtect((PFEATURE_DATA_WRITE_PROTECT)&lpConf[n]);
break;
case FeatureRandomReadable:
OutputGetConfigurationFeatureRandomReadable((PFEATURE_DATA_RANDOM_READABLE)&lpConf[n]);
break;
case FeatureMultiRead:
OutputGetConfigurationFeatureMultiRead((PFEATURE_DATA_MULTI_READ)&lpConf[n]);
break;
case FeatureCdRead:
OutputGetConfigurationFeatureCdRead((PFEATURE_DATA_CD_READ)&lpConf[n]);
SetFeatureCdRead((PFEATURE_DATA_CD_READ)&lpConf[n], pDevice);
break;
case FeatureDvdRead:
OutputGetConfigurationFeatureDvdRead((PFEATURE_DATA_DVD_READ)&lpConf[n]);
break;
case FeatureRandomWritable:
OutputGetConfigurationFeatureRandomWritable((PFEATURE_DATA_RANDOM_WRITABLE)&lpConf[n]);
break;
case FeatureIncrementalStreamingWritable:
OutputGetConfigurationFeatureIncrementalStreamingWritable((PFEATURE_DATA_INCREMENTAL_STREAMING_WRITABLE)&lpConf[n]);
break;
case FeatureSectorErasable:
OutputGetConfigurationFeatureSectorErasable((PFEATURE_DATA_SECTOR_ERASABLE)&lpConf[n]);
break;
case FeatureFormattable:
OutputGetConfigurationFeatureFormattable((PFEATURE_DATA_FORMATTABLE)&lpConf[n]);
break;
case FeatureDefectManagement:
OutputGetConfigurationFeatureDefectManagement((PFEATURE_DATA_DEFECT_MANAGEMENT)&lpConf[n]);
break;
case FeatureWriteOnce:
OutputGetConfigurationFeatureWriteOnce((PFEATURE_DATA_WRITE_ONCE)&lpConf[n]);
break;
case FeatureRestrictedOverwrite:
OutputGetConfigurationFeatureRestrictedOverwrite((PFEATURE_DATA_RESTRICTED_OVERWRITE)&lpConf[n]);
break;
case FeatureCdrwCAVWrite:
OutputGetConfigurationFeatureCdrwCAVWrite((PFEATURE_DATA_CDRW_CAV_WRITE)&lpConf[n]);
break;
case FeatureMrw:
OutputGetConfigurationFeatureMrw((PFEATURE_DATA_MRW)&lpConf[n]);
break;
case FeatureEnhancedDefectReporting:
OutputGetConfigurationFeatureEnhancedDefectReporting((PFEATURE_ENHANCED_DEFECT_REPORTING)&lpConf[n]);
break;
case FeatureDvdPlusRW:
OutputGetConfigurationFeatureDvdPlusRW((PFEATURE_DATA_DVD_PLUS_RW)&lpConf[n]);
break;
case FeatureDvdPlusR:
OutputGetConfigurationFeatureDvdPlusR((PFEATURE_DATA_DVD_PLUS_R)&lpConf[n]);
break;
case FeatureRigidRestrictedOverwrite:
OutputGetConfigurationFeatureRigidRestrictedOverwrite((PFEATURE_DATA_DVD_RW_RESTRICTED_OVERWRITE)&lpConf[n]);
break;
case FeatureCdTrackAtOnce:
OutputGetConfigurationFeatureCdTrackAtOnce((PFEATURE_DATA_CD_TRACK_AT_ONCE)&lpConf[n]);
break;
case FeatureCdMastering:
OutputGetConfigurationFeatureCdMastering((PFEATURE_DATA_CD_MASTERING)&lpConf[n]);
break;
case FeatureDvdRecordableWrite:
OutputGetConfigurationFeatureDvdRecordableWrite((PFEATURE_DATA_DVD_RECORDABLE_WRITE)&lpConf[n]);
break;
case FeatureLayerJumpRecording:
OutputGetConfigurationFeatureLayerJumpRecording((PFEATURE_DATA_LAYER_JUMP_RECORDING)&lpConf[n]);
break;
case FeatureCDRWMediaWriteSupport:
OutputGetConfigurationFeatureCDRWMediaWriteSupport((PFEATURE_CD_RW_MEDIA_WRITE_SUPPORT)&lpConf[n]);
break;
case FeatureDvdPlusRWDualLayer:
OutputGetConfigurationFeatureDvdPlusRWDualLayer((PFEATURE_DATA_DVD_PLUS_RW_DUAL_LAYER)&lpConf[n]);
break;
case FeatureDvdPlusRDualLayer:
OutputGetConfigurationFeatureDvdPlusRDualLayer((PFEATURE_DATA_DVD_PLUS_R_DUAL_LAYER)&lpConf[n]);
break;
case FeatureHybridDisc:
OutputGetConfigurationFeatureHybridDisc((PFEATURE_HYBRID_DISC)&lpConf[n]);
break;
case FeaturePowerManagement:
OutputGetConfigurationFeaturePowerManagement((PFEATURE_DATA_POWER_MANAGEMENT)&lpConf[n]);
break;
case FeatureSMART:
OutputGetConfigurationFeatureSMART((PFEATURE_DATA_SMART)&lpConf[n]);
break;
case FeatureEmbeddedChanger:
OutputGetConfigurationFeatureEmbeddedChanger((PFEATURE_DATA_EMBEDDED_CHANGER)&lpConf[n]);
break;
case FeatureCDAudioAnalogPlay:
OutputGetConfigurationFeatureCDAudioAnalogPlay((PFEATURE_DATA_CD_AUDIO_ANALOG_PLAY)&lpConf[n]);
break;
case FeatureMicrocodeUpgrade:
OutputGetConfigurationFeatureMicrocodeUpgrade((PFEATURE_DATA_MICROCODE_UPDATE)&lpConf[n]);
break;
case FeatureTimeout:
OutputGetConfigurationFeatureTimeout((PFEATURE_DATA_TIMEOUT)&lpConf[n]);
break;
case FeatureDvdCSS:
OutputGetConfigurationFeatureDvdCSS((PFEATURE_DATA_DVD_CSS)&lpConf[n]);
break;
case FeatureRealTimeStreaming:
OutputGetConfigurationFeatureRealTimeStreaming((PFEATURE_DATA_REAL_TIME_STREAMING)&lpConf[n]);
SetFeatureRealTimeStreaming((PFEATURE_DATA_REAL_TIME_STREAMING)&lpConf[n], pDevice);
break;
case FeatureLogicalUnitSerialNumber:
OutputGetConfigurationFeatureLogicalUnitSerialNumber((PFEATURE_DATA_LOGICAL_UNIT_SERIAL_NUMBER)&lpConf[n]);
break;
case FeatureMediaSerialNumber:
OutputGetConfigurationFeatureMediaSerialNumber((PFEATURE_MEDIA_SERIAL_NUMBER)&lpConf[n]);
break;
case FeatureDiscControlBlocks:
OutputGetConfigurationFeatureDiscControlBlocks((PFEATURE_DATA_DISC_CONTROL_BLOCKS)&lpConf[n]);
break;
case FeatureDvdCPRM:
OutputGetConfigurationFeatureDvdCPRM((PFEATURE_DATA_DVD_CPRM)&lpConf[n]);
break;
case FeatureFirmwareDate:
OutputGetConfigurationFeatureFirmwareDate((PFEATURE_DATA_FIRMWARE_DATE)&lpConf[n]);
break;
case FeatureAACS:
OutputGetConfigurationFeatureAACS((PFEATURE_DATA_AACS)&lpConf[n]);
break;
case FeatureVCPS:
OutputGetConfigurationFeatureVCPS((PFEATURE_VCPS)&lpConf[n]);
break;
default:
if (0x0111 <= wCode && wCode <= 0xfeff) {
OutputGetConfigurationFeatureReserved((PFEATURE_DATA_RESERVED)&lpConf[n]);
}
else if (0xff00 <= wCode && wCode <= 0xffff) {
OutputGetConfigurationFeatureVendorSpecific((PFEATURE_DATA_VENDOR_SPECIFIC)&lpConf[n]);
}
break;
}
n += sizeof(FEATURE_HEADER) + lpConf[n + 3];
}
}
VOID OutputCDAtip(
PCDROM_TOC_ATIP_DATA_BLOCK pAtip
) {
OutputDiscLogA(OUTPUT_DHYPHEN_PLUS_STR(TOC ATIP)
"\tCdrwReferenceSpeed: %u\n"
"\t WritePower: %u\n"
"\t UnrestrictedUse: %s\n"
, pAtip->CdrwReferenceSpeed
, pAtip->WritePower
, BOOLEAN_TO_STRING_YES_NO_A(pAtip->UnrestrictedUse)
);
switch (pAtip->IsCdrw)
{
case 0: OutputDiscLogA("\t DiscType: CD-R, DiscSubType: %u\n", pAtip->DiscSubType);
break;
case 1: OutputDiscLogA("\t DiscType: CD-RW, ");
switch (pAtip->DiscSubType)
{
case 0: OutputDiscLogA("DiscSubType: Standard Speed\n");
break;
case 1: OutputDiscLogA("DiscSubType: High Speed\n");
break;
default: OutputDiscLogA("DiscSubType: Unknown\n");
break;
}
break;
default: OutputDiscLogA(" DiscType: Unknown\n");
break;
}
OutputDiscLogA(
"\t LeadInMsf: %02u:%02u:%02u\n"
"\t LeadOutMsf: %02u:%02u:%02u\n"
, pAtip->LeadInMsf[0], pAtip->LeadInMsf[1], pAtip->LeadInMsf[2]
, pAtip->LeadOutMsf[0], pAtip->LeadOutMsf[1], pAtip->LeadOutMsf[2]
);
if (pAtip->A1Valid) {
OutputDiscLogA(
"\t A1Values: %02u:%02u:%02u\n"
, pAtip->A1Values[0], pAtip->A1Values[1], pAtip->A1Values[2]
);
}
if (pAtip->A2Valid) {
OutputDiscLogA(
"\t A2Values: %02u:%02u:%02u\n"
, pAtip->A2Values[0], pAtip->A2Values[1], pAtip->A2Values[2]
);
}
if (pAtip->A3Valid) {
OutputDiscLogA(
"\t A3Values: %02u:%02u:%02u\n"
, pAtip->A3Values[0], pAtip->A3Values[1], pAtip->A3Values[2]
);
}
}
VOID OutputCDTextOther(
PCDROM_TOC_CD_TEXT_DATA_BLOCK pDesc,
WORD wTocTextEntries,
BYTE bySizeInfoIdx,
BYTE bySizeInfoCnt
) {
INT nTocInfoCnt = 0;
INT nSizeInfoCnt = 0;
for (size_t z = 0; z <= bySizeInfoIdx; z++) {
if (pDesc[z].PackType == CDROM_CD_TEXT_PACK_TOC_INFO) {
// detail in Page 54-55 of EN 60908:1999
OutputDiscLogA("\tTocInfo\n");
if (nTocInfoCnt == 0) {
OutputDiscLogA(
"\t\t First track number: %u\n"
"\t\t Last track number: %u\n"
"\t\t Lead-out(msf): %u:%u:%u\n"
, pDesc[z].Text[0], pDesc[z].Text[1], pDesc[z].Text[3]
, pDesc[z].Text[4], pDesc[z].Text[5]);
}
if (nTocInfoCnt == 1) {
for (INT i = 0, j = 0; i < 4; i++, j += 3) {
OutputDiscLogA(
"\t\t Track %d(msf): %u:%u:%u\n"
, i + 1, pDesc[z].Text[j], pDesc[z].Text[j + 1], pDesc[z].Text[j + 2]);
}
}
nTocInfoCnt++;
}
else if (pDesc[z].PackType == CDROM_CD_TEXT_PACK_TOC_INFO2) {
OutputDiscLogA(
"\tTocInfo2\n"
"\t\t Priority number: %u\n"
"\t\t Number of intervals: %u\n"
"\t\t Start point(minutes): %u\n"
"\t\t Start point(seconds): %u\n"
"\t\t Start point(frames): %u\n"
"\t\t End point(minutes): %u\n"
"\t\t End point(seconds): %u\n"
"\t\t End point(frames): %u\n"
, pDesc[z].Text[0], pDesc[z].Text[1], pDesc[z].Text[6], pDesc[z].Text[7]
, pDesc[z].Text[8], pDesc[z].Text[9], pDesc[z].Text[10], pDesc[z].Text[11]);
}
else if (pDesc[z].PackType == CDROM_CD_TEXT_PACK_SIZE_INFO) {
// detail in Page 56 of EN 60908:1999
OutputDiscLogA("\tSizeInfo\n");
if (nSizeInfoCnt == 0) {
OutputDiscLogA(
"\t\t Charactor Code for this BLOCK: %u\n"
"\t\t First track Number: %u\n"
"\t\t Last track Number: %u\n"
"\t\t Mode2 & copy protection flags: %u\n"
"\t\tNumber of PACKS with ALBUM_NAME: %u\n"
"\t\t Number of PACKS with PERFORMER: %u\n"
"\t\tNumber of PACKS with SONGWRITER: %u\n"
"\t\t Number of PACKS with COMPOSER: %u\n"
"\t\t Number of PACKS with ARRANGER: %u\n"
"\t\t Number of PACKS with MESSAGES: %u\n"
"\t\t Number of PACKS with DISC_ID: %u\n"
"\t\t Number of PACKS with GENRE: %u\n",
pDesc[wTocTextEntries - bySizeInfoCnt].Text[0],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[1],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[2],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[3],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[4],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[5],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[6],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[7],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[8],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[9],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[10],
pDesc[wTocTextEntries - bySizeInfoCnt].Text[11]);
}
else if (nSizeInfoCnt == 1) {
OutputDiscLogA(
"\t\t Number of PACKS with TOC_INFO: %u\n"
"\t\t Number of PACKS with TOC_INFO2: %u\n"
"\t\t Number of PACKS with $8a: %u\n"
"\t\t Number of PACKS with $8b: %u\n"
"\t\t Number of PACKS with $8c: %u\n"
"\t\t Number of PACKS with $8d: %u\n"
"\t\t Number of PACKS with UPC_EAN: %u\n"
"\t\t Number of PACKS with SIZE_INFO: %u\n"
"\t\tLast Sequence number of BLOCK 0: %u\n"
"\t\tLast Sequence number of BLOCK 1: %u\n"
"\t\tLast Sequence number of BLOCK 2: %u\n"
"\t\tLast Sequence number of BLOCK 3: %u\n",
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[0],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[1],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[2],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[3],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[4],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[5],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[6],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[7],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[8],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[9],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[10],
pDesc[wTocTextEntries - bySizeInfoCnt + 1].Text[11]);
}
else if (nSizeInfoCnt == 2) {
OutputDiscLogA(
"\t\tLast Sequence number of BLOCK 4: %u\n"
"\t\tLast Sequence number of BLOCK 5: %u\n"
"\t\tLast Sequence number of BLOCK 6: %u\n"
"\t\tLast Sequence number of BLOCK 7: %u\n"
"\t\t Language code BLOCK 0: %u\n"
"\t\t Language code BLOCK 1: %u\n"
"\t\t Language code BLOCK 2: %u\n"
"\t\t Language code BLOCK 3: %u\n"
"\t\t Language code BLOCK 4: %u\n"
"\t\t Language code BLOCK 5: %u\n"
"\t\t Language code BLOCK 6: %u\n"
"\t\t Language code BLOCK 7: %u\n",
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[0],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[1],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[2],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[3],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[4],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[5],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[6],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[7],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[8],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[9],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[10],
pDesc[wTocTextEntries - bySizeInfoCnt + 2].Text[11]);
}
nSizeInfoCnt++;
}
}
}
VOID OutputDiscInformation(
PDISC_INFORMATION pDiscInformation
) {
LPCSTR lpDiscStatus[] = {
"Empty", "Incomplete", "Complete", "Others"
};
LPCSTR lpStateOfLastSession[] = {
"Empty", "Incomplete", "Reserved / Damaged", "Complete"
};
LPCSTR lpBGFormatStatus[] = {
"None", "Incomplete", "Running", "Complete"
};
OutputDiscLogA(
OUTPUT_DHYPHEN_PLUS_STR(DiscInformation)
"\t DiscStatus: %s\n"
"\t LastSessionStatus: %s\n"
"\t Erasable: %s\n"
"\t FirstTrackNumber: %u\n"
"\t NumberOfSessionsLsb: %u\n"
"\t LastSessionFirstTrackLsb: %u\n"
"\t LastSessionLastTrackLsb: %u\n"
"\t MrwStatus: %s\n"
"\t MrwDirtyBit: %s\n"
"\t UnrestrictedUse: %s\n"
"\t DiscBarCodeValid: %s\n"
"\t DiscIDValid: %s\n"
"\t DiscType: "
, lpDiscStatus[pDiscInformation->DiscStatus]
, lpStateOfLastSession[pDiscInformation->LastSessionStatus]
, BOOLEAN_TO_STRING_YES_NO_A(pDiscInformation->Erasable)
, pDiscInformation->FirstTrackNumber
, pDiscInformation->NumberOfSessionsLsb
, pDiscInformation->LastSessionFirstTrackLsb
, pDiscInformation->LastSessionLastTrackLsb
, lpBGFormatStatus[pDiscInformation->MrwStatus]
, BOOLEAN_TO_STRING_YES_NO_A(pDiscInformation->MrwDirtyBit)
, BOOLEAN_TO_STRING_YES_NO_A(pDiscInformation->URU)
, BOOLEAN_TO_STRING_YES_NO_A(pDiscInformation->DBC_V)
, BOOLEAN_TO_STRING_YES_NO_A(pDiscInformation->DID_V));
switch (pDiscInformation->DiscType) {
case DISK_TYPE_CDDA:
OutputDiscLogA("CD-DA or CD-ROM Disc\n");
break;
case DISK_TYPE_CDI:
OutputDiscLogA("CD-I Disc\n");
break;
case DISK_TYPE_XA:
OutputDiscLogA("CD-ROM XA Disc\n");
break;
case DISK_TYPE_UNDEFINED:
OutputDiscLogA("Undefined\n");
break;
default:
OutputDiscLogA("Reserved\n");
break;
}
if (pDiscInformation->DID_V) {
OutputDiscLogA(
"\t DiscIdentification: %u%u%u%u\n",
pDiscInformation->DiskIdentification[0],
pDiscInformation->DiskIdentification[1],
pDiscInformation->DiskIdentification[2],
pDiscInformation->DiskIdentification[3]);
}
OutputDiscLogA(
"\t LastSessionLeadIn: %02x:%02x:%02x:%02x\n"
"\tLastPossibleLeadOutStartTime: %02x:%02x:%02x:%02x\n",
pDiscInformation->LastSessionLeadIn[0],
pDiscInformation->LastSessionLeadIn[1],
pDiscInformation->LastSessionLeadIn[2],
pDiscInformation->LastSessionLeadIn[3],
pDiscInformation->LastPossibleLeadOutStartTime[0],
pDiscInformation->LastPossibleLeadOutStartTime[1],
pDiscInformation->LastPossibleLeadOutStartTime[2],
pDiscInformation->LastPossibleLeadOutStartTime[3]);
if (pDiscInformation->DBC_V) {
OutputDiscLogA(
"\t DiscBarCode: %u%u%u%u%u%u%u%u\n",
pDiscInformation->DiskBarCode[0],
pDiscInformation->DiskBarCode[1],
pDiscInformation->DiskBarCode[2],
pDiscInformation->DiskBarCode[3],
pDiscInformation->DiskBarCode[4],
pDiscInformation->DiskBarCode[5],
pDiscInformation->DiskBarCode[6],
pDiscInformation->DiskBarCode[7]);
}
OutputDiscLogA(
"\t NumberOPCEntries: %u\n",
pDiscInformation->NumberOPCEntries);
if (pDiscInformation->NumberOPCEntries) {
OutputDiscLogA(
"\t OPCTable\n");
}
for (INT i = 0; i < pDiscInformation->NumberOPCEntries; i++) {
OutputDiscLogA(
"\t\t Speed: %u%u\n"
"\t\t OPCValues: %u%u%u%u%u%u\n",
pDiscInformation->OPCTable[0].Speed[0],
pDiscInformation->OPCTable[0].Speed[1],
pDiscInformation->OPCTable[0].OPCValue[0],
pDiscInformation->OPCTable[0].OPCValue[1],
pDiscInformation->OPCTable[0].OPCValue[2],
pDiscInformation->OPCTable[0].OPCValue[3],
pDiscInformation->OPCTable[0].OPCValue[4],
pDiscInformation->OPCTable[0].OPCValue[5]);
}
}
VOID OutputModeParmeterHeader(
PMODE_PARAMETER_HEADER pHeader
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(ModeParmeterHeader)
"\t ModeDataLength: %u\n"
"\t MediumType: %u\n"
"\tDeviceSpecificParameter: %u\n"
"\t BlockDescriptorLength: %u\n"
, pHeader->ModeDataLength
, pHeader->MediumType
, pHeader->DeviceSpecificParameter
, pHeader->BlockDescriptorLength);
}
VOID OutputModeParmeterHeader10(
PMODE_PARAMETER_HEADER10 pHeader
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(ModeParmeterHeader10)
"\t ModeDataLength: %u\n"
"\t MediumType: %u\n"
"\tDeviceSpecificParameter: %u\n"
"\t BlockDescriptorLength: %u\n"
, MAKEWORD(pHeader->ModeDataLength[1],
pHeader->ModeDataLength[0])
, pHeader->MediumType
, pHeader->DeviceSpecificParameter
, MAKEWORD(pHeader->BlockDescriptorLength[1],
pHeader->BlockDescriptorLength[0]));
}
VOID OutputCDVDCapabilitiesPage(
PCDVD_CAPABILITIES_PAGE cdvd,
INT perKb
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(CDVD Capabilities & Mechanism Status Page)
"\t PageCode: %#04x\n"
"\t PSBit: %s\n"
"\t PageLength: %u\n"
"\t CDRRead: %s\n"
"\t CDERead: %s\n"
"\t Method2: %s\n"
"\t DVDROMRead: %s\n"
"\t DVDRRead: %s\n"
"\t DVDRAMRead: %s\n"
"\t CDRWrite: %s\n"
"\t CDEWrite: %s\n"
"\t TestWrite: %s\n"
"\t DVDRWrite: %s\n"
"\t DVDRAMWrite: %s\n"
"\t AudioPlay: %s\n"
"\t Composite: %s\n"
"\t DigitalPortOne: %s\n"
"\t DigitalPortTwo: %s\n"
"\t Mode2Form1: %s\n"
"\t Mode2Form2: %s\n"
"\t MultiSession: %s\n"
"\t BufferUnderrunFree: %s\n"
"\t CDDA: %s\n"
"\t CDDAAccurate: %s\n"
"\t RWSupported: %s\n"
"\t RWDeinterleaved: %s\n"
"\t C2Pointers: %s\n"
"\t ISRC: %s\n"
"\t UPC: %s\n"
"\t ReadBarCodeCapable: %s\n"
"\t Lock: %s\n"
"\t LockState: %s\n"
"\t PreventJumper: %s\n"
"\t Eject: %s\n"
"\t LoadingMechanismType: "
, cdvd->PageCode
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->PSBit)
, cdvd->PageLength
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDRRead)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDERead)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Method2)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DVDROMRead)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DVDRRead)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DVDRAMRead)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDRWrite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDEWrite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->TestWrite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DVDRWrite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DVDRAMWrite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->AudioPlay)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Composite)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DigitalPortOne)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->DigitalPortTwo)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Mode2Form1)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Mode2Form2)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->MultiSession)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->BufferUnderrunFree)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDDA)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->CDDAAccurate)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->RWSupported)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->RWDeinterleaved)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->C2Pointers)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->ISRC)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->UPC)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->ReadBarCodeCapable)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Lock)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->LockState)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->PreventJumper)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->Eject));
switch (cdvd->LoadingMechanismType) {
case LOADING_MECHANISM_CADDY:
OutputDriveLogA("caddy\n")
break;
case LOADING_MECHANISM_TRAY:
OutputDriveLogA("tray\n")
break;
case LOADING_MECHANISM_POPUP:
OutputDriveLogA("popup\n")
break;
case LOADING_MECHANISM_INDIVIDUAL_CHANGER:
OutputDriveLogA("individual changer\n")
break;
case LOADING_MECHANISM_CARTRIDGE_CHANGER:
OutputDriveLogA("cartridge changer\n")
break;
default:
OutputDriveLogA("unknown\n")
break;
}
WORD rsm = MAKEWORD(cdvd->ReadSpeedMaximum[1], cdvd->ReadSpeedMaximum[0]);
WORD rsc = MAKEWORD(cdvd->ReadSpeedCurrent[1], cdvd->ReadSpeedCurrent[0]);
WORD wsm = MAKEWORD(cdvd->WriteSpeedMaximum[1], cdvd->WriteSpeedMaximum[0]);
WORD wsc = MAKEWORD(cdvd->WriteSpeedCurrent[1], cdvd->WriteSpeedCurrent[0]);
WORD bs = MAKEWORD(cdvd->BufferSize[1], cdvd->BufferSize[0]);
OutputDriveLogA(
"\t SeparateVolume: %s\n"
"\t SeperateChannelMute: %s\n"
"\t SupportsDiskPresent: %s\n"
"\t SWSlotSelection: %s\n"
"\t SideChangeCapable: %s\n"
"\t RWInLeadInReadable: %s\n"
"\t ReadSpeedMaximum: %uKB/sec (%ux)\n"
"\t NumberVolumeLevels: %u\n"
"\t BufferSize: %u\n"
"\t ReadSpeedCurrent: %uKB/sec (%ux)\n"
"\t BCK: %s\n"
"\t RCK: %s\n"
"\t LSBF: %s\n"
"\t Length: %u\n"
"\t WriteSpeedMaximum: %uKB/sec (%ux)\n"
"\t WriteSpeedCurrent: %uKB/sec (%ux)\n"
"\tCopyManagementRevision: %u\n"
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->SeparateVolume)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->SeperateChannelMute)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->SupportsDiskPresent)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->SWSlotSelection)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->SideChangeCapable)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->RWInLeadInReadable)
, rsm, rsm / perKb
, MAKEWORD(cdvd->NumberVolumeLevels[1],
cdvd->NumberVolumeLevels[0])
, bs
, rsc, rsc / perKb
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->BCK)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->RCK)
, BOOLEAN_TO_STRING_YES_NO_A(cdvd->LSBF)
, cdvd->Length
, wsm, wsm / perKb
, wsc, wsc / perKb
, MAKEWORD(cdvd->CopyManagementRevision[1], cdvd->CopyManagementRevision[0]));
}
VOID OutputReadBufferCapacity(
PREAD_BUFFER_CAPACITY_DATA pReadBufCapaData
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(ReadBufferCapacity)
"\t TotalBufferSize: %luKByte\n"
"\tAvailableBufferSize: %luKByte\n",
MAKELONG(MAKEWORD(pReadBufCapaData->TotalBufferSize[3],
pReadBufCapaData->TotalBufferSize[2]),
MAKEWORD(pReadBufCapaData->TotalBufferSize[1],
pReadBufCapaData->TotalBufferSize[0])) / 1024,
MAKELONG(MAKEWORD(pReadBufCapaData->AvailableBufferSize[3],
pReadBufCapaData->AvailableBufferSize[2]),
MAKEWORD(pReadBufCapaData->AvailableBufferSize[1],
pReadBufCapaData->AvailableBufferSize[0])) / 1024);
}
VOID OutputSetSpeed(
PCDROM_SET_SPEED pSetspeed
) {
OutputDriveLogA(
OUTPUT_DHYPHEN_PLUS_STR(SetSpeed)
"\t RequestType: %s\n"
"\t ReadSpeed: %uKB/sec\n"
"\t WriteSpeed: %uKB/sec\n"
"\tRotationControl: %s\n",
pSetspeed->RequestType == 0 ?
"CdromSetSpeed" : "CdromSetStreaming",
pSetspeed->ReadSpeed,
pSetspeed->WriteSpeed,
pSetspeed->RotationControl == 0 ?
"CdromDefaultRotation" : "CdromCAVRotation");
}
VOID OutputEepromUnknownByte(
LPBYTE pBuf,
DWORD startIdx,
DWORD endIdx
) {
if (startIdx <= endIdx) {
OutputDriveLogA("\t Unknown[%03ld]: ", startIdx);
for (DWORD i = startIdx; i <= endIdx; i++) {
OutputDriveLogA("%02x ", pBuf[i]);
}
OutputDriveLogA("\n");
}
}
VOID OutputEepromOverPX712(
LPBYTE pBuf
) {
OutputDriveLogA("\t Silent Mode: ");
if (pBuf[0] == 1) {
OutputDriveLogA(
"Enabled\n"
"\t\t Access Time: ");
if (pBuf[1] == 0) {
OutputDriveLogA("Fast\n");
}
else if (pBuf[1] == 1) {
OutputDriveLogA("Slow\n");
}
OutputDriveLogA(
"\t\t Max Read Speed: %dx\n"
"\t\t Unknown: %dx\n"
"\t\t Max Write Speed: %dx\n"
"\t\t Unknown: %dx\n"
"\t\t Unknown: %02x\n"
"\t\t Tray Speed Eject: %02x (Low d0 - 80 High)\n"
"\t\tTray Speed Loading: %02x (Low 2f - 7f High)\n",
pBuf[2], pBuf[3], pBuf[4],
pBuf[5], pBuf[6], pBuf[7], pBuf[8]);
}
else {
OutputDriveLogA("Disable\n");
}
DWORD tmp = 9;
OutputDriveLogA("\t SecuRec: ");
while (tmp < 29) {
OutputDriveLogA("%02x ", pBuf[tmp]);
tmp += 1;
}
OutputDriveLogA("\n\t SpeedRead: ");
if (pBuf[29] == 0xf0 || pBuf[29] == 0) {
OutputDriveLogA("Enable");
}
else if (pBuf[29] == 0xff || pBuf[29] == 0x0f) {
OutputDriveLogA("Disable");
}
OutputDriveLogA("\n\t Unknown: %x\n", pBuf[30]);
OutputDriveLogA("\t Spindown Time: ");
switch (pBuf[31]) {
case 0:
OutputDriveLogA("Infinite\n");
break;
case 1:
OutputDriveLogA("125 ms\n");
break;
case 2:
OutputDriveLogA("250 ms\n");
break;
case 3:
OutputDriveLogA("500 ms\n");
break;
case 4:
OutputDriveLogA("1 second\n");
break;
case 5:
OutputDriveLogA("2 seconds\n");
break;
case 6:
OutputDriveLogA("4 seconds\n");
break;
case 7:
OutputDriveLogA("8 seconds\n");
break;
case 8:
OutputDriveLogA("16 seconds\n");
break;
case 9:
OutputDriveLogA("32 seconds\n");
break;
case 10:
OutputDriveLogA("1 minite\n");
break;
case 11:
OutputDriveLogA("2 minites\n");
break;
case 12:
OutputDriveLogA("4 minites\n");
break;
case 13:
OutputDriveLogA("8 minites\n");
break;
case 14:
OutputDriveLogA("16 minites\n");
break;
case 15:
OutputDriveLogA("32 minites\n");
break;
default:
OutputDriveLogA("Unset\n");
break;
}
LONG ucr =
MAKELONG(MAKEWORD(pBuf[37], pBuf[36]), MAKEWORD(pBuf[35], pBuf[34]));
LONG ucw =
MAKELONG(MAKEWORD(pBuf[41], pBuf[40]), MAKEWORD(pBuf[39], pBuf[38]));
LONG udr =
MAKELONG(MAKEWORD(pBuf[45], pBuf[44]), MAKEWORD(pBuf[43], pBuf[42]));
LONG udw =
MAKELONG(MAKEWORD(pBuf[49], pBuf[48]), MAKEWORD(pBuf[47], pBuf[46]));
OutputDriveLogA(
"\tDisc load count: %u\n"
"\t CD read time: %02lu:%02lu:%02lu\n"
"\t CD write time: %02lu:%02lu:%02lu\n"
"\t DVD read time: %02lu:%02lu:%02lu\n"
"\t DVD write time: %02lu:%02lu:%02lu\n"
, MAKEWORD(pBuf[33], pBuf[32])
, ucr / 3600, ucr / 60 % 60, ucr % 60
, ucw / 3600, ucw / 60 % 60, ucw % 60
, udr / 3600, udr / 60 % 60, udr % 60
, udw / 3600, udw / 60 % 60, udw % 60);
OutputEepromUnknownByte(pBuf, 50, 114);
OutputDriveLogA("\tChange BookType: ");
switch (pBuf[115]) {
case 0xfc:
OutputDriveLogA("for DVD+R, DVD+R DL\n");
break;
case 0xfd:
OutputDriveLogA("for DVD+R\n");
break;
case 0xfe:
OutputDriveLogA("for DVD+R DL\n");
break;
case 0xff:
OutputDriveLogA("Disable\n");
break;
default:
OutputDriveLogA("Unknown[%02x]\n", pBuf[115]);
break;
}
}
VOID OutputEeprom(
LPBYTE pBuf,
INT nRoop,
BOOL byPlxtrDrive
) {
if (nRoop == 0) {
OutputDriveLogA(
"\t Signature: %02x %02x\n"
"\t VendorId: %.8s\n"
"\t ProductId: %.16s\n"
"\t SerialNumber: %06lu\n"
, pBuf[0], pBuf[1]
, (LPCH)&pBuf[2]
, (LPCH)&pBuf[10]
, strtoul((LPCH)&pBuf[26], NULL, 16));
OutputEepromUnknownByte(pBuf, 31, 40);
switch (byPlxtrDrive) {
case PLXTR_DRIVE_TYPE::PX760A:
case PLXTR_DRIVE_TYPE::PX755A:
case PLXTR_DRIVE_TYPE::PX716AL:
case PLXTR_DRIVE_TYPE::PX716A:
case PLXTR_DRIVE_TYPE::PX714A:
case PLXTR_DRIVE_TYPE::PX712A:
OutputDriveLogA("\t TLA: %.4s\n", (LPCH)&pBuf[41]);
break;
default:
OutputEepromUnknownByte(pBuf, 41, 44);
break;
}
OutputEepromUnknownByte(pBuf, 45, 107);
switch (byPlxtrDrive) {
case PLXTR_DRIVE_TYPE::PX760A:
case PLXTR_DRIVE_TYPE::PX755A:
case PLXTR_DRIVE_TYPE::PX716AL:
case PLXTR_DRIVE_TYPE::PX716A:
case PLXTR_DRIVE_TYPE::PX714A:
OutputEepromUnknownByte(pBuf, 108, 255);
break;
case PLXTR_DRIVE_TYPE::PX712A:
OutputEepromUnknownByte(pBuf, 108, 255);
OutputEepromOverPX712(&pBuf[256]);
OutputEepromUnknownByte(pBuf, 372, 510);
OutputDriveLogA(
"\t Sum: %02x (SpeedRead: %02x + Spindown Time: %02x + BookType: %02x + Others)\n"
, pBuf[511], pBuf[285], pBuf[287], pBuf[371]);
break;
case PLXTR_DRIVE_TYPE::PX708A2:
case PLXTR_DRIVE_TYPE::PX708A:
case PLXTR_DRIVE_TYPE::PX704A:
{
OutputEepromUnknownByte(pBuf, 108, 114);
LONG ucr = MAKELONG(MAKEWORD(pBuf[120], pBuf[119]), MAKEWORD(pBuf[118], pBuf[117]));
LONG ucw = MAKELONG(MAKEWORD(pBuf[125], pBuf[124]), MAKEWORD(pBuf[123], pBuf[122]));
OutputDriveLogA(
"\tDisc load count: %u\n"
"\t CD read time: %02lu:%02lu:%02lu\n"
"\t Unknown: %02x\n"
"\t CD write time: %02lu:%02lu:%02lu\n"
, MAKEWORD(pBuf[116], pBuf[115])
, ucr / 3600, ucr / 60 % 60, ucr % 60
, pBuf[121]
, ucw / 3600, ucw / 60 % 60, ucw % 60);
OutputEepromUnknownByte(pBuf, 126, 211);
LONG udr =
MAKELONG(MAKEWORD(pBuf[215], pBuf[214]), MAKEWORD(pBuf[213], pBuf[212]));
LONG udw =
MAKELONG(MAKEWORD(pBuf[219], pBuf[218]), MAKEWORD(pBuf[217], pBuf[216]));
OutputDriveLogA(
"\t DVD read time: %02lu:%02lu:%02lu\n"
"\t DVD write time: %02lu:%02lu:%02lu\n"
, udr / 3600, udr / 60 % 60, udr % 60
, udw / 3600, udw / 60 % 60, udw % 60);
OutputEepromUnknownByte(pBuf, 220, 255);
break;
}
case PLXTR_DRIVE_TYPE::PX320A:
{
OutputEepromUnknownByte(pBuf, 108, 123);
LONG ucr = MAKELONG(MAKEWORD(pBuf[127], pBuf[126]), MAKEWORD(pBuf[125], pBuf[124]));
OutputDriveLogA(
"\t CD read time: %02lu:%02lu:%02lu\n"
, ucr / 3600, ucr / 60 % 60, ucr % 60);
OutputEepromUnknownByte(pBuf, 128, 187);
LONG udr =
MAKELONG(MAKEWORD(pBuf[191], pBuf[190]), MAKEWORD(pBuf[189], pBuf[188]));
OutputDriveLogA(
"\t DVD read time: %02lu:%02lu:%02lu\n"
, udr / 3600, udr / 60 % 60, udr % 60);
OutputEepromUnknownByte(pBuf, 192, 226);
OutputDriveLogA(
"\tDisc load count: %u\n"
, MAKEWORD(pBuf[228], pBuf[227]));
OutputEepromUnknownByte(pBuf, 229, 255);
break;
}
case PLXTR_DRIVE_TYPE::PREMIUM2:
case PLXTR_DRIVE_TYPE::PREMIUM:
case PLXTR_DRIVE_TYPE::PXW5224A:
case PLXTR_DRIVE_TYPE::PXW4824A:
case PLXTR_DRIVE_TYPE::PXW4012A:
case PLXTR_DRIVE_TYPE::PXW4012S:
{
LONG ucr = MAKELONG(MAKEWORD(pBuf[111], pBuf[110]), MAKEWORD(pBuf[109], pBuf[108]));
LONG ucw = MAKELONG(MAKEWORD(pBuf[125], pBuf[124]), MAKEWORD(pBuf[123], pBuf[122]));
OutputDriveLogA(
"\t CD read time: %02lu:%02lu:%02lu\n"
"\t Unknown: %02x %02x %02x %02x %02x %02x %02x %02x\n"
"\tDisc load count: %u\n"
"\t CD write time: %02lu:%02lu:%02lu\n"
, ucr / 3600, ucr / 60 % 60, ucr % 60
, pBuf[112], pBuf[113], pBuf[114], pBuf[115], pBuf[116], pBuf[117], pBuf[118], pBuf[119]
, MAKEWORD(pBuf[121], pBuf[120])
, ucw / 3600, ucw / 60 % 60, ucw % 60);
OutputEepromUnknownByte(pBuf, 126, 127);
break;
}
case PLXTR_DRIVE_TYPE::PXW2410A:
case PLXTR_DRIVE_TYPE::PXS88T:
case PLXTR_DRIVE_TYPE::PXW1610A:
case PLXTR_DRIVE_TYPE::PXW1210A:
case PLXTR_DRIVE_TYPE::PXW1210S:
{
OutputEepromUnknownByte(pBuf, 108, 119);
LONG ucw = MAKELONG(MAKEWORD(pBuf[125], pBuf[124]), MAKEWORD(pBuf[123], pBuf[122]));
OutputDriveLogA(
"\tDisc load count: %u\n"
"\t CD write time: %02lu:%02lu:%02lu\n"
, MAKEWORD(pBuf[121], pBuf[120])
, ucw / 3600, ucw / 60 % 60, ucw % 60);
OutputEepromUnknownByte(pBuf, 126, 127);
break;
}
case PLXTR_DRIVE_TYPE::PXW124TS:
case PLXTR_DRIVE_TYPE::PXW8432T:
case PLXTR_DRIVE_TYPE::PXW8220T:
case PLXTR_DRIVE_TYPE::PXW4220T:
case PLXTR_DRIVE_TYPE::PXR820T:
{
OutputEepromUnknownByte(pBuf, 108, 121);
LONG ucw = MAKELONG(MAKEWORD(pBuf[125], pBuf[124]), MAKEWORD(pBuf[123], pBuf[122]));
OutputDriveLogA(
"\t CD write time: %02lu:%02lu:%02lu\n"
, ucw / 3600, ucw / 60 % 60, ucw % 60);
OutputEepromUnknownByte(pBuf, 126, 127);
break;
}
case PLXTR_DRIVE_TYPE::PXR412C:
case PLXTR_DRIVE_TYPE::PX40TS:
case PLXTR_DRIVE_TYPE::PX40TSUW:
case PLXTR_DRIVE_TYPE::PX40TW:
case PLXTR_DRIVE_TYPE::PX32TS:
case PLXTR_DRIVE_TYPE::PX32CS:
case PLXTR_DRIVE_TYPE::PX20TS:
case PLXTR_DRIVE_TYPE::PX12TS:
case PLXTR_DRIVE_TYPE::PX12CS:
case PLXTR_DRIVE_TYPE::PX8XCS:
OutputEepromUnknownByte(pBuf, 108, 127);
break;
}
}
else if (nRoop == 1 && byPlxtrDrive <= PLXTR_DRIVE_TYPE::PX714A) {
OutputEepromOverPX712(pBuf);
OutputDriveLogA("\t Auto Strategy: ");
switch (pBuf[116]) {
case 0x06:
if (PLXTR_DRIVE_TYPE::PX716AL <= byPlxtrDrive && byPlxtrDrive <= PLXTR_DRIVE_TYPE::PX714A) {
OutputDriveLogA("AS OFF\n");
}
else {
OutputDriveLogA("Unknown[%02x]\n", pBuf[116]);
}
break;
case 0x07:
if (PLXTR_DRIVE_TYPE::PX716AL <= byPlxtrDrive && byPlxtrDrive <= PLXTR_DRIVE_TYPE::PX714A) {
OutputDriveLogA("Auto Selection\n");
}
else {
OutputDriveLogA("AS ON\n");
}
break;
case 0x0b:
OutputDriveLogA("AS ON(Forced)\n");
break;
case 0x0e:
if (byPlxtrDrive <= PLXTR_DRIVE_TYPE::PX755A) {
OutputDriveLogA("AS OFF\n");
}
else {
OutputDriveLogA("Unknown[%02x]\n", pBuf[116]);
}
break;
case 0x0f:
if (byPlxtrDrive <= PLXTR_DRIVE_TYPE::PX755A) {
OutputDriveLogA("Auto Selection\n");
}
else {
OutputDriveLogA("Unknown[%02x]\n", pBuf[116]);
}
break;
default:
OutputDriveLogA("Unknown[%02x]\n", pBuf[116]);
break;
}
OutputEepromUnknownByte(pBuf, 117, 254);
OutputDriveLogA(
"\t Sum: %02x (SpeedRead: %02x + Spindown Time: %02x + BookType: %02x + Auto Strategy: %02x + Others)\n"
, pBuf[255], pBuf[29], pBuf[31], pBuf[115], pBuf[116]);
}
else {
OutputEepromUnknownByte(pBuf, 0, 255);
}
}
| 33.268718 | 120 | 0.688735 | tungol |
4dce6c9ece96363ecd1f5bd5b0888a1db9332d9d | 1,896 | hpp | C++ | include/type_tools.hpp | ne0ndrag0n/BlastBASIC | f38f05c27fe5532f9ea52f4599f72d6a5353e15c | [
"MIT"
] | 2 | 2021-01-26T11:58:08.000Z | 2021-05-26T22:12:19.000Z | include/type_tools.hpp | ne0ndrag0n/GoldScorpion | f38f05c27fe5532f9ea52f4599f72d6a5353e15c | [
"MIT"
] | null | null | null | include/type_tools.hpp | ne0ndrag0n/GoldScorpion | f38f05c27fe5532f9ea52f4599f72d6a5353e15c | [
"MIT"
] | null | null | null | #pragma once
#include "token.hpp"
#include "result_type.hpp"
#include "symbol.hpp"
#include "ast.hpp"
#include <string>
#include <optional>
namespace GoldScorpion {
struct SymbolTypeSettings {
std::string fileId;
SymbolResolver& symbols;
};
using SymbolTypeResult = Result< SymbolType, std::string >;
std::optional< TokenType > typeIdToTokenType( const std::string& id );
std::optional< std::string > tokenTypeToTypeId( const TokenType type );
std::optional< std::string > tokenToTypeId( const Token& token );
bool tokenIsPrimitiveType( const Token& token );
bool typesComparable( const SymbolType& lhs, const SymbolType& rhs );
bool typeIsArray( const SymbolType& type );
bool typeIsFunction( const SymbolType& type );
bool typeIsUdt( const SymbolType& type );
bool typeIsInteger( const SymbolType& type );
bool typeIsString( const SymbolType& type );
bool typesMatch( const SymbolType& lhs, const SymbolType& rhs, SymbolTypeSettings settings );
bool integerTypesMatch( const SymbolType& lhs, const SymbolType& rhs );
bool assignmentCoercible( const SymbolType& lhs, const SymbolType& rhs );
bool coercibleToString( const SymbolType& lhs, const SymbolType& rhs );
SymbolNativeType promotePrimitiveTypes( const SymbolNativeType& lhs, const SymbolNativeType& rhs );
// New symbol type stuff that will replace the type stuff immediately above
SymbolTypeResult getType( const Primary& node, SymbolTypeSettings settings );
SymbolTypeResult getType( const CallExpression& node, SymbolTypeSettings settings );
SymbolTypeResult getType( const BinaryExpression& node, SymbolTypeSettings settings );
SymbolTypeResult getType( const AssignmentExpression& node, SymbolTypeSettings settings );
SymbolTypeResult getType( const Expression& node, SymbolTypeSettings settings );
}
| 34.472727 | 103 | 0.741561 | ne0ndrag0n |
4dd0fe514094f2a11e71db7d7051e1d553bbf0e5 | 876 | cpp | C++ | src/gb-lib/mem/mirrorbank.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | src/gb-lib/mem/mirrorbank.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | src/gb-lib/mem/mirrorbank.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | #include "mirrorbank.h"
#include <stdexcept>
#include "location/location.h"
#include "mem_tools.h"
MirrorBank::MirrorBank(const MemoryArea& mirrorArea, const MemoryArea& originalArea, IMemoryManagerSP mirrored)
: SingleAreaManager(mirrorArea)
, offset_(originalArea.from - mirrorArea.from)
, mirrored_(std::move(mirrored))
{
if (mirrorArea.to - mirrorArea.from > originalArea.to - originalArea.from) {
throw std::invalid_argument("Mirror bigger than original");
}
}
auto MirrorBank::getByte(address_type address) -> Location<uint8_t>
{
return mirrored_->getByte(mem_tools::translateAddressSafe(address, singleArea(), offset_));
}
auto MirrorBank::getWord(address_type address) -> Location<uint16_t>
{
mem_tools::assertSafe(address + 1, singleArea());
return mirrored_->getWord(mem_tools::translateAddressSafe(address, singleArea(), offset_));
}
| 31.285714 | 111 | 0.756849 | johannes51 |
4dd3a1cd09f0812fe436090c41b6f88e69478e24 | 1,231 | cc | C++ | fbstab/components/dense_data.cc | tcunis/fbstab | 25d5259f683427867f140567d739a55ed7359aca | [
"BSD-3-Clause"
] | 16 | 2019-08-09T18:43:17.000Z | 2022-01-07T12:38:27.000Z | fbstab/components/dense_data.cc | tcunis/fbstab | 25d5259f683427867f140567d739a55ed7359aca | [
"BSD-3-Clause"
] | 12 | 2019-08-14T17:33:29.000Z | 2021-02-01T12:03:36.000Z | fbstab/components/dense_data.cc | tcunis/fbstab | 25d5259f683427867f140567d739a55ed7359aca | [
"BSD-3-Clause"
] | 3 | 2019-08-09T19:03:23.000Z | 2020-05-07T23:03:33.000Z | #include "fbstab/components/dense_data.h"
#include <Eigen/Dense>
#include <cmath>
#include <stdexcept>
namespace fbstab {
using MatrixXd = Eigen::MatrixXd;
using VectorXd = Eigen::VectorXd;
void DenseData::gemvH(const Eigen::VectorXd &x, double a, double b,
Eigen::VectorXd *y) const {
*y = a * H_ * x + b * (*y);
}
void DenseData::gemvG(const Eigen::VectorXd &x, double a, double b,
Eigen::VectorXd *y) const {
*y = a * G_ * x + b * (*y);
}
void DenseData::gemvGT(const Eigen::VectorXd &x, double a, double b,
Eigen::VectorXd *y) const {
*y = a * G_.transpose() * x + b * (*y);
}
void DenseData::gemvA(const Eigen::VectorXd &x, double a, double b,
Eigen::VectorXd *y) const {
*y = a * A_ * x + b * (*y);
}
void DenseData::gemvAT(const Eigen::VectorXd &x, double a, double b,
Eigen::VectorXd *y) const {
*y = a * A_.transpose() * x + b * (*y);
}
void DenseData::axpyf(double a, Eigen::VectorXd *y) const { *y += a * f_; }
void DenseData::axpyh(double a, Eigen::VectorXd *y) const { *y += a * h_; }
void DenseData::axpyb(double a, Eigen::VectorXd *y) const { *y += a * b_; }
} // namespace fbstab
| 27.977273 | 75 | 0.576767 | tcunis |
4dd441fd93d7ec0f5533639612df4b552c50b987 | 2,661 | cpp | C++ | gueepo2D/engine/core/GameObject/GameWorld.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 1 | 2022-02-03T19:24:47.000Z | 2022-02-03T19:24:47.000Z | gueepo2D/engine/core/GameObject/GameWorld.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 4 | 2021-10-30T19:03:07.000Z | 2022-02-10T01:06:02.000Z | gueepo2D/engine/core/GameObject/GameWorld.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 1 | 2021-10-01T03:08:21.000Z | 2021-10-01T03:08:21.000Z | #include "gueepo2Dpch.h"
#include "GameWorld.h"
#include "Entity.h"
#include "GameObject.h"
namespace gueepo {
GameWorld* GameWorld::s_instance = nullptr;
GameWorld::GameWorld() {
if (s_instance != nullptr) {
LOG_ERROR("trying to create a second instance of the game world?!");
return;
}
s_instance = this;
}
GameWorld::~GameWorld() {}
void GameWorld::BeginPlay() {
for (auto entity : m_AllEntities) {
entity->BeginPlay();
}
}
void GameWorld::ProcessInput(const InputState& CurrentInputState) {
for (auto entity : m_AllEntities) {
entity->ProcessInput(CurrentInputState);
}
}
void GameWorld::Update(float DeltaTime) {
for (auto entity : m_AllEntities) {
entity->Update(DeltaTime);
}
Internal_Update(DeltaTime);
}
void GameWorld::Render(SpriteBatcher* batch) {
for (auto entity : m_AllEntities) {
entity->Render(batch);
}
}
void GameWorld::Destroy() {
for (auto entity : m_AllEntities) {
entity->Destroy();
}
}
Entity* GameWorld::CreateEntity(const std::string& name) {
Entity* newEntity = new Entity(name);
m_EntitiesToBeAdded.push_back(newEntity);
return newEntity;
}
gueepo::GameObject* GameWorld::CreateGameObject(Texture* tex, const std::string& name /*= "GameObject"*/) {
GameObject* newGameObject = new GameObject(tex, name);
m_EntitiesToBeAdded.push_back(newGameObject);
return newGameObject;
}
void GameWorld::KillEntity(Entity* entity) {
m_entitiesToBeRemoved.push_back(entity);
}
void GameWorld::Internal_Update(float DeltaTime) {
for(auto entity: m_EntitiesToBeAdded) {
m_AllEntities.push_back(entity);
}
m_EntitiesToBeAdded.clear();
for (auto entity : m_entitiesToBeRemoved) {
if (!entity->IsActive()) {
// it was already removed!
LOG_WARN("trying to remove entity that was already removed...");
continue;
}
auto toRemove = std::find(m_AllEntities.begin(), m_AllEntities.end(), entity);
if (toRemove != m_AllEntities.end()) {
std::iter_swap(toRemove, m_AllEntities.end() - 1);
entity->Destroy();
delete entity;
m_AllEntities.pop_back();
}
}
m_entitiesToBeRemoved.clear();
}
// =================================================
//
// static implementations
//
// =================================================
Entity* GameWorld::Create(const std::string& name) {
g2dassert(s_instance != nullptr, "can't create an entity without creating a game world!");
return s_instance->CreateEntity(name);
}
void GameWorld::Kill(Entity* entity) {
g2dassert(s_instance != nullptr, "can't destroy an entity without creating a game world!");
s_instance->KillEntity(entity);
}
} | 23.972973 | 108 | 0.668546 | guilhermepo2 |
4dd48978ce7b6d77a579bc94675ba8937c4c8aee | 148,518 | cpp | C++ | src/source.cpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/source.cpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | src/source.cpp | jlangvand/jucipp | 0a3102f13e62d78a329d488fb1eb8812181e448e | [
"MIT"
] | null | null | null | #include "source.hpp"
#include "config.hpp"
#include "ctags.hpp"
#include "directories.hpp"
#include "filesystem.hpp"
#include "git.hpp"
#include "info.hpp"
#include "json.hpp"
#include "menu.hpp"
#include "selection_dialog.hpp"
#include "terminal.hpp"
#include "utility.hpp"
#include <algorithm>
#include <boost/spirit/home/qi/char.hpp>
#include <boost/spirit/home/qi/operator.hpp>
#include <boost/spirit/home/qi/string.hpp>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <regex>
#include <set>
#ifdef _WIN32
#include <windows.h>
inline DWORD get_current_process_id() {
return GetCurrentProcessId();
}
#else
#include <unistd.h>
inline pid_t get_current_process_id() {
return getpid();
}
#endif
std::unique_ptr<TinyProcessLib::Process> Source::View::prettier_background_process = {};
Glib::RefPtr<Gsv::LanguageManager> Source::LanguageManager::get_default() {
static auto instance = Gsv::LanguageManager::create();
return instance;
}
Glib::RefPtr<Gsv::StyleSchemeManager> Source::StyleSchemeManager::get_default() {
static auto instance = Gsv::StyleSchemeManager::create();
static bool first = true;
if(first) {
instance->prepend_search_path((Config::get().home_juci_path / "styles").string());
first = false;
}
return instance;
}
Glib::RefPtr<Gsv::Language> Source::guess_language(const boost::filesystem::path &file_path) {
auto language_manager = LanguageManager::get_default();
bool result_uncertain = false;
auto filename = file_path.filename().string();
auto content_type = Gio::content_type_guess(filename, nullptr, 0, result_uncertain);
if(result_uncertain)
content_type.clear();
auto language = language_manager->guess_language(filename, content_type);
if(!language) {
auto extension = file_path.extension().string();
if(filename == "CMakeLists.txt")
language = language_manager->get_language("cmake");
else if(filename == "meson.build")
language = language_manager->get_language("meson");
else if(filename == "Makefile")
language = language_manager->get_language("makefile");
else if(extension == ".tcc")
language = language_manager->get_language("cpphdr");
else if(extension == ".ts" || extension == ".tsx" || extension == ".jsx" || extension == ".flow")
language = language_manager->get_language("js");
else if(extension == ".vert" || // listed on https://github.com/KhronosGroup/glslang
extension == ".frag" ||
extension == ".tesc" ||
extension == ".tese" ||
extension == ".geom" ||
extension == ".comp")
language = language_manager->get_language("glsl");
else if(!file_path.has_extension()) {
for(auto &part : file_path) {
if(part == "include") {
language = language_manager->get_language("cpphdr");
break;
}
}
}
}
else if(language->get_id() == "cuda") {
if(file_path.extension() == ".cuh")
language = language_manager->get_language("cpphdr");
else
language = language_manager->get_language("cpp");
}
else if(language->get_id() == "opencl")
language = language_manager->get_language("cpp");
return language;
}
Source::FixIt::FixIt(std::string source_, std::string path_, std::pair<Offset, Offset> offsets_) : source(std::move(source_)), path(std::move(path_)), offsets(std::move(offsets_)) {
if(this->source.size() == 0)
type = Type::erase;
else {
if(this->offsets.first == this->offsets.second)
type = Type::insert;
else
type = Type::replace;
}
}
std::string Source::FixIt::string(BaseView &view) {
bool in_current_view = path == view.file_path;
auto from_pos = (!in_current_view ? boost::filesystem::path(path).filename().string() + ':' : "") + std::to_string(offsets.first.line + 1) + ':' + std::to_string(offsets.first.index + 1);
std::string to_pos, text;
if(type != Type::insert) {
to_pos = std::to_string(offsets.second.line + 1) + ':' + std::to_string(offsets.second.index + 1);
if(in_current_view) {
text = view.get_buffer()->get_text(view.get_iter_at_line_index(offsets.first.line, offsets.first.index),
view.get_iter_at_line_index(offsets.second.line, offsets.second.index));
}
}
if(type == Type::insert)
return "Insert " + source + " at " + from_pos;
else if(type == Type::replace)
return "Replace " + (!text.empty() ? text + " at " : "") + from_pos + " - " + to_pos + " with " + source;
else
return "Erase " + (!text.empty() ? text + " at " : "") + from_pos + " - " + to_pos;
}
//////////////
//// View ////
//////////////
std::set<Source::View *> Source::View::non_deleted_views;
std::set<Source::View *> Source::View::views;
Source::View::View(const boost::filesystem::path &file_path, const Glib::RefPtr<Gsv::Language> &language, bool is_generic_view) : BaseView(file_path, language), SpellCheckView(file_path, language), DiffView(file_path, language) {
non_deleted_views.emplace(this);
views.emplace(this);
similar_symbol_tag = get_buffer()->create_tag();
similar_symbol_tag->property_weight() = Pango::WEIGHT_ULTRAHEAVY;
similar_symbol_tag->property_background_rgba() = Gdk::RGBA("rgba(255, 255, 255, 0.075)");
clickable_tag = get_buffer()->create_tag();
clickable_tag->property_underline() = Pango::Underline::UNDERLINE_SINGLE;
clickable_tag->property_underline_set() = true;
get_buffer()->create_tag("def:warning_underline");
get_buffer()->create_tag("def:error_underline");
auto mark_attr_debug_breakpoint = Gsv::MarkAttributes::create();
Gdk::RGBA rgba;
rgba.set_red(1.0);
rgba.set_green(0.5);
rgba.set_blue(0.5);
rgba.set_alpha(0.3);
mark_attr_debug_breakpoint->set_background(rgba);
set_mark_attributes("debug_breakpoint", mark_attr_debug_breakpoint, 100);
auto mark_attr_debug_stop = Gsv::MarkAttributes::create();
rgba.set_red(0.5);
rgba.set_green(0.5);
rgba.set_blue(1.0);
mark_attr_debug_stop->set_background(rgba);
set_mark_attributes("debug_stop", mark_attr_debug_stop, 101);
auto mark_attr_debug_breakpoint_and_stop = Gsv::MarkAttributes::create();
rgba.set_red(0.75);
rgba.set_green(0.5);
rgba.set_blue(0.75);
mark_attr_debug_breakpoint_and_stop->set_background(rgba);
set_mark_attributes("debug_breakpoint_and_stop", mark_attr_debug_breakpoint_and_stop, 102);
hide_tag = get_buffer()->create_tag();
hide_tag->property_scale() = 0.25;
if(is_c || is_cpp) {
use_fixed_continuation_indenting = false;
// TODO 2019: check if clang-format has improved...
// boost::filesystem::path clang_format_file;
// auto search_path=file_path.parent_path();
// boost::system::error_code ec;
// while(true) {
// clang_format_file=search_path/".clang-format";
// if(boost::filesystem::exists(clang_format_file, ec))
// break;
// clang_format_file=search_path/"_clang-format";
// if(boost::filesystem::exists(clang_format_file, ec))
// break;
// clang_format_file.clear();
// if(search_path==search_path.root_directory())
// break;
// search_path=search_path.parent_path();
// }
// if(!clang_format_file.empty()) {
// auto lines=filesystem::read_lines(clang_format_file);
// for(auto &line: lines) {
// std::cout << "1" << std::endl;
// if(!line.empty() && line.compare(0, 23, "ContinuationIndentWidth")==0) {
// std::cout << "2" << std::endl;
// use_continuation_indenting=true;
// break;
// }
// }
// }
}
setup_signals();
setup_format_style(is_generic_view);
std::string comment_characters;
if(is_bracket_language)
comment_characters = "//";
else {
if(is_language({"cmake", "makefile", "python", "python3", "sh", "perl", "ruby", "r", "asm", "automake", "yaml", "docker", "julia"}))
comment_characters = "#";
else if(is_language({"latex", "matlab", "octave", "bibtex"}))
comment_characters = "%";
else if(language_id == "fortran")
comment_characters = "!";
else if(language_id == "pascal")
comment_characters = "//";
else if(language_id == "lua")
comment_characters = "--";
}
if(!comment_characters.empty()) {
toggle_comments = [this, comment_characters = std::move(comment_characters)] {
std::vector<int> lines;
Gtk::TextIter selection_start, selection_end;
get_buffer()->get_selection_bounds(selection_start, selection_end);
auto line_start = selection_start.get_line();
auto line_end = selection_end.get_line();
if(line_start != line_end && selection_end.starts_line())
--line_end;
bool lines_commented = true;
bool extra_spaces = true;
int min_indentation = std::numeric_limits<int>::max();
for(auto line = line_start; line <= line_end; ++line) {
auto iter = get_buffer()->get_iter_at_line(line);
bool line_added = false;
bool line_commented = false;
bool extra_space = false;
int indentation = 0;
for(;;) {
if(iter.ends_line())
break;
else if(*iter == ' ' || *iter == '\t') {
++indentation;
iter.forward_char();
continue;
}
else {
lines.emplace_back(line);
line_added = true;
for(size_t c = 0; c < comment_characters.size(); ++c) {
if(iter.ends_line()) {
break;
}
else if(*iter == static_cast<unsigned int>(comment_characters[c])) {
if(c < comment_characters.size() - 1) {
iter.forward_char();
continue;
}
else {
line_commented = true;
if(!iter.ends_line()) {
iter.forward_char();
if(*iter == ' ')
extra_space = true;
}
break;
}
}
else
break;
}
break;
}
}
if(line_added) {
lines_commented &= line_commented;
extra_spaces &= extra_space;
min_indentation = std::min(min_indentation, indentation);
}
}
if(lines.size()) {
auto comment_characters_and_space = comment_characters + ' ';
get_buffer()->begin_user_action();
for(auto &line : lines) {
auto iter = get_buffer()->get_iter_at_line(line);
if(min_indentation != std::numeric_limits<int>::max())
iter.forward_chars(min_indentation);
if(lines_commented) {
auto end_iter = iter;
end_iter.forward_chars(comment_characters.size() + static_cast<int>(extra_spaces));
while(*iter == ' ' || *iter == '\t') {
iter.forward_char();
end_iter.forward_char();
}
get_buffer()->erase(iter, end_iter);
}
else
get_buffer()->insert(iter, comment_characters_and_space);
}
get_buffer()->end_user_action();
}
};
}
get_methods = [this]() {
std::vector<std::pair<Offset, std::string>> methods;
boost::filesystem::path file_path;
boost::system::error_code ec;
bool use_tmp_file = false;
bool is_cpp_standard_header = is_cpp && this->file_path.extension().empty();
if(this->get_buffer()->get_modified() || is_cpp_standard_header) {
use_tmp_file = true;
file_path = boost::filesystem::temp_directory_path(ec);
if(ec) {
Terminal::get().print("\e[31mError\e[m: could not get temporary directory folder\n", true);
return methods;
}
file_path /= "jucipp_get_methods" + std::to_string(get_current_process_id());
boost::filesystem::create_directory(file_path, ec);
if(ec) {
Terminal::get().print("\e[31mError\e[m: could not create temporary folder\n", true);
return methods;
}
file_path /= this->file_path.filename().string() + (is_cpp_standard_header ? ".hpp" : "");
filesystem::write(file_path, this->get_buffer()->get_text().raw());
}
else
file_path = this->file_path;
Ctags ctags(file_path, true, true);
if(use_tmp_file)
boost::filesystem::remove_all(file_path.parent_path(), ec);
if(!ctags) {
Info::get().print("No methods found in current buffer");
return methods;
}
std::string line;
while(std::getline(ctags.output, line)) {
auto location = ctags.get_location(line, true, is_cpp);
std::transform(location.kind.begin(), location.kind.end(), location.kind.begin(),
[](char c) { return std::tolower(c); });
std::vector<std::string> ignore_kinds = {"variable", "local", "constant", "global", "property", "member", "enum",
"class", "struct", "namespace",
"macro", "param", "header",
"typedef", "using", "alias",
"project", "option"};
if(std::none_of(ignore_kinds.begin(), ignore_kinds.end(), [&location](const std::string &e) { return location.kind.find(e) != std::string::npos; }) &&
location.source.find("<b>") != std::string::npos) {
std::string scope = !location.scope.empty() ? Glib::Markup::escape_text(location.scope) : "";
if(is_cpp && !scope.empty()) { // Remove namespace from location.source in C++ source files
auto pos = location.source.find(scope + "::<b>");
if(pos != std::string::npos)
location.source.erase(pos, scope.size() + 2);
}
methods.emplace_back(Offset(location.line, location.index), (!scope.empty() ? scope + ":" : "") + std::to_string(location.line + 1) + ": " + location.source);
}
}
std::sort(methods.begin(), methods.end(), [](const std::pair<Offset, std::string> &e1, const std::pair<Offset, std::string> &e2) {
return e1.first < e2.first;
});
if(methods.empty())
Info::get().print("No methods found in current buffer");
return methods;
};
}
Gsv::DrawSpacesFlags Source::View::parse_show_whitespace_characters(const std::string &text) {
namespace qi = boost::spirit::qi;
qi::symbols<char, Gsv::DrawSpacesFlags> options;
options.add("space", Gsv::DRAW_SPACES_SPACE)("tab", Gsv::DRAW_SPACES_TAB)("newline", Gsv::DRAW_SPACES_NEWLINE)("nbsp", Gsv::DRAW_SPACES_NBSP)("leading", Gsv::DRAW_SPACES_LEADING)("text", Gsv::DRAW_SPACES_TEXT)("trailing", Gsv::DRAW_SPACES_TRAILING)("all", Gsv::DRAW_SPACES_ALL);
std::set<Gsv::DrawSpacesFlags> out;
// parse comma-separated list of options
qi::phrase_parse(text.begin(), text.end(), options % ',', qi::space, out);
return out.count(Gsv::DRAW_SPACES_ALL) > 0 ? Gsv::DRAW_SPACES_ALL : static_cast<Gsv::DrawSpacesFlags>(std::accumulate(out.begin(), out.end(), 0));
}
bool Source::View::save() {
if(file_path.empty() || !get_buffer()->get_modified())
return false;
if(Config::get().source.cleanup_whitespace_characters)
cleanup_whitespace_characters();
if(format_style && file_path.filename() != "package.json") {
if(Config::get().source.format_style_on_save)
format_style(true, true);
else if(Config::get().source.format_style_on_save_if_style_file_found)
format_style(false, true);
hide_tooltips();
}
try {
auto io_channel = Glib::IOChannel::create_from_file(file_path.string(), "w");
auto start_iter = get_buffer()->begin();
auto end_iter = start_iter;
while(start_iter) {
end_iter.forward_chars(131072);
io_channel->write(get_buffer()->get_text(start_iter, end_iter));
start_iter = end_iter;
}
}
catch(const Glib::Error &error) {
Terminal::get().print("\e[31mError\e[m: could not save file " + filesystem::get_short_path(file_path).string() + ": " + error.what() + '\n', true);
return false;
}
boost::system::error_code ec;
last_write_time = boost::filesystem::last_write_time(file_path, ec);
if(ec)
last_write_time.reset();
// Remonitor file in case it did not exist before
monitor_file();
get_buffer()->set_modified(false);
Directories::get().on_save_file(file_path);
return true;
}
void Source::View::configure() {
SpellCheckView::configure();
DiffView::configure();
if(Config::get().source.style.size() > 0) {
auto scheme = StyleSchemeManager::get_default()->get_scheme(Config::get().source.style);
if(scheme)
get_source_buffer()->set_style_scheme(scheme);
}
set_draw_spaces(parse_show_whitespace_characters(Config::get().source.show_whitespace_characters));
{ // Set Word Wrap
namespace qi = boost::spirit::qi;
std::set<std::string> word_wrap_language_ids;
qi::phrase_parse(Config::get().source.word_wrap.begin(), Config::get().source.word_wrap.end(), (+(~qi::char_(','))) % ',', qi::space, word_wrap_language_ids);
if(std::any_of(word_wrap_language_ids.begin(), word_wrap_language_ids.end(), [this](const std::string &word_wrap_language_id) {
return word_wrap_language_id == language_id || word_wrap_language_id == "all";
}))
set_wrap_mode(Gtk::WrapMode::WRAP_WORD_CHAR);
else
set_wrap_mode(Gtk::WrapMode::WRAP_NONE);
}
property_highlight_current_line() = Config::get().source.highlight_current_line;
line_renderer->set_visible(Config::get().source.show_line_numbers);
#if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION >= 20)
Gdk::Rectangle rectangle;
get_iter_location(get_buffer()->begin(), rectangle);
set_bottom_margin((rectangle.get_height() + get_pixels_above_lines() + get_pixels_below_lines()) * 10);
#endif
if(Config::get().source.show_background_pattern)
gtk_source_view_set_background_pattern(this->gobj(), GTK_SOURCE_BACKGROUND_PATTERN_TYPE_GRID);
else
gtk_source_view_set_background_pattern(this->gobj(), GTK_SOURCE_BACKGROUND_PATTERN_TYPE_NONE);
if((property_show_right_margin() = Config::get().source.show_right_margin))
property_right_margin_position() = Config::get().source.right_margin_position;
//Create tags for diagnostic warnings and errors:
auto scheme = get_source_buffer()->get_style_scheme();
auto tag_table = get_buffer()->get_tag_table();
auto style = scheme->get_style("def:warning");
auto diagnostic_tag_underline = get_buffer()->get_tag_table()->lookup("def:warning_underline");
if(style && (style->property_foreground_set() || style->property_background_set())) {
Glib::ustring warning_property;
if(style->property_foreground_set())
warning_property = style->property_foreground().get_value();
else if(style->property_background_set())
warning_property = style->property_background().get_value();
diagnostic_tag_underline->property_underline() = Pango::Underline::UNDERLINE_ERROR;
auto tag_class = G_OBJECT_GET_CLASS(diagnostic_tag_underline->gobj()); //For older GTK+ 3 versions:
auto param_spec = g_object_class_find_property(tag_class, "underline-rgba");
if(param_spec)
diagnostic_tag_underline->set_property("underline-rgba", Gdk::RGBA(warning_property));
}
style = scheme->get_style("def:error");
diagnostic_tag_underline = get_buffer()->get_tag_table()->lookup("def:error_underline");
if(style && (style->property_foreground_set() || style->property_background_set())) {
Glib::ustring error_property;
if(style->property_foreground_set())
error_property = style->property_foreground().get_value();
else if(style->property_background_set())
error_property = style->property_background().get_value();
diagnostic_tag_underline->property_underline() = Pango::Underline::UNDERLINE_ERROR;
diagnostic_tag_underline->set_property("underline-rgba", Gdk::RGBA(error_property));
}
//TODO: clear tag_class and param_spec?
style = scheme->get_style("selection");
if(style && style->property_foreground_set())
extra_cursor_selection->property_foreground() = style->property_foreground().get_value();
else
extra_cursor_selection->property_foreground_rgba() = get_style_context()->get_color(Gtk::StateFlags::STATE_FLAG_SELECTED);
if(style && style->property_background_set())
extra_cursor_selection->property_background() = style->property_background().get_value();
else
extra_cursor_selection->property_background_rgba() = get_style_context()->get_background_color(Gtk::StateFlags::STATE_FLAG_SELECTED);
if(Config::get().menu.keys["source_show_completion"].empty()) {
get_completion()->unblock_interactive();
interactive_completion = true;
}
else {
get_completion()->block_interactive();
interactive_completion = false;
}
}
void Source::View::setup_signals() {
get_buffer()->signal_changed().connect([this]() {
if(update_status_location)
update_status_location(this);
hide_tooltips();
if(similar_symbol_tag_applied) {
get_buffer()->remove_tag(similar_symbol_tag, get_buffer()->begin(), get_buffer()->end());
similar_symbol_tag_applied = false;
}
if(clickable_tag_applied) {
get_buffer()->remove_tag(clickable_tag, get_buffer()->begin(), get_buffer()->end());
clickable_tag_applied = false;
}
previous_extended_selections.clear();
});
// Line numbers
line_renderer = Gtk::manage(new Gsv::GutterRendererText());
auto gutter = get_gutter(Gtk::TextWindowType::TEXT_WINDOW_LEFT);
line_renderer->set_alignment_mode(Gsv::GutterRendererAlignmentMode::GUTTER_RENDERER_ALIGNMENT_MODE_FIRST);
line_renderer->set_alignment(1.0, -1);
line_renderer->set_padding(3, -1);
gutter->insert(line_renderer, GTK_SOURCE_VIEW_GUTTER_POSITION_LINES);
auto set_line_renderer_width = [this] {
int width, height;
line_renderer->measure(std::to_string(get_buffer()->get_line_count()), width, height);
line_renderer->set_size(width);
};
set_line_renderer_width();
get_buffer()->signal_changed().connect([set_line_renderer_width] {
set_line_renderer_width();
});
signal_style_updated().connect([set_line_renderer_width] {
set_line_renderer_width();
});
line_renderer->signal_query_data().connect([this](const Gtk::TextIter &start, const Gtk::TextIter &end, Gsv::GutterRendererState state) {
if(!start.begins_tag(hide_tag) && !start.has_tag(hide_tag)) {
if(start.get_line() == get_buffer()->get_insert()->get_iter().get_line())
line_renderer->set_text(Gsv::Markup("<b>" + std::to_string(start.get_line() + 1) + "</b>"));
else
line_renderer->set_text(Gsv::Markup(std::to_string(start.get_line() + 1)));
}
});
line_renderer->signal_query_activatable().connect([](const Gtk::TextIter &, const Gdk::Rectangle &, GdkEvent *) {
return true;
});
line_renderer->signal_activate().connect([this](const Gtk::TextIter &iter, const Gdk::Rectangle &, GdkEvent *) {
if(toggle_breakpoint)
toggle_breakpoint(iter.get_line());
});
type_tooltips.on_motion = [this] {
delayed_tooltips_connection.disconnect();
};
diagnostic_tooltips.on_motion = [this] {
delayed_tooltips_connection.disconnect();
};
signal_motion_notify_event().connect([this](GdkEventMotion *event) {
if(on_motion_last_x != event->x || on_motion_last_y != event->y) {
delayed_tooltips_connection.disconnect();
if((event->state & GDK_BUTTON1_MASK) == 0) {
delayed_tooltips_connection = Glib::signal_timeout().connect(
[this, x = event->x, y = event->y]() {
type_tooltips.hide();
diagnostic_tooltips.hide();
Tooltips::init();
Gdk::Rectangle rectangle(x, y, 1, 1);
if(parsed) {
show_type_tooltips(rectangle);
show_diagnostic_tooltips(rectangle);
}
return false;
},
100);
}
if(clickable_tag_applied) {
get_buffer()->remove_tag(clickable_tag, get_buffer()->begin(), get_buffer()->end());
clickable_tag_applied = false;
}
if((event->state & primary_modifier_mask) && !(event->state & GDK_SHIFT_MASK) && !(event->state & GDK_BUTTON1_MASK)) {
delayed_tag_clickable_connection.disconnect();
delayed_tag_clickable_connection = Glib::signal_timeout().connect(
[this, x = event->x, y = event->y]() {
int buffer_x, buffer_y;
window_to_buffer_coords(Gtk::TextWindowType::TEXT_WINDOW_TEXT, x, y, buffer_x, buffer_y);
Gtk::TextIter iter;
get_iter_at_location(iter, buffer_x, buffer_y);
apply_clickable_tag(iter);
clickable_tag_applied = true;
return false;
},
100);
}
auto last_mouse_pos = std::make_pair<int, int>(on_motion_last_x, on_motion_last_y);
auto mouse_pos = std::make_pair<int, int>(event->x, event->y);
type_tooltips.hide(last_mouse_pos, mouse_pos);
diagnostic_tooltips.hide(last_mouse_pos, mouse_pos);
}
on_motion_last_x = event->x;
on_motion_last_y = event->y;
return false;
});
get_buffer()->signal_mark_set().connect([this](const Gtk::TextIter &iterator, const Glib::RefPtr<Gtk::TextBuffer::Mark> &mark) {
auto mark_name = mark->get_name();
if(mark_name == "selection_bound") {
if(get_buffer()->get_has_selection())
delayed_tooltips_connection.disconnect();
if(update_status_location)
update_status_location(this);
if(!keep_previous_extended_selections)
previous_extended_selections.clear();
}
else if(mark_name == "insert") {
hide_tooltips();
delayed_tooltips_connection.disconnect();
delayed_tooltips_connection = Glib::signal_timeout().connect(
[this]() {
Tooltips::init();
Gdk::Rectangle rectangle;
get_iter_location(get_buffer()->get_insert()->get_iter(), rectangle);
int location_window_x, location_window_y;
buffer_to_window_coords(Gtk::TextWindowType::TEXT_WINDOW_TEXT, rectangle.get_x(), rectangle.get_y(), location_window_x, location_window_y);
rectangle.set_x(location_window_x - 2);
rectangle.set_y(location_window_y);
rectangle.set_width(5);
if(parsed) {
show_type_tooltips(rectangle);
show_diagnostic_tooltips(rectangle);
}
return false;
},
500);
delayed_tag_similar_symbols_connection.disconnect();
delayed_tag_similar_symbols_connection = Glib::signal_timeout().connect(
[this] {
apply_similar_symbol_tag();
similar_symbol_tag_applied = true;
return false;
},
100);
if(SelectionDialog::get())
SelectionDialog::get()->hide();
if(CompletionDialog::get())
CompletionDialog::get()->hide();
if(update_status_location)
update_status_location(this);
if(!keep_previous_extended_selections)
previous_extended_selections.clear();
}
});
signal_key_release_event().connect([this](GdkEventKey *event) {
if((event->state & primary_modifier_mask) && clickable_tag_applied) {
get_buffer()->remove_tag(clickable_tag, get_buffer()->begin(), get_buffer()->end());
clickable_tag_applied = false;
}
return false;
});
signal_scroll_event().connect([this](GdkEventScroll *event) {
hide_tooltips();
hide_dialogs();
return false;
});
signal_focus_out_event().connect([this](GdkEventFocus *event) {
hide_tooltips();
if(clickable_tag_applied) {
get_buffer()->remove_tag(clickable_tag, get_buffer()->begin(), get_buffer()->end());
clickable_tag_applied = false;
}
return false;
});
signal_leave_notify_event().connect([this](GdkEventCrossing *) {
delayed_tooltips_connection.disconnect();
return false;
});
}
void Source::View::setup_format_style(bool is_generic_view) {
static auto prettier = filesystem::find_executable("prettier");
auto prefer_prettier = is_language({"js", "json", "css", "html", "markdown", "yaml"});
if(prettier.empty() && prefer_prettier && !filesystem::file_in_path(file_path, Config::get().home_juci_path)) {
static bool shown = false;
if(!shown) {
Terminal::get().print("\e[33mWarning\e[m: could not find Prettier code formatter.\n");
Terminal::get().print("To install Prettier, run the following command in a terminal: ");
#if defined(__APPLE__)
Terminal::get().print("brew install prettier");
#elif defined(__linux)
if(!filesystem::find_executable("pacman").empty())
Terminal::get().print("sudo pacman -S prettier");
else
Terminal::get().print("npm i -g prettier");
#else
Terminal::get().print("npm i -g prettier");
#endif
Terminal::get().print("\n");
}
shown = true;
}
if(!prettier.empty() && prefer_prettier) {
if(is_generic_view) {
goto_next_diagnostic = [this] {
place_cursor_at_next_diagnostic();
};
get_buffer()->signal_changed().connect([this] {
clear_diagnostic_tooltips();
status_diagnostics = std::make_tuple<size_t, size_t, size_t>(0, 0, 0);
if(update_status_diagnostics)
update_status_diagnostics(this);
});
}
format_style = [this, is_generic_view](bool continue_without_style_file, bool ignore_selection) {
if(!continue_without_style_file) {
auto search_path = file_path.parent_path();
while(true) {
static std::vector<boost::filesystem::path> files = {".prettierrc", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.json", ".prettierrc.toml", ".prettierrc.js", "prettier.config.js"};
boost::system::error_code ec;
bool found = false;
for(auto &file : files) {
if(boost::filesystem::exists(search_path / file, ec)) {
found = true;
break;
}
}
if(found)
break;
auto package_json = search_path / "package.json";
if(boost::filesystem::exists(package_json, ec)) {
try {
if(JSON(package_json).child_optional("prettier"))
break;
}
catch(...) {
}
}
if(search_path == search_path.root_directory())
return;
search_path = search_path.parent_path();
}
}
size_t num_warnings = 0, num_errors = 0, num_fix_its = 0;
if(is_generic_view)
clear_diagnostic_tooltips();
static auto get_prettier_library = [] {
std::string library;
TinyProcessLib::Process process(
"npm root -g", "",
[&library](const char *buffer, size_t length) {
library += std::string(buffer, length);
},
[](const char *, size_t) {});
if(process.get_exit_status() == 0) {
while(!library.empty() && (library.back() == '\n' || library.back() == '\r'))
library.pop_back();
library += "/prettier";
boost::system::error_code ec;
if(boost::filesystem::is_directory(library, ec))
return library;
else {
auto parent_path = prettier.parent_path();
if(parent_path.filename() == "bin") {
auto path = parent_path.parent_path() / "lib" / "prettier";
if(boost::filesystem::is_directory(path, ec))
return path.string();
}
// Try find prettier library installed with homebrew on MacOS
boost::filesystem::path path = "/usr/local/opt/prettier/libexec/lib/node_modules/prettier";
if(boost::filesystem::is_directory(path, ec))
return path.string();
path = "/opt/homebrew/opt/prettier/libexec/lib/node_modules/prettier";
if(boost::filesystem::is_directory(path, ec))
return path.string();
}
}
return std::string();
};
static auto prettier_library = get_prettier_library();
if(!prettier_library.empty()) {
struct Error {
std::string message;
int line = -1, index = -1;
};
struct Result {
std::string text;
int cursor_offset;
};
static Mutex mutex;
static boost::optional<Result> result GUARDED_BY(mutex);
static boost::optional<Error> error GUARDED_BY(mutex);
{
LockGuard lock(mutex);
result = {};
error = {};
}
static std::stringstream stdout_buffer;
static int curly_count = 0;
static bool key_or_value = false;
if(prettier_background_process) {
int exit_status;
if(prettier_background_process->try_get_exit_status(exit_status))
prettier_background_process = {};
}
if(!prettier_background_process) {
stdout_buffer = std::stringstream();
curly_count = 0;
key_or_value = false;
prettier_background_process = std::make_unique<TinyProcessLib::Process>(
"node -e \"const repl = require('repl');repl.start({prompt: '', ignoreUndefined: true, preview: false});\"",
"",
[](const char *bytes, size_t n) {
for(size_t i = 0; i < n; ++i) {
if(!key_or_value) {
if(bytes[i] == '{')
++curly_count;
else if(bytes[i] == '}')
--curly_count;
else if(bytes[i] == '"')
key_or_value = true;
}
else {
if(bytes[i] == '\\')
++i;
else if(bytes[i] == '"')
key_or_value = false;
}
}
stdout_buffer.write(bytes, n);
if(curly_count == 0) {
try {
JSON json(stdout_buffer);
LockGuard lock(mutex);
result = Result{json.string("formatted"), static_cast<int>(json.integer_or("cursorOffset", -1))};
}
catch(const std::exception &e) {
LockGuard lock(mutex);
error = Error{std::string(e.what()) + "\nOutput from prettier: " + stdout_buffer.str()};
}
stdout_buffer = std::stringstream();
key_or_value = false;
}
},
[](const char *bytes, size_t n) {
size_t i = 0;
for(; i < n; ++i) {
if(bytes[i] == '\n')
break;
}
std::string first_line(bytes, i);
std::string message;
int line = -1, line_index = -1;
if(starts_with(first_line, "ConfigError: "))
message = std::string(bytes + 13, n - 13);
else if(starts_with(first_line, "ParseError: ")) {
const static std::regex regex(R"(^(.*) \(([0-9]*):([0-9]*)\)$)", std::regex::optimize);
std::smatch sm;
first_line.erase(0, 12);
if(std::regex_match(first_line, sm, regex)) {
message = sm[1].str();
try {
line = std::stoi(sm[2].str());
line_index = std::stoi(sm[3].str());
}
catch(...) {
line = -1;
line_index = -1;
}
}
else
message = std::string(bytes + 12, n - 12);
}
else
message = std::string(bytes, n);
LockGuard lock(mutex);
error = Error{std::move(message), line, line_index};
},
true, TinyProcessLib::Config{1048576});
prettier_background_process->write("const prettier = require(\"" + escape(prettier_library, {'"'}) + "\");\n");
}
std::string options = "filepath: \"" + escape(file_path.string(), {'"'}) + "\"";
if(!ignore_selection && get_buffer()->get_has_selection()) { // Cannot be used together with cursorOffset
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
options += ", rangeStart: " + std::to_string(start.get_offset()) + ", rangeEnd: " + std::to_string(end.get_offset());
}
else
options += ", cursorOffset: " + std::to_string(get_buffer()->get_insert()->get_iter().get_offset());
prettier_background_process->write("{prettier.clearConfigCache();let _ = prettier.resolveConfig(\"" + escape(file_path.string(), {'"'}) + "\").then(options => {try{let _ = process.stdout.write(JSON.stringify(prettier.formatWithCursor(Buffer.from('");
prettier_background_process->write(to_hex_string(get_buffer()->get_text().raw()));
prettier_background_process->write("', 'hex').toString(), {...options, " + options + "})));}catch(error){let _ = process.stderr.write('ParseError: ' + error.message);}}).catch(error => {let _ = process.stderr.write('ConfigError: ' + error.message);});}\n");
int exit_status = -1;
while(true) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if(prettier_background_process->try_get_exit_status(exit_status))
break;
LockGuard lock(mutex);
if(result || error)
break;
}
{
LockGuard lock(mutex);
if(result) {
replace_text(result->text);
if(result->cursor_offset >= 0 && result->cursor_offset < get_buffer()->size()) {
get_buffer()->place_cursor(get_buffer()->get_iter_at_offset(result->cursor_offset));
hide_tooltips();
}
}
else if(error) {
if(error->line != -1 && error->index != -1) {
if(is_generic_view) {
auto start = get_iter_at_line_offset(error->line - 1, error->index - 1);
++num_errors;
while(start.ends_line() && start.backward_char()) {
}
auto end = start;
end.forward_char();
if(start == end)
start.backward_char();
add_diagnostic_tooltip(start, end, true, [error_message = std::move(error->message)](Tooltip &tooltip) {
tooltip.insert_with_links_tagged(error_message);
});
}
}
else
Terminal::get().print("\e[31mError (prettier)\e[m: " + error->message + '\n', true);
}
else if(exit_status >= 0)
Terminal::get().print("\e[31mError (prettier)\e[m: process exited with exit status " + std::to_string(exit_status) + '\n', true);
}
}
else {
auto command = prettier.string();
command += " --stdin-filepath " + filesystem::escape_argument(this->file_path.string());
if(!ignore_selection && get_buffer()->get_has_selection()) { // Cannot be used together with --cursor-offset
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
command += " --range-start " + std::to_string(start.get_offset());
command += " --range-end " + std::to_string(end.get_offset());
}
else
command += " --cursor-offset " + std::to_string(get_buffer()->get_insert()->get_iter().get_offset());
std::stringstream stdin_stream(get_buffer()->get_text().raw()), stdout_stream, stderr_stream;
auto exit_status = Terminal::get().process(stdin_stream, stdout_stream, command, this->file_path.parent_path(), &stderr_stream);
if(exit_status == 0) {
replace_text(stdout_stream.str());
std::string line;
std::getline(stderr_stream, line);
if(!line.empty() && line != "NaN") {
try {
auto offset = std::stoi(line);
if(offset < get_buffer()->size()) {
get_buffer()->place_cursor(get_buffer()->get_iter_at_offset(offset));
hide_tooltips();
}
}
catch(...) {
}
}
}
else {
const static std::regex regex(R"(^\[.*error.*\] [^:]*: (.*) \(([0-9]*):([0-9]*)\)$)", std::regex::optimize);
std::string line;
std::getline(stderr_stream, line);
std::smatch sm;
if(std::regex_match(line, sm, regex)) {
if(is_generic_view) {
try {
auto start = get_iter_at_line_offset(std::stoi(sm[2].str()) - 1, std::stoi(sm[3].str()) - 1);
++num_errors;
while(start.ends_line() && start.backward_char()) {
}
auto end = start;
end.forward_char();
if(start == end)
start.backward_char();
add_diagnostic_tooltip(start, end, true, [error_message = sm[1].str()](Tooltip &tooltip) {
tooltip.insert_with_links_tagged(error_message);
});
}
catch(...) {
}
}
}
else
Terminal::get().print("\e[31mError (prettier)\e[m: " + stderr_stream.str(), true);
}
}
if(is_generic_view) {
status_diagnostics = std::make_tuple(num_warnings, num_errors, num_fix_its);
if(update_status_diagnostics)
update_status_diagnostics(this);
}
};
}
else if(is_bracket_language) {
format_style = [this](bool continue_without_style_file, bool ignore_selection) {
static auto clang_format_command = filesystem::get_executable("clang-format").string();
auto command = clang_format_command + " -output-replacements-xml -assume-filename=" + filesystem::escape_argument(this->file_path.string());
if(!ignore_selection && get_buffer()->get_has_selection()) {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
command += " -lines=" + std::to_string(start.get_line() + 1) + ':' + std::to_string(end.get_line() + 1);
}
bool use_style_file = false;
auto style_file_search_path = this->file_path.parent_path();
boost::system::error_code ec;
while(true) {
if(boost::filesystem::exists(style_file_search_path / ".clang-format", ec) || boost::filesystem::exists(style_file_search_path / "_clang-format", ec)) {
use_style_file = true;
break;
}
if(style_file_search_path == style_file_search_path.root_directory())
break;
style_file_search_path = style_file_search_path.parent_path();
}
if(use_style_file)
command += " -style=file";
else {
if(!continue_without_style_file)
return;
unsigned indent_width;
std::string tab_style;
if(tab_char == '\t') {
indent_width = tab_size * 8;
tab_style = "UseTab: Always";
}
else {
indent_width = tab_size;
tab_style = "UseTab: Never";
}
command += " -style=\"{IndentWidth: " + std::to_string(indent_width);
command += ", " + tab_style;
command += ", " + std::string("AccessModifierOffset: -") + std::to_string(indent_width);
if(Config::get().source.clang_format_style != "")
command += ", " + Config::get().source.clang_format_style;
command += "}\"";
}
std::stringstream stdin_stream(get_buffer()->get_text()), stdout_stream;
auto exit_status = Terminal::get().process(stdin_stream, stdout_stream, command, this->file_path.parent_path());
if(exit_status == 0) {
// The following code is complex due to clang-format returning offsets in byte offsets instead of char offsets
// Create bytes_in_lines cache to significantly speed up the processing of finding iterators from byte offsets
std::vector<size_t> bytes_in_lines;
auto line_count = get_buffer()->get_line_count();
for(int line_nr = 0; line_nr < line_count; ++line_nr) {
auto iter = get_buffer()->get_iter_at_line(line_nr);
bytes_in_lines.emplace_back(iter.get_bytes_in_line());
}
get_buffer()->begin_user_action();
try {
boost::property_tree::ptree pt;
boost::property_tree::xml_parser::read_xml(stdout_stream, pt);
auto replacements_pt = pt.get_child("replacements", boost::property_tree::ptree());
for(auto it = replacements_pt.rbegin(); it != replacements_pt.rend(); ++it) {
if(it->first == "replacement") {
auto offset = it->second.get<size_t>("<xmlattr>.offset");
auto length = it->second.get<size_t>("<xmlattr>.length");
auto replacement_str = it->second.get<std::string>("");
size_t bytes = 0;
for(size_t c = 0; c < bytes_in_lines.size(); ++c) {
auto previous_bytes = bytes;
bytes += bytes_in_lines[c];
if(offset < bytes || (c == bytes_in_lines.size() - 1 && offset == bytes)) {
std::pair<size_t, size_t> line_index(c, offset - previous_bytes);
auto start = get_buffer()->get_iter_at_line_index(line_index.first, line_index.second);
// Use left gravity insert to avoid moving cursor from end of line
bool left_gravity_insert = false;
if(get_buffer()->get_insert()->get_iter() == start) {
auto iter = start;
do {
if(*iter != ' ' && *iter != '\t') {
left_gravity_insert = iter.ends_line();
break;
}
} while(iter.forward_char());
}
if(length > 0) {
auto offset_end = offset + length;
size_t bytes = 0;
for(size_t c = 0; c < bytes_in_lines.size(); ++c) {
auto previous_bytes = bytes;
bytes += bytes_in_lines[c];
if(offset_end < bytes || (c == bytes_in_lines.size() - 1 && offset_end == bytes)) {
auto end = get_buffer()->get_iter_at_line_index(c, offset_end - previous_bytes);
get_buffer()->erase(start, end);
start = get_buffer()->get_iter_at_line_index(line_index.first, line_index.second);
break;
}
}
}
if(left_gravity_insert) {
Mark mark(start);
get_buffer()->insert(start, replacement_str);
get_buffer()->place_cursor(mark->get_iter());
}
else
get_buffer()->insert(start, replacement_str);
break;
}
}
}
}
}
catch(const std::exception &e) {
Terminal::get().print(std::string("\e[31mError\e[m: error parsing clang-format output: ") + e.what() + '\n', true);
}
get_buffer()->end_user_action();
}
};
}
else if(language_id == "python") {
static auto yapf = filesystem::find_executable("yapf");
if(!yapf.empty()) {
format_style = [this](bool continue_without_style_file, bool ignore_selection) {
std::string command = "yapf";
if(!ignore_selection && get_buffer()->get_has_selection()) {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
command += " -l " + std::to_string(start.get_line() + 1) + '-' + std::to_string(end.get_line() + 1);
}
if(!continue_without_style_file) {
auto search_path = file_path.parent_path();
while(true) {
boost::system::error_code ec;
if(boost::filesystem::exists(search_path / ".python-format", ec) || boost::filesystem::exists(search_path / ".style.yapf", ec))
break;
if(search_path == search_path.root_directory())
return;
search_path = search_path.parent_path();
}
}
std::stringstream stdin_stream(get_buffer()->get_text()), stdout_stream;
auto exit_status = Terminal::get().process(stdin_stream, stdout_stream, command, this->file_path.parent_path());
if(exit_status == 0)
replace_text(stdout_stream.str());
};
}
}
}
Source::View::~View() {
delayed_tooltips_connection.disconnect();
delayed_tag_similar_symbols_connection.disconnect();
delayed_tag_clickable_connection.disconnect();
non_deleted_views.erase(this);
views.erase(this);
}
void Source::View::hide_tooltips() {
delayed_tooltips_connection.disconnect();
type_tooltips.hide();
diagnostic_tooltips.hide();
}
void Source::View::hide_dialogs() {
SpellCheckView::hide_dialogs();
if(SelectionDialog::get())
SelectionDialog::get()->hide();
if(CompletionDialog::get())
CompletionDialog::get()->hide();
}
void Source::View::scroll_to_cursor_delayed(bool center, bool show_tooltips) {
if(!show_tooltips)
hide_tooltips();
Glib::signal_idle().connect([this, center] {
if(views.find(this) != views.end()) {
if(center)
scroll_to(get_buffer()->get_insert(), 0.0, 1.0, 0.5);
else
scroll_to(get_buffer()->get_insert());
}
return false;
});
}
void Source::View::extend_selection() {
// Have tried to generalize this function as much as possible due to the complexity of this task,
// but some further workarounds for edge cases might be needed
// It is impossible to identify <> used for templates by syntax alone, but
// this function works in most cases.
auto is_template_arguments = [this](Gtk::TextIter start, Gtk::TextIter end) {
if(*start != '<' || *end != '>' || start.get_line() != end.get_line())
return false;
auto prev = start;
if(!prev.backward_char())
return false;
if(!is_token_char(*prev))
return false;
auto next = end;
next.forward_char();
if(*next != '(' && *next != ' ')
return false;
return true;
};
// Extends expression from 'here' in for instance: test->here(...), test.test(here) or here.test(test)
auto extend_expression = [&](Gtk::TextIter &start, Gtk::TextIter &end) {
auto start_stored = start;
auto end_stored = end;
bool extend_token_forward = true, extend_token_backward = true;
auto iter = start;
auto prev = iter;
if(prev.backward_char() && ((*prev == '(' && *end == ')') || (*prev == '[' && *end == ']') || (*prev == '<' && *end == '>') || (*prev == '{' && *end == '}'))) {
if(*prev == '<' && !is_template_arguments(prev, end))
return false;
iter = start = prev;
end.forward_char();
extend_token_forward = false;
}
else if(is_token_char(*iter)) {
auto token = get_token_iters(iter);
if(start != token.first || end != token.second)
return false;
extend_token_forward = false;
extend_token_backward = false;
}
else
return false;
// Extend expression forward passed for instance member function
{
auto iter = end;
bool extend_token = extend_token_forward;
while(forward_to_code(iter)) {
if(extend_token && is_token_char(*iter)) {
auto token = get_token_iters(iter);
iter = end = token.second;
extend_token = false;
continue;
}
if(!extend_token && *iter == '(' && iter.forward_char() && find_close_symbol_forward(iter, iter, '(', ')')) {
iter.forward_char();
end = iter;
extend_token = false;
continue;
}
if(!extend_token && *iter == '[' && iter.forward_char() && find_close_symbol_forward(iter, iter, '[', ']')) {
iter.forward_char();
end = iter;
extend_token = false;
continue;
}
auto prev = iter;
if(!extend_token && *iter == '<' && iter.forward_char() && find_close_symbol_forward(iter, iter, '<', '>') && is_template_arguments(prev, iter)) { // Only extend for instance std::max<int>(1, 2)
iter.forward_char();
end = iter;
extend_token = false;
continue;
}
if(!extend_token && *iter == '.') {
iter.forward_char();
extend_token = true;
continue;
}
auto next = iter;
if(!extend_token && next.forward_char() && ((*iter == ':' && *next == ':') || (*iter == '-' && *next == '>'))) {
iter = next;
iter.forward_char();
extend_token = true;
continue;
}
break;
}
// Extend through {}
auto prev = iter = end;
prev.backward_char();
if(*prev != '}' && forward_to_code(iter) && *iter == '{' && iter.forward_char() && find_close_symbol_forward(iter, iter, '{', '}')) {
iter.forward_char();
end = iter;
}
}
// Extend backward
iter = start;
bool extend_token = extend_token_backward;
while(true) {
if(!iter.backward_char() || !backward_to_code(iter))
break;
if(extend_token && is_token_char(*iter)) {
auto token = get_token_iters(iter);
start = iter = token.first;
extend_token = false;
continue;
}
if(extend_token && *iter == ')' && iter.backward_char() && find_open_symbol_backward(iter, iter, '(', ')')) {
start = iter;
extend_token = true;
continue;
}
if(extend_token && *iter == ']' && iter.backward_char() && find_open_symbol_backward(iter, iter, '[', ']')) {
start = iter;
extend_token = true;
continue;
}
auto angle_end = iter;
if(extend_token && *iter == '>' && iter.backward_char() && find_open_symbol_backward(iter, iter, '<', '>') && is_template_arguments(iter, angle_end)) { // Only extend for instance std::max<int>(1, 2)
start = iter;
continue;
}
if(*iter == '.') {
extend_token = true;
continue;
}
if(angle_end.backward_char() && ((*angle_end == ':' && *iter == ':') || (*angle_end == '-' && *iter == '>'))) {
iter = angle_end;
extend_token = true;
continue;
}
break;
}
if(start != start_stored || end != end_stored)
return true;
return false;
};
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
// If entire buffer is selected, do nothing
if(start == get_buffer()->begin() && end == get_buffer()->end())
return;
auto start_stored = start;
auto end_stored = end;
previous_extended_selections.emplace_back(start, end);
keep_previous_extended_selections = true;
ScopeGuard guard{[this] {
keep_previous_extended_selections = false;
}};
// Select token
if(!get_buffer()->get_has_selection()) {
auto iter = get_buffer()->get_insert()->get_iter();
if(is_token_char(*iter)) {
auto token = get_token_iters(iter);
get_buffer()->select_range(token.first, token.second);
return;
}
}
else { // Complete token selection
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
auto start_token = get_token_iters(start);
auto end_token = get_token_iters(end);
if(start_token.first < start || end_token.second > end) {
get_buffer()->select_range(start_token.first, end_token.second);
return;
}
}
// Select string or comment block
auto before_start = start;
if(!is_code_iter(start) && !(before_start.backward_char() && is_code_iter(before_start) && is_code_iter(end))) {
bool no_code_iter = true;
for(auto iter = start; iter.forward_char() && iter < end;) {
if(is_code_iter(iter)) {
no_code_iter = false;
break;
}
}
if(no_code_iter) {
if(backward_to_code(start)) {
while(start.forward_char() && (*start == ' ' || *start == '\t' || start.ends_line())) {
}
}
if(forward_to_code(end)) {
while(end.backward_char() && (*end == ' ' || *end == '\t' || end.ends_line())) {
}
end.forward_char();
}
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
start = start_stored;
end = end_stored;
}
}
// Select expression from token
if(get_buffer()->get_has_selection() && is_token_char(*start) && start.get_line() == end.get_line() && extend_expression(start, end)) {
get_buffer()->select_range(start, end);
return;
}
before_start = start;
auto before_end = end;
bool ignore_comma = false;
auto start_sentence_iter = get_buffer()->end();
auto end_sentence_iter = get_buffer()->end();
if(is_code_iter(start) && is_code_iter(end) && before_start.backward_char() && before_end.backward_char()) {
if((*before_start == '(' && *end == ')') ||
(*before_start == '[' && *end == ']') ||
(*before_start == '<' && *end == '>') ||
(*before_start == '{' && *end == '}')) {
// Select expression from selected brackets
if(!(*before_start == '<' && *end == '>' && is_js) &&
extend_expression(start, end)) {
get_buffer()->select_range(start, end);
return;
}
start = before_start;
end.forward_char();
}
else if((*before_start == ',' && *end == ',') ||
(*before_start == ',' && *end == ')') ||
(*before_start == ',' && *end == ']') ||
(*before_start == ',' && *end == '>') ||
(*before_start == ',' && *end == '}') ||
(*before_start == '(' && *end == ',') ||
(*before_start == '[' && *end == ',') ||
(*before_start == '<' && *end == ',') ||
(*before_start == '{' && *end == ','))
ignore_comma = true;
else if(start != end && (*before_end == ';' || *before_end == '}')) {
auto iter = end;
if(*before_end == '}' && forward_to_code(iter) && *iter == ';')
end_sentence_iter = iter;
else
end_sentence_iter = before_end;
}
}
int para_count = 0;
int square_count = 0;
int angle_count = 0;
int curly_count = 0;
auto start_comma_iter = get_buffer()->end();
auto start_angle_iter = get_buffer()->end();
auto start_angle_reversed_iter = get_buffer()->end();
while(start.backward_char()) {
if(*start == '(' && is_code_iter(start))
para_count++;
else if(*start == ')' && is_code_iter(start))
para_count--;
else if(*start == '[' && is_code_iter(start))
square_count++;
else if(*start == ']' && is_code_iter(start))
square_count--;
else if(*start == '<' && is_code_iter(start)) {
if(!start_angle_iter && para_count == 0 && square_count == 0 && angle_count == 0 && curly_count == 0)
start_angle_iter = start;
angle_count++;
}
else if(*start == '>' && is_code_iter(start)) {
auto prev = start;
if(!(prev.backward_char() && (*prev == '=' || *prev == '-'))) {
if(!start_angle_reversed_iter && para_count == 0 && square_count == 0 && angle_count == 0 && curly_count == 0)
start_angle_reversed_iter = start;
angle_count--;
}
}
else if(*start == '{' && is_code_iter(start)) {
if(!start_sentence_iter &&
para_count == 0 && square_count == 0 && curly_count == 0) {
start_sentence_iter = start;
}
curly_count++;
}
else if(*start == '}' && is_code_iter(start)) {
if(!start_sentence_iter &&
para_count == 0 && square_count == 0 && curly_count == 0) {
auto next = start;
if(next.forward_char() && forward_to_code(next) && *next != ';')
start_sentence_iter = start;
}
curly_count--;
}
else if(!ignore_comma && !start_comma_iter &&
para_count == 0 && square_count == 0 && curly_count == 0 &&
*start == ',' && is_code_iter(start))
start_comma_iter = start;
else if(!start_sentence_iter &&
para_count == 0 && square_count == 0 && curly_count == 0 &&
*start == ';' && is_code_iter(start))
start_sentence_iter = start;
if(*start == ';' && is_code_iter(start)) {
ignore_comma = true;
start_comma_iter = get_buffer()->end();
}
if(para_count > 0 || square_count > 0 || curly_count > 0)
break;
}
para_count = 0;
square_count = 0;
angle_count = 0;
curly_count = 0;
auto end_comma_iter = get_buffer()->end();
auto end_angle_iter = get_buffer()->end();
auto end_angle_reversed_iter = get_buffer()->end();
do {
if(*end == '(' && is_code_iter(end))
para_count++;
else if(*end == ')' && is_code_iter(end))
para_count--;
else if(*end == '[' && is_code_iter(end))
square_count++;
else if(*end == ']' && is_code_iter(end))
square_count--;
else if(*end == '<' && is_code_iter(end)) {
if(!end_angle_reversed_iter && para_count == 0 && square_count == 0 && angle_count == 0 && curly_count == 0)
end_angle_reversed_iter = end;
angle_count++;
}
else if(*end == '>' && is_code_iter(end)) {
auto prev = end;
if(!(prev.backward_char() && (*prev == '=' || *prev == '-'))) {
if(!end_angle_iter && para_count == 0 && square_count == 0 && angle_count == 0 && curly_count == 0)
end_angle_iter = end;
angle_count--;
}
}
else if(*end == '{' && is_code_iter(end))
curly_count++;
else if(*end == '}' && is_code_iter(end)) {
curly_count--;
if(!end_sentence_iter &&
para_count == 0 && square_count == 0 && curly_count == 0) {
auto next = end_sentence_iter = end;
if(next.forward_char() && forward_to_code(next) && *next == ';')
end_sentence_iter = next;
else if(is_js && *next == '>')
end_sentence_iter = get_buffer()->end();
}
}
else if(!ignore_comma && !end_comma_iter &&
para_count == 0 && square_count == 0 && curly_count == 0 &&
*end == ',' && is_code_iter(end))
end_comma_iter = end;
else if(!end_sentence_iter &&
para_count == 0 && square_count == 0 && curly_count == 0 &&
*end == ';' && is_code_iter(end))
end_sentence_iter = end;
if(*end == ';' && is_code_iter(end)) {
ignore_comma = true;
start_comma_iter = get_buffer()->end();
end_comma_iter = get_buffer()->end();
}
if(para_count < 0 || square_count < 0 || curly_count < 0)
break;
} while(end.forward_char());
// Extend HTML/JSX
if(is_js) {
static std::vector<std::string> void_elements = {"area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"};
auto get_element = [this](Gtk::TextIter iter) {
auto start = iter;
auto end = iter;
while(iter.backward_char() && (is_token_char(*iter) || *iter == '.'))
start = iter;
while((is_token_char(*end) || *end == '.') && end.forward_char()) {
}
return get_buffer()->get_text(start, end);
};
Gtk::TextIter start_backward_search = get_buffer()->end(), start_forward_search = get_buffer()->end();
auto start_stored_prev = start_stored;
if(start_angle_iter && end_angle_iter) { // If inside angle brackets in for instance <selection here>
auto next = start_angle_iter;
next.forward_char();
auto prev = end_angle_iter;
prev.backward_char();
auto element = get_element(next);
if(*next == '/') {
start_backward_search = start_forward_search = start_angle_iter;
start_backward_search.backward_char();
}
else if(*prev == '/' || std::any_of(void_elements.begin(), void_elements.end(), [&element](const std::string &e) { return e == element; })) {
end_angle_iter.forward_char();
get_buffer()->select_range(start_angle_iter, end_angle_iter);
return;
}
else {
start_backward_search = start_forward_search = end_angle_iter;
start_forward_search.forward_char();
}
}
else if(start_stored_prev.backward_char() && *start_stored_prev == '<' && *end_stored == '>') { // Matches for instance <div>, where div is selected
auto element = get_element(start_stored);
if(std::any_of(void_elements.begin(), void_elements.end(), [&element](const std::string &e) { return e == element; })) {
auto next = end_stored;
next.forward_char();
get_buffer()->select_range(start_stored_prev, next);
return;
}
start_backward_search = start_forward_search = end_stored;
start_forward_search.forward_char();
}
else if(start_angle_reversed_iter && end_angle_reversed_iter) { // If not inside angle brackets, for instance <>selection here</>
start_backward_search = start_angle_reversed_iter;
start_forward_search = end_angle_reversed_iter;
}
if(start_backward_search && start_forward_search) {
Gtk::TextIter start_children, end_children;
auto iter = start_backward_search;
int depth = 0;
// Search backward for opening element
while(find_open_symbol_backward(iter, iter, '>', '<') && iter.backward_char()) { // Backward to > (end of opening element)
start_children = iter;
start_children.forward_chars(2);
auto prev = iter;
prev.backward_char();
bool no_child_element = *iter == '/' && *prev != '<'; // Excludes </> as it is always closing element of <>
if(find_open_symbol_backward(iter, iter, '<', '>')) { // Backward to <
if(!no_child_element) {
iter.forward_char();
if(*iter == '/') {
if(!iter.backward_chars(2))
break;
--depth;
continue;
}
auto element = get_element(iter);
if(std::any_of(void_elements.begin(), void_elements.end(), [&element](const std::string &e) { return e == element; })) {
if(!iter.backward_chars(2))
break;
continue;
}
else if(depth == 0) {
iter.backward_char();
auto start_selection = iter;
iter = start_forward_search;
// Search forward for closing element
int depth = 0;
while(find_close_symbol_forward(iter, iter, '>', '<') && iter.forward_char()) { // Forward to < (start of closing element)
end_children = iter;
end_children.backward_char();
if(*iter == '/') {
if(iter.forward_char() && find_close_symbol_forward(iter, iter, '<', '>') && iter.forward_char()) { // Forward to >
if(depth == 0) {
if(start_children <= start_stored && end_children >= end_stored && (start_children != start_stored || end_children != end_stored)) // Select children
get_buffer()->select_range(start_children, end_children);
else
get_buffer()->select_range(start_selection, iter);
return;
}
else
--depth;
}
else
break;
}
else {
auto element = get_element(iter);
if(std::any_of(void_elements.begin(), void_elements.end(), [&element](const std::string &e) { return e == element; })) {
if(!(find_close_symbol_forward(iter, iter, '<', '>') && iter.forward_char())) // Forward to >
break;
}
else if(find_close_symbol_forward(iter, iter, '<', '>') && iter.backward_char()) { // Forward to >
if(*iter == '/')
iter.forward_chars(2);
else {
++depth;
iter.forward_chars(2);
}
}
else
break;
}
}
break;
}
else if(!iter.backward_chars(2))
break;
++depth;
}
else if(!iter.backward_char())
break;
}
else
break;
}
}
}
// Test for <> used for template arguments
if(start_angle_iter && end_angle_iter && is_template_arguments(start_angle_iter, end_angle_iter)) {
start_angle_iter.forward_char();
get_buffer()->select_range(start_angle_iter, end_angle_iter);
return;
}
// Test for matching brackets and try select regions within brackets separated by ','
bool comma_used = false;
bool select_matching_brackets = false;
if((*start == '(' && *end == ')') ||
(*start == '[' && *end == ']') ||
(*start == '<' && *end == '>') ||
(*start == '{' && *end == '}')) {
if(start_comma_iter && start < start_comma_iter) {
start = start_comma_iter;
comma_used = true;
}
if(end_comma_iter && end > end_comma_iter) {
end = end_comma_iter;
comma_used = true;
}
select_matching_brackets = true;
}
// Attempt to select a sentence, for instance: int a = 2;
if(!is_bracket_language) { // If for instance cmake, meson or python
if(!select_matching_brackets) {
bool select_end_block = is_language({"cmake", "meson", "julia", "xml"});
auto get_tabs = [this](Gtk::TextIter iter) -> boost::optional<int> {
iter = get_buffer()->get_iter_at_line(iter.get_line());
int tabs = 0;
while(!iter.ends_line() && (*iter == ' ' || *iter == '\t')) {
tabs++;
if(!iter.forward_char())
break;
}
if(iter.ends_line())
return {};
return tabs;
};
start = start_stored;
end = end_stored;
// Select following line with code (for instance when inside comment)
// Forward start to non-empty line
forward_to_code(start);
start = get_buffer()->get_iter_at_line(start.get_line());
while(!start.is_end() && (*start == ' ' || *start == '\t') && start.forward_char()) {
}
// Forward end of line
if(start > end)
end = start;
end = get_iter_at_line_end(end.get_line());
while(end.backward_char() && (*end == ' ' || *end == '\t' || end.ends_line())) {
}
end.forward_char();
if(end == end_stored) // Cancel line selection if the line is already selected
start = start_stored;
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
// Select current line
// Backward to line start
start = get_buffer()->get_iter_at_line(start.get_line());
auto start_tabs = get_tabs(start);
while((*start == ' ' || *start == '\t' || start.ends_line()) && start.forward_char()) {
}
// Forward to line end
end = get_iter_at_line_end(end.get_line());
bool include_children = false;
if(start_tabs) {
while(end.forward_char()) {
auto tabs = get_tabs(end);
if(tabs) {
if(tabs > start_tabs)
include_children = true;
else if(tabs == start_tabs) {
if(include_children && select_end_block)
end = get_iter_at_line_end(end.get_line());
break;
}
else
break;
}
end = get_iter_at_line_end(end.get_line());
}
}
// Backward end to non-empty line
while(end.backward_char() && (*end == ' ' || *end == '\t' || end.ends_line())) {
}
end.forward_char();
if(start != start_stored || end != end_stored) {
// Forward to closing symbol if open symbol is found between start and end
auto iter = start;
para_count = 0;
square_count = 0;
curly_count = 0;
do {
if(*iter == '(' && is_code_iter(iter))
para_count++;
else if(*iter == ')' && is_code_iter(iter))
para_count--;
else if(*iter == '[' && is_code_iter(iter))
square_count++;
else if(*iter == ']' && is_code_iter(iter))
square_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
if(para_count < 0 || square_count < 0 || curly_count < 0)
break;
} while(iter.forward_char() && iter < end);
if(iter == end && (para_count > 0 || square_count > 0 || curly_count > 0)) {
do {
if(*iter == '(' && is_code_iter(iter))
para_count++;
else if(*iter == ')' && is_code_iter(iter))
para_count--;
else if(*iter == '[' && is_code_iter(iter))
square_count++;
else if(*iter == ']' && is_code_iter(iter))
square_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
if(para_count == 0 && square_count == 0 && curly_count == 0)
break;
} while(iter.forward_char());
if(iter) {
end = iter;
end.forward_char();
}
}
get_buffer()->select_range(start, end);
return;
}
// Select block that cursor is within
// Backward start block start
if(start_tabs > 0) {
start = get_buffer()->get_iter_at_line(start.get_line());
while(start.backward_char()) {
auto tabs = get_tabs(start);
if(tabs && tabs < start_tabs)
break;
start = get_buffer()->get_iter_at_line(start.get_line());
}
while((*start == ' ' || *start == '\t' || start.ends_line()) && start.forward_char()) {
}
// Forward to block end
end = get_iter_at_line_end(end.get_line());
while(end.forward_char()) {
auto tabs = get_tabs(end);
if(tabs && tabs < start_tabs)
break;
end = get_iter_at_line_end(end.get_line());
}
// Backward end to non-empty line
while(end.backward_char() && (*end == ' ' || *end == '\t' || end.ends_line())) {
}
end.forward_char();
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
// Select expression surrounding block
// Backward to expression starting block
if(start.backward_char()) {
backward_to_code(start);
if(start_tabs > get_tabs(start)) {
start = get_buffer()->get_iter_at_line(start.get_line());
while((*start == ' ' || *start == '\t' || start.ends_line()) && start.forward_char()) {
}
}
else
start = start_stored;
}
// Forward to expression ending block
if(select_end_block) {
forward_to_code(end);
if(start_tabs > get_tabs(end)) {
end = get_iter_at_line_end(end.get_line());
while(end.backward_char() && (*end == ' ' || *end == '\t' || end.ends_line())) {
}
end.forward_char();
}
else
end = end_stored;
}
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
}
// Select no_spellcheck_tag block if markdown
if(language_id == "markdown" && no_spellcheck_tag && start.has_tag(no_spellcheck_tag) && end.has_tag(no_spellcheck_tag)) {
if(!start.starts_tag(no_spellcheck_tag))
start.backward_to_tag_toggle(no_spellcheck_tag);
if(!end.ends_tag(no_spellcheck_tag))
end.forward_to_tag_toggle(no_spellcheck_tag);
auto prev = start;
while(*start == '`' && start.forward_char()) {
}
if(start.get_offset() - prev.get_offset() > 1) {
start.forward_to_line_end();
start.forward_char();
}
while(end.backward_char() && *end == '`') {
}
if(!end.ends_line())
end.forward_char();
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
}
get_buffer()->select_range(get_buffer()->begin(), get_buffer()->end());
return;
}
}
else if(!comma_used && end_sentence_iter && end > end_sentence_iter) {
if(!start_sentence_iter)
start_sentence_iter = start;
else
start_sentence_iter.forward_char();
// Forward to code iter (move passed macros)
while(forward_to_code(start_sentence_iter) && *start_sentence_iter == '#' && start_sentence_iter.forward_to_line_end()) {
auto prev = start_sentence_iter;
if(prev.backward_char() && *prev == '\\' && start_sentence_iter.forward_char()) {
while(start_sentence_iter.forward_to_line_end()) {
prev = start_sentence_iter;
if(prev.backward_char() && *prev == '\\' && start_sentence_iter.forward_char())
continue;
break;
}
}
}
// Select sentence
end_sentence_iter.forward_char();
if((start_sentence_iter != start_stored || end_sentence_iter != end_stored) &&
((*start == '{' && *end == '}') || (start.is_start() && end.is_end()))) {
get_buffer()->select_range(start_sentence_iter, end_sentence_iter);
return;
}
}
if(select_matching_brackets)
start.forward_char();
if(start != start_stored || end != end_stored) {
get_buffer()->select_range(start, end);
return;
}
// In case of no change due to inbalanced brackets
previous_extended_selections.pop_back();
if(!start.backward_char() && !end.forward_char())
return;
get_buffer()->select_range(start, end);
extend_selection();
}
void Source::View::shrink_selection() {
if(previous_extended_selections.empty()) {
Info::get().print("No previous extended selections found");
return;
}
auto selection = previous_extended_selections.back();
keep_previous_extended_selections = true;
get_buffer()->select_range(selection.first, selection.second);
hide_tooltips();
keep_previous_extended_selections = false;
previous_extended_selections.pop_back();
}
void Source::View::show_or_hide() {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
if(start == end && !(start.starts_line() && start.ends_line())) { // Select code block instead if no current selection
start = get_buffer()->get_iter_at_line(start.get_line());
auto tabs_end = get_tabs_end_iter(start);
auto start_tabs = tabs_end.get_line_offset() - start.get_line_offset();
if(!end.ends_line())
end.forward_to_line_end();
auto last_empty = get_buffer()->end();
auto last_tabs_end = get_buffer()->end();
while(true) {
if(end.ends_line()) {
auto line_start = get_buffer()->get_iter_at_line(end.get_line());
auto tabs_end = get_tabs_end_iter(line_start);
if(end.starts_line() || tabs_end.ends_line()) { // Empty line
if(!last_empty)
last_empty = end;
}
else {
auto tabs = tabs_end.get_line_offset() - line_start.get_line_offset();
if((is_c || is_cpp) && tabs == 0 && *line_start == '#') { // C/C++ defines can be at the first line
if(end.get_line() == start.get_line()) // Do not try to find define blocks since these rarely are indented
break;
}
else if(tabs < start_tabs) {
end = get_buffer()->get_iter_at_line(end.get_line());
break;
}
else if(tabs == start_tabs) {
// Check for block continuation keywords
std::string text = get_buffer()->get_text(tabs_end, end);
if(end.get_line() != start.get_line()) {
if(text.empty()) {
end = get_buffer()->get_iter_at_line(end.get_line());
break;
}
static std::vector<std::string> starts_with_symbols = {"}", ")", "]", ">", "</"};
static std::vector<std::string> exact_tokens = {"else", "end", "endif", "elseif", "elif", "catch", "case", "default", "private", "public", "protected"};
if(text == "{") { // C/C++ sometimes starts a block with a standalone {
if(!is_token_char(*last_tabs_end)) {
end = get_buffer()->get_iter_at_line(end.get_line());
break;
}
else { // Check for ; at the end of last line
auto iter = tabs_end;
while(iter.backward_char() && iter > last_tabs_end && (*iter == ' ' || *iter == '\t' || iter.ends_line() || !is_code_iter(iter))) {
}
if(*iter == ';') {
end = get_buffer()->get_iter_at_line(end.get_line());
break;
}
}
}
else if(std::none_of(starts_with_symbols.begin(), starts_with_symbols.end(), [&text](const std::string &symbol) {
return starts_with(text, symbol);
}) &&
std::none_of(exact_tokens.begin(), exact_tokens.end(), [this, &text](const std::string &token) {
return starts_with(text, token) && (text.size() <= token.size() || !is_token_char(text[token.size()]));
})) {
end = get_buffer()->get_iter_at_line(end.get_line());
break;
}
}
last_tabs_end = tabs_end;
}
last_empty = get_buffer()->end();
}
}
if(end.is_end())
break;
end.forward_char();
}
if(last_empty)
end = get_buffer()->get_iter_at_line(last_empty.get_line());
}
if(start == end)
end.forward_char(); // Select empty line
if(!start.starts_line())
start = get_buffer()->get_iter_at_line(start.get_line());
if(!end.ends_line() && !end.starts_line())
end.forward_to_line_end();
if((start.begins_tag(hide_tag) || start.has_tag(hide_tag)) && (end.ends_tag(hide_tag) || end.has_tag(hide_tag))) {
get_buffer()->remove_tag(hide_tag, start, end);
return;
}
auto iter = start;
if(iter.forward_to_tag_toggle(hide_tag) && iter < end) {
get_buffer()->remove_tag(hide_tag, start, end);
return;
}
get_buffer()->apply_tag(hide_tag, start, end);
}
void Source::View::add_diagnostic_tooltip(const Gtk::TextIter &start, const Gtk::TextIter &end, bool error, std::function<void(Tooltip &)> &&set_buffer) {
diagnostic_offsets.emplace(start.get_offset());
std::string severity_tag_name = error ? "def:error" : "def:warning";
diagnostic_tooltips.emplace_back(this, start, end, [error, severity_tag_name, set_buffer = std::move(set_buffer)](Tooltip &tooltip) {
tooltip.buffer->insert_with_tag(tooltip.buffer->get_insert()->get_iter(), error ? "Error" : "Warning", severity_tag_name);
tooltip.buffer->insert(tooltip.buffer->get_insert()->get_iter(), ":\n");
set_buffer(tooltip);
});
get_buffer()->apply_tag_by_name(severity_tag_name + "_underline", start, end);
auto iter = get_buffer()->get_insert()->get_iter();
if(iter.ends_line()) {
auto next_iter = iter;
if(next_iter.forward_char())
get_buffer()->remove_tag_by_name(severity_tag_name + "_underline", iter, next_iter);
}
}
void Source::View::clear_diagnostic_tooltips() {
diagnostic_offsets.clear();
diagnostic_tooltips.clear();
get_buffer()->remove_tag_by_name("def:warning_underline", get_buffer()->begin(), get_buffer()->end());
get_buffer()->remove_tag_by_name("def:error_underline", get_buffer()->begin(), get_buffer()->end());
}
void Source::View::place_cursor_at_next_diagnostic() {
auto insert_offset = get_buffer()->get_insert()->get_iter().get_offset();
for(auto offset : diagnostic_offsets) {
if(offset > insert_offset) {
get_buffer()->place_cursor(get_buffer()->get_iter_at_offset(offset));
scroll_to(get_buffer()->get_insert(), 0.0, 1.0, 0.5);
return;
}
}
if(diagnostic_offsets.size() == 0)
Info::get().print("No diagnostics found in current buffer");
else {
auto iter = get_buffer()->get_iter_at_offset(*diagnostic_offsets.begin());
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert(), 0.0, 1.0, 0.5);
}
}
bool Source::View::backward_to_code(Gtk::TextIter &iter) {
while((*iter == ' ' || *iter == '\t' || iter.ends_line() || !is_code_iter(iter)) && iter.backward_char()) {
}
return !iter.is_start() || is_code_iter(iter);
}
bool Source::View::forward_to_code(Gtk::TextIter &iter) {
while((*iter == ' ' || *iter == '\t' || iter.ends_line() || !is_code_iter(iter)) && iter.forward_char()) {
}
return !iter.is_end();
}
bool Source::View::backward_to_code_or_line_start(Gtk::TextIter &iter) {
while(!iter.starts_line() && (*iter == ' ' || *iter == '\t' || iter.ends_line() || !is_code_iter(iter)) && iter.backward_char()) {
}
return !iter.is_start() || is_code_iter(iter);
}
bool Source::View::forward_to_code_or_line_end(Gtk::TextIter &iter) {
while(!iter.ends_line() && (*iter == ' ' || *iter == '\t' || !is_code_iter(iter)) && iter.forward_char()) {
}
return !iter.is_end();
}
Gtk::TextIter Source::View::get_start_of_expression(Gtk::TextIter iter) {
backward_to_code_or_line_start(iter);
if(iter.starts_line())
return iter;
bool has_semicolon = false;
bool has_open_curly = false;
if(is_bracket_language) {
if(*iter == ';' && is_code_iter(iter))
has_semicolon = true;
else if(*iter == '{' && is_code_iter(iter)) {
iter.backward_char();
has_open_curly = true;
}
}
int para_count = 0;
int square_count = 0;
long curly_count = 0;
do {
if(*iter == '(' && is_code_iter(iter))
para_count++;
else if(*iter == ')' && is_code_iter(iter))
para_count--;
else if(*iter == '[' && is_code_iter(iter))
square_count++;
else if(*iter == ']' && is_code_iter(iter))
square_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter)) {
curly_count--;
if(iter.starts_line())
break;
}
if(para_count > 0 || square_count > 0 || curly_count > 0)
break;
if(iter.starts_line() && para_count == 0 && square_count == 0) {
if(!is_bracket_language)
return iter;
// Handle << at the beginning of the sentence if iter initially started with ;
if(has_semicolon) {
auto test_iter = get_tabs_end_iter(iter);
if(!test_iter.starts_line() && *test_iter == '<' && is_code_iter(test_iter) &&
test_iter.forward_char() && *test_iter == '<')
continue;
}
// Handle for instance: test\n .test();
if(has_semicolon && use_fixed_continuation_indenting) {
auto test_iter = get_tabs_end_iter(iter);
if(!test_iter.starts_line() && *test_iter == '.' && is_code_iter(test_iter))
continue;
}
// Handle : at the beginning of the sentence if iter initially started with {
if(has_open_curly) {
auto test_iter = get_tabs_end_iter(iter);
if(!test_iter.starts_line() && *test_iter == ':' && is_code_iter(test_iter))
continue;
}
// Handle ',', ':', or operators that can be used between two lines, on previous line
// Return if previous line is empty
auto previous_iter = iter;
previous_iter.backward_char();
backward_to_code_or_line_start(previous_iter);
if(previous_iter.starts_line())
return iter;
// Handle for instance: Test::Test():\n test(2) {
if(has_open_curly && *previous_iter == ':') {
previous_iter.backward_char();
backward_to_code_or_line_start(previous_iter);
if(*previous_iter == ')') {
auto token = get_token(get_tabs_end_iter(previous_iter));
if(token != "case")
continue;
}
return iter;
}
// Handle for instance: int a =\n b;
if(*previous_iter == '=' || *previous_iter == '+' || *previous_iter == '-' || *previous_iter == '*' || *previous_iter == '/' ||
*previous_iter == '%' || *previous_iter == '<' || *previous_iter == '>' || *previous_iter == '&' || *previous_iter == '|') {
if(has_semicolon)
continue;
return iter;
}
if(*previous_iter != ',')
return iter;
else {
// Return if , is followed by }, for instance: {\n 1,\n 2,\n}
auto next_iter = iter;
if(forward_to_code_or_line_end(next_iter) && *next_iter == '}')
return iter;
}
}
} while(iter.backward_char());
return iter;
}
bool Source::View::find_close_symbol_forward(Gtk::TextIter iter, Gtk::TextIter &found_iter, unsigned int positive_char, unsigned int negative_char) {
long count = 0;
if(positive_char == '{' && negative_char == '}') {
do {
if(*iter == positive_char && is_code_iter(iter))
count++;
else if(*iter == negative_char && is_code_iter(iter)) {
if(count == 0) {
found_iter = iter;
return true;
}
count--;
}
} while(iter.forward_char());
return false;
}
else {
long curly_count = 0;
do {
if(curly_count == 0 && *iter == positive_char && is_code_iter(iter)) {
if((is_c || is_cpp) && positive_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '-')
continue;
}
else if(is_js && positive_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '=')
continue;
}
count++;
}
else if(curly_count == 0 && *iter == negative_char && is_code_iter(iter)) {
if((is_c || is_cpp) && negative_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '-')
continue;
}
else if(is_js && negative_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '=')
continue;
}
if(count == 0) {
found_iter = iter;
return true;
}
count--;
}
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter)) {
if(curly_count == 0)
return false;
curly_count--;
}
} while(iter.forward_char());
return false;
}
}
bool Source::View::find_open_symbol_backward(Gtk::TextIter iter, Gtk::TextIter &found_iter, unsigned int positive_char, unsigned int negative_char) {
long count = 0;
if(positive_char == '{' && negative_char == '}') {
do {
if(*iter == positive_char && is_code_iter(iter)) {
if(count == 0) {
found_iter = iter;
return true;
}
count++;
}
else if(*iter == negative_char && is_code_iter(iter))
count--;
} while(iter.backward_char());
return false;
}
else {
long curly_count = 0;
do {
if(curly_count == 0 && *iter == positive_char && is_code_iter(iter)) {
if((is_c || is_cpp) && positive_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '-')
continue;
}
else if(is_js && positive_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '=')
continue;
}
if(count == 0) {
found_iter = iter;
return true;
}
count++;
}
else if(curly_count == 0 && *iter == negative_char && is_code_iter(iter)) {
if((is_c || is_cpp) && negative_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '-')
continue;
}
else if(is_js && negative_char == '>') {
auto prev = iter;
if(prev.backward_char() && *prev == '=')
continue;
}
count--;
}
else if(*iter == '{' && is_code_iter(iter)) {
if(curly_count == 0)
return false;
curly_count++;
}
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
} while(iter.backward_char());
return false;
}
}
long Source::View::symbol_count(Gtk::TextIter iter, unsigned int positive_char, unsigned int negative_char) {
auto iter_stored = iter;
long symbol_count = 0;
if(positive_char == '{' && negative_char == '}') {
// If checking top-level curly brackets, check whole buffer
auto previous_iter = iter;
if(iter.starts_line() || (previous_iter.backward_char() && previous_iter.starts_line() && *previous_iter == '{')) {
auto iter = get_buffer()->begin();
do {
if(*iter == '{' && is_code_iter(iter))
++symbol_count;
else if(*iter == '}' && is_code_iter(iter))
--symbol_count;
} while(iter.forward_char());
return symbol_count;
}
// Can stop when text is found at top-level indentation
else {
do {
if(*iter == '{' && is_code_iter(iter))
++symbol_count;
else if(*iter == '}' && is_code_iter(iter))
--symbol_count;
if(iter.starts_line() && !iter.ends_line() && *iter != '#' && *iter != ' ' && *iter != '\t')
break;
} while(iter.backward_char());
iter = iter_stored;
if(!iter.forward_char())
return symbol_count;
do {
if(*iter == '{' && is_code_iter(iter))
++symbol_count;
else if(*iter == '}' && is_code_iter(iter))
--symbol_count;
if(iter.starts_line() && !iter.ends_line() && *iter != '#' && *iter != ' ' && *iter != '\t') {
if(*iter == 'p') {
auto token = get_token(iter);
if(token == "public" || token == "protected" || token == "private")
continue;
}
break;
}
} while(iter.forward_char());
return symbol_count;
}
}
long curly_count = 0;
do {
if(*iter == positive_char && is_code_iter(iter))
symbol_count++;
else if(*iter == negative_char && is_code_iter(iter))
symbol_count--;
else if(*iter == '{' && is_code_iter(iter)) {
if(curly_count == 0)
break;
curly_count++;
}
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
} while(iter.backward_char());
iter = iter_stored;
if(!iter.forward_char())
return symbol_count;
curly_count = 0;
do {
if(*iter == positive_char && is_code_iter(iter))
symbol_count++;
else if(*iter == negative_char && is_code_iter(iter))
symbol_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter)) {
if(curly_count == 0)
break;
curly_count--;
}
} while(iter.forward_char());
return symbol_count;
}
bool Source::View::is_templated_function(Gtk::TextIter iter, Gtk::TextIter &parenthesis_end_iter) {
auto iter_stored = iter;
long bracket_count = 0;
long curly_count = 0;
if(!(iter.backward_char() && *iter == '>' && *iter_stored == '('))
return false;
do {
if(*iter == '<' && is_code_iter(iter))
bracket_count++;
else if(*iter == '>' && is_code_iter(iter))
bracket_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
if(bracket_count == 0)
break;
if(curly_count > 0)
break;
} while(iter.backward_char());
if(bracket_count != 0)
return false;
iter = iter_stored;
bracket_count = 0;
curly_count = 0;
do {
if(*iter == '(' && is_code_iter(iter))
bracket_count++;
else if(*iter == ')' && is_code_iter(iter))
bracket_count--;
else if(*iter == '{' && is_code_iter(iter))
curly_count++;
else if(*iter == '}' && is_code_iter(iter))
curly_count--;
if(bracket_count == 0) {
parenthesis_end_iter = iter;
return true;
}
if(curly_count < 0)
return false;
} while(iter.forward_char());
return false;
}
bool Source::View::is_possible_argument() {
auto iter = get_buffer()->get_insert()->get_iter();
if(iter.backward_char() && (!interactive_completion || last_keyval == '(' || last_keyval == ',' || last_keyval == ' ' ||
last_keyval == GDK_KEY_Return || last_keyval == GDK_KEY_KP_Enter)) {
if(backward_to_code(iter) && (*iter == '(' || *iter == ','))
return true;
}
return false;
}
bool Source::View::on_key_press_event(GdkEventKey *event) {
enable_multiple_cursors = true;
ScopeGuard guard{[this] {
enable_multiple_cursors = false;
}};
if(SelectionDialog::get() && SelectionDialog::get()->is_visible()) {
if(SelectionDialog::get()->on_key_press(event))
return true;
}
if(CompletionDialog::get() && CompletionDialog::get()->is_visible()) {
if(CompletionDialog::get()->on_key_press(event))
return true;
}
if(last_keyval < GDK_KEY_Shift_L || last_keyval > GDK_KEY_Hyper_R)
previous_non_modifier_keyval = last_keyval;
last_keyval = event->keyval;
if((event->keyval == GDK_KEY_Tab || event->keyval == GDK_KEY_ISO_Left_Tab) && (event->state & GDK_SHIFT_MASK) == 0 && select_snippet_parameter())
return true;
if(on_key_press_event_extra_cursors(event))
return true;
{
LockGuard lock(snippets_mutex);
if(snippets) {
guint keyval_without_state;
gdk_keymap_translate_keyboard_state(gdk_keymap_get_default(), event->hardware_keycode, (GdkModifierType)0, 0, &keyval_without_state, nullptr, nullptr, nullptr);
for(auto &snippet : *snippets) {
if(snippet.key == keyval_without_state && (event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK | GDK_META_MASK)) == snippet.modifier) {
insert_snippet(get_buffer()->get_insert()->get_iter(), snippet.body);
return true;
}
}
}
}
get_buffer()->begin_user_action();
// Shift+enter: go to end of line and enter
if((event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) && (event->state & GDK_SHIFT_MASK) > 0) {
auto iter = get_buffer()->get_insert()->get_iter();
if(!iter.ends_line()) {
iter.forward_to_line_end();
get_buffer()->place_cursor(iter);
}
}
if(Config::get().source.smart_brackets && on_key_press_event_smart_brackets(event)) {
get_buffer()->end_user_action();
return true;
}
if(Config::get().source.smart_inserts && on_key_press_event_smart_inserts(event)) {
get_buffer()->end_user_action();
return true;
}
if(is_bracket_language && on_key_press_event_bracket_language(event)) {
get_buffer()->end_user_action();
return true;
}
else if(on_key_press_event_basic(event)) {
get_buffer()->end_user_action();
return true;
}
else {
get_buffer()->end_user_action();
return BaseView::on_key_press_event(event);
}
}
// Basic indentation
bool Source::View::on_key_press_event_basic(GdkEventKey *event) {
auto iter = get_buffer()->get_insert()->get_iter();
// Indent as in current or next line
if((event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) && !get_buffer()->get_has_selection() && !iter.starts_line()) {
cleanup_whitespace_characters(iter);
iter = get_buffer()->get_insert()->get_iter();
auto condition_iter = iter;
condition_iter.backward_char();
backward_to_code_or_line_start(condition_iter);
auto start_iter = get_start_of_expression(condition_iter);
auto tabs_end_iter = get_tabs_end_iter(start_iter);
auto tabs = get_line_before(tabs_end_iter);
// Python indenting after :
if(*condition_iter == ':' && language_id == "python") {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
// Indent as in current or next line
int line_nr = iter.get_line();
if(iter.ends_line() && (line_nr + 1) < get_buffer()->get_line_count()) {
auto next_tabs_end_iter = get_tabs_end_iter(line_nr + 1);
if(next_tabs_end_iter.get_line_offset() > tabs_end_iter.get_line_offset()) {
get_buffer()->insert_at_cursor('\n' + get_line_before(next_tabs_end_iter));
scroll_to(get_buffer()->get_insert());
return true;
}
}
get_buffer()->insert_at_cursor('\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
// Indent as in next or previous line
else if(event->keyval == GDK_KEY_Tab && (event->state & GDK_SHIFT_MASK) == 0) {
// Special case if insert is at beginning of empty line:
if(iter.starts_line() && iter.ends_line() && !get_buffer()->get_has_selection()) {
auto prev_line_iter = iter;
while(prev_line_iter.starts_line() && prev_line_iter.backward_char()) {
}
auto start_iter = get_start_of_expression(prev_line_iter);
auto prev_line_tabs_end_iter = get_tabs_end_iter(start_iter);
auto next_line_iter = iter;
while(next_line_iter.starts_line() && next_line_iter.forward_char()) {
}
auto next_line_tabs_end_iter = get_tabs_end_iter(next_line_iter);
Gtk::TextIter tabs_end_iter;
if(next_line_tabs_end_iter.get_line_offset() > prev_line_tabs_end_iter.get_line_offset())
tabs_end_iter = next_line_tabs_end_iter;
else
tabs_end_iter = prev_line_tabs_end_iter;
auto tabs = get_line_before(tabs_end_iter);
get_buffer()->insert_at_cursor(tabs.size() >= tab_size ? tabs : tab);
return true;
}
if(!Config::get().source.tab_indents_line && !get_buffer()->get_has_selection()) {
get_buffer()->insert_at_cursor(tab);
return true;
}
// Indent right when clicking tab, no matter where in the line the cursor is. Also works on selected text.
Gtk::TextIter selection_start, selection_end;
get_buffer()->get_selection_bounds(selection_start, selection_end);
Mark selection_end_mark(selection_end);
int line_start = selection_start.get_line();
int line_end = selection_end.get_line();
for(int line = line_start; line <= line_end; line++) {
auto line_it = get_buffer()->get_iter_at_line(line);
if(!get_buffer()->get_has_selection() || line_it != selection_end_mark->get_iter())
get_buffer()->insert(line_it, tab);
}
return true;
}
// Indent left when clicking shift-tab, no matter where in the line the cursor is. Also works on selected text.
else if((event->keyval == GDK_KEY_ISO_Left_Tab || event->keyval == GDK_KEY_Tab) && (event->state & GDK_SHIFT_MASK) > 0) {
Gtk::TextIter selection_start, selection_end;
get_buffer()->get_selection_bounds(selection_start, selection_end);
int line_start = selection_start.get_line();
int line_end = selection_end.get_line();
unsigned indent_left_steps = tab_size;
std::vector<bool> ignore_line;
for(int line_nr = line_start; line_nr <= line_end; line_nr++) {
auto line_it = get_buffer()->get_iter_at_line(line_nr);
if(!get_buffer()->get_has_selection() || line_it != selection_end) {
auto tabs_end_iter = get_tabs_end_iter(line_nr);
if(tabs_end_iter.starts_line() && tabs_end_iter.ends_line())
ignore_line.push_back(true);
else {
auto line_tabs = get_line_before(tabs_end_iter);
if(line_tabs.size() > 0) {
indent_left_steps = std::min(indent_left_steps, static_cast<unsigned>(line_tabs.size()));
ignore_line.push_back(false);
}
else
return true;
}
}
}
for(int line_nr = line_start; line_nr <= line_end; line_nr++) {
Gtk::TextIter line_it = get_buffer()->get_iter_at_line(line_nr);
Gtk::TextIter line_plus_it = line_it;
if(!get_buffer()->get_has_selection() || line_it != selection_end) {
line_plus_it.forward_chars(indent_left_steps);
if(!ignore_line.at(line_nr - line_start))
get_buffer()->erase(line_it, line_plus_it);
}
}
return true;
}
// "Smart" backspace key
else if(event->keyval == GDK_KEY_BackSpace && !get_buffer()->get_has_selection()) {
auto line = get_line_before();
bool do_smart_backspace = true;
for(auto &chr : line) {
if(chr != ' ' && chr != '\t') {
do_smart_backspace = false;
break;
}
}
if(iter.get_line() == 0) // Special case since there are no previous line
do_smart_backspace = false;
if(do_smart_backspace) {
auto previous_line_end_iter = iter;
if(previous_line_end_iter.backward_chars(line.size() + 1)) {
if(!previous_line_end_iter.ends_line()) // For CR+LF
previous_line_end_iter.backward_char();
if(previous_line_end_iter.starts_line()) // When previous line is empty, keep tabs in current line
get_buffer()->erase(previous_line_end_iter, get_buffer()->get_iter_at_line(iter.get_line()));
else
get_buffer()->erase(previous_line_end_iter, iter);
return true;
}
}
}
// "Smart" delete key
else if(event->keyval == GDK_KEY_Delete && !get_buffer()->get_has_selection()) {
auto insert_iter = iter;
bool do_smart_delete = true;
do {
if(*iter != ' ' && *iter != '\t' && !iter.ends_line()) {
do_smart_delete = false;
break;
}
if(iter.ends_line()) {
if(!iter.forward_char())
do_smart_delete = false;
break;
}
} while(iter.forward_char());
if(do_smart_delete) {
if(!insert_iter.starts_line()) {
while((*iter == ' ' || *iter == '\t') && iter.forward_char()) {
}
}
get_buffer()->erase(insert_iter, iter);
return true;
}
}
// Workaround for TextView::on_key_press_event bug sometimes causing segmentation faults
// TODO: figure out the bug and create pull request to gtk
// Have only experienced this on OS X
// Note: valgrind reports issues on TextView::on_key_press_event as well
auto unicode = gdk_keyval_to_unicode(event->keyval);
if((event->state & (GDK_CONTROL_MASK | GDK_META_MASK)) == 0 && unicode >= 32 && unicode != 127 &&
(previous_non_modifier_keyval < GDK_KEY_dead_grave || previous_non_modifier_keyval > GDK_KEY_dead_greek)) {
if(get_buffer()->get_has_selection()) {
Gtk::TextIter selection_start, selection_end;
get_buffer()->get_selection_bounds(selection_start, selection_end);
get_buffer()->erase(selection_start, selection_end);
}
get_buffer()->insert_at_cursor(Glib::ustring(1, unicode));
scroll_to(get_buffer()->get_insert());
// Trick to make the cursor visible right after insertion:
set_cursor_visible(false);
set_cursor_visible();
return true;
}
return false;
}
//Bracket language indentation
bool Source::View::on_key_press_event_bracket_language(GdkEventKey *event) {
const static std::regex no_bracket_statement_regex("^[ \t]*(if( +constexpr)?|for|while) *\\(.*[^;}{] *$|"
"^[ \t]*[}]? *else if( +constexpr)? *\\(.*[^;}{] *$|"
"^[ \t]*[}]? *else *$",
std::regex::extended | std::regex::optimize);
auto iter = get_buffer()->get_insert()->get_iter();
if(get_buffer()->get_has_selection())
return false;
if(!is_code_iter(iter)) {
// Add * at start of line in comment blocks
if(event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) {
if(!iter.starts_line() && (!string_tag || (!iter.has_tag(string_tag) && !iter.ends_tag(string_tag)))) {
cleanup_whitespace_characters(iter);
iter = get_buffer()->get_insert()->get_iter();
auto start_iter = get_tabs_end_iter(iter.get_line());
if(!is_code_iter(start_iter)) {
auto end_iter = start_iter;
end_iter.forward_chars(2);
auto start_of_sentence = get_buffer()->get_text(start_iter, end_iter);
if(!start_of_sentence.empty() && (start_of_sentence == "/*" || start_of_sentence[0] == '*')) {
auto tabs = get_line_before(start_iter);
auto insert_str = '\n' + tabs;
if(start_of_sentence[0] == '/')
insert_str += ' ';
insert_str += "* ";
get_buffer()->insert_at_cursor(insert_str);
return true;
}
}
}
else if(!comment_tag || !iter.ends_tag(comment_tag))
return false;
}
else
return false;
}
// Indent depending on if/else/etc and brackets
if((event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) && !iter.starts_line()) {
cleanup_whitespace_characters(iter);
iter = get_buffer()->get_insert()->get_iter();
auto previous_iter = iter;
previous_iter.backward_char();
// Remove matching bracket highlights that get extended when inserting text in between the brackets
ScopeGuard guard;
if((*previous_iter == '{' && *iter == '}') || (*previous_iter == '(' && *iter == ')') ||
(*previous_iter == '[' && *iter == ']') || (*previous_iter == '<' && *iter == '>')) {
get_source_buffer()->set_highlight_matching_brackets(false);
guard.on_exit = [this] {
get_source_buffer()->set_highlight_matching_brackets(true);
};
}
auto condition_iter = previous_iter;
backward_to_code_or_line_start(condition_iter);
auto start_iter = get_start_of_expression(condition_iter);
auto tabs_end_iter = get_tabs_end_iter(start_iter);
auto tabs = get_line_before(tabs_end_iter);
/*
* Change tabs after ending comment block with an extra space (as in this case)
*/
if(tabs.size() % tab_size == 1 && !start_iter.ends_line() && !is_code_iter(start_iter)) {
auto end_of_line_iter = start_iter;
end_of_line_iter.forward_to_line_end();
if(starts_with(get_buffer()->get_text(tabs_end_iter, end_of_line_iter).raw(), "*/")) {
tabs.pop_back();
get_buffer()->insert_at_cursor('\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Indent enter inside HTML or JSX elements, for instance:
// <div>CURSOR</div>
// to:
// <div>
// CURSOR
// </div>
// and
// <div>CURSORtest
// to
// <div>
// CURSORtest
if(*condition_iter == '>' && is_js) {
auto prev = condition_iter;
Gtk::TextIter open_element_iter;
if(prev.backward_char() && backward_to_code(prev) && *prev != '/' &&
find_open_symbol_backward(prev, open_element_iter, '<', '>') &&
open_element_iter.forward_char() && forward_to_code(open_element_iter) && *open_element_iter != '/') {
auto get_element = [this](Gtk::TextIter iter) {
auto start = iter;
auto end = iter;
while(iter.backward_char() && (is_token_char(*iter) || *iter == '.'))
start = iter;
while((is_token_char(*end) || *end == '.') && end.forward_char()) {
}
return get_buffer()->get_text(start, end);
};
auto open_element_token = get_element(open_element_iter);
static std::vector<std::string> void_elements = {"area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"};
if(std::none_of(void_elements.begin(), void_elements.end(), [&open_element_token](const std::string &e) { return e == open_element_token; })) {
auto close_element_iter = iter;
// If cursor is placed between open and close tag
if(*close_element_iter == '<' && close_element_iter.forward_char() && forward_to_code(close_element_iter) && *close_element_iter == '/' &&
close_element_iter.forward_char() && forward_to_code(close_element_iter) &&
open_element_token == get_element(close_element_iter)) {
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs);
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + 1)) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
close_element_iter = iter;
// Add closing tag if missing
if(close_element_iter.ends_line()) {
forward_to_code(close_element_iter);
auto close_element_tabs_size = static_cast<size_t>(get_tabs_end_iter(close_element_iter).get_line_offset());
if(!close_element_iter || close_element_tabs_size < tabs.size() ||
(close_element_tabs_size == tabs.size() && (*close_element_iter == '{' ||
(*close_element_iter == '<' && close_element_iter.forward_char() && forward_to_code(close_element_iter) &&
!(*close_element_iter == '/' && close_element_iter.forward_char() && forward_to_code(close_element_iter) && get_element(close_element_iter) == open_element_token))))) {
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs + "</" + open_element_token + '>');
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + 1 + open_element_token.size() + 3)) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
}
// If line ends with closing element, move content after open to new line, and closing tag on the next line thereafter
close_element_iter = iter;
if(!close_element_iter.ends_line())
close_element_iter.forward_to_line_end();
if(close_element_iter.backward_char() && *close_element_iter == '>' && close_element_iter.backward_char() &&
find_open_symbol_backward(close_element_iter, close_element_iter, '<', '>')) {
auto start_close_element_iter = close_element_iter;
auto content_size = start_close_element_iter.get_offset() - iter.get_offset();
if(close_element_iter.forward_char() && forward_to_code(close_element_iter) &&
*close_element_iter == '/' && close_element_iter.forward_char() && forward_to_code(close_element_iter) && get_element(close_element_iter) == open_element_token) {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
auto close_element_start_iter = get_buffer()->get_insert()->get_iter();
close_element_start_iter.forward_chars(content_size);
get_buffer()->insert(close_element_start_iter, '\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
}
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
// Special indentation of {, [ and ( for for instance JavaScript, JSON, Rust
if(use_fixed_continuation_indenting) {
unsigned int open_symbol = 0, close_symbol = 0;
if(*condition_iter == '[') {
open_symbol = '[';
close_symbol = ']';
}
else if(*condition_iter == '(') {
open_symbol = '(';
close_symbol = ')';
}
else if(*condition_iter == '{') {
open_symbol = '{';
close_symbol = '}';
}
if(open_symbol != 0 && is_code_iter(condition_iter)) {
Gtk::TextIter found_iter;
// Check if an ), ] or } is needed
bool has_right_bracket = false;
if(find_close_symbol_forward(iter, found_iter, open_symbol, close_symbol)) {
auto found_tabs_end_iter = get_tabs_end_iter(found_iter);
if(found_tabs_end_iter.get_line_offset() == tabs_end_iter.get_line_offset())
has_right_bracket = true;
}
if(*iter == close_symbol) {
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs);
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + 1)) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
else if(!has_right_bracket) {
// If line does not end with: (,[, or {, move contents after the left bracket to next line inside brackets
if(!iter.ends_line() && *iter != ')' && *iter != ']' && *iter != '}') {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
auto iter = get_buffer()->get_insert()->get_iter();
Mark mark(iter);
iter.forward_to_line_end();
get_buffer()->insert(iter, '\n' + tabs + static_cast<char>(close_symbol));
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(mark->get_iter());
return true;
}
else {
//Insert new lines with bracket end
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs + static_cast<char>(close_symbol));
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + 2)) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
}
else {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// JavaScript: simplified indentations inside brackets, after for example:
// [\n 1, 2, 3,\n
// return (\n
// ReactDOM.render(\n <div>\n
Gtk::TextIter found_iter;
auto after_start_iter = start_iter;
after_start_iter.forward_char();
if((*start_iter == '[' && (!find_close_symbol_forward(after_start_iter, found_iter, '[', ']') || found_iter > iter)) ||
(*start_iter == '(' && (!find_close_symbol_forward(after_start_iter, found_iter, '(', ')') || found_iter > iter)) ||
(*start_iter == '{' && (!find_close_symbol_forward(after_start_iter, found_iter, '{', '}') || found_iter > iter))) {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
else {
if(*condition_iter == '{' && is_code_iter(condition_iter)) {
Gtk::TextIter close_iter;
// Check if an '}' is needed
bool has_right_curly_bracket = false;
if(find_close_symbol_forward(iter, close_iter, '{', '}')) {
auto found_tabs_end_iter = get_tabs_end_iter(close_iter);
if(found_tabs_end_iter.get_line_offset() == tabs_end_iter.get_line_offset()) {
has_right_curly_bracket = true;
// Special case for functions and classes with no indentation after: namespace {
if(is_cpp && tabs_end_iter.starts_line()) {
auto iter = condition_iter;
Gtk::TextIter open_iter;
if(iter.backward_char() && find_open_symbol_backward(iter, open_iter, '{', '}')) {
if(open_iter.starts_line()) // in case of: namespace test\n{
open_iter.backward_char();
auto iter = get_buffer()->get_iter_at_line(open_iter.get_line());
if(get_token(iter) == "namespace")
has_right_curly_bracket = close_iter.forward_char() && find_close_symbol_forward(close_iter, close_iter, '{', '}');
}
}
}
/**
* Handle pressing enter after '{' in special expressions like:
* enum class A { a,
* b }
*/
else if(close_iter.get_line() > condition_iter.get_line() && close_iter.get_line_offset() > condition_iter.get_line_offset()) {
get_buffer()->insert_at_cursor('\n' + get_line_before(get_tabs_end_iter(condition_iter.get_line() + 1)));
scroll_to(get_buffer()->get_insert());
return true;
}
/**
* Handle pressing enter after '{' in special expressions like:
* test(2,
* []() {
* func();
* });
*/
else if(close_iter.get_line() > condition_iter.get_line() && close_iter.get_line_offset() == get_tabs_end_iter(condition_iter).get_line_offset()) {
get_buffer()->insert_at_cursor('\n' + get_line_before(get_tabs_end_iter(condition_iter)) + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Check if one should add semicolon after '}'
bool add_semicolon = false;
if(is_c || is_cpp) {
// add semicolon after class or struct?
auto token = get_token(tabs_end_iter);
if(token == "class" || token == "struct")
add_semicolon = true;
// Add semicolon after lambda unless it's an argument
else if(*start_iter != '(' && *start_iter != '{' && *start_iter != '[') {
auto it = condition_iter;
long para_count = 0;
long square_count = 0;
bool square_outside_para_found = false;
while(it.backward_char()) {
if(*it == ']' && is_code_iter(it)) {
--square_count;
if(para_count == 0)
square_outside_para_found = true;
}
else if(*it == '[' && is_code_iter(it))
++square_count;
else if(*it == ')' && is_code_iter(it))
--para_count;
else if(*it == '(' && is_code_iter(it))
++para_count;
if(square_outside_para_found && square_count == 0 && para_count == 0) {
// Look for equal sign
while(it.backward_char() && (*it == ' ' || *it == '\t' || it.ends_line())) {
}
if(*it == '=')
add_semicolon = true;
break;
}
if(it == start_iter)
break;
if(!square_outside_para_found && square_count == 0 && para_count == 0) {
if(is_token_char(*it) ||
*it == '-' || *it == ' ' || *it == '\t' || *it == '<' || *it == '>' || *it == '(' || *it == ':' ||
*it == '*' || *it == '&' || *it == '/' || it.ends_line() || !is_code_iter(it)) {
continue;
}
else
break;
}
}
}
}
if(*iter == '}') {
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs);
if(add_semicolon) {
// Check if semicolon exists
auto next_iter = get_buffer()->get_insert()->get_iter();
next_iter.forward_char();
if(*next_iter != ';')
get_buffer()->insert(next_iter, ";");
}
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + 1)) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
else if(!has_right_curly_bracket) {
// If line does not end with: {, move contents after { to next line inside brackets
if(!iter.ends_line() && *iter != ')' && *iter != ']') {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
auto iter = get_buffer()->get_insert()->get_iter();
Mark mark(iter);
iter.forward_to_line_end();
get_buffer()->insert(iter, '\n' + tabs + '}');
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(mark->get_iter());
return true;
}
else {
get_buffer()->insert_at_cursor('\n' + tabs + tab + '\n' + tabs + (add_semicolon ? "};" : "}"));
auto insert_it = get_buffer()->get_insert()->get_iter();
if(insert_it.backward_chars(tabs.size() + (add_semicolon ? 3 : 2))) {
scroll_to(get_buffer()->get_insert());
get_buffer()->place_cursor(insert_it);
}
return true;
}
}
else {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Indent multiline expressions
if(*start_iter == '(' || *start_iter == '[') {
auto iter = get_tabs_end_iter(start_iter);
auto tabs = get_line_before(iter);
while(iter <= start_iter) {
tabs += ' ';
iter.forward_char();
}
get_buffer()->insert_at_cursor('\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
}
auto after_condition_iter = condition_iter;
after_condition_iter.forward_char();
std::string sentence = get_buffer()->get_text(start_iter, after_condition_iter);
std::smatch sm;
// Indenting after for instance: if(...)\n
if(std::regex_match(sentence, sm, no_bracket_statement_regex)) {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
// Indenting after for instance: if(...)\n...;\n
else if(*condition_iter == ';' && condition_iter.get_line() > 0 && is_code_iter(condition_iter)) {
auto previous_end_iter = start_iter;
while(previous_end_iter.backward_char() && !previous_end_iter.ends_line()) {
}
backward_to_code_or_line_start(previous_end_iter);
auto previous_start_iter = get_tabs_end_iter(get_buffer()->get_iter_at_line(get_start_of_expression(previous_end_iter).get_line()));
auto previous_tabs = get_line_before(previous_start_iter);
if(!previous_end_iter.ends_line())
previous_end_iter.forward_char();
std::string previous_sentence = get_buffer()->get_text(previous_start_iter, previous_end_iter);
std::smatch sm2;
if(std::regex_match(previous_sentence, sm2, no_bracket_statement_regex)) {
get_buffer()->insert_at_cursor('\n' + previous_tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Indenting after ':'
else if(*condition_iter == ':' && is_code_iter(condition_iter)) {
bool perform_indent = true;
auto iter = condition_iter;
if(!iter.starts_line())
iter.backward_char();
backward_to_code_or_line_start(iter);
if(*iter == ')') {
auto token = get_token(get_tabs_end_iter(get_buffer()->get_iter_at_line(iter.get_line())));
if(token != "case") // Do not move left for instance: void Test::Test():
perform_indent = false;
}
if(perform_indent) {
Gtk::TextIter found_curly_iter;
if(find_open_symbol_backward(iter, found_curly_iter, '{', '}')) {
auto tabs_end_iter = get_tabs_end_iter(get_buffer()->get_iter_at_line(found_curly_iter.get_line()));
auto tabs_start_of_sentence = get_line_before(tabs_end_iter);
if(tabs.size() == (tabs_start_of_sentence.size() + tab_size)) {
auto start_line_iter = get_buffer()->get_iter_at_line(iter.get_line());
auto start_line_plus_tab_size = start_line_iter;
for(size_t c = 0; c < tab_size; c++)
start_line_plus_tab_size.forward_char();
get_buffer()->erase(start_line_iter, start_line_plus_tab_size);
get_buffer()->insert_at_cursor('\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
else {
get_buffer()->insert_at_cursor('\n' + tabs + tab);
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
}
// Indent as in current or next line
int line_nr = iter.get_line();
if(iter.ends_line() && (line_nr + 1) < get_buffer()->get_line_count()) {
auto next_tabs_end_iter = get_tabs_end_iter(line_nr + 1);
if(next_tabs_end_iter.get_line_offset() > tabs_end_iter.get_line_offset()) {
get_buffer()->insert_at_cursor('\n' + get_line_before(next_tabs_end_iter));
scroll_to(get_buffer()->get_insert());
return true;
}
}
get_buffer()->insert_at_cursor('\n' + tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
// Indent left when writing }, ) or ] on a new line
else if(event->keyval == GDK_KEY_braceright ||
(use_fixed_continuation_indenting && (event->keyval == GDK_KEY_bracketright || event->keyval == GDK_KEY_parenright))) {
std::string bracket;
if(event->keyval == GDK_KEY_braceright)
bracket = "}";
if(event->keyval == GDK_KEY_bracketright)
bracket = "]";
else if(event->keyval == GDK_KEY_parenright)
bracket = ")";
std::string line = get_line_before();
if(line.size() >= tab_size && iter.ends_line()) {
bool indent_left = true;
for(auto c : line) {
if(c != tab_char) {
indent_left = false;
break;
}
}
if(indent_left) {
auto line_it = get_buffer()->get_iter_at_line(iter.get_line());
auto line_plus_it = line_it;
line_plus_it.forward_chars(tab_size);
get_buffer()->erase(line_it, line_plus_it);
get_buffer()->insert_at_cursor(bracket);
return true;
}
}
}
// Indent left when writing { on a new line after for instance if(...)\n...
else if(event->keyval == GDK_KEY_braceleft) {
auto tabs_end_iter = get_tabs_end_iter();
auto tabs = get_line_before(tabs_end_iter);
size_t line_nr = iter.get_line();
if(line_nr > 0 && tabs.size() >= tab_size && iter == tabs_end_iter) {
auto previous_end_iter = iter;
while(previous_end_iter.backward_char() && !previous_end_iter.ends_line()) {
}
auto condition_iter = previous_end_iter;
backward_to_code_or_line_start(condition_iter);
auto previous_start_iter = get_tabs_end_iter(get_buffer()->get_iter_at_line(get_start_of_expression(condition_iter).get_line()));
auto previous_tabs = get_line_before(previous_start_iter);
auto after_condition_iter = condition_iter;
after_condition_iter.forward_char();
if((tabs.size() - tab_size) == previous_tabs.size()) {
std::string previous_sentence = get_buffer()->get_text(previous_start_iter, after_condition_iter);
std::smatch sm;
if(std::regex_match(previous_sentence, sm, no_bracket_statement_regex)) {
auto start_iter = iter;
start_iter.backward_chars(tab_size);
get_buffer()->erase(start_iter, iter);
get_buffer()->insert_at_cursor("{");
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
}
// Mark parameters of templated functions after pressing tab and after writing template argument
else if(event->keyval == GDK_KEY_Tab && (event->state & GDK_SHIFT_MASK) == 0) {
if(*iter == '>') {
iter.forward_char();
Gtk::TextIter parenthesis_end_iter;
if(*iter == '(' && is_templated_function(iter, parenthesis_end_iter)) {
iter.forward_char();
get_buffer()->select_range(iter, parenthesis_end_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Special case if insert is at beginning of empty line:
else if(iter.starts_line() && iter.ends_line() && !get_buffer()->get_has_selection()) {
// Indenting after for instance: if(...)\n...;\n
auto condition_iter = iter;
while(condition_iter.starts_line() && condition_iter.backward_char()) {
}
backward_to_code_or_line_start(condition_iter);
if(*condition_iter == ';' && condition_iter.get_line() > 0 && is_code_iter(condition_iter)) {
auto start_iter = get_start_of_expression(condition_iter);
auto previous_end_iter = start_iter;
while(previous_end_iter.backward_char() && !previous_end_iter.ends_line()) {
}
backward_to_code_or_line_start(previous_end_iter);
auto previous_start_iter = get_tabs_end_iter(get_buffer()->get_iter_at_line(get_start_of_expression(previous_end_iter).get_line()));
auto previous_tabs = get_line_before(previous_start_iter);
if(!previous_end_iter.ends_line())
previous_end_iter.forward_char();
std::string previous_sentence = get_buffer()->get_text(previous_start_iter, previous_end_iter);
std::smatch sm2;
if(std::regex_match(previous_sentence, sm2, no_bracket_statement_regex)) {
get_buffer()->insert_at_cursor(previous_tabs);
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
}
return false;
}
bool Source::View::on_key_press_event_smart_brackets(GdkEventKey *event) {
if(get_buffer()->get_has_selection())
return false;
auto iter = get_buffer()->get_insert()->get_iter();
auto previous_iter = iter;
previous_iter.backward_char();
if(is_code_iter(iter)) {
//Move after ')' if closed expression
if(event->keyval == GDK_KEY_parenright) {
if(*iter == ')' && symbol_count(iter, '(', ')') <= 0) {
iter.forward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
//Move after '>' if >( and closed expression
else if(event->keyval == GDK_KEY_greater) {
if(*iter == '>') {
iter.forward_char();
Gtk::TextIter parenthesis_end_iter;
if(*iter == '(' && is_templated_function(iter, parenthesis_end_iter)) {
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
//Move after '(' if >( and select text inside parentheses
else if(event->keyval == GDK_KEY_parenleft) {
auto previous_iter = iter;
previous_iter.backward_char();
if(*previous_iter == '>') {
Gtk::TextIter parenthesis_end_iter;
if(*iter == '(' && is_templated_function(iter, parenthesis_end_iter)) {
iter.forward_char();
get_buffer()->select_range(iter, parenthesis_end_iter);
scroll_to(iter);
return true;
}
}
}
}
return false;
}
bool Source::View::on_key_press_event_smart_inserts(GdkEventKey *event) {
keep_snippet_marks = true;
ScopeGuard guard{[this] {
keep_snippet_marks = false;
}};
if(get_buffer()->get_has_selection()) {
if(is_bracket_language) {
// Remove /**/ around selection
if(event->keyval == GDK_KEY_slash) {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
auto before_start = start;
auto after_end = end;
if(before_start.backward_char() && *before_start == '*' && before_start.backward_char() && *before_start == '/' &&
*after_end == '*' && after_end.forward_char() && *after_end == '/') {
Mark start_mark(start);
Mark end_mark(end);
get_buffer()->erase(before_start, start);
after_end = end_mark->get_iter();
after_end.forward_chars(2);
get_buffer()->erase(end_mark->get_iter(), after_end);
get_buffer()->select_range(start_mark->get_iter(), end_mark->get_iter());
return true;
}
}
}
Glib::ustring left, right;
// Insert () around selection
if(event->keyval == GDK_KEY_parenleft) {
left = '(';
right = ')';
}
// Insert [] around selection
else if(event->keyval == GDK_KEY_bracketleft) {
left = '[';
right = ']';
}
// Insert {} around selection
else if(event->keyval == GDK_KEY_braceleft) {
left = '{';
right = '}';
}
// Insert <> around selection
else if(event->keyval == GDK_KEY_less) {
left = '<';
right = '>';
}
// Insert '' around selection
else if(event->keyval == GDK_KEY_apostrophe) {
left = '\'';
right = '\'';
}
// Insert "" around selection
else if(event->keyval == GDK_KEY_quotedbl) {
left = '"';
right = '"';
}
// Insert /**/ around selection
else if(is_bracket_language && event->keyval == GDK_KEY_slash) {
left = "/*";
right = "*/";
}
else if(language_id == "markdown" ||
!is_code_iter(get_buffer()->get_insert()->get_iter()) || !is_code_iter(get_buffer()->get_selection_bound()->get_iter())) {
// Insert `` around selection
if(event->keyval == GDK_KEY_dead_grave) {
left = '`';
right = '`';
}
// Insert ** around selection
else if(event->keyval == GDK_KEY_asterisk) {
left = '*';
right = '*';
}
// Insert __ around selection
else if(event->keyval == GDK_KEY_underscore) {
left = '_';
right = '_';
}
// Insert ~~ around selection
else if(event->keyval == GDK_KEY_dead_tilde) {
left = '~';
right = '~';
}
}
if(!left.empty() && !right.empty()) {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
Mark start_mark(start);
Mark end_mark(end);
get_buffer()->insert(start, left);
get_buffer()->insert(end_mark->get_iter(), right);
auto start_mark_next_iter = start_mark->get_iter();
start_mark_next_iter.forward_chars(left.size());
get_buffer()->select_range(start_mark_next_iter, end_mark->get_iter());
return true;
}
return false;
}
auto iter = get_buffer()->get_insert()->get_iter();
auto previous_iter = iter;
previous_iter.backward_char();
auto next_iter = iter;
next_iter.forward_char();
auto allow_insertion = [](const Gtk::TextIter &iter) {
if(iter.ends_line() || *iter == ' ' || *iter == '\t' || *iter == ';' || *iter == ',' ||
*iter == ')' || *iter == ']' || *iter == '}' || *iter == '<' || *iter == '>' || *iter == '/')
return true;
return false;
};
if(is_code_iter(iter)) {
// Insert ()
if(event->keyval == GDK_KEY_parenleft && allow_insertion(iter)) {
if(symbol_count(iter, '(', ')') >= 0) {
get_buffer()->insert_at_cursor(")");
auto iter = get_buffer()->get_insert()->get_iter();
iter.backward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return false;
}
}
// Insert []
else if(event->keyval == GDK_KEY_bracketleft && allow_insertion(iter)) {
if(symbol_count(iter, '[', ']') >= 0) {
get_buffer()->insert_at_cursor("]");
auto iter = get_buffer()->get_insert()->get_iter();
iter.backward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return false;
}
}
// Move right on ] in []
else if(event->keyval == GDK_KEY_bracketright) {
if(*iter == ']' && symbol_count(iter, '[', ']') <= 0) {
iter.forward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Insert {}
else if(event->keyval == GDK_KEY_braceleft && allow_insertion(iter)) {
auto start_iter = get_start_of_expression(iter);
// Do not add } if { is at end of line and next line has a higher indentation
auto test_iter = iter;
while(!test_iter.ends_line() && (*test_iter == ' ' || *test_iter == '\t' || !is_code_iter(test_iter)) && test_iter.forward_char()) {
}
if(test_iter.ends_line()) {
if(iter.get_line() + 1 < get_buffer()->get_line_count() && *start_iter != '(' && *start_iter != '[' && *start_iter != '{') {
auto tabs_end_iter = (get_tabs_end_iter(get_buffer()->get_iter_at_line(start_iter.get_line())));
auto next_line_iter = get_buffer()->get_iter_at_line(iter.get_line() + 1);
auto next_line_tabs_end_iter = (get_tabs_end_iter(get_buffer()->get_iter_at_line(next_line_iter.get_line())));
if(next_line_tabs_end_iter.get_line_offset() > tabs_end_iter.get_line_offset())
return false;
}
}
Gtk::TextIter close_iter;
bool has_right_curly_bracket = false;
auto tabs_end_iter = get_tabs_end_iter(start_iter);
if(find_close_symbol_forward(iter, close_iter, '{', '}')) {
auto found_tabs_end_iter = get_tabs_end_iter(close_iter);
if(found_tabs_end_iter.get_line_offset() == tabs_end_iter.get_line_offset()) {
has_right_curly_bracket = true;
// Special case for functions and classes with no indentation after: namespace {:
if(is_cpp && tabs_end_iter.starts_line()) {
Gtk::TextIter open_iter;
if(find_open_symbol_backward(iter, open_iter, '{', '}')) {
if(open_iter.starts_line()) // in case of: namespace test\n{
open_iter.backward_char();
auto iter = get_buffer()->get_iter_at_line(open_iter.get_line());
if(get_token(iter) == "namespace")
has_right_curly_bracket = close_iter.forward_char() && find_close_symbol_forward(close_iter, close_iter, '{', '}');
}
}
// Inside for example {}:
else if(found_tabs_end_iter.get_line() == tabs_end_iter.get_line())
has_right_curly_bracket = symbol_count(iter, '{', '}') < 0;
}
}
if(!has_right_curly_bracket) {
get_buffer()->insert_at_cursor("}");
auto iter = get_buffer()->get_insert()->get_iter();
iter.backward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
}
return false;
}
// Move right on } in {}
else if(event->keyval == GDK_KEY_braceright) {
if(*iter == '}' && symbol_count(iter, '{', '}') <= 0) {
iter.forward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
// Insert ''
else if(event->keyval == GDK_KEY_apostrophe && allow_insertion(iter) && symbol_count(iter, '\'') % 2 == 0) {
get_buffer()->insert_at_cursor("''");
auto iter = get_buffer()->get_insert()->get_iter();
iter.backward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Insert ""
else if(event->keyval == GDK_KEY_quotedbl && allow_insertion(iter) && symbol_count(iter, '"') % 2 == 0) {
get_buffer()->insert_at_cursor("\"\"");
auto iter = get_buffer()->get_insert()->get_iter();
iter.backward_char();
get_buffer()->place_cursor(iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Move right on last ' in '', or last " in ""
else if(((event->keyval == GDK_KEY_apostrophe && *iter == '\'') || (event->keyval == GDK_KEY_quotedbl && *iter == '\"')) && is_spellcheck_iter(iter)) {
get_buffer()->place_cursor(next_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Insert ; at the end of line, if iter is at the last )
else if(event->keyval == GDK_KEY_semicolon) {
if(*iter == ')' && symbol_count(iter, '(', ')') <= 0 && next_iter.ends_line()) {
auto start_iter = get_start_of_expression(previous_iter);
if(*start_iter == '(') {
start_iter.backward_char();
if(*start_iter == ' ')
start_iter.backward_char();
auto token = get_token(start_iter);
if(token != "for" && token != "if" && token != "while" && token != "else") {
iter.forward_char();
get_buffer()->place_cursor(iter);
get_buffer()->insert_at_cursor(";");
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
}
// Delete ()
else if(event->keyval == GDK_KEY_BackSpace) {
if(*previous_iter == '(' && *iter == ')' && symbol_count(iter, '(', ')') <= 0) {
auto next_iter = iter;
next_iter.forward_char();
get_buffer()->erase(previous_iter, next_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Delete []
else if(*previous_iter == '[' && *iter == ']' && symbol_count(iter, '[', ']') <= 0) {
auto next_iter = iter;
next_iter.forward_char();
get_buffer()->erase(previous_iter, next_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Delete {}
else if(*previous_iter == '{' && *iter == '}' && symbol_count(iter, '{', '}') <= 0) {
auto next_iter = iter;
next_iter.forward_char();
get_buffer()->erase(previous_iter, next_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
// Delete '' or ""
else if(event->keyval == GDK_KEY_BackSpace) {
if((*previous_iter == '\'' && *iter == '\'') || (*previous_iter == '"' && *iter == '"')) {
get_buffer()->erase(previous_iter, next_iter);
scroll_to(get_buffer()->get_insert());
return true;
}
}
}
}
return false;
}
bool Source::View::on_button_press_event(GdkEventButton *event) {
// Select range when double clicking
if(event->type == GDK_2BUTTON_PRESS) {
Gtk::TextIter start, end;
get_buffer()->get_selection_bounds(start, end);
auto iter = start;
while((*iter >= 48 && *iter <= 57) || (*iter >= 65 && *iter <= 90) || (*iter >= 97 && *iter <= 122) || *iter == 95) {
start = iter;
if(!iter.backward_char())
break;
}
while((*end >= 48 && *end <= 57) || (*end >= 65 && *end <= 90) || (*end >= 97 && *end <= 122) || *end == 95) {
if(!end.forward_char())
break;
}
get_buffer()->select_range(start, end);
return true;
}
// Go to implementation or declaration
if((event->type == GDK_BUTTON_PRESS) && (event->button == 1)) {
if(event->state & primary_modifier_mask) {
int x, y;
window_to_buffer_coords(Gtk::TextWindowType::TEXT_WINDOW_TEXT, event->x, event->y, x, y);
Gtk::TextIter iter;
get_iter_at_location(iter, x, y);
if(iter)
get_buffer()->place_cursor(iter);
Menu::get().actions["source_goto_declaration_or_implementation"]->activate();
return true;
}
}
// Open right click menu
if((event->type == GDK_BUTTON_PRESS) && (event->button == 3)) {
hide_tooltips();
if(!get_buffer()->get_has_selection()) {
int x, y;
window_to_buffer_coords(Gtk::TextWindowType::TEXT_WINDOW_TEXT, event->x, event->y, x, y);
Gtk::TextIter iter;
get_iter_at_location(iter, x, y);
if(iter)
get_buffer()->place_cursor(iter);
Menu::get().right_click_line_menu->popup(event->button, event->time);
}
else {
Menu::get().right_click_selected_menu->popup(event->button, event->time);
}
return true;
}
return Gsv::View::on_button_press_event(event);
}
| 38.706802 | 280 | 0.583916 | jlangvand |
4de1e6ea25fb7a5f8a2ac2988c1414c88e5a2021 | 4,504 | cpp | C++ | tdmq/src/v20200217/model/ModifyRocketMQNamespaceRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | tdmq/src/v20200217/model/ModifyRocketMQNamespaceRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tdmq/src/v20200217/model/ModifyRocketMQNamespaceRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"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/tdmq/v20200217/model/ModifyRocketMQNamespaceRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tdmq::V20200217::Model;
using namespace std;
ModifyRocketMQNamespaceRequest::ModifyRocketMQNamespaceRequest() :
m_clusterIdHasBeenSet(false),
m_namespaceIdHasBeenSet(false),
m_ttlHasBeenSet(false),
m_retentionTimeHasBeenSet(false),
m_remarkHasBeenSet(false)
{
}
string ModifyRocketMQNamespaceRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_clusterIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ClusterId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_clusterId.c_str(), allocator).Move(), allocator);
}
if (m_namespaceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NamespaceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_namespaceId.c_str(), allocator).Move(), allocator);
}
if (m_ttlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Ttl";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_ttl, allocator);
}
if (m_retentionTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RetentionTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_retentionTime, allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string ModifyRocketMQNamespaceRequest::GetClusterId() const
{
return m_clusterId;
}
void ModifyRocketMQNamespaceRequest::SetClusterId(const string& _clusterId)
{
m_clusterId = _clusterId;
m_clusterIdHasBeenSet = true;
}
bool ModifyRocketMQNamespaceRequest::ClusterIdHasBeenSet() const
{
return m_clusterIdHasBeenSet;
}
string ModifyRocketMQNamespaceRequest::GetNamespaceId() const
{
return m_namespaceId;
}
void ModifyRocketMQNamespaceRequest::SetNamespaceId(const string& _namespaceId)
{
m_namespaceId = _namespaceId;
m_namespaceIdHasBeenSet = true;
}
bool ModifyRocketMQNamespaceRequest::NamespaceIdHasBeenSet() const
{
return m_namespaceIdHasBeenSet;
}
uint64_t ModifyRocketMQNamespaceRequest::GetTtl() const
{
return m_ttl;
}
void ModifyRocketMQNamespaceRequest::SetTtl(const uint64_t& _ttl)
{
m_ttl = _ttl;
m_ttlHasBeenSet = true;
}
bool ModifyRocketMQNamespaceRequest::TtlHasBeenSet() const
{
return m_ttlHasBeenSet;
}
uint64_t ModifyRocketMQNamespaceRequest::GetRetentionTime() const
{
return m_retentionTime;
}
void ModifyRocketMQNamespaceRequest::SetRetentionTime(const uint64_t& _retentionTime)
{
m_retentionTime = _retentionTime;
m_retentionTimeHasBeenSet = true;
}
bool ModifyRocketMQNamespaceRequest::RetentionTimeHasBeenSet() const
{
return m_retentionTimeHasBeenSet;
}
string ModifyRocketMQNamespaceRequest::GetRemark() const
{
return m_remark;
}
void ModifyRocketMQNamespaceRequest::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool ModifyRocketMQNamespaceRequest::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
| 26.494118 | 96 | 0.732682 | suluner |
4de31b71452a6d5c691aae0e7af3f36e6ee435b6 | 34,119 | cpp | C++ | src/AmpleObject.cpp | elmindreda/Ample | 7366b8591d8cd1f09ae03a6dd728130769891ba5 | [
"BSD-3-Clause"
] | 4 | 2015-02-25T17:43:10.000Z | 2016-07-29T14:14:02.000Z | src/AmpleObject.cpp | elmindreda/Ample | 7366b8591d8cd1f09ae03a6dd728130769891ba5 | [
"BSD-3-Clause"
] | null | null | null | src/AmpleObject.cpp | elmindreda/Ample | 7366b8591d8cd1f09ae03a6dd728130769891ba5 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------
// Simple C++ retained mode library for Verse
// Copyright (c) PDC, KTH
// Written by Camilla Berglund <[email protected]>
//---------------------------------------------------------------------
#include <verse.h>
#include <Ample.h>
namespace verse
{
namespace ample
{
//---------------------------------------------------------------------
MethodParam::MethodParam(const std::string& name, VNOParamType type):
mName(name),
mType(type)
{
}
size_t MethodParam::getSize(void) const
{
switch (mType)
{
case VN_O_METHOD_PTYPE_INT8:
case VN_O_METHOD_PTYPE_UINT8:
return sizeof(uint8);
case VN_O_METHOD_PTYPE_INT16:
case VN_O_METHOD_PTYPE_UINT16:
return sizeof(uint16);
case VN_O_METHOD_PTYPE_INT32:
case VN_O_METHOD_PTYPE_UINT32:
return sizeof(uint32);
case VN_O_METHOD_PTYPE_REAL32:
return sizeof(real32);
case VN_O_METHOD_PTYPE_REAL64:
return sizeof(real64);
case VN_O_METHOD_PTYPE_REAL32_VEC2:
return sizeof(real32) * 2;
case VN_O_METHOD_PTYPE_REAL32_VEC3:
return sizeof(real32) * 3;
case VN_O_METHOD_PTYPE_REAL32_VEC4:
return sizeof(real32) * 4;
case VN_O_METHOD_PTYPE_REAL64_VEC2:
return sizeof(real64) * 2;
case VN_O_METHOD_PTYPE_REAL64_VEC3:
return sizeof(real64) * 3;
case VN_O_METHOD_PTYPE_REAL64_VEC4:
return sizeof(real64) * 4;
case VN_O_METHOD_PTYPE_REAL32_MAT4:
return sizeof(real32) * 4;
case VN_O_METHOD_PTYPE_REAL32_MAT9:
return sizeof(real32) * 9;
case VN_O_METHOD_PTYPE_REAL32_MAT16:
return sizeof(real32) * 16;
case VN_O_METHOD_PTYPE_REAL64_MAT4:
return sizeof(real64) * 4;
case VN_O_METHOD_PTYPE_REAL64_MAT9:
return sizeof(real64) * 9;
case VN_O_METHOD_PTYPE_REAL64_MAT16:
return sizeof(real64) * 16;
case VN_O_METHOD_PTYPE_STRING:
return 500;
case VN_O_METHOD_PTYPE_NODE:
return sizeof(VNodeID);
case VN_O_METHOD_PTYPE_LAYER:
return sizeof(VLayerID);
}
}
//---------------------------------------------------------------------
void Method::destroy(void)
{
mGroup.getNode().getSession().push();
verse_send_o_method_destroy(mGroup.getNode().getID(), mGroup.getID(), mID);
mGroup.getNode().getSession().pop();
}
bool Method::call(const MethodArgumentList& arguments, VNodeID senderID)
{
if (arguments.size() != mParams.size())
return false;
// NOTE: This call isn't strictly portable, as we're assuming
// that &v[0] on an STL vector leads to a regular array.
// In other words; this is bad, don't do this.
VNOPackedParams* packedArguments = verse_method_call_pack(mTypes.size(), &mTypes[0], &arguments[0]);
mGroup.getNode().getSession().push();
verse_send_o_method_call(mGroup.getNode().getID(), mGroup.getID(), mID, senderID, packedArguments);
mGroup.getNode().getSession().pop();
free(packedArguments);
}
uint16 Method::getID(void) const
{
return mID;
}
const std::string& Method::getName(void) const
{
return mName;
}
uint8 Method::getParamCount(void) const
{
return mParams.size();
}
const MethodParam& Method::getParam(uint8 index)
{
return mParams[index];
}
MethodGroup& Method::getGroup(void) const
{
return mGroup;
}
Method::Method(uint16 ID, const std::string& name, MethodGroup& group):
mID(ID),
mName(name),
mGroup(group)
{
}
void Method::initialize(void)
{
verse_callback_set((void*) verse_send_o_method_call,
(void*) receiveMethodCall,
NULL);
}
void Method::receiveMethodCall(void* user, VNodeID nodeID, uint16 groupID, uint16 methodID, VNodeID senderID, const VNOPackedParams* arguments)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
MethodGroup* group = node->getMethodGroupByID(groupID);
if (!group)
return;
Method* method = group->getMethodByID(methodID);
if (!method)
return;
MethodArgumentList unpackedArguments;
unpackedArguments.resize(method->mParams.size());
verse_method_call_unpack(arguments, method->mParams.size(), &(method->mTypes[0]), &unpackedArguments[0]);
const ObserverList& observers = method->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onCall(*method, unpackedArguments);
}
//---------------------------------------------------------------------
void MethodObserver::onCall(Method& method, const MethodArgumentList& arguments)
{
}
void MethodObserver::onSetName(Method& method, const std::string& name)
{
}
void MethodObserver::onDestroy(Method& method)
{
}
//---------------------------------------------------------------------
void MethodGroup::destroy(void)
{
mNode.getSession().push();
verse_send_o_method_group_destroy(mNode.getID(), mID);
mNode.getSession().pop();
}
void MethodGroup::createMethod(const std::string& name, const MethodParamList& parameters)
{
const char** names;
VNOParamType* types;
names = (const char**) new char* [parameters.size()];
types = new VNOParamType [parameters.size()];
for (unsigned int i = 0; i < parameters.size(); i++)
{
types[i] = parameters[i].mType;
names[i] = parameters[i].mName.c_str();
}
mNode.getSession().push();
verse_send_o_method_create(mNode.getID(), mID, (uint16) ~0, name.c_str(), parameters.size(), types, names);
mNode.getSession().pop();
delete types;
delete names;
}
Method* MethodGroup::getMethodByID(uint16 methodID)
{
for (MethodList::iterator i = mMethods.begin(); i != mMethods.end(); i++)
if ((*i)->getID() == methodID)
return *i;
return NULL;
}
const Method* MethodGroup::getMethodByID(uint16 methodID) const
{
for (MethodList::const_iterator i = mMethods.begin(); i != mMethods.end(); i++)
if ((*i)->getID() == methodID)
return *i;
return NULL;
}
Method* MethodGroup::getMethodByIndex(unsigned int index)
{
return mMethods[index];
}
const Method* MethodGroup::getMethodByIndex(unsigned int index) const
{
return mMethods[index];
}
Method* MethodGroup::getMethodByName(const std::string& name)
{
for (MethodList::iterator i = mMethods.begin(); i != mMethods.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
const Method* MethodGroup::getMethodByName(const std::string& name) const
{
for (MethodList::const_iterator i = mMethods.begin(); i != mMethods.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
unsigned int MethodGroup::getMethodCount(void) const
{
return mMethods.size();
}
const uint16 MethodGroup::getID(void) const
{
return mID;
}
const std::string& MethodGroup::getName(void) const
{
return mName;
}
ObjectNode& MethodGroup::getNode(void) const
{
return mNode;
}
MethodGroup::MethodGroup(uint16 ID, const std::string& name, ObjectNode& node):
mID(ID),
mName(name),
mNode(node)
{
}
MethodGroup::~MethodGroup(void)
{
while (mMethods.size())
{
delete mMethods.back();
mMethods.pop_back();
}
}
void MethodGroup::initialize(void)
{
Method::initialize();
verse_callback_set((void*) verse_send_o_method_create,
(void*) receiveMethodCreate,
NULL);
verse_callback_set((void*) verse_send_o_method_destroy,
(void*) receiveMethodDestroy,
NULL);
}
void MethodGroup::receiveMethodCreate(void* user, VNodeID nodeID, uint16 groupID, uint16 methodID, const char* name, uint8 paramCount, const VNOParamType* paramTypes, const char** paramNames)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
MethodGroup* group = node->getMethodGroupByID(groupID);
if (!group)
return;
Method* method = group->getMethodByID(methodID);
if (method)
{
if (method->mName != name)
{
const Method::ObserverList& observers = method->getObservers();
for (Method::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onSetName(*method, name);
method->mName = name;
method->updateDataVersion();
}
// TODO: Notify observers of parameter changes.
}
else
{
method = new Method(methodID, name, *group);
for (unsigned int i = 0; i < paramCount; i++)
{
method->mParams.push_back(MethodParam(paramNames[i], paramTypes[i]));
method->mTypes.push_back(paramTypes[i]);
}
group->mMethods.push_back(method);
group->updateStructureVersion();
const MethodGroup::ObserverList& observers = group->getObservers();
for (MethodGroup::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onCreateMethod(*group, *method);
}
}
void MethodGroup::receiveMethodDestroy(void* user, VNodeID nodeID, uint16 groupID, uint16 methodID)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
MethodGroup* group = node->getMethodGroupByID(groupID);
if (!group)
return;
MethodList& methods = group->mMethods;
for (MethodList::iterator method = methods.begin(); method != methods.end(); method++)
{
if ((*method)->getID() == methodID)
{
// Notify method observers.
{
const Method::ObserverList& observers = (*method)->getObservers();
for (Method::ObserverList::const_iterator observer = observers.begin(); observer != observers.end(); observer++)
(*observer)->onDestroy(*(*method));
}
// Notify method group observers.
{
const ObserverList& observers = group->getObservers();
for (ObserverList::const_iterator observer = observers.begin(); observer != observers.end(); observer++)
(*observer)->onDestroyMethod(*group, *(*method));
}
delete *method;
methods.erase(method);
group->updateStructureVersion();
break;
}
}
}
//---------------------------------------------------------------------
void MethodGroupObserver::onCreateMethod(MethodGroup& group, Method& method)
{
}
void MethodGroupObserver::onDestroyMethod(MethodGroup& group, Method& method)
{
}
void MethodGroupObserver::onSetName(MethodGroup& group, const std::string& name)
{
}
void MethodGroupObserver::onDestroy(MethodGroup& group)
{
}
//---------------------------------------------------------------------
void Link::destroy(void)
{
mNode.getSession().push();
verse_send_o_link_destroy(mNode.getID(), mID);
mNode.getSession().pop();
}
uint16 Link::getID(void) const
{
return mID;
}
VNodeID Link::getLinkedNodeID(void) const
{
return mState.mNodeID;
}
Node* Link::getLinkedNode(void) const
{
return mNode.getSession().getNodeByID(mState.mNodeID);
}
void Link::setLinkedNode(VNodeID nodeID)
{
mCache.mNodeID = nodeID;
sendData();
}
VNodeID Link::getTargetNodeID(void) const
{
return mState.mTargetID;
}
Node* Link::getTargetNode(void) const
{
return mNode.getSession().getNodeByID(mState.mTargetID);
}
void Link::setTargetNode(VNodeID nodeID)
{
mCache.mTargetID = nodeID;
sendData();
}
const std::string& Link::getName(void) const
{
return mState.mName;
}
void Link::setName(const std::string& name)
{
mCache.mName = name;
sendData();
}
ObjectNode& Link::getNode(void) const
{
return mNode;
}
Link::Link(uint16 ID, const std::string& name, VNodeID nodeID, VNodeID targetID, ObjectNode& node):
mID(ID),
mNode(node)
{
mCache.mName = mState.mName = name;
mCache.mNodeID = mState.mNodeID = nodeID;
mCache.mTargetID = mState.mTargetID = targetID;
}
void Link::sendData(void)
{
mNode.getSession().push();
verse_send_o_link_set(mNode.getID(),
mID,
mCache.mNodeID,
mCache.mName.c_str(),
mCache.mTargetID);
mNode.getSession().pop();
}
void Link::receiveLinkSet(void* user,
VNodeID nodeID,
uint16 linkID,
VNodeID linkedNodeID,
const char* name,
uint32 targetNodeID)
{
if (mState.mName != name)
{
const Link::ObserverList& observers = getObservers();
for (Link::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onSetName(*this, name);
mCache.mName = mState.mName = name;
updateDataVersion();
}
if (mState.mNodeID != linkedNodeID)
{
const Link::ObserverList& observers = getObservers();
for (Link::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onSetLinkedNode(*this, linkedNodeID);
mCache.mNodeID = mState.mNodeID = linkedNodeID;
updateDataVersion();
}
if (mState.mTargetID != targetNodeID)
{
const Link::ObserverList& observers = getObservers();
for (Link::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onSetTargetNode(*this, targetNodeID);
mCache.mTargetID = mState.mTargetID = targetNodeID;
updateDataVersion();
}
}
//---------------------------------------------------------------------
void LinkObserver::onSetLinkedNode(Link& link, VNodeID nodeID)
{
}
void LinkObserver::onSetTargetNode(Link& link, VNodeID targetID)
{
}
void LinkObserver::onSetName(Link& link, const std::string name)
{
}
void LinkObserver::onDestroy(Link& link)
{
}
//---------------------------------------------------------------------
void ObjectNode::createMethodGroup(const std::string& name)
{
getSession().push();
verse_send_o_method_group_create(getID(), (uint16) ~0, name.c_str());
getSession().pop();
}
void ObjectNode::createLink(const std::string& name, VNodeID nodeID, VNodeID targetID)
{
getSession().push();
verse_send_o_link_set(getID(), (uint16) ~0, nodeID, name.c_str(), targetID);
getSession().pop();
}
bool ObjectNode::isLight(void) const
{
return mIntensity.r == 0.f && mIntensity.g == 0.f && mIntensity.b == 0.f;
}
void ObjectNode::setLightIntensity(const ColorRGB& intensity)
{
getSession().push();
verse_send_o_light_set(getID(), intensity.r, intensity.g, intensity.b);
getSession().pop();
}
const ColorRGB& ObjectNode::getLightIntensity(void) const
{
return mIntensity;
}
MethodGroup* ObjectNode::getMethodGroupByID(uint16 groupID)
{
for (MethodGroupList::iterator i = mGroups.begin(); i != mGroups.end(); i++)
if ((*i)->getID() == groupID)
return *i;
return NULL;
}
const MethodGroup* ObjectNode::getMethodGroupByID(uint16 groupID) const
{
for (MethodGroupList::const_iterator i = mGroups.begin(); i != mGroups.end(); i++)
if ((*i)->getID() == groupID)
return *i;
return NULL;
}
MethodGroup* ObjectNode::getMethodGroupByIndex(unsigned int index)
{
return mGroups[index];
}
const MethodGroup* ObjectNode::getMethodGroupByIndex(unsigned int index) const
{
return mGroups[index];
}
MethodGroup* ObjectNode::getMethodGroupByName(const std::string& name)
{
for (MethodGroupList::iterator i = mGroups.begin(); i != mGroups.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
const MethodGroup* ObjectNode::getMethodGroupByName(const std::string& name) const
{
for (MethodGroupList::const_iterator i = mGroups.begin(); i != mGroups.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
unsigned int ObjectNode::getMethodGroupCount(void) const
{
return mGroups.size();
}
Link* ObjectNode::getLinkByID(uint16 linkID)
{
for (LinkList::iterator i = mLinks.begin(); i != mLinks.end(); i++)
if ((*i)->getID() == linkID)
return *i;
return NULL;
}
const Link* ObjectNode::getLinkByID(uint16 linkID) const
{
for (LinkList::const_iterator i = mLinks.begin(); i != mLinks.end(); i++)
if ((*i)->getID() == linkID)
return *i;
return NULL;
}
Link* ObjectNode::getLinkByIndex(unsigned int index)
{
return mLinks[index];
}
const Link* ObjectNode::getLinkByIndex(unsigned int index) const
{
return mLinks[index];
}
Link* ObjectNode::getLinkByName(const std::string& name)
{
for (LinkList::iterator i = mLinks.begin(); i != mLinks.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
const Link* ObjectNode::getLinkByName(const std::string& name) const
{
for (LinkList::const_iterator i = mLinks.begin(); i != mLinks.end(); i++)
if ((*i)->getName() == name)
return *i;
return NULL;
}
unsigned int ObjectNode::getLinkCount(void) const
{
return mLinks.size();
}
Node* ObjectNode::getNodeByLinkName(const std::string& name) const
{
const Link* link = getLinkByName(name);
if (!link)
return NULL;
return link->getLinkedNode();
}
void ObjectNode::setTranslation(const Translation& translation)
{
mTranslationCache = translation;
sendTranslation();
}
void ObjectNode::setRotation(const Rotation& rotation)
{
mRotationCache = rotation;
sendRotation();
}
const Vector3d& ObjectNode::getPosition(void) const
{
return mTranslation.mPosition;
}
void ObjectNode::setPosition(const Vector3d& position)
{
mTranslationCache.mPosition = position;
sendTranslation();
}
const Vector3d& ObjectNode::getSpeed(void) const
{
return mTranslation.mSpeed;
}
void ObjectNode::setSpeed(const Vector3d& speed)
{
mTranslationCache.mSpeed = speed;
sendTranslation();
}
const Vector3d& ObjectNode::getAccel(void) const
{
return mTranslation.mAccel;
}
void ObjectNode::setAccel(const Vector3d& accel)
{
mTranslationCache.mAccel = accel;
sendTranslation();
}
const Quaternion64& ObjectNode::getRotation(void) const
{
return mRotation.mRotation;
}
void ObjectNode::setRotation(const Quaternion64& rotation)
{
mRotationCache.mRotation = rotation;
sendRotation();
}
const Quaternion64& ObjectNode::getRotationSpeed(void) const
{
return mRotation.mSpeed;
}
void ObjectNode::setRotationSpeed(const Quaternion64& speed)
{
mRotationCache.mSpeed = speed;
sendRotation();
}
const Quaternion64& ObjectNode::getRotationAccel(void) const
{
return mRotation.mAccel;
}
void ObjectNode::setRotationAccel(const Quaternion64& accel)
{
mRotationCache.mAccel = accel;
sendRotation();
}
const Vector3d& ObjectNode::getScale(void) const
{
return mScale;
}
void ObjectNode::setScale(const Vector3d& scale)
{
getSession().push();
verse_send_o_transform_scale_real64(getID(), scale.x, scale.y, scale.z);
getSession().pop();
}
ObjectNode::ObjectNode(VNodeID ID, VNodeOwner owner, Session& session):
Node(ID, V_NT_OBJECT, owner, session)
{
}
ObjectNode::~ObjectNode(void)
{
while (mLinks.size())
{
delete mLinks.back();
mLinks.pop_back();
}
while (mGroups.size())
{
delete mGroups.back();
mGroups.pop_back();
}
}
void ObjectNode::sendTranslation(void)
{
getSession().push();
verse_send_o_transform_pos_real64(getID(),
mTranslationCache.mSeconds,
mTranslationCache.mFraction,
mTranslationCache.mPosition,
mTranslationCache.mSpeed,
mTranslationCache.mAccel,
mTranslationCache.mDragNormal,
mTranslationCache.mDrag);
getSession().pop();
}
void ObjectNode::sendRotation(void)
{
getSession().push();
verse_send_o_transform_rot_real64(getID(),
mRotationCache.mSeconds,
mRotationCache.mFraction,
&mRotationCache.mRotation,
&mRotationCache.mSpeed,
&mRotationCache.mAccel,
&mRotationCache.mDragNormal,
mRotationCache.mDrag);
getSession().pop();
}
void ObjectNode::initialize(void)
{
MethodGroup::initialize();
verse_callback_set((void*) verse_send_o_transform_pos_real32,
(void*) receiveTransformPosReal32,
NULL);
verse_callback_set((void*) verse_send_o_transform_rot_real32,
(void*) receiveTransformRotReal32,
NULL);
verse_callback_set((void*) verse_send_o_transform_scale_real32,
(void*) receiveTransformScaleReal32,
NULL);
verse_callback_set((void*) verse_send_o_transform_pos_real64,
(void*) receiveTransformPosReal64,
NULL);
verse_callback_set((void*) verse_send_o_transform_rot_real64,
(void*) receiveTransformRotReal64,
NULL);
verse_callback_set((void*) verse_send_o_transform_scale_real64,
(void*) receiveTransformScaleReal64,
NULL);
verse_callback_set((void*) verse_send_o_light_set,
(void*) receiveLightSet,
NULL);
verse_callback_set((void*) verse_send_o_link_set,
(void*) receiveLinkSet,
NULL);
verse_callback_set((void*) verse_send_o_link_destroy,
(void*) receiveLinkDestroy,
NULL);
verse_callback_set((void*) verse_send_o_method_group_create,
(void*) receiveMethodGroupCreate,
NULL);
verse_callback_set((void*) verse_send_o_method_group_destroy,
(void*) receiveMethodGroupDestroy,
NULL);
verse_callback_set((void*) verse_send_o_anim_run,
(void*) receiveAnimRun,
NULL);
}
void ObjectNode::receiveTransformPosReal32(void* user,
VNodeID nodeID,
uint32 seconds,
uint32 fraction,
const real32* position,
const real32* speed,
const real32* accel,
const real32* dragNormal,
real32 drag)
{
}
void ObjectNode::receiveTransformRotReal32(void* user,
VNodeID nodeID,
uint32 seconds,
uint32 fraction,
const VNQuat32* rotation,
const VNQuat32* speed,
const VNQuat32* accelerate,
const VNQuat32* dragNormal,
real32 drag)
{
}
void ObjectNode::receiveTransformScaleReal32(void* user,
VNodeID nodeID,
real32 scaleX,
real32 scaleY,
real32 scaleZ)
{
}
void ObjectNode::receiveTransformPosReal64(void* user,
VNodeID nodeID,
uint32 seconds,
uint32 fraction,
const real64* position,
const real64* speed,
const real64* accel,
const real64* dragNormal,
real64 drag)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
// TODO: Add observer notifications.
if (position)
{
Vector3d pos(position[0], position[1], position[2]);
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onSetPosition(*node, pos);
}
node->mTranslation.mPosition.set(position[0], position[1], position[2]);
node->mTranslationCache.mPosition = node->mTranslation.mPosition;
}
if (speed)
{
node->mTranslation.mSpeed.set(speed[0], speed[1], speed[2]);
node->mTranslationCache.mSpeed = node->mTranslation.mSpeed;
}
if (accel)
{
node->mTranslation.mAccel.set(accel[0], accel[1], accel[2]);
node->mTranslationCache.mAccel = node->mTranslation.mAccel;
}
if (dragNormal)
{
node->mTranslation.mDragNormal.set(dragNormal[0], dragNormal[1], dragNormal[2]);
node->mTranslationCache.mDragNormal = node->mTranslation.mDragNormal;
node->mTranslationCache.mDrag = node->mTranslation.mDrag = drag;
}
node->mTranslationCache.mSeconds = node->mTranslation.mSeconds = seconds;
node->mTranslationCache.mFraction = node->mTranslation.mFraction = fraction;
node->updateDataVersion();
}
void ObjectNode::receiveTransformRotReal64(void* user,
VNodeID nodeID,
uint32 seconds,
uint32 fraction,
const VNQuat64* rotation,
const VNQuat64* speed,
const VNQuat64* accel,
const VNQuat64* dragNormal,
real64 drag)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
// TODO: Add observer notifications.
if (rotation)
{
Quaternion64 rot(rotation->x, rotation->y, rotation->z, rotation->w);
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onSetRotation(*node, rot);
}
node->mRotation.mRotation = *rotation;
node->mRotationCache.mRotation = *rotation;
}
if (speed)
{
node->mRotation.mSpeed = *speed;
node->mRotationCache.mSpeed = *speed;
}
if (accel)
{
node->mRotation.mAccel = *accel;
node->mRotationCache.mAccel = *accel;
}
if (dragNormal)
{
node->mRotation.mDragNormal = *dragNormal;
node->mRotationCache.mDragNormal = *dragNormal;
node->mRotationCache.mDrag = node->mRotation.mDrag = drag;
}
node->mRotationCache.mSeconds = node->mRotation.mSeconds = seconds;
node->mRotationCache.mFraction = node->mRotation.mFraction = fraction;
node->updateDataVersion();
}
void ObjectNode::receiveTransformScaleReal64(void* user,
VNodeID nodeID,
real64 scaleX,
real64 scaleY,
real64 scaleZ)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
Vector3d scale(scaleX, scaleY, scaleZ);
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onSetScale(*node, scale);
}
node->mScale = scale;
node->updateDataVersion();
}
void ObjectNode::receiveLightSet(void* user,
VNodeID nodeID,
real64 lightR,
real64 lightG,
real64 lightB)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
ColorRGB intensity(lightR, lightG, lightB);
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onSetLightIntensity(*node, intensity);
}
node->mIntensity = intensity;
node->updateDataVersion();
}
void ObjectNode::receiveLinkSet(void* user,
VNodeID nodeID,
uint16 linkID,
VNodeID linkedNodeID,
const char* name,
uint32 targetNodeID)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
Link* link = node->getLinkByID(linkID);
if (link)
link->receiveLinkSet(user, nodeID, linkID, linkedNodeID, name, targetNodeID);
else
{
link = new Link(linkID, name, linkedNodeID, targetNodeID, *node);
node->mLinks.push_back(link);
node->updateStructureVersion();
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onCreateLink(*node, *link);
}
}
}
void ObjectNode::receiveLinkDestroy(void* user, VNodeID nodeID, uint16 linkID)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
for (LinkList::iterator link = node->mLinks.begin(); link != node->mLinks.end(); link++)
{
if ((*link)->getID() == linkID)
{
// Notify link observers.
{
const Link::ObserverList& observers = (*link)->getObservers();
for (Link::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onDestroy(*(*link));
}
// Notify node observers.
{
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onDestroyLink(*node, *(*link));
}
}
delete *link;
node->mLinks.erase(link);
node->updateStructureVersion();
break;
}
}
}
void ObjectNode::receiveMethodGroupCreate(void* user, VNodeID nodeID, uint16 groupID, const char* name)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
MethodGroup* group = node->getMethodGroupByID(groupID);
if (group)
{
if (group->getName() != name)
{
// TODO: Move this into MethodGroup.
const MethodGroup::ObserverList& observers = group->getObservers();
for (MethodGroup::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
(*i)->onSetName(*group, name);
group->mName = name;
group->updateDataVersion();
}
}
else
{
group = new MethodGroup(groupID, name, *node);
node->mGroups.push_back(group);
node->updateStructureVersion();
const ObserverList& observers = node->getObservers();
for (ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onCreateMethodGroup(*node, *group);
}
verse_send_o_method_group_subscribe(node->getID(), groupID);
}
}
void ObjectNode::receiveMethodGroupDestroy(void* user, VNodeID nodeID, uint16 groupID)
{
Session* session = Session::getCurrent();
ObjectNode* node = dynamic_cast<ObjectNode*>(session->getNodeByID(nodeID));
if (!node)
return;
MethodGroupList& groups = node->mGroups;
for (MethodGroupList::iterator group = groups.begin(); group != groups.end(); group++)
{
if ((*group)->getID() == groupID)
{
// Notify method group observers.
{
const MethodGroup::ObserverList& observers = (*group)->getObservers();
for (MethodGroup::ObserverList::const_iterator observer = observers.begin(); observer != observers.end(); observer++)
(*observer)->onDestroy(**group);
}
// Notify node observers.
{
const Node::ObserverList& observers = node->getObservers();
for (Node::ObserverList::const_iterator i = observers.begin(); i != observers.end(); i++)
{
if (ObjectNodeObserver* observer = dynamic_cast<ObjectNodeObserver*>(*i))
observer->onDestroyMethodGroup(*node, **group);
}
}
delete *group;
groups.erase(group);
node->updateStructureVersion();
break;
}
}
}
void ObjectNode::receiveAnimRun(void* user, VNodeID nodeID, uint16 linkID, uint32 seconds, uint32 fraction, real64 pos, real64 speed, real64 accel, real64 scale, real64 scaleSpeed)
{
}
//---------------------------------------------------------------------
void ObjectNodeObserver::onSetPosition(ObjectNode& node, Vector3d& position)
{
}
void ObjectNodeObserver::onSetRotation(ObjectNode& node, Quaternion64& rotation)
{
}
void ObjectNodeObserver::onSetScale(ObjectNode& node, Vector3d& scale)
{
}
void ObjectNodeObserver::onCreateMethodGroup(ObjectNode& node, MethodGroup& group)
{
}
void ObjectNodeObserver::onDestroyMethodGroup(ObjectNode& node, MethodGroup& group)
{
}
void ObjectNodeObserver::onCreateLink(ObjectNode& node, Link& link)
{
}
void ObjectNodeObserver::onDestroyLink(ObjectNode& node, Link& link)
{
}
void ObjectNodeObserver::onSetLightIntensity(ObjectNode& node, const ColorRGB& color)
{
}
//---------------------------------------------------------------------
} /*namespace ample*/
} /*namespace verse*/
| 27.100079 | 191 | 0.615698 | elmindreda |
4e2e3d639888fdbe1725897136f1919eb1da7d9f | 2,806 | cpp | C++ | WS01/w1_p2.cpp | Rainbow1nTheDark/OOP345 | 1d56e8875ab2c1c8b31b5c520add799ebf8d8ec5 | [
"Apache-2.0"
] | null | null | null | WS01/w1_p2.cpp | Rainbow1nTheDark/OOP345 | 1d56e8875ab2c1c8b31b5c520add799ebf8d8ec5 | [
"Apache-2.0"
] | null | null | null | WS01/w1_p2.cpp | Rainbow1nTheDark/OOP345 | 1d56e8875ab2c1c8b31b5c520add799ebf8d8ec5 | [
"Apache-2.0"
] | null | null | null | // Workshop 1 - Linkage, Storage Duration, Namespaces, and OS Interface
// Cornel - 2020/01/08
#include <iostream>
#include <fstream>
#include "event.h"
#include "event.h"
/* input file format: a coma separated set of fields; some fields have a single parameter
T175,SComputer Starting,P,
codes
T - time (parameter: a number representing the time--measured in seconds--when the following codes apply)
S - start event (parameter: a string representing the description for the event that starts)
E - end the event
P - print to screen
A - archive
*/
// TODO: write the prototype for the main function
// to accept command line arguments
int main(int argc, char* argv[]) {
std::cout << "Command Line:\n";
// TODO: print the command line here, in the format
// 1: first argument
// 2: second argument
// 3: third argument
for (auto i = 0; i < argc; i++)
{
std::cout << i + 1 << ": " << argv[i] << std::endl;
}
std::cout << std::endl;
// the archive can store maximum 10 events
sdds::Event archive[10];
// the index of the next available position in the archive
size_t idxArchive = 0;
sdds::Event currentEvent;
const size_t secInDay = 60u * 60u * 24u;// day has 86400 seconds
for (auto day = 1; day < argc; ++day)
{
// each parameter for an application contains the events from one day
// process each one
std::cout << "--------------------\n";
std::cout << " Day " << day << '\n';
std::cout << "--------------------\n";
std::ifstream in(argv[day]);
char opcode = '\0';
size_t time = secInDay + 1;
in >> opcode >> time;
// starting at midnight, until the end of the day
for (::g_sysClock = 0u; ::g_sysClock < secInDay; ::g_sysClock++)
{
// what should happen this second
while (time == ::g_sysClock)
{
// skip the delimiter
in.ignore();
// read the next opcode
in >> opcode;
// end of the file
if (in.fail())
break;
// handle the operation code
switch (opcode)
{
case 'T': // a new time code, this is exit the while loop
in >> time;
break;
case 'S': // start a new event, the old event is automatically finished
char buffer[1024];
in.get(buffer, 1024, ',');
currentEvent.setDescription(buffer);
break;
case 'E': // end the current event
currentEvent.setDescription(nullptr);
break;
case 'P': // print to scren the information about the current event
currentEvent.display();
break;
case 'A': // add a copy of the current event to the archive
sdds::Event copy(currentEvent);
archive[idxArchive++] = copy;
break;
}
}
}
}
// print the archive
std::cout << "--------------------\n";
std::cout << " Archive\n";
std::cout << "--------------------\n";
for (auto i = 0u; i < idxArchive; ++i)
archive[i].display();
std::cout << "--------------------\n";
} | 26.471698 | 106 | 0.619031 | Rainbow1nTheDark |
4e32ab1e4d494dbca1f82cc38c383ae0abad06fe | 761 | hpp | C++ | include/react/sandbox/requirements_of.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 6 | 2015-06-05T17:48:12.000Z | 2020-10-04T03:45:18.000Z | include/react/sandbox/requirements_of.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 1 | 2021-06-23T05:51:46.000Z | 2021-06-23T05:51:46.000Z | include/react/sandbox/requirements_of.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 2 | 2016-05-06T06:55:40.000Z | 2020-03-25T19:19:14.000Z | /*!
* @file
* Defines `react::requirements_of`.
*/
#ifndef REACT_REQUIREMENTS_OF_HPP
#define REACT_REQUIREMENTS_OF_HPP
#include <react/sandbox/detail/fetch_nested.hpp>
#include <boost/mpl/set.hpp>
namespace react {
#ifdef REACT_DOXYGEN_INVOKED
/*!
* Returns the requirements of a computation.
*
* If the computation does not have a nested `requirements` type,
* the computation has no requirements.
*
* @return A Boost.MPL AssociativeSequence of
* @ref Requirement "Requirements"
*/
template <typename Computation>
struct requirements_of { };
#else
REACT_FETCH_NESTED(requirements_of, requirements, boost::mpl::set0<>)
#endif
} // end namespace react
#endif // !REACT_REQUIREMENTS_OF_HPP
| 23.060606 | 73 | 0.701708 | ldionne |
4e34a6899ffd8a6bc8f021318f42eb10f1be54e0 | 11,206 | cpp | C++ | source/code/scxsystemlib/common/scxsmbios.cpp | snchennapragada/pal | 9ee3e116dc2fadb44efa0938de7f0b737784fe16 | [
"MIT"
] | 37 | 2016-04-14T20:06:15.000Z | 2019-05-06T17:30:17.000Z | source/code/scxsystemlib/common/scxsmbios.cpp | snchennapragada/pal | 9ee3e116dc2fadb44efa0938de7f0b737784fe16 | [
"MIT"
] | 37 | 2016-03-11T20:47:11.000Z | 2019-04-01T22:53:04.000Z | source/code/scxsystemlib/common/scxsmbios.cpp | snchennapragada/pal | 9ee3e116dc2fadb44efa0938de7f0b737784fe16 | [
"MIT"
] | 20 | 2016-05-26T23:53:01.000Z | 2019-05-06T08:54:08.000Z | /*--------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.
*/
/**
\file
\brief This file contains the abstraction of the smbios on Linux and Solaris x86.
\date 2011-03-21 16:51:51
*/
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxfile.h>
#include <scxsystemlib/scxsmbios.h>
namespace SCXSystemLib
{
/*----------------------------------------------------------------------------*/
/**
Default constructor.
*/
SMBIOSPALDependencies::SMBIOSPALDependencies()
{
#if (defined(sun) && !defined(sparc))
m_deviceName = L"/dev/xsvc";
#elif defined(linux)
m_deviceName = L"/dev/mem";
#endif
m_log = SCXLogHandleFactory::GetLogHandle(std::wstring(L"scx.core.common.pal.system.common.scxsmbios"));
}
/*----------------------------------------------------------------------------*/
/**
Read Smbios Table Entry Point on non-EFI system,from 0xF0000 to 0xFFFFF in device file.
*/
bool SMBIOSPALDependencies::ReadSpecialMemory(MiddleData &buf) const
{
if(1 > buf.size()) return false;
SCXFilePath devicePath(m_deviceName);
size_t length = cEndAddress - cStartAddress + 1;
size_t offsetStart = cStartAddress;
SCX_LOGTRACE(m_log, StrAppend(L"SMBIOSPALDependencies ReadSpecialMemory() - device name: ", m_deviceName));
SCX_LOGTRACE(m_log, StrAppend(L"SMBIOSPALDependencies ReadSpecialMemory() - length: ", length));
SCX_LOGTRACE(m_log, StrAppend(L"SMBIOSPALDependencies ReadSpecialMemory() - offsetStart: ", offsetStart));
int readReturnCode = SCXFile::ReadAvailableBytesAsUnsigned(devicePath,&(buf[0]),length,offsetStart);
if(readReturnCode == 0)
{
SCX_LOGTRACE(m_log, L"ReadSpecialMemory() - status of reading is: success");
}
else
{
SCX_LOGTRACE(m_log, L"ReadSpecialMemory() - status of reading is: failure");
SCX_LOGTRACE(m_log, StrAppend(L"ReadSpecialMemory() - reason for read failure: ", readReturnCode));
return false;
}
return true;
}
/*----------------------------------------------------------------------------*/
/**
Read Smbios Table Entry Point on EFI system.
We will implement this function on EFI system later.
*/
bool SMBIOSPALDependencies::ReadSpecialmemoryEFI(MiddleData &buf) const
{
//Just to avoid warning here
bool bRet = true;
buf.size();
return bRet;
}
/*----------------------------------------------------------------------------*/
/**
Get SMBIOS Table content.
*/
bool SMBIOSPALDependencies::GetSmbiosTable(const struct SmbiosEntry& entryPoint,
MiddleData &buf) const
{
if(1 > buf.size()) return false;
//
//Read Smbios Table from device system file according to info inside SmbiosEntry.
//
SCXFilePath devicePath(m_deviceName);
int readReturnCode = SCXFile::ReadAvailableBytesAsUnsigned(devicePath,&(buf[0]),
entryPoint.tableLength,entryPoint.tableAddress);
if(readReturnCode == 0)
{
SCX_LOGTRACE(m_log, L"GetSmbiosTable() -the status of reading is : success");
}
else
{
SCX_LOGTRACE(m_log, L"GetSmbiosTable() -the status of reading is : failure");
SCX_LOGTRACE(m_log, StrAppend(L"GetSmbiosTable() - reason for read failure: ", readReturnCode));
return false;
}
return true;
}
/*----------------------------------------------------------------------------*/
/**
Default constructor.
*/
SCXSmbios::SCXSmbios(SCXCoreLib::SCXHandle<SMBIOSPALDependencies> deps):
m_deps(deps)
{
m_log = SCXLogHandleFactory::GetLogHandle(std::wstring(L"scx.core.common.pal.system.common.scxsmbios"));
}
/*----------------------------------------------------------------------------*/
/**
Parse SMBIOS Structure Table Entry Point.
Parameter[out]: smbiosEntry- Part fields value of SMBIOS Structure Table Entry Point.
Returns: whether it's successful to parse it.
*/
bool SCXSmbios::ParseSmbiosEntryStructure(struct SmbiosEntry &smbiosEntry)const
{
bool fRet = false;
try
{
//
//Read Smbios Table Entry Point on non-EFI system,from 0xF0000 to 0xFFFFF in device file.
//
size_t ilength = cEndAddress - cStartAddress + 1;
MiddleData entryPoint(ilength);
fRet = m_deps->ReadSpecialMemory(entryPoint);
if (!fRet)
{
std::wstring sMsg(L"ParseSmbiosEntryStructure - Failed to read special memory.");
SCX_LOGINFO(m_log, sMsg);
smbiosEntry.smbiosPresent = false;
}
//
//Searching for the anchor-string "_SM_" on paragraph (16-byte) boundaries mentioned in doc DSP0134_2.7.0.pdf
//
unsigned char* pbuf = &(entryPoint[0]);
for(size_t i = 0; fRet && ((i + cParagraphLength) <= ilength); i += cParagraphLength)
{
if (memcmp(pbuf+i,"_SM_", cAnchorString) == 0)
{
unsigned char *pcurBuf = pbuf+i;
// Before proceeding, verify that the SMBIOS is present.
// (Reference: (dmidecode.c ver 2.1: http://download.savannah.gnu.org/releases/dmidecode/)
if ( CheckSum(pcurBuf, pcurBuf[0x05]) &&
memcmp(pcurBuf+0x10, "_DMI_", cDMIAnchorString) == 0 &&
CheckSum(pcurBuf+0x10, 15))
{
SCX_LOGTRACE(m_log, std::wstring(L"SMBIOS is present."));
SCX_LOGTRACE(m_log, std::wstring(L"ParseSmbiosEntryStructure -anchor: _SM_"));
//
//Length of the Entry Point Structure.
//
size_t tmpLength = pcurBuf[cLengthEntry];
if(!CheckSum(pcurBuf,tmpLength))
{
throw SCXCoreLib::SCXInternalErrorException(L"Failed to CheckSum in ParseSmbiosEntryStructure().", SCXSRCLOCATION);
}
//
//Read the address,length and SMBIOS structure number of SMBIOS Structure Table.
//
unsigned int address = MAKELONG(MAKEWORD(pcurBuf+cAddressTable,pcurBuf+cAddressTable+1),MAKEWORD(pcurBuf+cAddressTable+2,pcurBuf+cAddressTable+3));
unsigned short length = MAKEWORD(pcurBuf+cLengthTable,pcurBuf+cLengthTable+1);
unsigned short number = MAKEWORD(pcurBuf+cNumberStructures,pcurBuf+cNumberStructures+1);
unsigned short majorVersion = pcurBuf[cMajorVersion];
unsigned short minorVersion = pcurBuf[cMiniorVersion];
smbiosEntry.majorVersion = majorVersion;
smbiosEntry.minorVersion = minorVersion;
smbiosEntry.smbiosPresent = true;
smbiosEntry.tableAddress = address;
SCX_LOGTRACE(m_log, StrAppend(L"ParseSmbiosEntryStructure - address: ", address));
smbiosEntry.tableLength = length;
SCX_LOGTRACE(m_log, StrAppend(L"ParseSmbiosEntryStructure - length: ", length));
smbiosEntry.structureNumber = number;
SCX_LOGTRACE(m_log, StrAppend(L"ParseSmbiosEntryStructure - number: ", number));
}
break;
}
else if (memcmp(pbuf+i, "_DMI_", cDMIAnchorString) == 0)
{
SCX_LOGTRACE(m_log, std::wstring(L"Legacy DMI is present."));
}
}
}
catch(const SCXException& e)
{
throw SCXCoreLib::SCXInternalErrorException(L"Failed to parse Smbios Entry Structure." + e.What(), SCXSRCLOCATION);
}
return fRet;
}
/*----------------------------------------------------------------------------*/
/**
Check the checksum of the Entry Point Structure.
Checksum of the Entry Point Structure,added to all other bytes in the Entry Point Structure,
results in the value 00h(using 8-bit addition calculations).
Checksum is the value of the 4th byte, so the above algorithm is equal to add all the bytes in the Entry Point Structure.
Parameter[in]: pEntry- the address of Entry Point Structure.
Parameter[in]: length- the length of Entry Point Structure.
Returns: true,the checksum is 0;otherwise,false.
*/
bool SCXSmbios::CheckSum(const unsigned char* pEntry,const size_t& length)const
{
unsigned char sum = 0;
for(size_t i=0;i<length;++i)
{
sum = static_cast<unsigned char>(sum + pEntry[i]);
}
return (0 == sum);
}
/*----------------------------------------------------------------------------*/
/**
Read specified index string.
Parameter[in]: buf- SMBIOS Structure Table.
Parameter[in]: length- offset to the start address of SMBIOS Structure Table.
Parameter[in]: index- index of string.
Returns: The string which the program read.
*/
std::wstring SCXSmbios::ReadSpecifiedString(const MiddleData& buf,const size_t& length,const size_t& index)const
{
std::wstring strRet = L"";
if(1 > buf.size()) return strRet;
unsigned char* ptablebuf = const_cast<unsigned char*>(&(buf[0]));
size_t curLength = length;
size_t numstr = 1;
while(numstr < index)
{
char *pcurstr = reinterpret_cast<char*>(ptablebuf+curLength);
curLength = curLength + strlen(pcurstr);
//
// At last add 1 for the terminal char '\0'
//
curLength += 1;
numstr++;
}
std::string curString = reinterpret_cast<char*>(ptablebuf + curLength);
strRet = StrFromUTF8(curString);
SCX_LOGTRACE(m_log, StrAppend(L"ReadSpecifiedString() - ParsedStr is : ", strRet));
return strRet;
}
/*----------------------------------------------------------------------------*/
/**
Get SMBIOS Table content.
Parameter[in]: entryPoint- EntryPoint Structure.
Parameter[out]: buf- Smbios Table.
Returns: whether it's successful to get smbios table.
*/
bool SCXSmbios::GetSmbiosTable(const struct SmbiosEntry& entryPoint,MiddleData &buf) const
{
return m_deps->GetSmbiosTable(entryPoint,buf);
}
}
/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/
| 38.245734 | 172 | 0.536766 | snchennapragada |
4e37ef49b7148400b6417ea85f769e43e8c40861 | 3,950 | cpp | C++ | Source/Motor2D/j1TextUI.cpp | Needlesslord/PaintWars_by_BrainDeadStudios | 578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf | [
"MIT"
] | 2 | 2020-03-06T11:32:40.000Z | 2020-03-20T12:17:30.000Z | Source/Motor2D/j1TextUI.cpp | Needlesslord/Heathen_Games | 578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf | [
"MIT"
] | 2 | 2020-03-03T09:56:57.000Z | 2020-05-02T15:50:45.000Z | Source/Motor2D/j1TextUI.cpp | Needlesslord/Heathen_Games | 578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf | [
"MIT"
] | 1 | 2020-03-17T18:50:53.000Z | 2020-03-17T18:50:53.000Z | #include "j1UIElements.h"
#include "j1UI_Manager.h"
#include "j1App.h"
#include "j1FontsUI.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Input.h"
#include "j1Window.h"
#include "j1TextUI.h"
j1TextUI::j1TextUI()
{
this->type = TypeOfUI::GUI_LABEL;
}
j1TextUI::~j1TextUI() {
}
bool j1TextUI::Start()
{
font_name_black = App->fonts->Load("textures/fonts/font_black.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_white = App->fonts->Load("textures/fonts/font_white.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_black_small = App->fonts->Load("textures/fonts/font_black_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_white_small = App->fonts->Load("textures/fonts/font_white_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_black_extra_small = App->fonts->Load("textures/fonts/font_black_extra_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_white_extra_small = App->fonts->Load("textures/fonts/font_white_extra_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_red = App->fonts->Load("textures/fonts/font_red_extra_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_red_small = App->fonts->Load("textures/fonts/font_red_small.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
font_name_red_extra_small = App->fonts->Load("textures/fonts/font_red.png", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef ghijklmnopqrstuvwxyz0123456789=/-", 2);
return true;
}
bool j1TextUI::PreUpdate()
{
return true;
}
bool j1TextUI::Update(float dt)
{
if (enabled)
{
switch (fontType) {
case FONT::FONT_MEDIUM:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_black, text, layer);
break;
case FONT::FONT_MEDIUM_WHITE:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_white, text, layer);
break;
case FONT::FONT_SMALL:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_black_small, text, layer);
break;
case FONT::FONT_SMALL_WHITE:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_white_small, text, layer);
break;
case FONT::FONT_EXTRA_SMALL:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_black_extra_small, text, layer);
break;
case FONT::FONT_EXTRA_SMALL_WHITE:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_white_extra_small, text, layer);
break;
case FONT::FONT_EXTRA_SMALL_RED:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_red, text, layer);
break;
case FONT::FONT_SMALL_RED:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_red_small, text, layer);
break;
case FONT::FONT_MEDIUM_RED:
App->fonts->BlitText(map_position.x + inside_position.x, map_position.y + inside_position.y, font_name_red_extra_small, text, layer);
break;
}
}
return true;
}
bool j1TextUI::PostUpdate()
{
return true;
}
bool j1TextUI::CleanUp()
{
App->fonts->UnLoad(font_name_black);
App->fonts->UnLoad(font_name_black_small);
App->fonts->UnLoad(font_name_black_extra_small);
App->fonts->UnLoad(font_name_white);
App->fonts->UnLoad(font_name_white_small);
App->fonts->UnLoad(font_name_white_extra_small);
App->fonts->UnLoad(font_name_red);
App->fonts->UnLoad(font_name_red_small);
App->fonts->UnLoad(font_name_red_extra_small);
text = " ";
return true;
}
| 33.193277 | 167 | 0.766076 | Needlesslord |
4e448891d7d94daa75f5f8e8c717194279ea91e4 | 5,463 | cpp | C++ | renderer.cpp | nvpro-samples/gl_cadscene_rendertechniques | 70becfc08318c54c2de45f1791e6c7f821144029 | [
"Apache-2.0"
] | 134 | 2015-01-09T13:00:56.000Z | 2022-02-06T06:23:25.000Z | renderer.cpp | nvpro-samples/gl_cadscene_rendertechniques | 70becfc08318c54c2de45f1791e6c7f821144029 | [
"Apache-2.0"
] | 4 | 2015-08-23T17:44:59.000Z | 2019-11-14T14:08:27.000Z | renderer.cpp | nvpro-samples/gl_cadscene_rendertechniques | 70becfc08318c54c2de45f1791e6c7f821144029 | [
"Apache-2.0"
] | 38 | 2015-02-13T22:27:09.000Z | 2021-10-16T00:36:26.000Z | /*
* Copyright (c) 2014-2021, 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.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
/* Contact [email protected] (Christoph Kubisch) for feedback */
#include <assert.h>
#include <algorithm>
#include "renderer.hpp"
#include <nvmath/nvmath_glsltypes.h>
#include "common.h"
#pragma pack(1)
namespace csfviewer
{
//////////////////////////////////////////////////////////////////////////
bool Renderer::s_bindless_ubo = false;
CullingSystem Renderer::s_cullsys;
ScanSystem Renderer::s_scansys;
const char* toString( enum ShadeType st )
{
switch(st){
case SHADE_SOLID: return "solid";
case SHADE_SOLIDWIRE: return "solid w edges";
case SHADE_SOLIDWIRE_SPLIT: return "solid w edges (split)";
}
return NULL;
}
static void FillCache( std::vector<Renderer::DrawItem>& drawItems, const CadScene::Object& obj, const CadScene::Geometry& geo, bool solid, int objectIndex )
{
int begin = 0;
const CadScene::DrawRangeCache &cache = solid ? obj.cacheSolid : obj.cacheWire;
for (size_t s = 0; s < cache.state.size(); s++)
{
const CadScene::DrawStateInfo &state = cache.state[s];
for (int d = 0; d < cache.stateCount[s]; d++){
// evict
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = state.matrixIndex;
di.materialIndex = state.materialIndex;
di.objectIndex = objectIndex;
di.solid = solid;
di.range.offset = cache.offsets[begin + d];
di.range.count = cache.counts [begin + d];
drawItems.push_back(di);
}
begin += cache.stateCount[s];
}
}
static void FillJoin( std::vector<Renderer::DrawItem>& drawItems, const CadScene::Object& obj, const CadScene::Geometry& geo, bool solid, int objectIndex )
{
CadScene::DrawRange range;
int lastMaterial = -1;
int lastMatrix = -1;
for (size_t p = 0; p < obj.parts.size(); p++){
const CadScene::ObjectPart& part = obj.parts[p];
const CadScene::GeometryPart& mesh = geo.parts[p];
if (!part.active) continue;
if (part.materialIndex != lastMaterial || part.matrixIndex != lastMatrix){
if (range.count){
// evict
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = lastMatrix;
di.materialIndex = lastMaterial;
di.objectIndex = objectIndex;
di.solid = solid;
di.range = range;
drawItems.push_back(di);
}
range = CadScene::DrawRange();
lastMaterial = part.materialIndex;
lastMatrix = part.matrixIndex;
}
if (!range.count){
range.offset = solid ? mesh.indexSolid.offset : mesh.indexWire.offset;
}
range.count += solid ? mesh.indexSolid.count : mesh.indexWire.count;
}
// evict
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = lastMatrix;
di.materialIndex = lastMaterial;
di.objectIndex = objectIndex;
di.solid = solid;
di.range = range;
drawItems.push_back(di);
}
static void FillIndividual( std::vector<Renderer::DrawItem>& drawItems, const CadScene::Object& obj, const CadScene::Geometry& geo, bool solid, int objectIndex )
{
for (size_t p = 0; p < obj.parts.size(); p++){
const CadScene::ObjectPart& part = obj.parts[p];
const CadScene::GeometryPart& mesh = geo.parts[p];
if (!part.active) continue;
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = part.matrixIndex;
di.materialIndex = part.materialIndex;
di.objectIndex = objectIndex;
di.solid = solid;
di.range = solid ? mesh.indexSolid : mesh.indexWire;
drawItems.push_back(di);
}
}
void Renderer::fillDrawItems( std::vector<DrawItem>& drawItems, size_t from, size_t to, bool solid, bool wire )
{
const CadScene* NV_RESTRICT scene = m_scene;
for (size_t i = from; i < scene->m_objects.size() && i < to; i++){
const CadScene::Object& obj = scene->m_objects[i];
const CadScene::Geometry& geo = scene->m_geometry[obj.geometryIndex];
if (m_strategy == STRATEGY_GROUPS){
if (solid) FillCache(drawItems, obj, geo, true, int(i));
if (wire) FillCache(drawItems, obj, geo, false, int(i));
}
else if (m_strategy == STRATEGY_JOIN) {
if (solid) FillJoin(drawItems, obj, geo, true, int(i));
if (wire) FillJoin(drawItems, obj, geo, false, int(i));
}
else if (m_strategy == STRATEGY_INDIVIDUAL){
if (solid) FillIndividual(drawItems, obj, geo, true, int(i));
if (wire) FillIndividual(drawItems, obj, geo, false, int(i));
}
}
}
}
| 29.52973 | 164 | 0.630789 | nvpro-samples |
4e458759d26deebe795d4939bb6305e76105278c | 728 | cpp | C++ | aoc2017/aoc170201.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2017/aoc170201.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2017/aoc170201.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | #include <boost/circular_buffer.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <range/v3/algorithm.hpp>
#include <range/v3/numeric.hpp>
#include <range/v3/view.hpp>
namespace views = ranges::views;
int main(int argc, char **argv)
{
if (argc > 1) {
std::ifstream ifs(argv[1]);
std::string line;
int n = 0;
while (std::getline(ifs, line)) {
std::istringstream iss(line);
std::istream_iterator<int> b(iss);
std::istream_iterator<int> e;
std::vector<int> v;
std::copy(b, e, std::back_inserter(v));
auto [pmin, pmax] = std::minmax_element(v.begin(), v.end());
n += (*pmax - *pmin);
}
std::cout << n << std::endl;
}
} | 26 | 66 | 0.614011 | jiayuehua |
4e46dc1c41aee16314813d8300b5ba6fc7137fe2 | 25,402 | cpp | C++ | src/chain_action/self_pass_generator.cpp | sanmit/HFO-benchmark | 0104ff7527485c8a7c159e6bf16c410eded72c0a | [
"MIT"
] | 1 | 2018-11-22T16:04:55.000Z | 2018-11-22T16:04:55.000Z | allejos2d/src/chain_action/self_pass_generator.cpp | PmecSimulation/Allejos2D | d0b3cb48e88f44b509e7dfe0329bb035bab748ce | [
"Apache-2.0"
] | null | null | null | allejos2d/src/chain_action/self_pass_generator.cpp | PmecSimulation/Allejos2D | d0b3cb48e88f44b509e7dfe0329bb035bab748ce | [
"Apache-2.0"
] | null | null | null | // -*-c++-*-
/*!
\file self_pass_generator.cpp
\brief self pass generator Source File
*/
/*
*Copyright:
Copyright (C) Hidehisa AKIYAMA
This code 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, or (at your option)
any later version.
This code 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 code; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*EndCopyright:
*/
/////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "self_pass_generator.h"
#include "dribble.h"
#include "field_analyzer.h"
#include <rcsc/action/kick_table.h>
#include <rcsc/player/world_model.h>
#include <rcsc/common/server_param.h>
#include <rcsc/common/logger.h>
#include <rcsc/timer.h>
#include <limits>
#include <cmath>
#define DEBUG_PROFILE
// #define DEBUG_PRINT
// #define DEBUG_PRINT_SELF_CACHE
// #define DEBUG_PRINT_OPPONENT
// #define DEBUG_PRINT_OPPONENT_LEVEL2
// #define DEBUG_PRINT_SUCCESS_COURSE
// #define DEBUG_PRINT_FAILED_COURSE
using namespace rcsc;
namespace {
inline
void
debug_paint_failed( const int count,
const Vector2D & receive_point )
{
dlog.addRect( Logger::DRIBBLE,
receive_point.x - 0.1, receive_point.y - 0.1,
0.2, 0.2,
"#ff0000" );
char num[8];
snprintf( num, 8, "%d", count );
dlog.addMessage( Logger::DRIBBLE,
receive_point, num );
}
}
/*-------------------------------------------------------------------*/
/*!
*/
SelfPassGenerator::SelfPassGenerator()
{
M_courses.reserve( 128 );
clear();
}
/*-------------------------------------------------------------------*/
/*!
*/
SelfPassGenerator &
SelfPassGenerator::instance()
{
static SelfPassGenerator s_instance;
return s_instance;
}
/*-------------------------------------------------------------------*/
/*!
*/
void
SelfPassGenerator::clear()
{
M_total_count = 0;
M_courses.clear();
}
/*-------------------------------------------------------------------*/
/*!
*/
void
SelfPassGenerator::generate( const WorldModel & wm )
{
if ( M_update_time == wm.time() )
{
return;
}
M_update_time = wm.time();
clear();
if ( wm.gameMode().type() != GameMode::PlayOn
&& ! wm.gameMode().isPenaltyKickMode() )
{
return;
}
if ( ! wm.self().isKickable()
|| wm.self().isFrozen() )
{
return;
}
#ifdef DEBUG_PROFILE
Timer timer;
#endif
createCourses( wm );
std::sort( M_courses.begin(), M_courses.end(),
CooperativeAction::DistCompare( ServerParam::i().theirTeamGoalPos() ) );
#ifdef DEBUG_PROFILE
dlog.addText( Logger::DRIBBLE,
__FILE__": (generate) PROFILE size=%d/%d elapsed %.3f [ms]",
(int)M_courses.size(),
M_total_count,
timer.elapsedReal() );
#endif
}
/*-------------------------------------------------------------------*/
/*!
*/
void
SelfPassGenerator::createCourses( const WorldModel & wm )
{
static const int ANGLE_DIVS = 60;
static const double ANGLE_STEP = 360.0 / ANGLE_DIVS;
static std::vector< Vector2D > self_cache( 24 );
const ServerParam & SP = ServerParam::i();
const Vector2D ball_pos = wm.ball().pos();
const AngleDeg body_angle = wm.self().body();
const int min_dash = 5;
const int max_dash = ( ball_pos.x < -20.0 ? 6
: ball_pos.x < 0.0 ? 7
: ball_pos.x < 10.0 ? 13
: ball_pos.x < 20.0 ? 15
: 20 );
const PlayerType & ptype = wm.self().playerType();
const double max_effective_turn
= ptype.effectiveTurn( SP.maxMoment(),
wm.self().vel().r() * ptype.playerDecay() );
const Vector2D our_goal = ServerParam::i().ourTeamGoalPos();
const double goal_dist_thr2 = std::pow( 18.0, 2 ); // Magic Number
for ( int a = 0; a < ANGLE_DIVS; ++a )
{
const double add_angle = ANGLE_STEP * a;
int n_turn = 0;
if ( a != 0 )
{
if ( AngleDeg( add_angle ).abs() > max_effective_turn )
{
// cannot turn by 1 step
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"?: xxx SelfPass rel_angle=%.1f > maxTurn=%.1f cannot turn by 1 step.",
add_angle, max_effective_turn );
#endif
continue;
}
n_turn = 1;
}
const AngleDeg dash_angle = body_angle + add_angle;
if ( ball_pos.x < SP.theirPenaltyAreaLineX() + 5.0
&& dash_angle.abs() > 85.0 ) // Magic Number
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"?: xxx SelfPass angle=%.1f over angle.",
dash_angle.degree() );
#endif
continue;
}
createSelfCache( wm, dash_angle,
n_turn, max_dash,
self_cache );
int n_dash = self_cache.size() - n_turn;
if ( n_dash < min_dash )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"?: xxx SelfPass angle=%.1f turn=%d dash=%d too short dash step.",
dash_angle.degree(),
n_turn, n_dash );
#endif
continue;
}
#if (defined DEBUG_PRINT_SUCCESS_COURSE) || (defined DEBUG_PRINT_SUCCESS_COURSE)
dlog.addText( Logger::DRIBBLE,
"===== SelfPass angle=%.1f turn=%d dash=%d =====",
dash_angle.degree(),
n_turn,
n_dash );
#endif
int count = 0;
int dash_dec = 2;
for ( ; n_dash >= min_dash; n_dash -= dash_dec )
{
++M_total_count;
if ( n_dash <= 10 )
{
dash_dec = 1;
}
const Vector2D receive_pos = self_cache[n_turn + n_dash - 1];
if ( receive_pos.dist2( our_goal ) < goal_dist_thr2 )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass step=%d(t:%d,d:%d) pos=(%.1f %.1f) near our goal",
M_total_count,
1 + n_turn, n_turn, n_dash,
receive_pos.x, receive_pos.y );
#endif
continue;
}
if ( ! canKick( wm, n_turn, n_dash, receive_pos ) )
{
continue;
}
if ( ! checkOpponent( wm, n_turn, n_dash, ball_pos, receive_pos ) )
{
continue;
}
// double first_speed = calc_first_term_geom_series( ball_pos.dist( receive_pos ),
// ServerParam::i().ballDecay(),
// 1 + n_turn + n_dash );
double first_speed = SP.firstBallSpeed( ball_pos.dist( receive_pos ),
1 + n_turn + n_dash );
CooperativeAction::Ptr ptr( new Dribble( wm.self().unum(),
receive_pos,
first_speed,
1, // 1 kick
n_turn,
n_dash,
"SelfPass" ) );
ptr->setIndex( M_total_count );
M_courses.push_back( ptr );
#ifdef DEBUG_PRINT_SUCCESS_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: ok SelfPass step=%d(t:%d,d:%d) pos=(%.1f %.1f) speed=%.3f",
M_total_count,
1 + n_turn + n_dash, n_turn, n_dash,
receive_pos.x, receive_pos.y,
first_speed );
char num[8];
snprintf( num, 8, "%d", M_total_count );
dlog.addMessage( Logger::DRIBBLE,
receive_pos, num );
dlog.addRect( Logger::DRIBBLE,
receive_pos.x - 0.1, receive_pos.y - 0.1,
0.2, 0.2,
"#00ff00" );
#endif
++count;
if ( count >= 10 )
{
break;
}
}
}
}
/*-------------------------------------------------------------------*/
/*!
*/
void
SelfPassGenerator::createSelfCache( const WorldModel & wm,
const AngleDeg & dash_angle,
const int n_turn,
const int n_dash,
std::vector< Vector2D > & self_cache )
{
self_cache.clear();
const PlayerType & ptype = wm.self().playerType();
const double dash_power = ServerParam::i().maxDashPower();
const double stamina_thr = ( wm.self().staminaModel().capacityIsEmpty()
? -ptype.extraStamina() // minus value to set available stamina
: ServerParam::i().recoverDecThrValue() + 350.0 );
StaminaModel stamina_model = wm.self().staminaModel();
Vector2D my_pos = wm.self().pos();
Vector2D my_vel = wm.self().vel();
//
// 1 kick
//
my_pos += my_vel;
my_vel *= ptype.playerDecay();
stamina_model.simulateWait( ptype );
//
// turns
//
for ( int i = 0; i < n_turn; ++i )
{
my_pos += my_vel;
my_vel *= ptype.playerDecay();
stamina_model.simulateWait( ptype );
self_cache.push_back( my_pos );
}
//
// simulate dashes
//
for ( int i = 0; i < n_dash; ++i )
{
if ( stamina_model.stamina() < stamina_thr )
{
#ifdef DEBUG_PRINT_SELF_CACHE
dlog.addText( Logger::DRIBBLE,
"?: SelfPass (createSelfCache) turn=%d dash=%d. stamina=%.1f < threshold",
n_turn, n_dash, stamina_model.stamina() );
#endif
break;
}
double available_stamina = std::max( 0.0, stamina_model.stamina() - stamina_thr );
double actual_dash_power = std::min( dash_power, available_stamina );
double accel_mag = actual_dash_power * ptype.dashPowerRate() * stamina_model.effort();
Vector2D dash_accel = Vector2D::polar2vector( accel_mag, dash_angle );
// TODO: check playerSpeedMax & update actual_dash_power if necessary
// if ( ptype.normalizeAccel( my_vel, &dash_accel ) ) actual_dash_power = ...
my_vel += dash_accel;
my_pos += my_vel;
// #ifdef DEBUG_PRINT_SELF_CACHE
// dlog.addText( Logger::DRIBBLE,
// "___ dash=%d accel=(%.2f %.2f)r=%.2f th=%.1f pos=(%.2f %.2f) vel=(%.2f %.2f)",
// i + 1,
// dash_accel.x, dash_accel.y, dash_accel.r(), dash_accel.th().degree(),
// my_pos.x, my_pos.y,
// my_vel.x, my_vel.y );
// #endif
if ( my_pos.x > ServerParam::i().pitchHalfLength() - 2.5 )
{
#ifdef DEBUG_PRINT_SELF_CACHE
dlog.addText( Logger::DRIBBLE,
"?: SelfPass (createSelfCache) turn=%d dash=%d. my_x=%.2f. over goal line",
n_turn, n_dash, my_pos.x );
#endif
break;
}
if ( my_pos.absY() > ServerParam::i().pitchHalfWidth() - 3.0
&& ( ( my_pos.y > 0.0 && dash_angle.degree() > 0.0 )
|| ( my_pos.y < 0.0 && dash_angle.degree() < 0.0 ) )
)
{
#ifdef DEBUG_PRINT_SELF_CACHE
dlog.addText( Logger::DRIBBLE,
"?: SelfPass (createSelfCache) turn=%d dash=%d."
" my_pos=(%.2f %.2f). dash_angle=%.1f",
n_turn, n_dash,
my_pos.x, my_pos.y,
dash_angle.degree() );
dlog.addText( Logger::DRIBBLE,
"__ dash_accel=(%.2f %.2f)r=%.2f vel=(%.2f %.2f)r=%.2f th=%.1f",
dash_accel.x, dash_accel.y, accel_mag,
my_vel.x, my_vel.y, my_vel.r(), my_vel.th().degree() );
#endif
break;
}
my_vel *= ptype.playerDecay();
stamina_model.simulateDash( ptype, actual_dash_power );
self_cache.push_back( my_pos );
}
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
SelfPassGenerator::canKick( const WorldModel & wm,
const int n_turn,
const int n_dash,
const Vector2D & receive_pos )
{
const ServerParam & SP = ServerParam::i();
const Vector2D ball_pos = wm.ball().pos();
const Vector2D ball_vel = wm.ball().vel();
const AngleDeg target_angle = ( receive_pos - ball_pos ).th();
//
// check kick possibility
//
double first_speed = calc_first_term_geom_series( ball_pos.dist( receive_pos ),
SP.ballDecay(),
1 + n_turn + n_dash );
Vector2D max_vel = KickTable::calc_max_velocity( target_angle,
wm.self().kickRate(),
ball_vel );
if ( max_vel.r2() < std::pow( first_speed, 2 ) )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass step=%d(t:%d,d=%d) cannot kick by 1 step."
" first_speed=%.2f > max_speed=%.2f",
M_total_count,
1 + n_turn + n_dash, n_turn, n_dash,
first_speed,
max_vel.r() );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
//
// check collision
//
const Vector2D my_next = wm.self().pos() + wm.self().vel();
const Vector2D ball_next
= ball_pos
+ ( receive_pos - ball_pos ).setLengthVector( first_speed );
if ( my_next.dist2( ball_next ) < std::pow( wm.self().playerType().playerSize()
+ SP.ballSize()
+ 0.1,
2 ) )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass step=%d(t:%d,d=%d) maybe collision. next_dist=%.3f first_speed=%.2f",
M_total_count,
1 + n_turn + n_dash, n_turn, n_dash,
my_next.dist( ball_next ),
first_speed );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
//
// check opponent kickable area
//
const PlayerPtrCont::const_iterator o_end = wm.opponentsFromSelf().end();
for ( PlayerPtrCont::const_iterator o = wm.opponentsFromSelf().begin();
o != o_end;
++o )
{
const PlayerType * ptype = (*o)->playerTypePtr();
Vector2D o_next = (*o)->pos() + (*o)->vel();
const double control_area = ( ( (*o)->goalie()
&& ball_next.x > SP.theirPenaltyAreaLineX()
&& ball_next.absY() < SP.penaltyAreaHalfWidth() )
? SP.catchableArea()
: ptype->kickableArea() );
if ( ball_next.dist2( o_next ) < std::pow( control_area + 0.1, 2 ) )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass (canKick) opponent may be kickable(1) dist=%.3f < control=%.3f + 0.1",
M_total_count, ball_next.dist( o_next ), control_area );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
if ( (*o)->bodyCount() <= 1 )
{
o_next += Vector2D::from_polar( SP.maxDashPower() * ptype->dashPowerRate() * ptype->effortMax(),
(*o)->body() );
}
else
{
o_next += (*o)->vel().setLengthVector( SP.maxDashPower()
* ptype->dashPowerRate()
* ptype->effortMax() );
}
if ( ball_next.dist2( o_next ) < std::pow( control_area, 2 ) )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d xxx SelfPass (canKick) opponent may be kickable(2) dist=%.3f < control=%.3f",
M_total_count, ball_next.dist( o_next ), control_area );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
}
return true;
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
SelfPassGenerator::checkOpponent( const WorldModel & wm,
const int n_turn,
const int n_dash,
const Vector2D & ball_pos,
const Vector2D & receive_pos )
{
const ServerParam & SP = ServerParam::i();
const int self_step = 1 + n_turn + n_dash;
const AngleDeg target_angle = ( receive_pos - ball_pos ).th();
const bool in_penalty_area = ( receive_pos.x > SP.theirPenaltyAreaLineX()
&& receive_pos.absY() < SP.penaltyAreaHalfWidth() );
#ifdef DEBUG_PRINT_OPPONENT
dlog.addText( Logger::DRIBBLE,
"%d: (checkOpponent) selfStep=%d(t:%d,d:%d) recvPos(%.2f %.2f)",
M_total_count,
self_step, n_turn, n_dash,
receive_pos.x, receive_pos.y );
#endif
int min_step = 1000;
const PlayerPtrCont::const_iterator o_end = wm.opponentsFromSelf().end();
for ( PlayerPtrCont::const_iterator o = wm.opponentsFromSelf().begin();
o != o_end;
++o )
{
const Vector2D & opos = ( (*o)->seenPosCount() <= (*o)->posCount()
? (*o)->seenPos()
: (*o)->pos() );
const Vector2D ball_to_opp_rel = ( opos - ball_pos ).rotatedVector( -target_angle );
if ( ball_to_opp_rel.x < -4.0 )
{
#ifdef DEBUG_PRINT_OPPONENT_LEVEL2
dlog.addText( Logger::DRIBBLE,
"__ opponent[%d](%.2f %.2f) relx=%.2f",
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
ball_to_opp_rel.x );
#endif
continue;
}
const Vector2D & ovel = ( (*o)->seenVelCount() <= (*o)->velCount()
? (*o)->seenVel()
: (*o)->vel() );
const PlayerType * ptype = (*o)->playerTypePtr();
const bool goalie = ( (*o)->goalie() && in_penalty_area );
const double control_area ( goalie
? SP.catchableArea()
: ptype->kickableArea() );
Vector2D opp_pos = ptype->inertiaPoint( opos, ovel, self_step );
double target_dist = opp_pos.dist( receive_pos );
if ( target_dist
> ptype->realSpeedMax() * ( self_step + (*o)->posCount() ) + control_area )
{
#ifdef DEBUG_PRINT_OPPONENT_LEVEL2
dlog.addText( Logger::DRIBBLE,
"__ opponent[%d](%.2f %.2f) too far. ignore. dist=%.1f",
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
target_dist );
#endif
continue;
}
if ( target_dist - control_area < 0.001 )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass (checkOpponent) step=%d(t:%d,d=%d) pos=(%.1f %.1f)"
" opponent %d(%.1f %.1f) is already at receive point",
M_total_count,
self_step, n_turn, n_dash,
receive_pos.x, receive_pos.y,
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
double dash_dist = target_dist;
dash_dist -= control_area;
dash_dist -= 0.2;
dash_dist -= (*o)->distFromSelf() * 0.01;
int opp_n_dash = ptype->cyclesToReachDistance( dash_dist );
int opp_n_turn = ( (*o)->bodyCount() > 1
? 0
: FieldAnalyzer::predict_player_turn_cycle( ptype,
(*o)->body(),
ovel.r(),
target_dist,
( receive_pos - opp_pos ).th(),
control_area,
false ) );
int opp_n_step = ( opp_n_turn == 0
? opp_n_turn + opp_n_dash
: opp_n_turn + opp_n_dash + 1 );
int bonus_step = 0;
if ( receive_pos.x < 27.0 )
{
bonus_step += 1;
}
if ( (*o)->isTackling() )
{
bonus_step = -5;
}
if ( ball_to_opp_rel.x > 0.8 )
{
bonus_step += 1;
bonus_step += bound( 0, (*o)->posCount() - 1, 8 );
#ifdef DEBUG_PRINT_OPPONENT_LEVEL2
dlog.addText( Logger::DRIBBLE,
"__ opponent[%d](%.2f %.2f) forward bonus = %d",
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
bonus_step );
#endif
}
else
{
int penalty_step = ( ( receive_pos.x > wm.offsideLineX()
|| receive_pos.x > 35.0 )
? 1
: 0 );
bonus_step = bound( 0, (*o)->posCount() - penalty_step, 3 );
#ifdef DEBUG_PRINT_OPPONENT_LEVEL2
dlog.addText( Logger::DRIBBLE,
"__ opponent[%d](%.2f %.2f) backward bonus = %d",
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
bonus_step );
#endif
}
// if ( goalie )
// {
// opp_n_step -= 1;
// }
#ifdef DEBUG_PRINT_OPPONENT
dlog.addText( Logger::DRIBBLE,
"__ opponent[%d](%.2f %.2f) oppStep=%d(t:%d,d:%d) selfStep=%d rel.x=%.2f",
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
opp_n_step, opp_n_turn, opp_n_dash,
self_step,
ball_to_opp_rel.x );
#endif
if ( opp_n_step - bonus_step <= self_step )
{
#ifdef DEBUG_PRINT_FAILED_COURSE
dlog.addText( Logger::DRIBBLE,
"%d: xxx SelfPass step=%d(t:%d,d:%d) pos=(%.1f %.1f)"
" opponent %d(%.1f %.1f) can reach."
" oppStep=%d(turn=%d,bonus=%d)",
M_total_count,
1 + n_turn + n_dash, n_turn, n_dash,
receive_pos.x, receive_pos.y,
(*o)->unum(),
(*o)->pos().x, (*o)->pos().y,
opp_n_step, opp_n_turn, bonus_step );
debug_paint_failed( M_total_count, receive_pos );
#endif
return false;
}
if ( min_step > opp_n_step )
{
min_step = opp_n_step;
}
}
#ifdef DEBUG_PRINT_OPPONENT
dlog.addText( Logger::DRIBBLE,
"%d: (checkOpponent) selfStep=%d(t:%d,d:%d) oppStep=%d",
M_total_count,
self_step, n_turn, n_dash,
min_step );
#endif
return true;
}
| 32.692407 | 114 | 0.459846 | sanmit |
4e4c666994ce0cc1b2c2f139e3cd877a6d192ace | 1,866 | cpp | C++ | src/api/api-example.cpp | knzm/kytea | e29eaf9933cc31f4461a8e726cff5141253a9727 | [
"Apache-2.0"
] | 1 | 2018-10-25T07:49:10.000Z | 2018-10-25T07:49:10.000Z | src/api/api-example.cpp | knzm/kytea | e29eaf9933cc31f4461a8e726cff5141253a9727 | [
"Apache-2.0"
] | null | null | null | src/api/api-example.cpp | knzm/kytea | e29eaf9933cc31f4461a8e726cff5141253a9727 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
// a file including the main program
#include "kytea/kytea.h"
// a file including sentence, word, and pronunciation objects
#include "kytea/kytea-struct.h"
using namespace std;
using namespace kytea;
int main(int argc, char** argv) {
// Create an instance of the Kytea program
Kytea kytea;
// Load a KyTea model from a model file
// this can be a binary or text model in any character encoding,
// it will be detected automatically
kytea.readModel("../../data/model.bin");
// Get the string utility class. This allows you to convert from
// the appropriate string encoding to Kytea's internal format
StringUtil* util = kytea.getStringUtil();
// Get the configuration class, this allows you to read or set the
// configuration for the analysis
KyteaConfig* config = kytea.getConfig();
// Map a plain text string to a KyteaString, and create a sentence object
KyteaSentence sentence(util->mapString("これはテストです。"));
// Find the word boundaries
kytea.calculateWS(sentence);
// Find the pronunciations for each tag level
for(int i = 0; i < config->getNumTags(); i++)
kytea.calculateTags(sentence,i);
// For each word in the sentence
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
// Print the word
cout << util->showString(words[i].surf);
// For each tag level
for(int j = 0; j < (int)words[i].tags.size(); j++) {
cout << "\t";
// Print each of its tags
for(int k = 0; k < (int)words[i].tags[j].size(); k++) {
cout << " " << util->showString(words[i].tags[j][k].first) <<
"/" << words[i].tags[j][k].second;
}
}
cout << endl;
}
cout << endl;
}
| 32.736842 | 78 | 0.606109 | knzm |
4e54adde281a096d1950fd62bbc8c1b4f49accf0 | 6,893 | cpp | C++ | Day 22 Part 2/main.cpp | Miroslav-Cetojevic/aoc-2015 | 2807fcd3fc684843ae4222b25af6fd086fac77f5 | [
"Unlicense"
] | 1 | 2019-11-19T20:19:18.000Z | 2019-11-19T20:19:18.000Z | Day 22 Part 2/main.cpp | Miroslav-Cetojevic/aoc-2015 | 2807fcd3fc684843ae4222b25af6fd086fac77f5 | [
"Unlicense"
] | null | null | null | Day 22 Part 2/main.cpp | Miroslav-Cetojevic/aoc-2015 | 2807fcd3fc684843ae4222b25af6fd086fac77f5 | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
// ========
// Entities
// ========
struct Hero {
std::int64_t health;
std::uint64_t mana;
std::uint64_t armor;
};
struct Boss {
std::int64_t health;
std::uint64_t damage;
};
// ================
// Spells & Effects
// ================
// need to forward declare these structs
// so I can use them for the function pointer
struct GameState;
struct Page;
using DoMagic = void (*) (GameState&, Page&);
struct Effect {
DoMagic apply;
std::int64_t value;
std::uint64_t turns_max;
std::uint64_t turns_left;
};
struct Spell {
DoMagic cast;
std::uint64_t cost;
std::uint64_t value;
};
struct Page {
Effect effect;
Spell spell;
std::uint64_t id;
};
using Spellbook = std::vector<Page>;
struct GameState {
Hero hero;
Boss boss;
Spellbook spellbook;
std::uint64_t current_page;
std::uint64_t mana_spent;
};
auto subtract_mana(GameState& state, const Page& page) {
state.hero.mana -= page.spell.cost;
}
auto subtract_boss_health(GameState& state, const Page& page) {
state.boss.health -= page.spell.value;
}
auto calc_mana_spent(GameState& state, const Page& page) {
state.mana_spent += page.spell.cost;
}
auto init_effect(GameState& state, Page& page) {
subtract_mana(state, page);
page.effect.turns_left = page.effect.turns_max;
}
auto apply_immediate_effects(GameState& state, const Page& page) {
subtract_mana(state, page);
subtract_boss_health(state, page);
calc_mana_spent(state, page);
}
auto cast_missile(GameState& state, Page& page) {
apply_immediate_effects(state, page);
}
auto cast_drain(GameState& state, Page& page) {
apply_immediate_effects(state, page);
state.hero.health += page.spell.value;
}
auto activate_effect(GameState& state, Page& page) {
init_effect(state, page);
calc_mana_spent(state, page);
}
auto cast_poison(GameState& state, Page& page) {
activate_effect(state, page);
}
auto cast_recharge(GameState& state, Page& page) {
activate_effect(state, page);
}
auto cast_shield(GameState& state, Page& page) {
activate_effect(state, page);
state.hero.armor = page.spell.value;
}
auto apply_missile(GameState&, Page&) {}
auto apply_drain(GameState&, Page&) {}
template<typename F>
auto apply_effect(GameState& state, Page& page, F effect) {
if(page.effect.turns_left > 0) {
--(page.effect.turns_left);
effect(state, page);
}
}
auto apply_poison(GameState& state, Page& page) {
apply_effect(state, page, [] (auto& state, auto& page) {
state.boss.health -= page.effect.value;
});
}
auto apply_recharge(GameState& state, Page& page) {
apply_effect(state, page, [] (auto& state, auto& page) {
state.hero.mana += page.effect.value;
});
}
auto apply_shield(GameState& state, Page& page) {
apply_effect(state, page, [] (auto& state, auto& page) {
if(page.effect.turns_left == 0) {
state.hero.armor = 0;
}
});
}
auto boss_attack(GameState& state) {
const auto boss_dmg = state.boss.damage;
const auto hero_ac = state.hero.armor;
const auto boss_real_dmg = (hero_ac < boss_dmg) ? (boss_dmg - hero_ac) : 1;
state.hero.health -= boss_real_dmg;
}
// ========
// The Game
// ========
int main() {
const auto spellbook = Spellbook{
{{apply_missile, 0, 0, 0}, {cast_missile, 53, 4}, 0},
{{apply_drain, 0, 0, 0}, {cast_drain, 73, 2}, 1},
{{apply_shield, 0, 6, 0}, {cast_shield, 113, 7}, 2},
{{apply_poison, 3, 6, 0}, {cast_poison, 173, 0}, 3},
{{apply_recharge, 101, 5, 0}, {cast_recharge, 229, 0}, 4}
};
auto hero = Hero{50, 500, 0};
auto boss = Boss{55, 8};
auto states = std::vector<GameState>{{hero, boss, spellbook, 0, 0}};
auto least_mana = std::numeric_limits<decltype(hero.mana)>::max();
const auto save_state = [&states] (auto& state) {
// each new state means re-reading the spellbook from the beginning
state.current_page = 0;
states.push_back(state);
};
const auto delete_state = [&states] () {
states.pop_back();
};
const auto apply_effects = [] (auto& state) {
for(auto& page : state.spellbook) {
page.effect.apply(state, page);
}
};
const auto has_won = [] (const auto& state) {
return (state.boss.health <= 0);
};
const auto has_lost = [] (const auto& state) {
return (state.hero.health <= 0);
};
const auto end_of_spellbook = [] (const auto& state) {
return (state.current_page == state.spellbook.size());
};
const auto get_least_mana = [least_mana, &delete_state] (const auto& state) {
// a victory has been attained, the last state is not needed anymore
delete_state();
// the state argument will be a reference to the copy of the state
// that we just deleted, so it's safe to refer to it
return std::min(least_mana, state.mana_spent);
};
// each iteration (and thus each state) represents two turns played
do {
auto state = GameState(states.back());
// ===========
// hero's turn
// ===========
--(state.hero.health);
if(has_lost(state)) {
delete_state();
continue;
}
apply_effects(state);
if(has_won(state)) {
least_mana = get_least_mana(state);
continue;
}
// there's no spell to be cast, so we discard the current state
if(end_of_spellbook(state)) {
delete_state();
continue;
}
const auto begin = state.spellbook.begin() + state.current_page;
const auto end = state.spellbook.end();
const auto check = [&state, least_mana] (auto& page) {
const auto mana_spent = state.mana_spent;
const auto spell_cost = page.spell.cost;
const auto turns_left = page.effect.turns_left;
const auto hero_mana = state.hero.mana;
const auto reduces_mana_cost = (least_mana > 0) && ((mana_spent + spell_cost) >= least_mana);
const auto is_spell_castable = (turns_left == 0) && (hero_mana >= spell_cost);
return !reduces_mana_cost && is_spell_castable;
};
const auto eligible_spell = std::find_if(begin, end, check);
const auto has_castable_spell = (eligible_spell != state.spellbook.end());
if(has_castable_spell) {
// the hero attacks
eligible_spell->spell.cast(state, *eligible_spell);
// if we return to this state later on, the hero may only cast the next spell,
// because casting any of the previous ones will simply result in an already visited scenario
++(states.back().current_page);
}
// no spells were cast either because
// 1. there was not enough mana for any of them, or
// 2. there's already a victory scenario with equal or less total mana spent
if(!has_castable_spell) {
delete_state();
continue;
}
if(has_won(state)) {
least_mana = get_least_mana(state);
continue;
}
// ==========
// boss' turn
// ==========
apply_effects(state);
if(has_won(state)) {
least_mana = get_least_mana(state);
continue;
}
boss_attack(state);
if(has_lost(state)) {
delete_state();
continue;
}
save_state(state);
} while(!states.empty());
std::cout << least_mana << std::endl;
return 0;
}
| 23.130872 | 96 | 0.673582 | Miroslav-Cetojevic |
4e5682a1650bc6673e1e26c04f80e9b921f3ca6a | 15,398 | cpp | C++ | NOLF/Shared/SharedMission.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | 65 | 2015-02-28T03:35:14.000Z | 2021-09-23T05:43:33.000Z | NOLF/Shared/SharedMission.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | null | null | null | NOLF/Shared/SharedMission.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | 27 | 2015-02-28T07:42:01.000Z | 2022-02-11T01:35:20.000Z | // ----------------------------------------------------------------------- //
//
// MODULE : SharedMission.cpp
//
// PURPOSE : SharedMission implementation - shared mission summary stuff
//
// CREATED : 9/16/99
//
// (c) 1999 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "SharedMission.h"
#define PLAYERRANK_TAG "RankData"
#define PLAYERRANK_HEALTH "Health"
#define PLAYERRANK_ARMOR "Armor"
#define PLAYERRANK_AMMO "Ammo"
#define PLAYERRANK_DAM "Damage"
#define PLAYERRANK_PERTURB "Perturb"
#define PLAYERRANK_STEALTH "Stealth"
#define PLAYERRANK_REP "Reputation"
#define MISSIONSUMMARY_TOTALLEVELINTEL "TotalLevelIntel"
#define MISSIONSUMMARY_MAXNUMLEVELINTEL "MaxNumLevelIntel"
static char s_aAttName[100];
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::PLAYERRANK
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
PLAYERRANK::PLAYERRANK()
{
Reset();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::Reset
//
// PURPOSE: Reset all the data
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::Reset()
{
fHealthMultiplier = 1.0f;
fArmorMultiplier = 1.0f;
fAmmoMultiplier = 1.0f;
fDamageMultiplier = 1.0f;
fPerturbMultiplier = 1.0f;
fStealthMultiplier = 1.0f;
nReputation = 0;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::Write
//
// PURPOSE: Write the data to be sent to the client
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::Write(ILTCSBase *pInterface, HMESSAGEWRITE hWrite)
{
if (!hWrite) return;
pInterface->WriteToMessageFloat(hWrite, fHealthMultiplier);
pInterface->WriteToMessageFloat(hWrite, fArmorMultiplier);
pInterface->WriteToMessageFloat(hWrite, fAmmoMultiplier);
pInterface->WriteToMessageFloat(hWrite, fDamageMultiplier);
pInterface->WriteToMessageFloat(hWrite, fPerturbMultiplier);
pInterface->WriteToMessageFloat(hWrite, fStealthMultiplier);
pInterface->WriteToMessageByte(hWrite, nReputation);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::ReadClientData
//
// PURPOSE: Read the data sent to the client
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::Read(ILTCSBase *pInterface, HMESSAGEREAD hRead)
{
if (!hRead) return;
fHealthMultiplier = pInterface->ReadFromMessageFloat(hRead);
fArmorMultiplier = pInterface->ReadFromMessageFloat(hRead);
fAmmoMultiplier = pInterface->ReadFromMessageFloat(hRead);
fDamageMultiplier = pInterface->ReadFromMessageFloat(hRead);
fPerturbMultiplier = pInterface->ReadFromMessageFloat(hRead);
fStealthMultiplier = pInterface->ReadFromMessageFloat(hRead);
nReputation = pInterface->ReadFromMessageByte(hRead);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::WriteRankData
//
// PURPOSE: Write the data to the butefile
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::WriteRankData(CButeMgr & buteMgr)
{
// Write the global data for each level...
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_HEALTH, fHealthMultiplier);
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_ARMOR, fArmorMultiplier);
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_AMMO, fAmmoMultiplier);
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_DAM, fDamageMultiplier);
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_PERTURB, fPerturbMultiplier);
buteMgr.SetFloat(PLAYERRANK_TAG, PLAYERRANK_STEALTH, fStealthMultiplier);
buteMgr.SetInt( PLAYERRANK_TAG, PLAYERRANK_REP, nReputation);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::ClearRankData
//
// PURPOSE: Reset the data in the butefile
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::ClearRankData(CButeMgr & buteMgr)
{
Reset();
WriteRankData(buteMgr);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: PLAYERRANK::ReadRankData
//
// PURPOSE: Read the data from the butefile
//
// ----------------------------------------------------------------------- //
void PLAYERRANK::ReadRankData(CButeMgr & buteMgr)
{
// Write the global data for each level...
fHealthMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_HEALTH, 1.0f);
fArmorMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_ARMOR, 1.0f);
fAmmoMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_AMMO, 1.0f);
fDamageMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_DAM, 1.0f);
fPerturbMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_PERTURB, 1.0f);
fStealthMultiplier = buteMgr.GetFloat(PLAYERRANK_TAG, PLAYERRANK_STEALTH, 1.0f);
nReputation = buteMgr.GetByte(PLAYERRANK_TAG, PLAYERRANK_REP, 0);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: LEVELSUMMARY::LEVELSUMMARY
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
LEVELSUMMARY::LEVELSUMMARY()
{
// Global data...
nTotalIntel = -1;
nMaxNumIntel = 0;
// Instant data...
nCurNumIntel = 0;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::MISSIONSUMMARY
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
MISSIONSUMMARY::MISSIONSUMMARY()
{
nId = -1;
nNumLevels = 0;
fBestRank = 0.0f;
fOldBestRank = 0.0f;
fCurRank = 0.0f;
fTotalMissionTime = 0.0f;
dwNumShotsFired = 0;
dwNumHits = 0;
dwNumTimesDetected = 0;
dwNumDisturbances = 0;
dwNumBodies = 0;
dwNumEnemyKills = 0;
dwNumFriendKills = 0;
dwNumNeutralKills = 0;
dwNumTimesHit = 0;
m_nMissionTotalIntel = 0;
m_nMissionMaxIntel = 0;
m_nMissionCurNumIntel = 0;
for (int i = 0; i < HL_NUM_LOCS; i++)
dwHitLocations[i] = 0;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::Init
//
// PURPOSE: Build the mission summary struct
//
// ----------------------------------------------------------------------- //
LTBOOL MISSIONSUMMARY::Init(CButeMgr & buteMgr, char* aTagName, MISSION* pMission)
{
if (!aTagName || !pMission) return LTFALSE;
// Read in the data for each level...
nNumLevels = pMission->nNumLevels;
for (int i=0; i < nNumLevels; i++)
{
sprintf(s_aAttName, "%s%d", MISSIONSUMMARY_TOTALLEVELINTEL, i);
if (buteMgr.Exist(aTagName, s_aAttName))
{
Levels[i].nTotalIntel = buteMgr.GetInt(aTagName, s_aAttName);
}
else
{
buteMgr.SetInt(aTagName, s_aAttName, Levels[i].nTotalIntel);
}
sprintf(s_aAttName, "%s%d", MISSIONSUMMARY_MAXNUMLEVELINTEL, i);
if (buteMgr.Exist(aTagName, s_aAttName))
{
Levels[i].nMaxNumIntel = buteMgr.GetInt(aTagName, s_aAttName);
}
else
{
buteMgr.SetInt(aTagName, s_aAttName, Levels[i].nMaxNumIntel);
}
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::WriteClientData
//
// PURPOSE: Write the data to be sent to the client
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::WriteClientData(ILTCSBase *pInterface, HMESSAGEWRITE hWrite)
{
if (!hWrite) return;
int nTotalIntel=0, nMaxIntel=0, nCurIntel=0;
int i;
for (i=0; i < nNumLevels; i++)
{
nTotalIntel += (Levels[i].nTotalIntel > 0 ? Levels[i].nTotalIntel : 0);
nMaxIntel += (Levels[i].nMaxNumIntel > 0 ? Levels[i].nMaxNumIntel : 0);
nCurIntel += (Levels[i].nCurNumIntel > 0 ? Levels[i].nCurNumIntel : 0);
}
LTFLOAT fTime = fTotalMissionTime > 0 ? fTotalMissionTime : pInterface->GetTime();
pInterface->WriteToMessageByte(hWrite, nTotalIntel);
pInterface->WriteToMessageByte(hWrite, nMaxIntel);
pInterface->WriteToMessageByte(hWrite, nCurIntel);
pInterface->WriteToMessageFloat(hWrite, fBestRank);
pInterface->WriteToMessageFloat(hWrite, fOldBestRank);
pInterface->WriteToMessageFloat(hWrite, fCurRank);
pInterface->WriteToMessageFloat(hWrite, fTime);
pInterface->WriteToMessageDWord(hWrite, dwNumShotsFired);
pInterface->WriteToMessageDWord(hWrite, dwNumHits);
pInterface->WriteToMessageDWord(hWrite, dwNumTimesDetected);
pInterface->WriteToMessageDWord(hWrite, dwNumDisturbances);
pInterface->WriteToMessageDWord(hWrite, dwNumBodies);
pInterface->WriteToMessageDWord(hWrite, dwNumEnemyKills);
pInterface->WriteToMessageDWord(hWrite, dwNumFriendKills);
pInterface->WriteToMessageDWord(hWrite, dwNumNeutralKills);
pInterface->WriteToMessageDWord(hWrite, dwNumTimesHit);
for (i = 0; i < HL_NUM_LOCS; i++)
pInterface->WriteToMessageDWord(hWrite,dwHitLocations[i]);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::ReadClientData
//
// PURPOSE: Read the data sent to the client
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::ReadClientData(ILTCSBase *pInterface, HMESSAGEREAD hRead)
{
if (!hRead) return;
uint8 nTotalIntel, nMaxIntel, nCurIntel;
nTotalIntel = pInterface->ReadFromMessageByte(hRead);
nMaxIntel = pInterface->ReadFromMessageByte(hRead);
nCurIntel = pInterface->ReadFromMessageByte(hRead);
fBestRank = pInterface->ReadFromMessageFloat(hRead);
fOldBestRank = pInterface->ReadFromMessageFloat(hRead);
fCurRank = pInterface->ReadFromMessageFloat(hRead);
fTotalMissionTime = pInterface->ReadFromMessageFloat(hRead);
dwNumShotsFired = pInterface->ReadFromMessageDWord(hRead);
dwNumHits = pInterface->ReadFromMessageDWord(hRead);
dwNumTimesDetected = pInterface->ReadFromMessageDWord(hRead);
dwNumDisturbances = pInterface->ReadFromMessageDWord(hRead);
dwNumBodies = pInterface->ReadFromMessageDWord(hRead);
dwNumEnemyKills = pInterface->ReadFromMessageDWord(hRead);
dwNumFriendKills = pInterface->ReadFromMessageDWord(hRead);
dwNumNeutralKills = pInterface->ReadFromMessageDWord(hRead);
dwNumTimesHit = pInterface->ReadFromMessageDWord(hRead);
for (int i = 0; i < HL_NUM_LOCS; i++)
dwHitLocations[i] = pInterface->ReadFromMessageDWord(hRead);
// Just store the intel totals in level 0...
m_nMissionTotalIntel = nTotalIntel;
m_nMissionMaxIntel = nMaxIntel;
m_nMissionCurNumIntel = nCurIntel;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::WriteGlobalData
//
// PURPOSE: Write the global data to the bute mgr
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::WriteGlobalData(CButeMgr & buteMgr, char* aTagName)
{
if (!aTagName || !aTagName[0]) return;
// Write the global data for each level...
for (int i=0; i < nNumLevels; i++)
{
sprintf(s_aAttName, "%s%d", MISSIONSUMMARY_TOTALLEVELINTEL, i);
buteMgr.SetInt(aTagName, s_aAttName, Levels[i].nTotalIntel);
sprintf(s_aAttName, "%s%d", MISSIONSUMMARY_MAXNUMLEVELINTEL, i);
buteMgr.SetInt(aTagName, s_aAttName, Levels[i].nMaxNumIntel);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::ClearGlobalData
//
// PURPOSE: Clear the global data in the bute mgr
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::ClearGlobalData(CButeMgr & buteMgr, char* aTagName)
{
if (!aTagName || !aTagName[0]) return;
// Write the global data for each level...
for (int i=0; i < nNumLevels; i++)
{
Levels[i].nMaxNumIntel = 0;
sprintf(s_aAttName, "%s%d", MISSIONSUMMARY_MAXNUMLEVELINTEL, i);
buteMgr.SetInt(aTagName, s_aAttName, Levels[i].nMaxNumIntel);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::WriteIntantData
//
// PURPOSE: Write the instant data
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::WriteInstantData(ILTCSBase *pInterface, HMESSAGEWRITE hWrite)
{
if (!hWrite) return;
// Write the instant summary data...
pInterface->WriteToMessageFloat(hWrite, fTotalMissionTime);
pInterface->WriteToMessageDWord(hWrite, dwNumShotsFired);
pInterface->WriteToMessageDWord(hWrite, dwNumHits);
pInterface->WriteToMessageDWord(hWrite, dwNumTimesDetected);
pInterface->WriteToMessageDWord(hWrite, dwNumDisturbances);
pInterface->WriteToMessageDWord(hWrite, dwNumBodies);
pInterface->WriteToMessageDWord(hWrite, dwNumEnemyKills);
pInterface->WriteToMessageDWord(hWrite, dwNumFriendKills);
pInterface->WriteToMessageDWord(hWrite, dwNumNeutralKills);
pInterface->WriteToMessageDWord(hWrite, dwNumTimesHit);
int i;
for (i = 0; i < HL_NUM_LOCS; i++)
pInterface->WriteToMessageDWord(hWrite,dwHitLocations[i]);
pInterface->WriteToMessageByte(hWrite, nNumLevels);
for (i=0; i < nNumLevels; i++)
{
pInterface->WriteToMessageByte(hWrite, Levels[i].nCurNumIntel);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: MISSIONSUMMARY::ReadIntantData
//
// PURPOSE: Read the instant data
//
// ----------------------------------------------------------------------- //
void MISSIONSUMMARY::ReadInstantData(ILTCSBase *pInterface, HMESSAGEREAD hRead)
{
if (!hRead) return;
// Read the instant summary data...
fTotalMissionTime = pInterface->ReadFromMessageFloat(hRead);
dwNumShotsFired = pInterface->ReadFromMessageDWord(hRead);
dwNumHits = pInterface->ReadFromMessageDWord(hRead);
dwNumTimesDetected = pInterface->ReadFromMessageDWord(hRead);
dwNumDisturbances = pInterface->ReadFromMessageDWord(hRead);
dwNumBodies = pInterface->ReadFromMessageDWord(hRead);
dwNumEnemyKills = pInterface->ReadFromMessageDWord(hRead);
dwNumFriendKills = pInterface->ReadFromMessageDWord(hRead);
dwNumNeutralKills = pInterface->ReadFromMessageDWord(hRead);
dwNumTimesHit = pInterface->ReadFromMessageDWord(hRead);
int i;
for (i = 0; i < HL_NUM_LOCS; i++)
dwHitLocations[i] = pInterface->ReadFromMessageDWord(hRead);
nNumLevels = pInterface->ReadFromMessageByte(hRead);
for (i=0; i < nNumLevels; i++)
{
Levels[i].nCurNumIntel = pInterface->ReadFromMessageByte(hRead);
}
} | 33.257019 | 87 | 0.584167 | rastrup |
4e5cb6c13d0ce471472e6712fb9bc163b8cb8cfb | 20,676 | cpp | C++ | libraries/ine-vm/tests/spec/call_indirect_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | libraries/ine-vm/tests/spec/call_indirect_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | libraries/ine-vm/tests/spec/call_indirect_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <cmath>
#include <cstdlib>
#include <catch2/catch.hpp>
#include <utils.hpp>
#include <wasm_config.hpp>
#include <inery/vm/backend.hpp>
using namespace inery;
using namespace inery::vm;
extern wasm_allocator wa;
BACKEND_TEST_CASE( "Testing wasm <call_indirect_0_wasm>", "[call_indirect_0_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.0.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bkend.call_with_return(nullptr, "env", "type-i32")->to_ui32() == UINT32_C(306));
CHECK(bkend.call_with_return(nullptr, "env", "type-i64")->to_ui64() == UINT32_C(356));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-f32")->to_f32()) == UINT32_C(1165172736));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-f64")->to_f64()) == UINT64_C(4660882566700597248));
CHECK(bkend.call_with_return(nullptr, "env", "type-index")->to_ui64() == UINT32_C(100));
CHECK(bkend.call_with_return(nullptr, "env", "type-first-i32")->to_ui32() == UINT32_C(32));
CHECK(bkend.call_with_return(nullptr, "env", "type-first-i64")->to_ui64() == UINT32_C(64));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-first-f32")->to_f32()) == UINT32_C(1068037571));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-first-f64")->to_f64()) == UINT64_C(4610064722561534525));
CHECK(bkend.call_with_return(nullptr, "env", "type-second-i32")->to_ui32() == UINT32_C(32));
CHECK(bkend.call_with_return(nullptr, "env", "type-second-i64")->to_ui64() == UINT32_C(64));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "type-second-f32")->to_f32()) == UINT32_C(1107296256));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "type-second-f64")->to_f64()) == UINT64_C(4634211053438658150));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch", UINT32_C(5), UINT64_C(2))->to_ui64() == UINT32_C(2));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch", UINT32_C(5), UINT64_C(5))->to_ui64() == UINT32_C(5));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch", UINT32_C(12), UINT64_C(5))->to_ui64() == UINT32_C(120));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch", UINT32_C(13), UINT64_C(5))->to_ui64() == UINT32_C(8));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch", UINT32_C(20), UINT64_C(2))->to_ui64() == UINT32_C(2));
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch", UINT32_C(0), UINT64_C(2)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch", UINT32_C(15), UINT64_C(2)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch", UINT32_C(29), UINT64_C(2)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch", UINT32_C(4294967295), UINT64_C(2)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch", UINT32_C(1213432423), UINT64_C(2)), std::exception);
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i64", UINT32_C(5))->to_ui64() == UINT32_C(9));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i64", UINT32_C(12))->to_ui64() == UINT32_C(362880));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i64", UINT32_C(13))->to_ui64() == UINT32_C(55));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i64", UINT32_C(20))->to_ui64() == UINT32_C(9));
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-i64", UINT32_C(11)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-i64", UINT32_C(22)), std::exception);
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i32", UINT32_C(4))->to_ui32() == UINT32_C(9));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i32", UINT32_C(23))->to_ui32() == UINT32_C(362880));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i32", UINT32_C(26))->to_ui32() == UINT32_C(55));
CHECK(bkend.call_with_return(nullptr, "env", "dispatch-structural-i32", UINT32_C(19))->to_ui32() == UINT32_C(9));
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-i32", UINT32_C(9)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-i32", UINT32_C(21)), std::exception);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f32", UINT32_C(6))->to_f32()) == UINT32_C(1091567616));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f32", UINT32_C(24))->to_f32()) == UINT32_C(1219571712));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f32", UINT32_C(27))->to_f32()) == UINT32_C(1113325568));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f32", UINT32_C(21))->to_f32()) == UINT32_C(1091567616));
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-f32", UINT32_C(8)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-f32", UINT32_C(19)), std::exception);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f64", UINT32_C(7))->to_f64()) == UINT64_C(4621256167635550208));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f64", UINT32_C(25))->to_f64()) == UINT64_C(4689977843394805760));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f64", UINT32_C(28))->to_f64()) == UINT64_C(4632937379169042432));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "dispatch-structural-f64", UINT32_C(22))->to_f64()) == UINT64_C(4621256167635550208));
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-f64", UINT32_C(10)), std::exception);
CHECK_THROWS_AS(bkend(nullptr, "env", "dispatch-structural-f64", UINT32_C(18)), std::exception);
CHECK(bkend.call_with_return(nullptr, "env", "fac-i64", UINT64_C(0))->to_ui64() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i64", UINT64_C(1))->to_ui64() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i64", UINT64_C(5))->to_ui64() == UINT32_C(120));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i64", UINT64_C(25))->to_ui64() == UINT32_C(7034535277573963776));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i32", UINT32_C(0))->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i32", UINT32_C(1))->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i32", UINT32_C(5))->to_ui32() == UINT32_C(120));
CHECK(bkend.call_with_return(nullptr, "env", "fac-i32", UINT32_C(10))->to_ui32() == UINT32_C(3628800));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fac-f32", bit_cast<float>(UINT32_C(0)))->to_f32()) == UINT32_C(1065353216));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fac-f32", bit_cast<float>(UINT32_C(1065353216)))->to_f32()) == UINT32_C(1065353216));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fac-f32", bit_cast<float>(UINT32_C(1084227584)))->to_f32()) == UINT32_C(1123024896));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fac-f32", bit_cast<float>(UINT32_C(1092616192)))->to_f32()) == UINT32_C(1247640576));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fac-f64", bit_cast<double>(UINT64_C(0)))->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fac-f64", bit_cast<double>(UINT64_C(4607182418800017408)))->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fac-f64", bit_cast<double>(UINT64_C(4617315517961601024)))->to_f64()) == UINT64_C(4638144666238189568));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fac-f64", bit_cast<double>(UINT64_C(4621819117588971520)))->to_f64()) == UINT64_C(4705047200009289728));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i64", UINT64_C(0))->to_ui64() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i64", UINT64_C(1))->to_ui64() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i64", UINT64_C(2))->to_ui64() == UINT32_C(2));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i64", UINT64_C(5))->to_ui64() == UINT32_C(8));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i64", UINT64_C(20))->to_ui64() == UINT32_C(10946));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i32", UINT32_C(0))->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i32", UINT32_C(1))->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i32", UINT32_C(2))->to_ui32() == UINT32_C(2));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i32", UINT32_C(5))->to_ui32() == UINT32_C(8));
CHECK(bkend.call_with_return(nullptr, "env", "fib-i32", UINT32_C(20))->to_ui32() == UINT32_C(10946));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fib-f32", bit_cast<float>(UINT32_C(0)))->to_f32()) == UINT32_C(1065353216));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fib-f32", bit_cast<float>(UINT32_C(1065353216)))->to_f32()) == UINT32_C(1065353216));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fib-f32", bit_cast<float>(UINT32_C(1073741824)))->to_f32()) == UINT32_C(1073741824));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fib-f32", bit_cast<float>(UINT32_C(1084227584)))->to_f32()) == UINT32_C(1090519040));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "fib-f32", bit_cast<float>(UINT32_C(1101004800)))->to_f32()) == UINT32_C(1177225216));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fib-f64", bit_cast<double>(UINT64_C(0)))->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fib-f64", bit_cast<double>(UINT64_C(4607182418800017408)))->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fib-f64", bit_cast<double>(UINT64_C(4611686018427387904)))->to_f64()) == UINT64_C(4611686018427387904));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fib-f64", bit_cast<double>(UINT64_C(4617315517961601024)))->to_f64()) == UINT64_C(4620693217682128896));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "fib-f64", bit_cast<double>(UINT64_C(4626322717216342016)))->to_f64()) == UINT64_C(4667243241467281408));
CHECK(bkend.call_with_return(nullptr, "env", "even", UINT32_C(0))->to_ui32() == UINT32_C(44));
CHECK(bkend.call_with_return(nullptr, "env", "even", UINT32_C(1))->to_ui32() == UINT32_C(99));
CHECK(bkend.call_with_return(nullptr, "env", "even", UINT32_C(100))->to_ui32() == UINT32_C(44));
CHECK(bkend.call_with_return(nullptr, "env", "even", UINT32_C(77))->to_ui32() == UINT32_C(99));
CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT32_C(0))->to_ui32() == UINT32_C(99));
CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT32_C(1))->to_ui32() == UINT32_C(44));
CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT32_C(200))->to_ui32() == UINT32_C(99));
CHECK(bkend.call_with_return(nullptr, "env", "odd", UINT32_C(77))->to_ui32() == UINT32_C(44));
CHECK(bkend.call_with_return(nullptr, "env", "as-select-first")->to_ui32() == UINT32_C(306));
CHECK(bkend.call_with_return(nullptr, "env", "as-select-mid")->to_ui32() == UINT32_C(2));
CHECK(bkend.call_with_return(nullptr, "env", "as-select-last")->to_ui32() == UINT32_C(2));
CHECK(bkend.call_with_return(nullptr, "env", "as-if-condition")->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "as-br_if-first")->to_ui64() == UINT32_C(356));
CHECK(bkend.call_with_return(nullptr, "env", "as-br_if-last")->to_ui32() == UINT32_C(2));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "as-br_table-first")->to_f32()) == UINT32_C(1165172736));
CHECK(bkend.call_with_return(nullptr, "env", "as-br_table-last")->to_ui32() == UINT32_C(2));
CHECK(!bkend.call_with_return(nullptr, "env", "as-store-first"));
CHECK(!bkend.call_with_return(nullptr, "env", "as-store-last"));
CHECK(bkend.call_with_return(nullptr, "env", "as-memory.grow-value")->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "as-return-value")->to_ui32() == UINT32_C(1));
CHECK(!bkend.call_with_return(nullptr, "env", "as-drop-operand"));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "as-br-value")->to_f32()) == UINT32_C(1065353216));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "as-local.set-value")->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "as-local.tee-value")->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "as-global.set-value")->to_f64()) == UINT64_C(4607182418800017408));
CHECK(bkend.call_with_return(nullptr, "env", "as-load-operand")->to_ui32() == UINT32_C(1));
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "as-unary-operand")->to_f32()) == UINT32_C(0));
CHECK(bkend.call_with_return(nullptr, "env", "as-binary-left")->to_ui32() == UINT32_C(11));
CHECK(bkend.call_with_return(nullptr, "env", "as-binary-right")->to_ui32() == UINT32_C(9));
CHECK(bkend.call_with_return(nullptr, "env", "as-test-operand")->to_ui32() == UINT32_C(0));
CHECK(bkend.call_with_return(nullptr, "env", "as-compare-left")->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "as-compare-right")->to_ui32() == UINT32_C(1));
CHECK(bkend.call_with_return(nullptr, "env", "as-convert-operand")->to_ui64() == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_12_wasm>", "[call_indirect_12_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.12.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_13_wasm>", "[call_indirect_13_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.13.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_14_wasm>", "[call_indirect_14_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.14.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_15_wasm>", "[call_indirect_15_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.15.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_16_wasm>", "[call_indirect_16_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.16.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_17_wasm>", "[call_indirect_17_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.17.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_18_wasm>", "[call_indirect_18_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.18.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_19_wasm>", "[call_indirect_19_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.19.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_20_wasm>", "[call_indirect_20_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.20.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_21_wasm>", "[call_indirect_21_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.21.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_22_wasm>", "[call_indirect_22_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.22.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_23_wasm>", "[call_indirect_23_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.23.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_24_wasm>", "[call_indirect_24_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.24.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_25_wasm>", "[call_indirect_25_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.25.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_26_wasm>", "[call_indirect_26_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.26.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_27_wasm>", "[call_indirect_27_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.27.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_28_wasm>", "[call_indirect_28_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.28.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_29_wasm>", "[call_indirect_29_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.29.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_30_wasm>", "[call_indirect_30_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.30.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_31_wasm>", "[call_indirect_31_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.31.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_32_wasm>", "[call_indirect_32_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.32.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
BACKEND_TEST_CASE( "Testing wasm <call_indirect_33_wasm>", "[call_indirect_33_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "call_indirect.33.wasm");
CHECK_THROWS_AS(backend_t(code), std::exception);
}
| 75.736264 | 172 | 0.725285 | inery-blockchain |
4e5ce4235b7297fb7247875394ab7857c7d331eb | 13,717 | cpp | C++ | src/drivers/goindol.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 33 | 2015-08-10T11:13:47.000Z | 2021-08-30T10:00:46.000Z | src/drivers/goindol.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 13 | 2015-08-25T03:53:08.000Z | 2022-03-30T18:02:35.000Z | src/drivers/goindol.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 40 | 2015-08-25T05:09:21.000Z | 2022-02-08T05:02:30.000Z | #include "../vidhrdw/goindol.cpp"
/***************************************************************************
GOINDOL
Driver provided by Jarek Parchanski ([email protected])
***************************************************************************/
#include "driver.h"
int goindol_vh_start(void);
void goindol_vh_stop(void);
WRITE_HANDLER( goindol_fg_videoram_w );
WRITE_HANDLER( goindol_bg_videoram_w );
void goindol_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void goindol_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
extern unsigned char *goindol_fg_scrollx;
extern unsigned char *goindol_fg_scrolly;
extern unsigned char *goindol_fg_videoram;
extern unsigned char *goindol_bg_videoram;
extern unsigned char *goindol_spriteram1;
extern unsigned char *goindol_spriteram2;
extern size_t goindol_spriteram_size;
extern size_t goindol_fg_videoram_size;
extern size_t goindol_bg_videoram_size;
extern int goindol_char_bank;
WRITE_HANDLER( goindol_bankswitch_w )
{
int bankaddress;
unsigned char *RAM = memory_region(REGION_CPU1);
bankaddress = 0x10000 + ((data & 3) * 0x4000);
cpu_setbank(1,&RAM[bankaddress]);
goindol_char_bank = data & 0x10;
}
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xc000, 0xc7ff, MRA_RAM },
{ 0xc800, 0xc800, MRA_NOP },
{ 0xd000, 0xefff, MRA_RAM },
{ 0xf000, 0xf000, input_port_3_r },
{ 0xf800, 0xf800, input_port_4_r },
{ 0xc834, 0xc834, input_port_1_r },
{ 0xc820, 0xc820, input_port_2_r },
{ 0xc830, 0xc830, input_port_0_r },
{ 0xe000, 0xefff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ 0xc810, 0xc810, goindol_bankswitch_w },
{ 0xc820, 0xd820, MWA_RAM, &goindol_fg_scrollx },
{ 0xc830, 0xd830, MWA_RAM, &goindol_fg_scrolly },
{ 0xc800, 0xc800, soundlatch_w },
{ 0xd000, 0xd03f, MWA_RAM, &goindol_spriteram1, &goindol_spriteram_size },
{ 0xd040, 0xd7ff, MWA_RAM },
{ 0xd800, 0xdfff, goindol_bg_videoram_w, &goindol_bg_videoram, &goindol_bg_videoram_size },
{ 0xe000, 0xe03f, MWA_RAM, &goindol_spriteram2 },
{ 0xe040, 0xe7ff, MWA_RAM },
{ 0xe800, 0xefff, goindol_fg_videoram_w, &goindol_fg_videoram, &goindol_fg_videoram_size },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0xc000, 0xc7ff, MRA_RAM },
{ 0xd800, 0xd800, soundlatch_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sound_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ 0xa000, 0xa000, YM2203_control_port_0_w },
{ 0xa001, 0xa001, YM2203_write_port_0_w },
{ -1 } /* end of table */
};
INPUT_PORTS_START( goindol )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT_IMPULSE( 0x80, IP_ACTIVE_LOW, IPT_COIN1, 1 )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT_IMPULSE( 0x80, IP_ACTIVE_LOW, IPT_COIN2, 1 )
PORT_START /* IN2 - spinner */
PORT_ANALOG( 0xff, 0x00, IPT_DIAL , 40, 10, 0, 0)
PORT_START /* DSW0 */
PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x03, "2" )
PORT_DIPSETTING( 0x02, "3" )
PORT_DIPSETTING( 0x01, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x1c, 0x0c, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x1c, "Easiest" )
PORT_DIPSETTING( 0x18, "Very Very Easy" )
PORT_DIPSETTING( 0x14, "Very Easy" )
PORT_DIPSETTING( 0x10, "Easy" )
PORT_DIPSETTING( 0x0c, "Normal" )
PORT_DIPSETTING( 0x08, "Difficult" )
PORT_DIPSETTING( 0x04, "Hard" )
PORT_DIPSETTING( 0x00, "Very Hard" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ))
PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
PORT_START /* DSW1 */
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x04, "30k and every 50k" )
PORT_DIPSETTING( 0x05, "50k and every 100k" )
PORT_DIPSETTING( 0x06, "50k and every 200k" )
PORT_DIPSETTING( 0x07, "100k and every 200k" )
PORT_DIPSETTING( 0x01, "10000 only" )
PORT_DIPSETTING( 0x02, "30000 only" )
PORT_DIPSETTING( 0x03, "50000 only" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x38, 0x00, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x28, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x30, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x38, DEF_STR( 1C_6C ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x40, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
INPUT_PORTS_START( homo )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT_IMPULSE( 0x80, IP_ACTIVE_LOW, IPT_COIN1, 1 )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT_IMPULSE( 0x80, IP_ACTIVE_LOW, IPT_COIN2, 1 )
PORT_START /* IN2 - spinner */
PORT_ANALOG( 0xff, 0x00, IPT_DIAL , 40, 10, 0, 0)
PORT_START /* DSW0 */
PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x03, "2" )
PORT_DIPSETTING( 0x02, "3" )
PORT_DIPSETTING( 0x01, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x1c, 0x0c, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x1c, "Easiest" )
PORT_DIPSETTING( 0x18, "Very Very Easy" )
PORT_DIPSETTING( 0x14, "Very Easy" )
PORT_DIPSETTING( 0x10, "Easy" )
PORT_DIPSETTING( 0x0c, "Normal" )
PORT_DIPSETTING( 0x08, "Difficult" )
PORT_DIPSETTING( 0x04, "Hard" )
PORT_DIPSETTING( 0x00, "Very Hard" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ))
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ))
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
PORT_START /* DSW1 */
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x04, "30k and every 50k" )
PORT_DIPSETTING( 0x05, "50k and every 100k" )
PORT_DIPSETTING( 0x06, "50k and every 200k" )
PORT_DIPSETTING( 0x07, "100k and every 200k" )
PORT_DIPSETTING( 0x01, "10000 only" )
PORT_DIPSETTING( 0x02, "30000 only" )
PORT_DIPSETTING( 0x03, "50000 only" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x38, 0x00, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x28, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x30, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x38, DEF_STR( 1C_6C ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x40, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
static struct GfxLayout charlayout =
{
8,8, /* 8*8 characters */
4096, /* 1024 characters */
3, /* 2 bits per pixel */
{ 0, 0x8000*8, 0x10000*8 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0, 8, 16, 24, 32, 40, 48, 56 },
8*8 /* every char takes 8 consecutive bytes */
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &charlayout, 0, 32 },
{ REGION_GFX2, 0, &charlayout, 0, 32 },
{ -1 } /* end of array */
};
static struct YM2203interface ym2203_interface =
{
1, /* 1 chip */
2000000, /* 2 MHz (?) */
{ YM2203_VOL(25,25) },
{ 0 },
{ 0 },
{ 0 },
{ 0 }
};
static struct MachineDriver machine_driver_goindol =
{
/* basic machine hardware */
{
{
CPU_Z80,
6000000, /* 6 Mhz (?) */
readmem,writemem,0,0,
interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
4000000, /* 4 Mhz (?) */
sound_readmem,sound_writemem,0,0,
interrupt,4
}
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1,
0,
/* video hardware */
32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 },
gfxdecodeinfo,
256,32*8+32*8,
goindol_vh_convert_color_prom,
VIDEO_TYPE_RASTER,
0,
goindol_vh_start,
goindol_vh_stop,
goindol_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_YM2203,
&ym2203_interface
}
}
};
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( goindol )
ROM_REGION( 0x20000, REGION_CPU1 ) /* 2*64k for code */
ROM_LOAD( "r1", 0x00000, 0x8000, 0x3111c61b ) /* Code 0000-7fff */
ROM_LOAD( "r2", 0x10000, 0x8000, 0x1ff6e3a2 ) /* Paged data */
ROM_LOAD( "r3", 0x18000, 0x8000, 0xe9eec24a ) /* Paged data */
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU */
ROM_LOAD( "r10", 0x00000, 0x8000, 0x72e1add1 )
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "r4", 0x00000, 0x8000, 0x1ab84225 ) /* Characters */
ROM_LOAD( "r5", 0x08000, 0x8000, 0x4997d469 )
ROM_LOAD( "r6", 0x10000, 0x8000, 0x752904b0 )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "r7", 0x00000, 0x8000, 0x362f2a27 )
ROM_LOAD( "r8", 0x08000, 0x8000, 0x9fc7946e )
ROM_LOAD( "r9", 0x10000, 0x8000, 0xe6212fe4 )
ROM_REGION( 0x0300, REGION_PROMS )
ROM_LOAD( "am27s21.pr1", 0x0000, 0x0100, 0x361f0868 ) /* palette red bits */
ROM_LOAD( "am27s21.pr2", 0x0100, 0x0100, 0xe355da4d ) /* palette green bits */
ROM_LOAD( "am27s21.pr3", 0x0200, 0x0100, 0x8534cfb5 ) /* palette blue bits */
ROM_END
ROM_START( homo )
ROM_REGION( 0x20000, REGION_CPU1 ) /* 2*64k for code */
ROM_LOAD( "homo.01", 0x00000, 0x8000, 0x28c539ad ) /* Code 0000-7fff */
ROM_LOAD( "r2", 0x10000, 0x8000, 0x1ff6e3a2 ) /* Paged data */
ROM_LOAD( "r3", 0x18000, 0x8000, 0xe9eec24a ) /* Paged data */
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for the audio CPU */
ROM_LOAD( "r10", 0x00000, 0x8000, 0x72e1add1 )
ROM_REGION( 0x18000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "r4", 0x00000, 0x8000, 0x1ab84225 ) /* Characters */
ROM_LOAD( "r5", 0x08000, 0x8000, 0x4997d469 )
ROM_LOAD( "r6", 0x10000, 0x8000, 0x752904b0 )
ROM_REGION( 0x18000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "r7", 0x00000, 0x8000, 0x362f2a27 )
ROM_LOAD( "r8", 0x08000, 0x8000, 0x9fc7946e )
ROM_LOAD( "r9", 0x10000, 0x8000, 0xe6212fe4 )
ROM_REGION( 0x0300, REGION_PROMS )
ROM_LOAD( "am27s21.pr1", 0x0000, 0x0100, 0x361f0868 ) /* palette red bits */
ROM_LOAD( "am27s21.pr2", 0x0100, 0x0100, 0xe355da4d ) /* palette green bits */
ROM_LOAD( "am27s21.pr3", 0x0200, 0x0100, 0x8534cfb5 ) /* palette blue bits */
ROM_END
void init_goindol(void)
{
unsigned char *rom = memory_region(REGION_CPU1);
/* I hope that's all patches to avoid protection */
rom[0x04a7] = 0xc9;
rom[0x0641] = 0xc9;
rom[0x0831] = 0xc9;
rom[0x0b30] = 0x00;
rom[0x0c13] = 0xc9;
rom[0x134e] = 0xc9;
rom[0x172e] = 0xc9;
rom[0x1785] = 0xc9;
rom[0x17cc] = 0xc9;
rom[0x1aa5] = 0x7b;
rom[0x1aa6] = 0x17;
rom[0x1bee] = 0xc9;
rom[0x218c] = 0x00;
rom[0x218d] = 0x00;
rom[0x218e] = 0x00;
rom[0x333d] = 0xc9;
rom[0x3365] = 0x00;
}
void init_homo(void)
{
unsigned char *rom = memory_region(REGION_CPU1);
rom[0x218c] = 0x00;
rom[0x218d] = 0x00;
rom[0x218e] = 0x00;
}
GAME( 1987, goindol, 0, goindol, goindol, goindol, ROT90, "Sun a Electronics", "Goindol" )
GAME( 1987, homo, goindol, goindol, homo, homo, ROT90, "bootleg", "Homo" )
| 32.504739 | 119 | 0.680469 | gameblabla |
4e63569fff87e19a34116a1204caea2bb1375857 | 172 | hpp | C++ | src/controllers/hotkeys/HotkeyHelpers.hpp | agenttud/chatterino7 | b40763c5f847c017106115f92b864b40b3a20501 | [
"MIT"
] | 200 | 2017-01-24T11:23:03.000Z | 2019-05-15T19:31:18.000Z | src/controllers/hotkeys/HotkeyHelpers.hpp | agenttud/chatterino7 | b40763c5f847c017106115f92b864b40b3a20501 | [
"MIT"
] | 878 | 2017-02-06T13:25:24.000Z | 2019-05-18T16:15:21.000Z | src/controllers/hotkeys/HotkeyHelpers.hpp | agenttud/chatterino7 | b40763c5f847c017106115f92b864b40b3a20501 | [
"MIT"
] | 138 | 2017-02-07T18:01:49.000Z | 2019-05-18T19:00:03.000Z | #pragma once
#include <QString>
#include <vector>
namespace chatterino {
std::vector<QString> parseHotkeyArguments(QString argumentString);
} // namespace chatterino
| 14.333333 | 66 | 0.767442 | agenttud |
4e6665fe6dbf02a5fb4af8c55d94b849798b8836 | 4,826 | cpp | C++ | src/Screens/MusicSelect/Drawables/ControlPanels.cpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 19 | 2020-02-28T20:34:12.000Z | 2022-01-28T20:18:25.000Z | src/Screens/MusicSelect/Drawables/ControlPanels.cpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 7 | 2019-10-22T09:43:16.000Z | 2022-03-12T00:15:13.000Z | src/Screens/MusicSelect/Drawables/ControlPanels.cpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 5 | 2019-10-22T08:14:57.000Z | 2021-03-13T06:32:04.000Z | #include "ControlPanels.hpp"
#include "../../../Toolkit/SFMLHelpers.hpp"
namespace MusicSelect {
void LeftButton::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform();
sf::CircleShape circle{get_panel_size()*0.4f};
circle.setFillColor(sf::Color::Black);
circle.setOutlineThickness(0.02f*get_panel_size());
circle.setOutlineColor(sf::Color::White);
Toolkit::set_origin_normalized(circle, 0.5f, 0.5f);
circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(circle, states);
sf::RectangleShape arrow_part{sf::Vector2f{0.1f,0.4f}*get_panel_size()};
arrow_part.setFillColor(sf::Color::White);
Toolkit::set_origin_normalized(arrow_part, 2.f, 0.5f);
arrow_part.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
arrow_part.move(0.05f*get_panel_size(), 0.f);
arrow_part.rotate(45.f);
target.draw(arrow_part, states);
arrow_part.rotate(-90.f);
target.draw(arrow_part, states);
}
void RightButton::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform();
sf::CircleShape circle{get_panel_size()*0.4f};
circle.setFillColor(sf::Color::Black);
circle.setOutlineThickness(0.02f*get_panel_size());
circle.setOutlineColor(sf::Color::White);
Toolkit::set_origin_normalized(circle, 0.5f, 0.5f);
circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(circle, states);
sf::RectangleShape arrow_part{sf::Vector2f{0.1f,0.4f}*get_panel_size()};
arrow_part.setFillColor(sf::Color::White);
Toolkit::set_origin_normalized(arrow_part, -1.f, 0.5f);
arrow_part.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
arrow_part.move(-0.05f*get_panel_size(), 0.f);
arrow_part.rotate(45.f);
target.draw(arrow_part, states);
arrow_part.rotate(-90.f);
target.draw(arrow_part, states);
}
void OptionsButton::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform();
sf::CircleShape circle{get_panel_size()*0.4f};
circle.setFillColor(sf::Color::Black);
circle.setOutlineThickness(0.02f*get_panel_size());
circle.setOutlineColor(sf::Color::White);
Toolkit::set_origin_normalized(circle, 0.5f, 0.5f);
circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(circle, states);
sf::Text label{
"OPTIONS",
shared.fallback_font.black,
static_cast<unsigned int>(0.2f*get_panel_size())
};
label.setFillColor(sf::Color::White);
Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f);
label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
label.setScale(0.8f, 1.0f);
target.draw(label, states);
}
void StartButton::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform();
sf::CircleShape circle{get_panel_size()*0.4f};
circle.setFillColor(sf::Color::Black);
circle.setOutlineThickness(0.02f*get_panel_size());
circle.setOutlineColor(shared.BSC_color);
Toolkit::set_origin_normalized(circle, 0.5f, 0.5f);
circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(circle, states);
sf::Text label{
"START",
shared.fallback_font.black,
static_cast<unsigned int>(0.2f*get_panel_size())
};
label.setFillColor(shared.BSC_color);
Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f);
label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(label, states);
}
void BackButton::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform();
sf::CircleShape circle{get_panel_size()*0.4f};
circle.setFillColor(sf::Color::Black);
circle.setOutlineThickness(0.02f*get_panel_size());
circle.setOutlineColor(shared.EXT_color);
Toolkit::set_origin_normalized(circle, 0.5f, 0.5f);
circle.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(circle, states);
sf::Text label{
"BACK",
shared.fallback_font.black,
static_cast<unsigned int>(0.2f*get_panel_size())
};
label.setFillColor(shared.EXT_color);
Toolkit::set_local_origin_normalized(label, 0.5f, 0.5f);
label.setPosition(get_panel_size()*0.5f, get_panel_size()*0.5f);
target.draw(label, states);
}
} | 43.477477 | 87 | 0.648363 | Subject38 |
4e6ae5947b7e3480f74525a74eceeda1ab1347ef | 752 | cpp | C++ | lib/DBMS/DBMS.cpp | travisolbrich/315-P1-DBMS | 84168bbb3f5fe7518cbb212baa01d54ca7e6815d | [
"MIT"
] | null | null | null | lib/DBMS/DBMS.cpp | travisolbrich/315-P1-DBMS | 84168bbb3f5fe7518cbb212baa01d54ca7e6815d | [
"MIT"
] | null | null | null | lib/DBMS/DBMS.cpp | travisolbrich/315-P1-DBMS | 84168bbb3f5fe7518cbb212baa01d54ca7e6815d | [
"MIT"
] | 3 | 2016-02-15T22:32:31.000Z | 2021-01-10T14:41:14.000Z | #include "../SqlTokenizer/SqlTokenizer.h"
#include "../SqlTokenizer/Token.h"
#include "../SqlParser/SqlParser.h"
#include "../DBMSEngine/Relation.h"
#include "../DBMSEngine/Engine.h"
#include "DBMS.h"
#include <string>
#include <vector>
/**
Returns:
0: valid answer
1: Exception
2: Exit called
**/
int DBMS::execute(string query)
{
try
{
SqlTokenizer* tokenizer = new SqlTokenizer(query);
vector<Token> tokens = tokenizer->split();
if(tokens[0].getType() == Token::EXIT) return 2;
SqlParser* parser = new SqlParser(tokens, engine);
parser->parse();
}
catch (exception& e)
{
cout << "!!! " << e.what() << "\n";
return 1;
}
return 0;
}
Relation DBMS::relation(string relation)
{
return *engine->getRelation(relation);
} | 18.341463 | 52 | 0.660904 | travisolbrich |
4e6af3670917df035958d0dbc1368177dd4e0669 | 157 | cpp | C++ | problem-2/main.cpp | ProgrammingLanguagesClass/Assignment-2 | a65ff25decee4da401660a0c85bb3467f065e119 | [
"MIT"
] | 1 | 2019-12-10T11:03:59.000Z | 2019-12-10T11:03:59.000Z | problem-2/main.cpp | ProgrammingLanguagesClass/Assignment-2 | a65ff25decee4da401660a0c85bb3467f065e119 | [
"MIT"
] | null | null | null | problem-2/main.cpp | ProgrammingLanguagesClass/Assignment-2 | a65ff25decee4da401660a0c85bb3467f065e119 | [
"MIT"
] | 1 | 2019-01-03T11:00:30.000Z | 2019-01-03T11:00:30.000Z | #include <iostream>
#include "main.h"
using namespace std;
string getGrade(int score)
{
string grade;
// Write your code here
return grade;
} | 12.076923 | 27 | 0.66879 | ProgrammingLanguagesClass |
4e6c736bb84dcefe43dc1cdebe261f47dc437c97 | 6,678 | cpp | C++ | test/distribution/joint_distribution_iid_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | test/distribution/joint_distribution_iid_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | test/distribution/joint_distribution_iid_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
* University of Southern California
* Jan Issac ([email protected])
* Manuel Wuthrich ([email protected])
*
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* \file joint_distribution_iid_test.cpp
* \date Febuary 2015
* \author Jan Issac ([email protected])
*/
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/joint_distribution_iid.hpp>
TEST(JointDistribution_IID_Tests, fixed_fixed_single_gaussian)
{
constexpr int dim = 2;
typedef Eigen::Matrix<double, dim, 1> FVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<FVariate>, 1>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<FVariate>());
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(fl::are_similar(
joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
TEST(JointDistribution_IID_Tests, fixed_dynamic_single_gaussian)
{
typedef Eigen::Matrix<double, -1, 1> DVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<DVariate>, 1>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<DVariate>(13));
constexpr int dim = 13;
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(
fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(
fl::are_similar(joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
TEST(JointDistribution_IID_Tests, dynamic_dynamic_single_gaussian)
{
typedef Eigen::Matrix<double, -1, 1> DVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<DVariate>, -1>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<DVariate>(13), 1);
constexpr int dim = 13;
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(
fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(
fl::are_similar(joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
TEST(JointDistribution_IID_Tests, fixed_fixed_three_gaussian)
{
typedef Eigen::Matrix<double, 13, 1> FVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<FVariate>, 3>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<FVariate>());
constexpr int dim = 3 * 13;
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(
fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(
fl::are_similar(joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
TEST(JointDistribution_IID_Tests, fixed_dynamic_three_gaussian)
{
typedef Eigen::Matrix<double, -1, 1> DVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<DVariate>, 3>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<DVariate>(13));
constexpr int dim = 3 * 13;
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(
fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(
fl::are_similar(joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
TEST(JointDistribution_IID_Tests, dynamic_dynamic_three_gaussian)
{
typedef Eigen::Matrix<double, -1, 1> DVariate;
typedef fl::JointDistribution<
fl::MultipleOf<fl::Gaussian<DVariate>, -1>
> FSingeDistribution;
FSingeDistribution joint_distr =
FSingeDistribution(fl::Gaussian<DVariate>(13), 3);
constexpr int dim = 3 * 13;
typedef Eigen::Matrix<double, dim, 1> ExpectedMean;
typedef Eigen::Matrix<double, dim, dim> ExpectedCovariance;
EXPECT_EQ(joint_distr.dimension(), dim);
EXPECT_TRUE(
fl::are_similar(joint_distr.mean(), ExpectedMean::Zero(dim, 1)));
EXPECT_TRUE(
fl::are_similar(joint_distr.covariance(),
ExpectedCovariance::Identity(dim, dim)));
}
| 33.727273 | 81 | 0.686733 | aeolusbot-tommyliu |
4e6d1fa6994a4c3374ff41e672058f0baf99e5ab | 576 | cpp | C++ | Opportunity.ChakraBridge.WinRT/Value/JsString.cpp | OpportunityLiu/ChakraBridge | 38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3 | [
"MIT"
] | null | null | null | Opportunity.ChakraBridge.WinRT/Value/JsString.cpp | OpportunityLiu/ChakraBridge | 38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3 | [
"MIT"
] | null | null | null | Opportunity.ChakraBridge.WinRT/Value/JsString.cpp | OpportunityLiu/ChakraBridge | 38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "JsString.h"
using namespace Opportunity::ChakraBridge::WinRT;
JsStringImpl::~JsStringImpl()
{
// ignore error.
JsRelease(Reference.Ref, nullptr);
}
JsStringImpl::JsStringImpl(RawValue ref)
:JsValueImpl(std::move(ref))
{
Reference.AddRef();
}
uint32 JsStringImpl::Length::get()
{
return static_cast<uint32>(Reference.StrLength());
}
string^ JsStringImpl::ToString()
{
return Reference.ToString();
}
IJsString^ JsString::Create(string^ value)
{
return ref new JsStringImpl(RawValue(value->Data(),value->Length()));
}
| 18 | 73 | 0.704861 | OpportunityLiu |
4e70497236b5f181b81da3ed17ebe1bd946a0c23 | 382 | hpp | C++ | src/geocode/protocol_mapquest.hpp | stephaneyfx/geocode-cpp | 18ec8f62cbd71953f200c41887408028a03cd8a5 | [
"MIT"
] | null | null | null | src/geocode/protocol_mapquest.hpp | stephaneyfx/geocode-cpp | 18ec8f62cbd71953f200c41887408028a03cd8a5 | [
"MIT"
] | null | null | null | src/geocode/protocol_mapquest.hpp | stephaneyfx/geocode-cpp | 18ec8f62cbd71953f200c41887408028a03cd8a5 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Stephane Raux. Distributed under the MIT license.
#pragma once
#include "protocol.hpp"
#include <string>
class ProtocolMapQuest {
public:
explicit ProtocolMapQuest(std::string key);
std::string host() const;
Coordinates parse(const Response& resp) const;
Request request(const std::string& location) const;
private:
std::string key;
};
| 21.222222 | 71 | 0.719895 | stephaneyfx |
4e73d28eaf35e20955ff67c5a9a70c97c9781d65 | 1,318 | cpp | C++ | raizes_equacao.cpp | Institutionoffoz/Teste1 | cfb5c67b8b93daf0a777caed15f8fcefa1fce51d | [
"MIT"
] | null | null | null | raizes_equacao.cpp | Institutionoffoz/Teste1 | cfb5c67b8b93daf0a777caed15f8fcefa1fce51d | [
"MIT"
] | null | null | null | raizes_equacao.cpp | Institutionoffoz/Teste1 | cfb5c67b8b93daf0a777caed15f8fcefa1fce51d | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int raizes(double a, double b, double c, double *px1, double *px2)
{
double delta;
if(a == 0.0)
{
*px1 = *px2 = -c/b;
}
else
{
delta = b * b - 4 * a * c;
if(delta < 0)
{
*px1 = *px2 = -3.14159265359;
}
else
{
if(delta == 0.0)
{
*px1 = *px2 = -b/(2*a);
}
else
{
delta = sqrt(delta);
*px1 = (-b+delta)/(2*a);
*px2 = (-b-delta)/(2*a);
}
}
}
}
int main()
{
double a, b, c;
double x1, x2;
printf("programa que calcula as raizes de uma equacao do segundo grau\n");
printf("informe os coeficientes (a b c)\n");
printf("informe a\n");
scanf("%lf", &a);
printf("informe b\n");
scanf("%lf", &b);
printf("informe c\n");
scanf("%lf", &c);
raizes(a,b,c,&x1,&x2);
if(x1 == -3.14159265359)
{
printf("raizes reais inexistentes\n");
}
else
{
if(x1==x2)
{
printf("uma raiz real %.2lf\n", x1);
}
else
{
printf("duas raizes reais: %.2lf , %.2lf\n", x1, x2);
}
}
return 0;
} | 19.671642 | 78 | 0.403642 | Institutionoffoz |
4e81115ab7d2f1b129ff498bd35b15abddc3dcb6 | 710 | cpp | C++ | src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 1 | 2018-10-01T06:07:16.000Z | 2018-10-01T06:07:16.000Z | src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 4 | 2018-06-04T20:26:40.000Z | 2018-07-27T14:54:55.000Z | src/Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Evolution/Systems/Burgers/BoundaryConditions/RegisterDerivedWithCharm.hpp"
#include "Evolution/Systems/Burgers/BoundaryConditions/BoundaryCondition.hpp"
#include "Evolution/Systems/Burgers/BoundaryConditions/Dirichlet.hpp"
#include "Evolution/Systems/Burgers/BoundaryConditions/DirichletAnalytic.hpp"
#include "Evolution/Systems/Burgers/BoundaryConditions/Outflow.hpp"
#include "Parallel/RegisterDerivedClassesWithCharm.hpp"
namespace Burgers::BoundaryConditions {
void register_derived_with_charm() noexcept {
Parallel::register_derived_classes_with_charm<BoundaryCondition>();
}
} // namespace Burgers::BoundaryConditions
| 41.764706 | 84 | 0.840845 | macedo22 |
4e829278fb9227290b2d2fe71b937f2cd66e3766 | 10,357 | cpp | C++ | src/driveshaft-config.cpp | tlalexan/driveshaft | 122422e78e561053ec859015a4de5990f97a297b | [
"MIT"
] | 43 | 2015-09-22T21:07:56.000Z | 2020-08-05T16:10:03.000Z | src/driveshaft-config.cpp | tlalexan/driveshaft | 122422e78e561053ec859015a4de5990f97a297b | [
"MIT"
] | 16 | 2015-09-22T15:53:18.000Z | 2020-08-10T16:22:48.000Z | src/driveshaft-config.cpp | tlalexan/driveshaft | 122422e78e561053ec859015a4de5990f97a297b | [
"MIT"
] | 11 | 2015-09-21T20:36:37.000Z | 2020-06-16T13:40:05.000Z | #include <fstream>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/filesystem.hpp>
#include "driveshaft-config.h"
namespace Driveshaft {
namespace cfgkeys {
static std::string GEARMAN_SERVERS_LIST = "gearman_servers_list";
static std::string POOLS_LIST = "pools_list";
static std::string POOL_WORKER_COUNT = "worker_count";
static std::string POOL_JOB_LIST = "jobs_list";
static std::string POOL_JOB_PROCESSING_URI = "job_processing_uri";
}
DriveshaftConfig::DriveshaftConfig() noexcept :
m_config_filename(),
m_server_list(),
m_pool_map(),
m_load_time(0) {
}
bool DriveshaftConfig::load(const std::string& config_filename, std::shared_ptr<Json::CharReader> json_parser) {
if (!this->needsConfigUpdate(config_filename)) {
return false;
}
LOG4CXX_INFO(MainLogger, "Reloading config");
this->m_config_filename = config_filename;
std::string config_file_contents(this->fetchFileContents(config_filename));
return this->parseConfig(config_file_contents, json_parser);
}
bool DriveshaftConfig::parseConfig(const std::string& config_data, std::shared_ptr<Json::CharReader> json_parser) {
Json::Value tree;
std::string parse_errors;
if (!json_parser->parse(config_data.data(),
config_data.data() + config_data.length(),
&tree, &parse_errors)) {
LOG4CXX_ERROR(MainLogger, "Failed to parse " << this->m_config_filename <<
". Errors: " << parse_errors);
throw std::runtime_error("config parse failure");
}
if (!this->validateConfigNode(tree)) {
throw std::runtime_error("config parse failure");
}
this->m_load_time = std::time(nullptr);
this->m_server_list.clear();
this->m_pool_map.clear();
this->parseServerList(tree);
this->parsePoolList(tree);
return true;
}
void DriveshaftConfig::supersede(DriveshaftConfig& old, PoolWatcher& watcher) const {
StringSet pools_to_shut;
std::tie(pools_to_shut, std::ignore) = old.compare(*this);
for (const auto& pool : pools_to_shut) {
old.clearWorkerCount(pool, watcher);
}
for (auto const& i : this->m_pool_map) {
const auto &pool_name = i.first;
const auto &pool_data = i.second;
watcher.inform(pool_data.worker_count, pool_name, this->m_server_list,
pool_data.job_list, pool_data.job_processing_uri);
}
}
void DriveshaftConfig::clearWorkerCount(const std::string& pool_name, PoolWatcher& watcher) {
auto pool_iter = this->m_pool_map.find(pool_name);
if (pool_iter == this->m_pool_map.end()) {
LOG4CXX_ERROR(MainLogger, "clearWorkerCounts requested, " << pool_name << " does not exist in config");
throw std::runtime_error("invalid config detected in clearWorkerCounts");
}
auto& pool_data = pool_iter->second;
pool_data.worker_count = 0;
watcher.inform(0, pool_name, this->m_server_list,
pool_data.job_list, pool_data.job_processing_uri);
}
void DriveshaftConfig::clearAllWorkerCounts(PoolWatcher& watcher) {
for (const auto& i : this->m_pool_map) {
this->clearWorkerCount(i.first, watcher);
}
}
std::pair<StringSet, StringSet> DriveshaftConfig::compare(const DriveshaftConfig& that) const noexcept {
LOG4CXX_DEBUG(MainLogger, "Beginning config compare");
StringSet current_pool_names, latest_pool_names;
boost::copy(m_pool_map | boost::adaptors::map_keys,
std::inserter(current_pool_names, current_pool_names.begin()));
boost::copy(that.m_pool_map | boost::adaptors::map_keys,
std::inserter(latest_pool_names, latest_pool_names.begin()));
if (this->m_server_list != that.m_server_list) {
// Everything needs restarting
return std::pair<StringSet, StringSet>(std::move(current_pool_names),
std::move(latest_pool_names));
} else {
StringSet pools_turn_off, pools_turn_on;
// See what's present in current and missing in new. This is to be turned off.
std::set_difference(current_pool_names.begin(), current_pool_names.end(),
latest_pool_names.begin(), latest_pool_names.end(),
std::inserter(pools_turn_off, pools_turn_off.begin()));
// Reverse of above. See what's to be turned on.
std::set_difference(latest_pool_names.begin(), latest_pool_names.end(),
current_pool_names.begin(), current_pool_names.end(),
std::inserter(pools_turn_on, pools_turn_on.begin()));
// Check for changed jobs or processing URI
for (const auto& i : m_pool_map) {
auto found = that.m_pool_map.find(i.first);
if (found != that.m_pool_map.end()) {
bool should_restart = false;
if (found->second.job_processing_uri != i.second.job_processing_uri) {
should_restart = true;
} else {
const auto& lhs_jobs_set = i.second.job_list;
const auto& rhs_jobs_set = found->second.job_list;
StringSet diff;
std::set_symmetric_difference(lhs_jobs_set.begin(), lhs_jobs_set.end(),
rhs_jobs_set.begin(), rhs_jobs_set.end(),
std::inserter(diff, diff.begin()));
if (diff.size()) {
should_restart = true;
}
}
if (should_restart) {
pools_turn_off.insert(i.first);
pools_turn_on.insert(i.first);
}
}
}
return std::pair<StringSet, StringSet>(std::move(pools_turn_off), std::move(pools_turn_on));
}
}
void DriveshaftConfig::parseServerList(const Json::Value& node) {
const auto& servers_list = node[cfgkeys::GEARMAN_SERVERS_LIST];
for (auto i = servers_list.begin(); i != servers_list.end(); ++i) {
if (!i->isString()) {
LOG4CXX_ERROR(MainLogger, cfgkeys::GEARMAN_SERVERS_LIST << " does not contain strings");
throw std::runtime_error("config server list type failure");
}
const auto& name = i->asString();
this->m_server_list.insert(name);
LOG4CXX_DEBUG(MainLogger, "Read server: " << name);
}
}
void DriveshaftConfig::parsePoolList(const Json::Value& node) {
const auto& pools_list = node[cfgkeys::POOLS_LIST];
for (auto i = pools_list.begin(); i != pools_list.end(); ++i) {
const auto& pool_name = i.name();
const auto& pool_node = *i;
if (!pool_node.isMember(cfgkeys::POOL_WORKER_COUNT) ||
!pool_node.isMember(cfgkeys::POOL_JOB_LIST) ||
!pool_node.isMember(cfgkeys::POOL_JOB_PROCESSING_URI) ||
!pool_node[cfgkeys::POOL_WORKER_COUNT].isUInt() ||
!pool_node[cfgkeys::POOL_JOB_LIST].isArray() ||
!pool_node[cfgkeys::POOL_JOB_PROCESSING_URI].isString()) {
LOG4CXX_ERROR(
MainLogger,
"Config (" << m_config_filename << ") has invalid " <<
cfgkeys::POOLS_LIST << " elements: (" <<
cfgkeys::POOL_WORKER_COUNT << ", " <<
cfgkeys::POOL_JOB_PROCESSING_URI << ", " <<
cfgkeys::POOL_JOB_LIST << ")"
);
throw std::runtime_error("config jobs list parse failure");
}
auto& pool_data = this->m_pool_map[pool_name];
pool_data.worker_count = pool_node[cfgkeys::POOL_WORKER_COUNT].asUInt();
pool_data.job_processing_uri = pool_node[cfgkeys::POOL_JOB_PROCESSING_URI].asString();
LOG4CXX_DEBUG(
MainLogger,
"Read pool: " << pool_name << " with count " <<
pool_data.worker_count << " and URI " << pool_data.job_processing_uri
);
const auto& job_list = pool_node[cfgkeys::POOL_JOB_LIST];
for (auto j = job_list.begin(); j != job_list.end(); ++j) {
if (!j->isString()) {
LOG4CXX_ERROR(MainLogger, cfgkeys::POOL_JOB_LIST << " does not contain strings");
}
const auto& name = j->asString();
pool_data.job_list.insert(name);
LOG4CXX_DEBUG(MainLogger, "Pool " << pool_name << " adding job " << name);
}
}
}
bool DriveshaftConfig::needsConfigUpdate(const std::string& new_config_filename) const {
boost::filesystem::path config_path(new_config_filename);
boost::system::error_code ec;
std::time_t modified_time = boost::filesystem::last_write_time(config_path, ec);
if (ec) {
LOG4CXX_ERROR(
MainLogger,
"Unable to ascertain config mtime " << new_config_filename <<
". Error: " << ec.message()
);
throw std::runtime_error("config stat failure");
}
return modified_time > this->m_load_time;
}
std::string DriveshaftConfig::fetchFileContents(const std::string& filename) const {
std::ifstream config_filestream(filename, std::ios::in | std::ios::binary);
if (config_filestream.fail()) {
LOG4CXX_ERROR(MainLogger, "Unable to load file " << filename);
throw std::runtime_error("config read failure");
}
std::ostringstream contents;
contents << config_filestream.rdbuf();
config_filestream.close();
return contents.str();
}
bool DriveshaftConfig::validateConfigNode(const Json::Value& node) const {
using namespace cfgkeys;
if (!node.isMember(GEARMAN_SERVERS_LIST) ||
!node.isMember(POOLS_LIST)) {
LOG4CXX_ERROR(
MainLogger,
"Config is missing one or more elements (" <<
GEARMAN_SERVERS_LIST << ", " <<
POOLS_LIST << ")"
);
return false;
}
if (!node[GEARMAN_SERVERS_LIST].isArray() ||
!node[POOLS_LIST].isObject()) {
LOG4CXX_ERROR(
MainLogger,
"Config has one or more malformed elements (" <<
GEARMAN_SERVERS_LIST << ", " <<
POOLS_LIST << ")"
);
return false;
}
return true;
}
} // namespace Driveshaft
| 38.359259 | 115 | 0.615043 | tlalexan |
4e849a62bed6f7e3b8b87854d60e114f1c5e8169 | 2,282 | cpp | C++ | src/Client/States/Game/AuthenticationState.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | src/Client/States/Game/AuthenticationState.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | src/Client/States/Game/AuthenticationState.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <Client/States/Game/AuthenticationState.hpp>
#include <Client/ClientApp.hpp>
#include <Client/States/LoginState.hpp>
#include <Client/States/Game/AssetDownloadState.hpp>
namespace bw
{
AuthenticationState::AuthenticationState(std::shared_ptr<StateData> stateData, std::shared_ptr<ClientSession> clientSession) :
StatusState(std::move(stateData)),
m_clientSession(std::move(clientSession))
{
m_onAuthFailedSlot.Connect(m_clientSession->OnAuthFailure, [this](ClientSession*, const Packets::AuthFailure& /*data*/)
{
UpdateStatus("Failed to authenticate", Nz::Color::Red);
m_nextState = std::make_shared<LoginState>(GetStateDataPtr());
m_nextStateDelay = 3.f;
});
m_onAuthSucceededSlot.Connect(m_clientSession->OnAuthSuccess, [this](ClientSession*, const Packets::AuthSuccess& data)
{
UpdateStatus("Authentication succeeded, waiting for match data...", Nz::Color::White);
m_authSuccessPacket = data;
});
m_onMatchDataSlot.Connect(m_clientSession->OnMatchData, [this](ClientSession*, const Packets::MatchData& data)
{
if (!m_authSuccessPacket)
{
UpdateStatus("Protocol error", Nz::Color::Red);
m_nextState = std::make_shared<LoginState>(GetStateDataPtr());
m_nextStateDelay = 3.f;
return;
}
UpdateStatus("Received match data", Nz::Color::White);
m_nextState = std::make_shared<AssetDownloadState>(GetStateDataPtr(), m_clientSession, m_authSuccessPacket.value(), data);
m_nextStateDelay = 0.5f;
});
}
void AuthenticationState::Enter(Ndk::StateMachine& fsm)
{
StatusState::Enter(fsm);
ConfigFile& playerConfig = GetStateData().app->GetPlayerSettings();
Packets::Auth authPacket;
authPacket.players.emplace_back().nickname = playerConfig.GetStringValue("Player.Name");
m_clientSession->SendPacket(std::move(authPacket));
}
bool AuthenticationState::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
if (!StatusState::Update(fsm, elapsedTime))
return false;
if (m_nextState)
{
if ((m_nextStateDelay -= elapsedTime) < 0.f)
{
fsm.ChangeState(m_nextState);
return true;
}
}
return true;
}
}
| 29.636364 | 127 | 0.73532 | ImperatorS79 |
4e8c4643c574217df23249e076d4a0f507de4d5c | 3,026 | cpp | C++ | engine/engine.cpp | geefr/vulkan-learning | 47018427bb3322f8d6fd6c74ac4b8f0ff670b583 | [
"BSD-3-Clause"
] | null | null | null | engine/engine.cpp | geefr/vulkan-learning | 47018427bb3322f8d6fd6c74ac4b8f0ff670b583 | [
"BSD-3-Clause"
] | null | null | null | engine/engine.cpp | geefr/vulkan-learning | 47018427bb3322f8d6fd6c74ac4b8f0ff670b583 | [
"BSD-3-Clause"
] | null | null | null | /*
* Provided under the BSD 3-Clause License, see LICENSE.
*
* Copyright (c) 2020, Gareth Francis
* All rights reserved.
*/
#include "engine.h"
#include "renderer.h"
#include "node.h"
Engine::Engine()
: mRend(new Renderer(*this))
, mNodeGraph(new Node())
, mQuit(false)
{}
Engine::~Engine() {}
void Engine::run() {
initRenderer();
mNodeGraph->init(*mRend.get());
mNodeGraph->upload(*mRend.get());
mTimeStart = std::chrono::high_resolution_clock::now();
mTimeCurrent = mTimeStart;
loop();
cleanup();
}
std::shared_ptr<Node> Engine::nodegraph() { return mNodeGraph; }
void Engine::initRenderer() {
mRend->initWindow();
mRend->initVK();
}
void Engine::loop() {
while (true) {
try {
// Calculate the frame time
std::chrono::time_point<std::chrono::high_resolution_clock> current = std::chrono::high_resolution_clock::now();
auto deltaT = ((double)(current - mTimeCurrent).count()) / 1.0e9;
mTimeCurrent = current;
// Poll for events
// TODO: Just handling the window here - should poll any
// other input devices/systems like joysticks, VR controllers, etc
mEventQueue.clear();
// Renderer can request a quit here - TODO: Should really handle as a QuitEvent instance
if (!mRend->pollWindowEvents()) break;
// Handle explicit event callbacks (Not bound to any particular node/script)
callEventCallbacks();
// Renderer or other events may have asked us to stop rendering
if (mQuit) break;
// Perform the update traversal
mNodeGraph->update(*this, deltaT);
// Start the frame (Let the renderer reset what it needs)
mRend->frameStart();
// Render the scene
mNodeGraph->render(*mRend.get(), mCamera.mViewMatrix, mCamera.mProjectionMatrix);
// Finish the frame, renderer sends commands to gpu here
mRend->frameEnd();
}
catch (...) {
// Something went wrong, we don't know what but
// it's critical that we unwind the renderer's resources properly
cleanup();
// And just forward the error to whoever is listening
throw;
}
}
}
void Engine::cleanup() {
mRend->waitIdle();
mNodeGraph->cleanup(*mRend.get());
mRend->cleanup();
}
Camera& Engine::camera() { return mCamera; }
float Engine::windowWidth() const { return static_cast<float>(mRend->windowWidth()); }
float Engine::windowHeight() const { return static_cast<float>(mRend->windowHeight()); }
void Engine::addEvent(std::shared_ptr<Event> e) { mEventQueue.emplace_back(e); }
void Engine::addEvent(Event* e) { mEventQueue.emplace_back(e); }
void Engine::addGlobalEventCallback(Engine::GlobalEventCallback callback) {
mGlobalEventCallbacks.emplace_back(callback);
}
void Engine::callEventCallbacks() {
for (auto& e : mEventQueue) {
for (auto& c : mGlobalEventCallbacks) {
c(*this, *e.get());
}
}
}
const std::list<std::shared_ptr<Event>>& Engine::events() const { return mEventQueue; }
void Engine::quit() { mQuit = true; }
| 26.778761 | 118 | 0.665235 | geefr |
4e8c6449fdf88de8b6820f9925ebd7946112ca71 | 2,095 | cpp | C++ | Vic2ToHoI4/Source/HOI4World/Technologies.cpp | CarbonY26/Vic2ToHoI4 | af3684d6aaaafea81aaadfb64a21a2b696f618e1 | [
"MIT"
] | 25 | 2018-12-10T03:41:49.000Z | 2021-10-04T10:42:36.000Z | Vic2ToHoI4/Source/HOI4World/Technologies.cpp | CarbonY26/Vic2ToHoI4 | af3684d6aaaafea81aaadfb64a21a2b696f618e1 | [
"MIT"
] | 739 | 2018-12-13T02:01:20.000Z | 2022-03-28T02:57:13.000Z | Vic2ToHoI4/Source/HOI4World/Technologies.cpp | CarbonY26/Vic2ToHoI4 | af3684d6aaaafea81aaadfb64a21a2b696f618e1 | [
"MIT"
] | 43 | 2018-12-10T03:41:58.000Z | 2022-03-22T23:55:41.000Z | #include "Technologies.h"
HoI4::technologies::technologies(const Mappers::TechMapper& techMapper,
const Mappers::ResearchBonusMapper& researchBonusMapper,
const std::set<std::string>& oldTechnologiesAndInventions)
{
for (const auto& techMapping: techMapper.getTechMappings())
{
bool requirementViolated = false;
for (const auto& requirement: techMapping.getVic2Requirements())
{
if (!oldTechnologiesAndInventions.contains(requirement))
{
requirementViolated = true;
break;
}
}
if (requirementViolated)
{
continue;
}
const auto& limit = techMapping.getLimit();
for (const auto& technology: techMapping.getTechs())
{
auto [itr, inserted] = technologiesByLimits.insert(std::make_pair(limit, std::set{technology}));
if (!inserted)
{
itr->second.insert(technology);
}
}
}
for (const auto& bonusMapping: researchBonusMapper.getResearchBonusMappings())
{
bool requirementViolated = false;
for (const auto& requirement: bonusMapping.getVic2Requirements())
{
if (!oldTechnologiesAndInventions.contains(requirement))
{
requirementViolated = true;
break;
}
}
if (requirementViolated)
{
continue;
}
for (const auto& bonus: bonusMapping.getResearchBonuses())
{
setResearchBonus(bonus.first, bonus.second);
}
}
}
int HoI4::technologies::getTechnologyCount() const
{
int totalTechnologies = 0;
for (const auto& [unused, technologies]: technologiesByLimits)
{
totalTechnologies += static_cast<int>(technologies.size());
}
return totalTechnologies;
}
void HoI4::technologies::setResearchBonus(const std::string& tech, int bonus)
{
std::map<std::string, int>::iterator researchBonusEntry = researchBonuses.find(tech);
if ((researchBonusEntry == researchBonuses.end()) || (researchBonusEntry->second < bonus))
{
researchBonuses[tech] = bonus;
}
}
bool HoI4::technologies::hasTechnology(const std::string& technology) const
{
for (const auto& [unused, technologies]: technologiesByLimits)
{
if (technologies.contains(technology))
{
return true;
}
}
return false;
} | 22.526882 | 99 | 0.717422 | CarbonY26 |
4e8f378117d7cf1af642fddb5a300b0e295ecb84 | 11,861 | cc | C++ | ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc | shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 216 | 2018-09-09T11:53:56.000Z | 2022-03-19T13:41:35.000Z | ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc | gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 13 | 2018-10-23T08:29:09.000Z | 2021-09-08T06:45:34.000Z | ACAP_linux/3rd/CoMISo/NSolver/NewtonSolver.cc | shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 41 | 2018-09-13T08:50:41.000Z | 2022-02-23T00:33:54.000Z | //=============================================================================
//
// CLASS NewtonSolver - IMPLEMENTATION
//
//=============================================================================
//== INCLUDES =================================================================
#include "NewtonSolver.hh"
#include <CoMISo/Solver/CholmodSolver.hh>
#include <Base/Debug/DebTime.hh>
//== NAMESPACES ===============================================================
namespace COMISO {
//== IMPLEMENTATION ==========================================================
// solve
int
NewtonSolver::
solve(NProblemGmmInterface* _problem)
{
DEB_enter_func;
#if COMISO_SUITESPARSE_AVAILABLE
// get problem size
int n = _problem->n_unknowns();
// hesse matrix
NProblemGmmInterface::SMatrixNP H;
// gradient
std::vector<double> x(n), x_new(n), dx(n), g(n);
// get initial x, initial grad and initial f
_problem->initial_x(P(x));
double f = _problem->eval_f(P(x));
double reg = 1e-3;
COMISO::CholmodSolver chol;
for(int i=0; i<max_iters_; ++i)
{
_problem->eval_gradient(P(x), P(g));
// check for convergence
if( gmm::vect_norm2(g) < eps_)
{
DEB_line(2, "Newton Solver converged after " << i << " iterations");
_problem->store_result(P(x));
return true;
}
// get current hessian
_problem->eval_hessian(P(x), H);
// regularize
double reg_comp = reg*gmm::mat_trace(H)/double(n);
for(int j=0; j<n; ++j)
H(j,j) += reg_comp;
// solve linear system
bool factorization_ok = false;
if(constant_hessian_structure_ && i != 0)
factorization_ok = chol.update_system_gmm(H);
else
factorization_ok = chol.calc_system_gmm(H);
bool improvement = false;
if(factorization_ok)
if(chol.solve( dx, g))
{
gmm::add(x, gmm::scaled(dx,-1.0),x_new);
double f_new = _problem->eval_f(P(x_new));
if( f_new < f)
{
// swap x and x_new (and f and f_new)
x_new.swap(x);
f = f_new;
improvement = true;
DEB_line(2, "energy improved to " << f);
}
}
// adapt regularization
if(improvement)
{
if(reg > 1e-9)
reg *= 0.1;
}
else
{
if(reg < 1e4)
reg *= 10.0;
else
{
_problem->store_result(P(x));
DEB_line(2, "Newton solver reached max regularization but did not "
"converge");
return false;
}
}
}
_problem->store_result(P(x));
DEB_line(2, "Newton Solver did not converge!!! after iterations.");
return false;
#else
DEB_warning(1,"NewtonSolver requires not-available CholmodSolver");
return false;
#endif
}
//-----------------------------------------------------------------------------
int NewtonSolver::solve(NProblemInterface* _problem, const SMatrixD& _A,
const VectorD& _b)
{
DEB_time_func_def;
const double KKT_res_eps = 1e-6;
const int max_KKT_regularization_iters = 40;
double regularize_constraints_limit = 1e-6;
const double max_allowed_constraint_violation2 = 1e-12;
// number of unknowns
size_t n = _problem->n_unknowns();
// number of constraints
size_t m = _b.size();
DEB_line(2, "optimize via Newton with " << n << " unknowns and " << m <<
" linear constraints");
// initialize vectors of unknowns
VectorD x(n);
_problem->initial_x(x.data());
double initial_constraint_violation2 = (_A*x-_b).squaredNorm();
// storage of update vector dx and rhs of KKT system
VectorD dx(n+m), rhs(n+m), g(n);
rhs.setZero();
// resize temp vector for line search (and set to x1 to approx Hessian correctly if problem is non-quadratic!)
x_ls_ = x;
// indicate that system matrix is symmetric
lu_solver_.isSymmetric(true);
// start with no regularization
double regularize_hessian(0.0);
double regularize_constraints(0.0);
int iter=0;
bool first_factorization = true;
while( iter < max_iters_)
{
double kkt_res2(0.0);
double constraint_res2(0.0);
int reg_iters(0);
do
{
// get Newton search direction by solving LSE
bool fact_ok = factorize(_problem, _A, _b, x, regularize_hessian, regularize_constraints, first_factorization);
first_factorization = false;
if(fact_ok)
{
// get rhs
_problem->eval_gradient(x.data(), g.data());
rhs.head(n) = -g;
rhs.tail(m) = _b - _A*x;
// solve KKT system
solve_kkt_system(rhs, dx);
// check numerical stability of KKT system and regularize if necessary
kkt_res2 = (KKT_*dx-rhs).squaredNorm();
constraint_res2 = (_A*dx.head(n)-rhs.tail(m)).squaredNorm();
}
if(!fact_ok || kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2)
{
DEB_warning(2, "Numerical issues in KKT system");
// alternate hessian and constraints regularization
if(reg_iters % 2 == 0 || regularize_constraints >= regularize_constraints_limit)
{
DEB_line(2, "residual ^ 2 " << kkt_res2 << "->regularize hessian");
if(regularize_hessian == 0.0)
regularize_hessian = 1e-6;
else
regularize_hessian *= 2.0;
}
else
{
DEB_line(2, "residual^2 " << kkt_res2 << " -> regularize constraints");
if(regularize_constraints == 0.0)
regularize_constraints = 1e-8;
else
regularize_constraints *= 2.0;
}
}
++reg_iters;
}
while( (kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2) && reg_iters < max_KKT_regularization_iters);
// no valid step could be found?
if(kkt_res2 > KKT_res_eps || constraint_res2 > max_allowed_constraint_violation2 || reg_iters >= max_KKT_regularization_iters)
{
DEB_error("numerical issues in KKT system could not be resolved "
"-> terminating NewtonSolver with current solution");
_problem->store_result(x.data());
return 0;
}
// get maximal reasonable step
double t_max = std::min(1.0,
0.5 * _problem->max_feasible_step(x.data(), dx.data()));
// perform line-search
double newton_decrement(0.0);
double fx(0.0);
double t = backtracking_line_search(_problem, x, g, dx, newton_decrement, fx, t_max);
// perform update
x += dx.head(n)*t;
double constraint_violation2 = (_A*x-_b).squaredNorm();
if(constraint_violation2 > 2*initial_constraint_violation2 && constraint_violation2 > max_allowed_constraint_violation2)
{
DEB_warning(2, "Numerical issues in KKT system lead to "
"constraint violation -> recovery phase");
// restore old solution
x -= dx.head(n)*t;
regularize_constraints *= 0.5;
regularize_constraints_limit = regularize_constraints;
}
DEB_line(2, "iter: " << iter
<< ", f(x) = " << fx << ", t = " << t << " (tmax=" << t_max << ")"
<< (t < t_max ? " _clamped_" : "")
<< ", eps = [Newton decrement] = " << newton_decrement
<< ", constraint violation prior = " << rhs.tail(m).norm()
<< ", after = " << (_b - _A*x).norm()
<< ", KKT residual^2 = " << kkt_res2);
// converged?
if(newton_decrement < eps_ || std::abs(t) < eps_ls_)
break;
++iter;
}
// store result
_problem->store_result(x.data());
// return success
return 1;
}
//-----------------------------------------------------------------------------
bool NewtonSolver::factorize(NProblemInterface* _problem,
const SMatrixD& _A, const VectorD& _b, const VectorD& _x, double& _regularize_hessian, double& _regularize_constraints,
const bool _first_factorization)
{
DEB_enter_func;
const int n = _problem->n_unknowns();
const int m = _A.rows();
const int nf = n+m;
// get hessian of quadratic problem
SMatrixD H(n,n);
_problem->eval_hessian(_x.data(), H);
// set up KKT matrix
// create sparse matrix
std::vector< Triplet > trips;
trips.reserve(H.nonZeros() + 2*_A.nonZeros());
// add elements of H
for (int k=0; k<H.outerSize(); ++k)
for (SMatrixD::InnerIterator it(H,k); it; ++it)
trips.push_back(Triplet(it.row(),it.col(),it.value()));
// add elements of _A
for (int k=0; k<_A.outerSize(); ++k)
for (SMatrixD::InnerIterator it(_A,k); it; ++it)
{
// insert _A block below
trips.push_back(Triplet(it.row()+n,it.col(),it.value()));
// insert _A^T block right
trips.push_back(Triplet(it.col(),it.row()+n,it.value()));
}
// regularize constraints
// if(_regularize_constraints != 0.0)
for( int i=0; i<m; ++i)
trips.push_back(Triplet(n+i,n+i,_regularize_constraints));
// regularize Hessian
// if(_regularize_hessian != 0.0)
{
double ad(0.0);
for( int i=0; i<n; ++i)
ad += H.coeffRef(i,i);
ad *= _regularize_hessian/double(n);
for( int i=0; i<n; ++i)
trips.push_back(Triplet(i,i,ad));
}
// create KKT matrix
KKT_.resize(nf,nf);
KKT_.setFromTriplets(trips.begin(), trips.end());
// compute LU factorization
if(_first_factorization)
analyze_pattern(KKT_);
return numerical_factorization(KKT_);
}
//-----------------------------------------------------------------------------
double NewtonSolver::backtracking_line_search(NProblemInterface* _problem,
VectorD& _x, VectorD& _g, VectorD& _dx, double& _newton_decrement,
double& _fx, const double _t_start)
{
DEB_enter_func;
size_t n = _x.size();
// pre-compute objective
double fx = _problem->eval_f(_x.data());
// pre-compute dot product
double gtdx = _g.transpose()*_dx.head(n);
_newton_decrement = std::abs(gtdx);
// current step size
double t = _t_start;
// backtracking (stable in case of NAN and with max 100 iterations)
for(int i=0; i<100; ++i)
{
// current update
x_ls_ = _x + _dx.head(n)*t;
double fx_ls = _problem->eval_f(x_ls_.data());
if( fx_ls <= fx + alpha_ls_*t*gtdx )
{
_fx = fx_ls;
return t;
}
else
t *= beta_ls_;
}
DEB_warning(1, "line search could not find a valid step within 100 "
"iterations");
_fx = fx;
return 0.0;
}
//-----------------------------------------------------------------------------
void NewtonSolver::analyze_pattern(SMatrixD& _KKT)
{
DEB_enter_func;
switch(solver_type_)
{
case LS_EigenLU: lu_solver_.analyzePattern(_KKT); break;
#if COMISO_SUITESPARSE_AVAILABLE
case LS_Umfpack: umfpack_solver_.analyzePattern(_KKT); break;
#endif
default: DEB_warning(1, "selected linear solver not availble");
}
}
//-----------------------------------------------------------------------------
bool NewtonSolver::numerical_factorization(SMatrixD& _KKT)
{
DEB_enter_func;
switch(solver_type_)
{
case LS_EigenLU:
lu_solver_.factorize(_KKT);
return (lu_solver_.info() == Eigen::Success);
#if COMISO_SUITESPARSE_AVAILABLE
case LS_Umfpack:
umfpack_solver_.factorize(_KKT);
return (umfpack_solver_.info() == Eigen::Success);
#endif
default:
DEB_warning(1, "selected linear solver not availble!");
return false;
}
}
//-----------------------------------------------------------------------------
void NewtonSolver::solve_kkt_system(const VectorD& _rhs, VectorD& _dx)
{
DEB_enter_func;
switch(solver_type_)
{
case LS_EigenLU: _dx = lu_solver_.solve(_rhs); break;
#if COMISO_SUITESPARSE_AVAILABLE
case LS_Umfpack: _dx = umfpack_solver_.solve(_rhs); break;
#endif
default: DEB_warning(1, "selected linear solver not availble"); break;
}
}
//=============================================================================
} // namespace COMISO
//=============================================================================
| 27.329493 | 136 | 0.579715 | shubhMaheshwari |
4e9d9f7a9a6f5f95ca34946c0031440deee25059 | 2,086 | cpp | C++ | 2015/9.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | 2 | 2020-08-06T22:14:51.000Z | 2020-08-10T19:42:36.000Z | 2015/9.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | null | null | null | 2015/9.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | null | null | null | #include <iostream>
#include <string>
#include <algorithm>
int index(std::string location) {
switch(location[0]) {
case 'F':
return 2;
case 'N':
return 3;
case 'A':
switch(location[1]) {
case 'l':return 0;
case 'r':return 1;
}
break;
case 'S':
switch(location[1]) {
case 'n': return 4;
case 't': return 5;
}
break;
case 'T':
switch(location[1]) {
case 'a':return 6;
case 'r':return 7;
}
}
std::cout<<"UNKNOWN LOCATION: ";
for (unsigned i=0;i<location.size();i++) {
std::cout<<location[i]<<'('<<static_cast<int>(location[i])<<')';
}std::cout<<std::endl;
return 0;
}
int main() {
std::string location_0, location_1;
static unsigned long distances[8][8];
unsigned minimal=-1,maximal=0;
unsigned route[8] = {0,1,2,3,4,5,6,7};
while (true) {
std::getline(std::cin, location_0,' ');
if(std::cin.eof())
break;
else if (std::cin.get()!='t')
std::cout<<"ILL FORMED INPUT"<<std::endl;
else if(std::cin.get()!='o')
std::cout<<"ILL FORMED_INPUT"<<std::endl;
else if(std::cin.get()!=' ')
std::cout<<"ILL_FORMED_INPUT"<<std::endl;
std::getline(std::cin, location_1,' ');
if (std::cin.get()!='=')
std::cout<<"ILL INPUT"<<std::endl;
else if(std::cin.get() !=' ')
std::cout<<"ILL_INPUT"<<std::endl;
std::cin>>distances[index(location_0)][index(location_1)];
distances[index(location_1)][index(location_0)] = distances[index(location_0)][index(location_1)];
std::cin.get();//Gobble newline
}
do {
unsigned max = 0,min=-1;
unsigned tot_dist=0;
for (int i=0;i<8;i++) {
unsigned dummy = distances[route[i]][route[(i+1)%8]];
tot_dist += dummy;
if (dummy > max) {
max = dummy;
}
if (dummy < min) {
min = dummy;
}
}
if (tot_dist - max < minimal)
minimal = tot_dist - max;
if (tot_dist - min > maximal)
maximal = tot_dist - min;
} while (std::next_permutation(route, route+8));
std::cout<<minimal<<' '<<maximal<<std::endl;;
return 0;
}
| 24.833333 | 103 | 0.5628 | wgevaert |
4ea17060b3ee1a6c462fd96f99afe957f375c45a | 7,740 | cpp | C++ | tests/ip/address_v4.cpp | chriskohlhoff/ip-address | 38251ff2f9a2cb5e4152c7314e14d2e65e69f27d | [
"BSL-1.0"
] | 31 | 2015-01-25T13:09:27.000Z | 2021-04-22T04:58:14.000Z | tests/ip/address_v4.cpp | chriskohlhoff/ip-address | 38251ff2f9a2cb5e4152c7314e14d2e65e69f27d | [
"BSL-1.0"
] | 1 | 2018-12-06T07:06:53.000Z | 2018-12-06T07:06:53.000Z | tests/ip/address_v4.cpp | chriskohlhoff/ip-address | 38251ff2f9a2cb5e4152c7314e14d2e65e69f27d | [
"BSL-1.0"
] | 7 | 2016-01-10T07:20:12.000Z | 2021-08-07T01:22:07.000Z | //
// address_v4.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Test that header file is self-contained.
#include "std/net/ip/address_v4.hpp"
#include "../unit_test.hpp"
#include <sstream>
#include "std/net/ip/address_v6.hpp"
//------------------------------------------------------------------------------
// ip_address_v4_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all public member functions on the class
// ip::address_v4 compile and link correctly. Runtime failures are ignored.
namespace ip_address_v4_compile {
void test()
{
namespace ip = std::experimental::net::ip;
try
{
std::error_code ec;
std::string string_value;
// address_v4 constructors.
ip::address_v4 addr1;
const ip::address_v4::bytes_type const_bytes_value(127, 0, 0, 1);
ip::address_v4 addr2(const_bytes_value);
const unsigned long const_ulong_value = 0x7F000001;
ip::address_v4 addr3(const_ulong_value);
ip::address_v4 addr4("127.0.0.1");
ip::address_v4 addr5("127.0.0.1", ec);
ip::address_v4 addr6(string_value);
ip::address_v4 addr7(string_value, ec);
// address_v4 functions.
bool b = addr1.is_loopback();
(void)b;
b = addr1.is_unspecified();
(void)b;
b = addr1.is_class_a();
(void)b;
b = addr1.is_class_b();
(void)b;
b = addr1.is_class_c();
(void)b;
b = addr1.is_multicast();
(void)b;
ip::address_v4::bytes_type bytes_value = addr1.to_bytes();
(void)bytes_value;
unsigned long ulong_value = addr1.to_ulong();
(void)ulong_value;
string_value = addr1.to_string();
string_value = addr1.to_string(ec);
// address_v4 static functions.
addr1 = ip::address_v4::any();
addr1 = ip::address_v4::loopback();
addr1 = ip::address_v4::broadcast();
addr1 = ip::address_v4::broadcast(addr2, addr3);
// address_v4 comparisons.
b = (addr1 == addr2);
(void)b;
b = (addr1 != addr2);
(void)b;
b = (addr1 < addr2);
(void)b;
b = (addr1 > addr2);
(void)b;
b = (addr1 <= addr2);
(void)b;
b = (addr1 >= addr2);
(void)b;
// address_v4 creation.
addr1 = ip::make_address_v4(const_bytes_value);
addr1 = ip::make_address_v4(const_ulong_value);
addr1 = ip::make_address_v4(ip::v4_mapped, ip::address_v6());
addr1 = ip::make_address_v4("127.0.0.1");
addr1 = ip::make_address_v4("127.0.0.1", ec);
addr1 = ip::make_address_v4(string_value);
addr1 = ip::make_address_v4(string_value, ec);
// address_v4 I/O.
std::ostringstream os;
os << addr1;
std::wostringstream wos;
wos << addr1;
}
catch (std::exception&)
{
}
}
} // namespace ip_address_v4_compile
//------------------------------------------------------------------------------
// ip_address_v4_runtime test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that the various public member functions meet the
// necessary postconditions.
namespace ip_address_v4_runtime {
void test()
{
using std::experimental::net::ip::address_v4;
address_v4 a1;
STDNET_CHECK(a1.to_bytes()[0] == 0);
STDNET_CHECK(a1.to_bytes()[1] == 0);
STDNET_CHECK(a1.to_bytes()[2] == 0);
STDNET_CHECK(a1.to_bytes()[3] == 0);
STDNET_CHECK(a1.to_ulong() == 0);
address_v4::bytes_type b1(1, 2, 3, 4);
address_v4 a2(b1);
STDNET_CHECK(a2.to_bytes()[0] == 1);
STDNET_CHECK(a2.to_bytes()[1] == 2);
STDNET_CHECK(a2.to_bytes()[2] == 3);
STDNET_CHECK(a2.to_bytes()[3] == 4);
STDNET_CHECK(((a2.to_ulong() >> 24) & 0xFF) == b1[0]);
STDNET_CHECK(((a2.to_ulong() >> 16) & 0xFF) == b1[1]);
STDNET_CHECK(((a2.to_ulong() >> 8) & 0xFF) == b1[2]);
STDNET_CHECK((a2.to_ulong() & 0xFF) == b1[3]);
address_v4 a3(0x01020304);
STDNET_CHECK(a3.to_bytes()[0] == 1);
STDNET_CHECK(a3.to_bytes()[1] == 2);
STDNET_CHECK(a3.to_bytes()[2] == 3);
STDNET_CHECK(a3.to_bytes()[3] == 4);
STDNET_CHECK(a3.to_ulong() == 0x01020304);
STDNET_CHECK(address_v4(0x7F000001).is_loopback());
STDNET_CHECK(address_v4(0x7F000002).is_loopback());
STDNET_CHECK(!address_v4(0x00000000).is_loopback());
STDNET_CHECK(!address_v4(0x01020304).is_loopback());
STDNET_CHECK(address_v4(0x00000000).is_unspecified());
STDNET_CHECK(!address_v4(0x7F000001).is_unspecified());
STDNET_CHECK(!address_v4(0x01020304).is_unspecified());
STDNET_CHECK(address_v4(0x01000000).is_class_a());
STDNET_CHECK(address_v4(0x7F000000).is_class_a());
STDNET_CHECK(!address_v4(0x80000000).is_class_a());
STDNET_CHECK(!address_v4(0xBFFF0000).is_class_a());
STDNET_CHECK(!address_v4(0xC0000000).is_class_a());
STDNET_CHECK(!address_v4(0xDFFFFF00).is_class_a());
STDNET_CHECK(!address_v4(0xE0000000).is_class_a());
STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_a());
STDNET_CHECK(!address_v4(0xF0000000).is_class_a());
STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_a());
STDNET_CHECK(!address_v4(0x01000000).is_class_b());
STDNET_CHECK(!address_v4(0x7F000000).is_class_b());
STDNET_CHECK(address_v4(0x80000000).is_class_b());
STDNET_CHECK(address_v4(0xBFFF0000).is_class_b());
STDNET_CHECK(!address_v4(0xC0000000).is_class_b());
STDNET_CHECK(!address_v4(0xDFFFFF00).is_class_b());
STDNET_CHECK(!address_v4(0xE0000000).is_class_b());
STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_b());
STDNET_CHECK(!address_v4(0xF0000000).is_class_b());
STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_b());
STDNET_CHECK(!address_v4(0x01000000).is_class_c());
STDNET_CHECK(!address_v4(0x7F000000).is_class_c());
STDNET_CHECK(!address_v4(0x80000000).is_class_c());
STDNET_CHECK(!address_v4(0xBFFF0000).is_class_c());
STDNET_CHECK(address_v4(0xC0000000).is_class_c());
STDNET_CHECK(address_v4(0xDFFFFF00).is_class_c());
STDNET_CHECK(!address_v4(0xE0000000).is_class_c());
STDNET_CHECK(!address_v4(0xEFFFFFFF).is_class_c());
STDNET_CHECK(!address_v4(0xF0000000).is_class_c());
STDNET_CHECK(!address_v4(0xFFFFFFFF).is_class_c());
STDNET_CHECK(!address_v4(0x01000000).is_multicast());
STDNET_CHECK(!address_v4(0x7F000000).is_multicast());
STDNET_CHECK(!address_v4(0x80000000).is_multicast());
STDNET_CHECK(!address_v4(0xBFFF0000).is_multicast());
STDNET_CHECK(!address_v4(0xC0000000).is_multicast());
STDNET_CHECK(!address_v4(0xDFFFFF00).is_multicast());
STDNET_CHECK(address_v4(0xE0000000).is_multicast());
STDNET_CHECK(address_v4(0xEFFFFFFF).is_multicast());
STDNET_CHECK(!address_v4(0xF0000000).is_multicast());
STDNET_CHECK(!address_v4(0xFFFFFFFF).is_multicast());
address_v4 a4 = address_v4::any();
STDNET_CHECK(a4.to_bytes()[0] == 0);
STDNET_CHECK(a4.to_bytes()[1] == 0);
STDNET_CHECK(a4.to_bytes()[2] == 0);
STDNET_CHECK(a4.to_bytes()[3] == 0);
STDNET_CHECK(a4.to_ulong() == 0);
address_v4 a5 = address_v4::loopback();
STDNET_CHECK(a5.to_bytes()[0] == 0x7F);
STDNET_CHECK(a5.to_bytes()[1] == 0);
STDNET_CHECK(a5.to_bytes()[2] == 0);
STDNET_CHECK(a5.to_bytes()[3] == 0x01);
STDNET_CHECK(a5.to_ulong() == 0x7F000001);
address_v4 a6 = address_v4::broadcast();
STDNET_CHECK(a6.to_bytes()[0] == 0xFF);
STDNET_CHECK(a6.to_bytes()[1] == 0xFF);
STDNET_CHECK(a6.to_bytes()[2] == 0xFF);
STDNET_CHECK(a6.to_bytes()[3] == 0xFF);
STDNET_CHECK(a6.to_ulong() == 0xFFFFFFFF);
}
} // namespace ip_address_v4_runtime
//------------------------------------------------------------------------------
STDNET_TEST_SUITE
(
"ip/address_v4",
STDNET_TEST_CASE(ip_address_v4_compile::test)
STDNET_TEST_CASE(ip_address_v4_runtime::test)
)
| 30.352941 | 80 | 0.669121 | chriskohlhoff |
4ea7caa0902b92b741a1d815d0e82c3879e9dc0f | 306 | cpp | C++ | Wumpus.cpp | GoldenMean58/wumpus | 51d7b850523383f1f1d4304c8fc763d58205f641 | [
"Apache-2.0"
] | null | null | null | Wumpus.cpp | GoldenMean58/wumpus | 51d7b850523383f1f1d4304c8fc763d58205f641 | [
"Apache-2.0"
] | null | null | null | Wumpus.cpp | GoldenMean58/wumpus | 51d7b850523383f1f1d4304c8fc763d58205f641 | [
"Apache-2.0"
] | null | null | null | #include "Wumpus.h"
Wumpus::Wumpus() : _dead(false) { this->_type = ObjectType::WumpusType; }
Wumpus::Wumpus(int x, int y) : _dead(false) {
this->_x = x;
this->_y = y;
this->_type = ObjectType::WumpusType;
}
bool Wumpus::is_dead() { return this->_dead; }
void Wumpus::kill() { this->_dead = true; }
| 27.818182 | 73 | 0.643791 | GoldenMean58 |
4eaa821ea34976f9846029924a4311c94415d791 | 514 | cpp | C++ | src/OpenLoco/Map/SurfaceTile.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 180 | 2018-01-18T07:56:44.000Z | 2019-02-18T21:33:45.000Z | src/OpenLoco/Map/SurfaceTile.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 186 | 2018-01-18T13:17:58.000Z | 2019-02-10T12:28:35.000Z | src/OpenLoco/Map/SurfaceTile.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 35 | 2018-01-18T12:38:26.000Z | 2018-11-14T16:01:32.000Z | #include "../TownManager.h"
#include "../ViewportManager.h"
#include "TileManager.h"
namespace OpenLoco::Map
{
void SurfaceElement::removeIndustry(const Map::Pos2& pos)
{
if (hasHighTypeFlag())
{
setHighTypeFlag(false);
setVar6SLR5(0);
setIndustry(IndustryId(0));
auto z = baseHeight();
Ui::ViewportManager::invalidate(pos, z, z + 32, ZoomLevel::eighth);
TownManager::sub_497DC1(pos, 0, 0, -30, 0);
}
}
}
| 25.7 | 79 | 0.568093 | JimmyAllnighter |
4eaadad1ebb68857cb29ffd0c08d0f1b294c64be | 1,309 | cpp | C++ | Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 387 | 2016-10-04T03:30:38.000Z | 2022-03-31T15:42:29.000Z | Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 9 | 2017-04-04T04:23:47.000Z | 2020-07-11T05:05:54.000Z | Arcane/src/Arcane/Graphics/IBL/ReflectionProbe.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 36 | 2017-07-02T07:11:40.000Z | 2022-03-08T01:49:24.000Z | #include "arcpch.h"
#include "ReflectionProbe.h"
#include <Arcane/Graphics/Shader.h>
#include <Arcane/Graphics/Texture/Texture.h>
#include <Arcane/Graphics/Texture/Cubemap.h>
namespace Arcane
{
Texture* ReflectionProbe::s_BRDF_LUT = nullptr;
ReflectionProbe::ReflectionProbe(glm::vec3 &probePosition, glm::vec2 &probeResolution)
: m_Position(probePosition), m_ProbeResolution(probeResolution), m_Generated(false), m_PrefilterMap(nullptr)
{}
ReflectionProbe::~ReflectionProbe() {
delete m_PrefilterMap;
}
void ReflectionProbe::Generate() {
// Generate the HDR reflection probe and set the generated flag
CubemapSettings settings;
settings.TextureFormat = GL_RGBA16F;
settings.TextureMinificationFilterMode = GL_LINEAR_MIPMAP_LINEAR;
settings.HasMips = true;
m_PrefilterMap = new Cubemap(settings);
for (int i = 0; i < 6; i++) {
m_PrefilterMap->GenerateCubemapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, (unsigned int)m_ProbeResolution.x, (unsigned int)m_ProbeResolution.y, GL_RGB, nullptr);
}
m_Generated = true;
}
void ReflectionProbe::Bind(Shader *shader) {
shader->SetUniform("reflectionProbeMipCount", REFLECTION_PROBE_MIP_COUNT);
m_PrefilterMap->Bind(2);
shader->SetUniform("prefilterMap", 2);
s_BRDF_LUT->Bind(3);
shader->SetUniform("brdfLUT", 3);
}
}
| 29.75 | 162 | 0.760886 | flygod1159 |
4eb1e5f442196822ac2f9b707c440f7676220cab | 593 | cpp | C++ | src/problem132/Solution.cpp | MyYaYa/leetcode | d779c215516ede594267b15abdfba5a47dc879dd | [
"Apache-2.0"
] | 1 | 2016-09-29T14:23:59.000Z | 2016-09-29T14:23:59.000Z | src/problem132/Solution.cpp | MyYaYa/leetcode | d779c215516ede594267b15abdfba5a47dc879dd | [
"Apache-2.0"
] | null | null | null | src/problem132/Solution.cpp | MyYaYa/leetcode | d779c215516ede594267b15abdfba5a47dc879dd | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int minCut(string s) {
if (s == "")
return 0;
vector<int> dp(s.size() + 1, 0);
dp[s.size()] = -1;
vector<vector<bool>> bm(s.size(), vector<bool>(s.size(), false));
for (int i = s.size() - 1; i >= 0; --i) {
dp[i] = INT_MAX;
for (int j = i; j < s.size(); ++j) {
if (s[j] == s[i] && (j - i < 2 || bm[i+1][j-1])) {
bm[i][j] = true;
dp[i] = min(dp[i], dp[j+1]+1);
}
}
}
return dp[0];
}
};
| 28.238095 | 73 | 0.338954 | MyYaYa |
4ebb6cda05e82a436aa0724f8a471ce93d50e1b4 | 4,537 | cpp | C++ | src/core/LoaderComponent.cpp | talesm/glBoilerplate | 46d8f418408290698e3f889b8cc053ac7ce4c824 | [
"MIT"
] | null | null | null | src/core/LoaderComponent.cpp | talesm/glBoilerplate | 46d8f418408290698e3f889b8cc053ac7ce4c824 | [
"MIT"
] | null | null | null | src/core/LoaderComponent.cpp | talesm/glBoilerplate | 46d8f418408290698e3f889b8cc053ac7ce4c824 | [
"MIT"
] | null | null | null | #include "LoaderComponent.hpp"
#include "Camera.hpp"
#include "SceneDetail.hpp"
#include "util/fastMath.hpp"
using namespace std;
inline int
getAreaToReload(int offset)
{
int areaToReload = abs(offset) - (CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA);
int remaining = areaToReload % CHUNK_LOAD_DELTA;
if (remaining) {
return areaToReload + CHUNK_LOAD_DELTA - remaining;
}
return areaToReload;
}
template<int axisI, int axisJ = (axisI + 1) % 3, int axisK = (axisI + 2) % 3>
void
checkAndRefreshChunk(Chunk* chunk,
SceneLoader& generator,
glm::ivec3& center,
const glm::ivec3& delta)
{
if (delta[axisI] < -(CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA)) {
int areaToReload = getAreaToReload(delta[axisI]);
center[axisI] -= areaToReload;
int r = floorMod(center[axisJ] - CHUNK_HALF_SIDE, CHUNK_SIDE);
int q = floorMod(center[axisK] - CHUNK_HALF_SIDE, CHUNK_SIDE);
glm::ivec3 lBound, hBound, offset;
lBound[axisI] = CHUNK_SIDE - areaToReload;
lBound[axisJ] = r;
lBound[axisK] = q;
hBound[axisI] = CHUNK_SIDE;
hBound[axisJ] = CHUNK_SIDE;
hBound[axisK] = CHUNK_SIDE;
offset[axisI] = center[axisI] - CHUNK_SIDE * 3 / 2 + areaToReload;
offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
if (r) {
lBound[axisJ] = 0;
lBound[axisK] = q;
hBound[axisJ] = r;
hBound[axisK] = CHUNK_SIDE;
offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
}
if (q) {
lBound[axisJ] = r;
lBound[axisK] = 0;
hBound[axisJ] = CHUNK_SIDE;
hBound[axisK] = q;
offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
if (r) {
lBound[axisJ] = 0;
lBound[axisK] = 0;
hBound[axisJ] = r;
hBound[axisK] = q;
offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
}
}
} else if (delta[axisI] >= (CHUNK_HALF_SIDE - CHUNK_LOAD_DELTA)) {
int areaToReload = getAreaToReload(delta[axisI]);
center[axisI] += areaToReload;
int r = floorMod(center[axisJ] - CHUNK_HALF_SIDE, CHUNK_SIDE);
int q = floorMod(center[axisK] - CHUNK_HALF_SIDE, CHUNK_SIDE);
glm::ivec3 lBound, hBound, offset;
lBound[axisI] = 0;
lBound[axisJ] = r;
lBound[axisK] = q;
hBound[axisI] = areaToReload;
hBound[axisJ] = CHUNK_SIDE;
hBound[axisK] = CHUNK_SIDE;
offset[axisI] = center[axisI] - CHUNK_HALF_SIDE + areaToReload;
offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
if (r) {
lBound[axisJ] = 0;
lBound[axisK] = q;
hBound[axisJ] = r;
hBound[axisK] = CHUNK_SIDE;
offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] - CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
}
if (q) {
lBound[axisJ] = r;
lBound[axisK] = 0;
hBound[axisJ] = CHUNK_SIDE;
hBound[axisK] = q;
offset[axisJ] = center[axisJ] - CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
if (r) {
lBound[axisJ] = 0;
lBound[axisK] = 0;
hBound[axisJ] = r;
hBound[axisK] = q;
offset[axisJ] = center[axisJ] + CHUNK_HALF_SIDE - r;
offset[axisK] = center[axisK] + CHUNK_HALF_SIDE - q;
generator(lBound, hBound, offset, chunk);
}
}
}
}
void
LoaderComponent::onUpdate(float delta)
{
if (!generator)
return;
glm::ivec3 offset = glm::ivec3(scene()->camera->position()) - center;
auto& chunk = scene()->chunk;
checkAndRefreshChunk<0>(&chunk, generator, center, offset);
checkAndRefreshChunk<1>(&chunk, generator, center, offset);
checkAndRefreshChunk<2>(&chunk, generator, center, offset);
}
void
LoaderComponent::reset()
{
if (!generator) {
return;
}
center = glm::ivec3(CHUNK_SIDE / 2);
generator(
glm::ivec3(0), glm::vec3(CHUNK_SIDE), glm::vec3(0), &scene()->chunk);
}
| 33.116788 | 77 | 0.616046 | talesm |
4ec06cb47d3b5f9e5853c6ee73687c2ec1d8cfff | 226,398 | cpp | C++ | test/grapheme_iterator_06.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | null | null | null | test/grapheme_iterator_06.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | 1 | 2021-03-05T12:56:59.000Z | 2021-03-05T13:11:53.000Z | test/grapheme_iterator_06.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | 3 | 2019-10-30T18:38:15.000Z | 2021-03-05T12:10:13.000Z | // Warning! This file is autogenerated.
#include <boost/text/grapheme_iterator.hpp>
#include <boost/text/transcode_iterator.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(grapheme, iterator_06_0_fwd)
{
// ÷ 0903 ÷ AC01 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_0_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_0_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_0_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_0_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0xAC01 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_1_fwd)
{
// ÷ 0903 × 0308 ÷ AC01 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_1_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_1_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_1_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_1_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0308, 0xAC01 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_2_fwd)
{
// ÷ 0903 ÷ 231A ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] WATCH (ExtPict) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_2_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_2_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_2_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_2_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x231A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_3_fwd)
{
// ÷ 0903 × 0308 ÷ 231A ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] WATCH (ExtPict) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_3_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_3_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_3_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_3_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0308, 0x231A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_4_fwd)
{
// ÷ 0903 × 0300 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_4_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_4_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_4_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_4_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0300 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_5_fwd)
{
// ÷ 0903 × 0308 × 0300 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_5_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_5_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_5_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_5_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0308, 0x0300 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_6_fwd)
{
// ÷ 0903 × 200D ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_6_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_6_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_6_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_6_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x200D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_7_fwd)
{
// ÷ 0903 × 0308 × 200D ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_7_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_7_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_7_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_7_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0308, 0x200D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_8_fwd)
{
// ÷ 0903 ÷ 0378 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_8_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_8_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_8_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_8_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0378 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_9_fwd)
{
// ÷ 0903 × 0308 ÷ 0378 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_9_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_9_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_9_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_9_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x0903, 0x0308, 0x0378 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_10_fwd)
{
// ÷ 0903 ÷ D800 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_10_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_10_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_10_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
// Skipping from-utf8 test due to presence of surrogate code point.
TEST(grapheme, iterator_06_11_fwd)
{
// ÷ 0903 × 0308 ÷ D800 ÷
// ÷ [0.2] DEVANAGARI SIGN VISARGA (SpacingMark) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_11_rev)
{
{
// reverse
uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_11_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_11_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x0903, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
// Skipping from-utf8 test due to presence of surrogate code point.
TEST(grapheme, iterator_06_12_fwd)
{
// ÷ 1100 ÷ 0020 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] SPACE (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_12_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_12_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_12_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_12_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0020 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_13_fwd)
{
// ÷ 1100 × 0308 ÷ 0020 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] SPACE (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_13_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_13_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_13_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_13_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0020 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_14_fwd)
{
// ÷ 1100 ÷ 000D ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_14_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_14_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_14_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_14_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x000D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_15_fwd)
{
// ÷ 1100 × 0308 ÷ 000D ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_15_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_15_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_15_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x000D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_15_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x000D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_16_fwd)
{
// ÷ 1100 ÷ 000A ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_16_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_16_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_16_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_16_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x000A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_17_fwd)
{
// ÷ 1100 × 0308 ÷ 000A ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_17_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_17_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_17_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x000A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_17_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x000A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_18_fwd)
{
// ÷ 1100 ÷ 0001 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_18_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_18_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_18_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_18_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0001 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_19_fwd)
{
// ÷ 1100 × 0308 ÷ 0001 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_19_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_19_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_19_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_19_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0001 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_20_fwd)
{
// ÷ 1100 × 034F ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_20_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_20_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_20_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_20_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x034F };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_21_fwd)
{
// ÷ 1100 × 0308 × 034F ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_21_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_21_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_21_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x034F };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_21_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x034F };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_22_fwd)
{
// ÷ 1100 ÷ 1F1E6 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_22_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_22_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_22_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_22_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x1F1E6 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_23_fwd)
{
// ÷ 1100 × 0308 ÷ 1F1E6 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_23_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_23_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_23_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_23_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x1F1E6 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_24_fwd)
{
// ÷ 1100 ÷ 0600 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_24_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_24_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_24_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_24_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0600 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_25_fwd)
{
// ÷ 1100 × 0308 ÷ 0600 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_25_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_25_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_25_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_25_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0600 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_26_fwd)
{
// ÷ 1100 × 0903 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_26_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_26_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_26_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_26_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0903 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_27_fwd)
{
// ÷ 1100 × 0308 × 0903 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_27_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_27_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_27_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_27_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0903 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_28_fwd)
{
// ÷ 1100 × 1100 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_28_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_28_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_28_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_28_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x1100 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_29_fwd)
{
// ÷ 1100 × 0308 ÷ 1100 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_29_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_29_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_29_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_29_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x1100 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_30_fwd)
{
// ÷ 1100 × 1160 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_30_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_30_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_30_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_30_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x1160 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_31_fwd)
{
// ÷ 1100 × 0308 ÷ 1160 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_31_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_31_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_31_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_31_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x1160 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_32_fwd)
{
// ÷ 1100 ÷ 11A8 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_32_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_32_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_32_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_32_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x11A8 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_33_fwd)
{
// ÷ 1100 × 0308 ÷ 11A8 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_33_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_33_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_33_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_33_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x11A8 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_34_fwd)
{
// ÷ 1100 × AC00 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GA (LV) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_34_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_34_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_34_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_34_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0xAC00 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_35_fwd)
{
// ÷ 1100 × 0308 ÷ AC00 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_35_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_35_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_35_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_35_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC00 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_36_fwd)
{
// ÷ 1100 × AC01 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [6.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_36_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_36_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_36_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_36_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0xAC01 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_37_fwd)
{
// ÷ 1100 × 0308 ÷ AC01 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_37_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_37_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_37_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_37_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0xAC01 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_38_fwd)
{
// ÷ 1100 ÷ 231A ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] WATCH (ExtPict) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_38_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_38_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_38_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_38_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x231A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_39_fwd)
{
// ÷ 1100 × 0308 ÷ 231A ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] WATCH (ExtPict) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_39_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_39_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_39_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x231A };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_39_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x231A };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_40_fwd)
{
// ÷ 1100 × 0300 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_40_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_40_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_40_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_40_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0300 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_41_fwd)
{
// ÷ 1100 × 0308 × 0300 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_41_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_41_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_41_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_41_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0300 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_42_fwd)
{
// ÷ 1100 × 200D ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_42_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_42_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_42_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_42_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x200D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_43_fwd)
{
// ÷ 1100 × 0308 × 200D ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_43_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_43_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
}
}
TEST(grapheme, iterator_06_43_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x200D };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_43_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x200D };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_44_fwd)
{
// ÷ 1100 ÷ 0378 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_44_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_44_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_44_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_44_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0378 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_45_fwd)
{
// ÷ 1100 × 0308 ÷ 0378 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_45_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_45_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_45_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_45_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1100, 0x0308, 0x0378 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_46_fwd)
{
// ÷ 1100 ÷ D800 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_46_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_46_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_46_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
// Skipping from-utf8 test due to presence of surrogate code point.
TEST(grapheme, iterator_06_47_fwd)
{
// ÷ 1100 × 0308 ÷ D800 ÷
// ÷ [0.2] HANGUL CHOSEONG KIYEOK (L) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3]
{
uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_47_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_47_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_47_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1100, 0x0308, 0xD800 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
// Skipping from-utf8 test due to presence of surrogate code point.
TEST(grapheme, iterator_06_48_fwd)
{
// ÷ 1160 ÷ 0020 ÷
// ÷ [0.2] HANGUL JUNGSEONG FILLER (V) ÷ [999.0] SPACE (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1160, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_48_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1160, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_48_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1160, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 2);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
}
}
TEST(grapheme, iterator_06_48_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1160, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 2, cps + 2);
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 1);
++it;
EXPECT_EQ(it.base(), cps + 1);
EXPECT_EQ((*it).begin(), cps + 1);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_48_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1160, 0x0020 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 2),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 2, cps + 2),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[1]);
++it;
EXPECT_EQ(*it.base(), cps[1]);
EXPECT_EQ(*it->begin(), cps[1]);
EXPECT_EQ(it.base().base(), cus + cp_indices[1]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[1]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_49_fwd)
{
// ÷ 1160 × 0308 ÷ 0020 ÷
// ÷ [0.2] HANGUL JUNGSEONG FILLER (V) × [9.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] SPACE (Other) ÷ [0.3]
{
uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_49_rev)
{
{
// reverse
uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_49_fab)
{
{
// forth and back
uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps, cps + 3);
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
}
}
TEST(grapheme, iterator_06_49_baf)
{
{
// back and forth
uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 };
boost::text::grapheme_iterator<uint32_t const *> it(cps, cps + 3, cps + 3);
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
--it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
--it;
EXPECT_EQ(it.base(), cps + 0);
EXPECT_EQ((*it).begin(), cps + 0);
EXPECT_EQ((*it).end(), cps + 2);
++it;
EXPECT_EQ(it.base(), cps + 2);
EXPECT_EQ((*it).begin(), cps + 2);
EXPECT_EQ((*it).end(), cps + 3);
++it;
EXPECT_EQ(it.base(), cps + 3);
EXPECT_EQ((*it).begin(), (*it).end());
}
}
TEST(grapheme, iterator_06_49_utf8)
{
{
// from UTF8
uint32_t const cps[] = { 0x1160, 0x0308, 0x0020 };
char cus[1024] = { 0 };
int cp_indices[1024] = { 0 };
std::copy(
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps, cps + 3),
boost::text::utf_32_to_8_iterator<uint32_t const *>(cps, cps + 3, cps + 3),
cus);
boost::text::null_sentinel sentinel;
int * index_it = cp_indices;
for (boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel> it(cus, cus, boost::text::null_sentinel{}); ; ++it) {
*index_it++ = it.base() - cus;
if (it == sentinel)
break;
}
using iter_t = boost::text::utf_8_to_32_iterator<char const *, boost::text::null_sentinel>;
boost::text::grapheme_iterator<iter_t, boost::text::null_sentinel> it(
iter_t{cus, cus, boost::text::null_sentinel{}}, iter_t{cus, cus, boost::text::null_sentinel{}}, sentinel);
EXPECT_EQ(*it.base(), cps[0]);
EXPECT_EQ(*it->begin(), cps[0]);
EXPECT_EQ(*it->end(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[0]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[0]);
EXPECT_EQ(it->end().base(), cus + cp_indices[2]);
++it;
EXPECT_EQ(*it.base(), cps[2]);
EXPECT_EQ(*it->begin(), cps[2]);
EXPECT_EQ(it.base().base(), cus + cp_indices[2]);
EXPECT_EQ(it->begin().base(), cus + cp_indices[2]);
EXPECT_EQ(it->end().base(), cus + cp_indices[3]);
++it;
EXPECT_EQ(it.base().base(), cus + cp_indices[3]);
EXPECT_EQ(it->begin(), (*it).end());
}
}
| 28.148452 | 157 | 0.502959 | eightysquirrels |
4ec2ce4271211ca8b20a2ff6db692b3ce2e98d99 | 5,994 | cpp | C++ | src/joystick.cpp | allender/emulator | 8310afee84b74cff7d91ecd78f7976264a8df900 | [
"MIT"
] | 53 | 2017-01-19T08:08:40.000Z | 2022-01-26T03:01:24.000Z | src/joystick.cpp | allender/emulator | 8310afee84b74cff7d91ecd78f7976264a8df900 | [
"MIT"
] | 15 | 2017-03-10T22:55:53.000Z | 2021-04-14T13:29:38.000Z | src/joystick.cpp | allender/emulator | 8310afee84b74cff7d91ecd78f7976264a8df900 | [
"MIT"
] | 1 | 2019-07-09T07:19:53.000Z | 2019-07-09T07:19:53.000Z | /*
MIT License
Copyright (c) 2016-2017 Mark Allender
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include "SDL.h"
#include "apple2emu_defs.h"
#include "apple2emu.h"
#include "memory.h"
#include "joystick.h"
static int Num_controllers;
static const char *Game_controller_mapping_file = "gamecontrollerdb.txt";
// information for joysticks
class controller {
public:
bool m_initialized; // is this joystick initialized
SDL_GameController *m_gc; // pointer to game controller structure
const char *m_name; // name of controller
int8_t m_button_state[SDL_CONTROLLER_BUTTON_MAX];
int16_t m_axis_state[SDL_CONTROLLER_AXIS_MAX];
uint32_t m_axis_timer_state[SDL_CONTROLLER_AXIS_MAX];
SDL_GameControllerButton m_buttons[SDL_CONTROLLER_BUTTON_MAX]; // mapping from button number to button enum
SDL_GameControllerAxis m_axis[SDL_CONTROLLER_AXIS_MAX]; // mapping from axis number to axis enum
controller() :m_initialized(false) {};
};
const float Joystick_cycles_scale = 2816.0f / 255.0f; // ~2816 total cycles for 558 timer
const int Max_controllers = 16;
controller Controllers[Max_controllers];
// reads the status of button num from the joystick structures
static uint8_t joystick_read_button(int button_num)
{
uint8_t val = SDL_GameControllerGetButton(Controllers[0].m_gc, Controllers[0].m_buttons[button_num]);
// signals is active low. So return 0 when on, and high bit set when not
return val ? 0x80 : 0;
}
static uint8_t joystick_read_axis(int axis_num)
{
// timer state for paddles is controlled by ths number of cycles. The axis
// timer state will have been previously set to the total cycles run
// plus the axis value * number of cycles
if (Total_cycles < Controllers[0].m_axis_timer_state[axis_num]) {
return 0x80;
}
return 0;
}
uint8_t joystick_soft_switch_handler(uint16_t addr, uint8_t val, bool write)
{
UNREFERENCED(write);
UNREFERENCED(val);
uint8_t return_val = 0;
addr = addr & 0xff;
switch (addr) {
case 0x61:
case 0x62:
case 0x63:
return_val = joystick_read_button(addr - 0x61);
break;
case 0x64:
case 0x65:
case 0x66:
case 0x67:
return_val = joystick_read_axis(addr - 0x64);
break;
// this function initiates the analog to digital conversion from the
// controllers (paddles/joysticks) to 0-255 digital value which will
// be read from the axis read handler. Basically set up
// internal timer to indicate when the 558 timer should time out
// based on the paddle/joystick value. Read Inside the Apple ][e
// chapter 10 for more information
case 0x70:
// set the axis timer state to be current cycle count
// plus the cycle count when the timer should time out.
// The internal paddle read routine reads every 11ms
for (auto i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) {
int16_t value = SDL_GameControllerGetAxis(Controllers[0].m_gc, Controllers[0].m_axis[i]);
value = (uint16_t)(floor((float)(value + 32768) * (float)(255.0f / 65535.0f)));
// from kegs and other emulators. I need to dig into why this is necessary because
// based on timings, it should not work like this. Currently, I am getting a value
// back from the pdl read code of around 235 when axis at max value (instead of
// 255). So this code (as is in other emulators) will force us to get to 255. But
// seems like we should solve this the real way with timing.
if (value >= 255) {
value = 280;
}
Controllers[0].m_axis_timer_state[i] = Total_cycles + uint32_t(value * Joystick_cycles_scale);
}
}
if (write) {
return 0;
}
return return_val | memory_read_floating_bus();
}
void joystick_init()
{
// load game controller mappings
int num_mappings = SDL_GameControllerAddMappingsFromFile(Game_controller_mapping_file);
if (num_mappings == -1) {
printf("Unable to load mappings file %s for SDL game controllers.\n", Game_controller_mapping_file);
return;
}
Num_controllers = SDL_NumJoysticks();
for (auto i = 0; i < Num_controllers; i++) {
if (SDL_IsGameController(i)) {
Controllers[i].m_gc = SDL_GameControllerOpen(i);
if (Controllers[i].m_gc != nullptr) {
Controllers[i].m_initialized = true;
Controllers[i].m_name = SDL_GameControllerNameForIndex(i);
for (auto j = 0; j < SDL_CONTROLLER_BUTTON_MAX; j++) {
Controllers[i].m_button_state[j] = 0;
Controllers[i].m_buttons[j] = static_cast<SDL_GameControllerButton>(static_cast<int>(SDL_CONTROLLER_BUTTON_A) + j);
}
for (auto j = 0; j < SDL_CONTROLLER_AXIS_MAX; j++) {
Controllers[i].m_axis_state[j] = 0;
Controllers[i].m_axis_timer_state[j] = 0;
Controllers[i].m_axis[j] = static_cast<SDL_GameControllerAxis>(static_cast<int>(SDL_CONTROLLER_AXIS_LEFTX) + j);
}
}
}
}
}
void joystick_shutdown()
{
for (auto i = 0; i < Num_controllers; i++) {
if (Controllers[i].m_initialized == true) {
SDL_GameControllerClose(Controllers[i].m_gc);
}
}
}
| 35.467456 | 120 | 0.72973 | allender |
4ec80fde7b7c5457c8fbd6f93bd04ec2013f1625 | 100,040 | cpp | C++ | src/parallel/PetscSolverFeti.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | src/parallel/PetscSolverFeti.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | src/parallel/PetscSolverFeti.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | /******************************************************************************
*
* AMDiS - Adaptive multidimensional simulations
*
* Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
* Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
*
* Authors:
* Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*
* This file is part of AMDiS
*
* See also license.opensource.txt in the distribution.
*
******************************************************************************/
#include "MatrixVector.h"
#include "parallel/PetscHelper.hpp"
#include "parallel/PetscSolverFeti.hpp"
#include "parallel/PetscSolverFetiDebug.hpp"
#include "parallel/PetscSolverFetiMonitor.hpp"
#include "parallel/PetscSolverFetiStructs.hpp"
#include "parallel/PetscSolverFetiOperators.hpp"
#include "parallel/PetscSolverFetiTimings.hpp"
#include "parallel/StdMpi.hpp"
#include "parallel/MpiHelper.hpp"
#include "parallel/PetscSolverGlobalMatrix.hpp"
#include "io/VtkWriter.hpp"
namespace AMDiS
{
namespace Parallel
{
using namespace std;
PetscSolverFeti::PetscSolverFeti(string name)
: PetscSolver(name),
fetiSolverType(EXACT),
dofMapSubDomain(FESPACE_WISE, true),
primalDofMap(COMPONENT_WISE),
dualDofMap(COMPONENT_WISE),
interfaceDofMap(COMPONENT_WISE),
localDofMap(COMPONENT_WISE),
lagrangeMap(COMPONENT_WISE),
interiorDofMap(COMPONENT_WISE),
schurPrimalSolver(0),
levelMode(1),
subDomainIsLocal(true),
subdomain(NULL),
massMatrixSolver(NULL),
printTimings(false),
augmentedLagrange(false),
nRankEdges(0),
nOverallEdges(0),
dirichletMode(0),
stokesMode(false),
pressureComponent(-1)
{
FUNCNAME("PetscSolverFeti::PetscSolverFeti()");
string preconditionerName = "";
Parameters::get(name + "->left precon", preconditionerName);
if (preconditionerName == "" || preconditionerName == "no")
{
MSG("Create FETI-DP solver with no preconditioner!\n");
fetiPreconditioner = FETI_NONE;
}
else if (preconditionerName == "dirichlet")
{
MSG("Create FETI-DP solver with Dirichlet preconditioner!\n");
fetiPreconditioner = FETI_DIRICHLET;
}
else if (preconditionerName == "lumped")
{
MSG("Create FETI-DP solver with lumped preconditioner!\n");
fetiPreconditioner = FETI_LUMPED;
}
else
{
ERROR_EXIT("Preconditioner \"%s\" not available!\n",
preconditionerName.c_str());
}
preconditionerName = "";
Parameters::get(name + "->right precon", preconditionerName);
if (preconditionerName != "" && preconditionerName != "no")
{
ERROR_EXIT("FETI-DP does not support right preconditioning! (parameter \"%s->right precon\" has value \"%s\")\n",
name.c_str(), preconditionerName.c_str());
}
Parameters::get(name + "->feti->schur primal solver", schurPrimalSolver);
TEST_EXIT(schurPrimalSolver == 0 || schurPrimalSolver == 1)
("Wrong solver \"%d\"for the Schur primal complement!\n",
schurPrimalSolver);
Parameters::get(name + "->feti->stokes mode", stokesMode);
if (stokesMode)
{
Parameters::get(name + "->feti->pressure component", pressureComponent);
TEST_EXIT(pressureComponent >= 0)
("FETI-DP in Stokes mode, no pressure component defined!\n");
}
Parameters::get(name + "->feti->augmented lagrange", augmentedLagrange);
Parameters::get(name + "->feti->symmetric", isSymmetric);
{
MSG("WARNING: CHECK THIS HERE BEFORE GOING INTO RUNNING MULTILEVEL FETI-DP!\n");
Parameters::get("parallel->level mode", levelMode);
}
{
int tmp = 0;
Parameters::get(name + "->feti->inexact", tmp);
if (tmp == 1)
fetiSolverType = INEXACT;
if (tmp == 2)
fetiSolverType = INEXACT_REDUCED;
}
Parameters::get("parallel->print timings", printTimings);
}
void PetscSolverFeti::init(vector<const FiniteElemSpace*>& fe0,
vector<const FiniteElemSpace*>& fe1,
bool createGlobalMapping)
{
FUNCNAME_DBG("PetscSolverFeti::init()");
super::init(fe0, fe1, createGlobalMapping);
MeshLevelData& levelData = meshDistributor->getMeshLevelData();
int nLevels = levelData.getNumberOfLevels();
TEST_EXIT_DBG(nLevels >= 1)("nLevels < 1! Should not happen!\n");
if (createGlobalMapping)
{
if (meshLevel + 1 < nLevels &&
levelData.getMpiComm(meshLevel + 1) != MPI::COMM_SELF)
{
dofMapSubDomain.init(componentSpaces, feSpaces);
dofMapSubDomain.setMpiComm(levelData.getMpiComm(meshLevel + 1));
dofMapSubDomain.setDofComms(meshDistributor->getDofComms(), meshLevel + 1);
dofMapSubDomain.clear();
meshDistributor->registerDofMap(dofMapSubDomain);
}
}
}
void PetscSolverFeti::initialize()
{
FUNCNAME("PetscSolverFeti::initialize()");
#if (DEBUG != 0)
MSG("Init FETI-DP on mesh level %d\n", meshLevel);
#endif
TEST_EXIT_DBG(meshLevel + 2 <=
meshDistributor->getMeshLevelData().getNumberOfLevels())
("Mesh hierarchy does not contain at least %d levels!\n", meshLevel + 2);
MeshLevelData& levelData = meshDistributor->getMeshLevelData();
subDomainIsLocal = (levelData.getMpiComm(meshLevel + 1) == MPI::COMM_SELF);
if (subdomain == NULL)
{
string subSolverInitStr = name + "->subsolver";
string solverType = "petsc";
Parameters::get(subSolverInitStr, solverType);
solverType = "p_" + solverType;
LinearSolverCreator* solverCreator =
dynamic_cast<LinearSolverCreator*>(CreatorMap<LinearSolverInterface>::getCreator(solverType, name));
TEST_EXIT(solverCreator)
("No valid solver type found in parameter \"%s\"\n",
name.c_str());
solverCreator->setName(subSolverInitStr);
subdomain = dynamic_cast<PetscSolver*>(solverCreator->create());
subdomain->setSymmetric(isSymmetric);
subdomain->setHandleDirichletRows(dirichletMode == 0);
subdomain->setMeshDistributor(meshDistributor, meshLevel + 1);
subdomain->init(componentSpaces, feSpaces);
delete solverCreator;
}
primalDofMap.init(componentSpaces, feSpaces);
dualDofMap.init(componentSpaces, feSpaces, false);
localDofMap.init(componentSpaces, feSpaces, !subDomainIsLocal);
lagrangeMap.init(componentSpaces, feSpaces);
if (stokesMode)
interfaceDofMap.init(componentSpaces, feSpaces);
if (fetiPreconditioner == FETI_DIRICHLET)
{
TEST_EXIT(levelMode == 1)
("Dirichlet preconditioner not yet implemented for multilevel FETI-DP\n");
interiorDofMap.init(componentSpaces, feSpaces, false);
}
}
void PetscSolverFeti::createDirichletData(Matrix<DOFMatrix*>& mat)
{
FUNCNAME("PetscSolverFeti::createDirichletData()");
if (dirichletMode == 1)
{
int nComponents = mat.getNumRows();
for (int component = 0; component < nComponents; component++)
{
DOFMatrix* dofMat = mat[component][component];
if (!dofMat)
continue;
dirichletRows[component] = dofMat->getDirichletRows();
}
}
}
void PetscSolverFeti::createFetiData()
{
FUNCNAME("PetscSolverFeti::createFetiData()");
double timeCounter = MPI::Wtime();
MeshLevelData& levelData = meshDistributor->getMeshLevelData();
primalDofMap.clear();
dualDofMap.clear();
lagrangeMap.clear();
localDofMap.clear();
if (fetiPreconditioner == FETI_DIRICHLET)
interiorDofMap.clear();
primalDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel);
lagrangeMap.setDofComms(meshDistributor->getDofComms(), meshLevel);
primalDofMap.setMpiComm(levelData.getMpiComm(meshLevel));
dualDofMap.setMpiComm(levelData.getMpiComm(meshLevel));
lagrangeMap.setMpiComm(levelData.getMpiComm(meshLevel));
localDofMap.setMpiComm(levelData.getMpiComm(meshLevel + 1));
if (fetiPreconditioner == FETI_DIRICHLET)
interiorDofMap.setMpiComm(levelData.getMpiComm(meshLevel + 1));
localDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel + 1);
if (stokesMode)
{
interfaceDofMap.clear();
interfaceDofMap.setDofComms(meshDistributor->getDofComms(), meshLevel);
interfaceDofMap.setMpiComm(levelData.getMpiComm(0));
}
int nComponents = componentSpaces.size();
for (int component = 0; component < nComponents; component++)
{
createPrimals(component);
createDuals(component);
createInterfaceNodes(component);
createIndexB(component);
}
primalDofMap.update();
dualDofMap.update();
localDofMap.update();
if (fetiPreconditioner == FETI_DIRICHLET)
interiorDofMap.update();
if (stokesMode)
interfaceDofMap.update();
for (int component = 0; component < nComponents; component++)
{
createLagrange(component);
createAugmentedLagrange(component);
}
lagrangeMap.update();
// === ===
if (subDomainIsLocal)
{
MSG("WARNING: MAKE GENERAL!\n");
rStartInterior = 0;
int localDofs = localDofMap.getOverallDofs();
mpi::getDofNumbering(domainComm, localDofs,
rStartInterior, nGlobalOverallInterior);
}
else
{
MSG("WARNING: MAKE GENERAL!\n");
MeshLevelData& levelData = meshDistributor->getMeshLevelData();
int groupRowsInterior = 0;
if (levelData.getMpiComm(1).Get_rank() == 0)
groupRowsInterior = localDofMap.getOverallDofs();
mpi::getDofNumbering(domainComm, groupRowsInterior,
rStartInterior, nGlobalOverallInterior);
int tmp = 0;
if (levelData.getMpiComm(1).Get_rank() == 0)
tmp = rStartInterior;
levelData.getMpiComm(1).Allreduce(&tmp, &rStartInterior, 1,
MPI_INT, MPI_SUM);
}
for (int i = 0; i < static_cast<int>(componentSpaces.size()); i++)
{
const FiniteElemSpace* feSpace = componentSpaces[i];
MSG("FETI-DP data for %d-ith component (FE space %p):\n", i, feSpace);
if (i == pressureComponent)
{
MSG(" nRankInterface = %d nOverallInterface = %d\n",
interfaceDofMap[i].nRankDofs,
interfaceDofMap[i].nOverallDofs);
}
else
{
MSG(" nRankPrimals = %d nLocalPrimals = %d nOverallPrimals = %d\n",
primalDofMap[i].nRankDofs,
primalDofMap[i].nLocalDofs,
primalDofMap[i].nOverallDofs);
MSG(" nRankDuals = %d nOverallDuals = %d\n",
dualDofMap[i].nRankDofs,
dualDofMap[i].nOverallDofs);
MSG(" nRankLagrange = %d nOverallLagrange = %d\n",
lagrangeMap[i].nRankDofs,
lagrangeMap[i].nOverallDofs);
MSG(" nRankLocal = %d nOverallLocal = %d\n",
localDofMap[i].nRankDofs,
localDofMap[i].nOverallDofs);
}
}
subdomain->setDofMapping(&localDofMap);
subdomain->setCoarseSpaceDofMapping(&primalDofMap);
if (stokesMode)
subdomain->setCoarseSpaceDofMapping(&interfaceDofMap, pressureComponent);
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
timeCounter = MPI::Wtime() - timeCounter;
MSG("FETI-DP timing 01: %.5f seconds (creation of basic data structures)\n",
timeCounter);
}
bool writePrimals = false;
Parameters::get("parallel->debug->write primals", writePrimals);
if (writePrimals)
PetscSolverFetiDebug::writePrimalFiles(*this);
}
void PetscSolverFeti::createPrimals(int component)
{
FUNCNAME("PetscSolverFeti::createPrimals()");
if (component == pressureComponent)
return;
const FiniteElemSpace* feSpace = componentSpaces[component];
// === Define all vertices on the interior boundaries of the macro mesh ===
// === to be primal variables. ===
// Set of DOF indices that are considered to be primal variables.
DofContainerSet& vertices =
meshDistributor->getBoundaryDofInfo(feSpace, meshLevel).geoDofs[VERTEX];
DofIndexSet primals;
for (DofContainerSet::iterator it = vertices.begin();
it != vertices.end(); ++it)
{
if (dirichletRows[component].count(**it))
continue;
if (meshLevel == 1 && not (*interiorMap)[component].isSet(**it))
continue;
if (subDomainIsLocal)
{
primals.insert(**it);
}
else
{
double e = 1e-8;
WorldVector<double> c;
feSpace->getMesh()->getDofIndexCoords(*it, feSpace, c);
if ((fabs(c[0]) < e && fabs(c[1] - 12.5) < e) ||
(fabs(c[0] - 25.0) < e && fabs(c[1] - 12.5) < e) ||
(fabs(c[0] - 12.5) < e && fabs(c[1]) < e) ||
(fabs(c[0] - 12.5) < e && fabs(c[1] - 25.0) < e) ||
(fabs(c[0] - 12.5) < e && fabs(c[1] - 12.5) < e))
{
MSG("PRIMAL COORD %f %f\n", c[0], c[1]);
primals.insert(**it);
}
else
{
MSG("OMMIT SOME PRIMAL!\n");
}
}
}
// === Calculate the number of primals that are owned by the rank and ===
// === create local indices of the primals starting at zero. ===
for (DofIndexSet::iterator it = primals.begin(); it != primals.end(); ++it)
{
if (dofMap[feSpace].isRankDof(*it))
{
primalDofMap[component].insertRankDof(*it);
}
else
{
primalDofMap[component].insertNonRankDof(*it);
}
}
}
void PetscSolverFeti::createDuals(int component)
{
FUNCNAME("PetscSolverFeti::createDuals()");
if (component == pressureComponent)
return;
const FiniteElemSpace* feSpace = componentSpaces[component];
// === Create global index of the dual nodes on each rank. ===
DofContainer allBoundaryDofs;
meshDistributor->getAllBoundaryDofs(feSpace, meshLevel, allBoundaryDofs);
for (DofContainer::iterator it = allBoundaryDofs.begin();
it != allBoundaryDofs.end(); ++it)
{
if (dirichletRows[component].count(**it))
continue;
if (isPrimal(component, **it))
continue;
if (meshLevel == 1 && not (*interiorMap)[component].isSet(**it))
continue;
if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(**it))
dualDofMap[component].insertRankDof(**it);
}
}
void PetscSolverFeti::createInterfaceNodes(int component)
{
FUNCNAME("PetscSolverFeti::createInterfaceNodes()");
if (component != pressureComponent)
return;
const FiniteElemSpace* feSpace = componentSpaces[component];
DofContainer allBoundaryDofs;
meshDistributor->getAllBoundaryDofs(feSpace, meshLevel, allBoundaryDofs);
for (DofContainer::iterator it = allBoundaryDofs.begin();
it != allBoundaryDofs.end(); ++it)
{
if (dirichletRows[component].count(**it))
continue;
if (dofMap[feSpace].isRankDof(**it))
interfaceDofMap[component].insertRankDof(**it);
else
interfaceDofMap[component].insertNonRankDof(**it);
}
}
void PetscSolverFeti::createLagrange(int component)
{
FUNCNAME("PetscSolverFeti::createLagrange()");
if (component == pressureComponent)
return;
const FiniteElemSpace* feSpace = componentSpaces[component];
Mesh* mesh = feSpace->getMesh();
boundaryDofRanks[feSpace].clear();
// Stores for all rank owned communication DOFs, if the counterpart is
// a rank owned DOF in its subdomain. Thus, the following map stores to
// each rank number all DOFs that fulfill this requirenment.
map<int, std::set<DegreeOfFreedom>> subDomainRankDofs;
if (not subDomainIsLocal)
{
StdMpi<vector<int>> stdMpi(domainComm);
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace);
!it.end(); it.nextRank())
{
vector<int> dofs;
dofs.reserve(it.getDofs().size());
for (; !it.endDofIter(); it.nextDof())
{
if (dofMapSubDomain[feSpace].isRankDof(it.getDofIndex()))
dofs.push_back(1);
else
dofs.push_back(0);
}
stdMpi.send(it.getRank(), dofs);
}
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace);
!it.end(); it.nextRank())
stdMpi.recv(it.getRank());
stdMpi.startCommunication();
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace);
!it.end(); it.nextRank())
for (; !it.endDofIter(); it.nextDof())
if (!isPrimal(component, it.getDofIndex()) &&
stdMpi.getRecvData(it.getRank())[it.getDofCounter()] == 1)
subDomainRankDofs[it.getRank()].insert(it.getDofIndex());
}
if (dualDofMap[component].nLocalDofs == 0)
return;
// === Create for each dual node that is owned by the rank, the set ===
// === of ranks that contain this node (denoted by W(x_j)). ===
int mpiRank = domainComm.Get_rank();
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace);
!it.end(); it.nextRank())
{
for (; !it.endDofIter(); it.nextDof())
{
if (!isPrimal(component, it.getDofIndex()))
{
boundaryDofRanks[feSpace][it.getDofIndex()].insert(mpiRank);
// If the subdomain is local, always add the counterpart rank,
// otherwise check if the other rank is the owner of the DOF in
// its subdomain.
if (subDomainIsLocal ||
subDomainRankDofs[it.getRank()].count(it.getDofIndex()))
boundaryDofRanks[feSpace][it.getDofIndex()].insert(it.getRank());
}
}
}
// === Communicate these sets for all rank owned dual nodes to other ===
// === ranks that also have this node. ===
StdMpi<vector<std::set<int>>> stdMpi(meshDistributor->getMpiComm(meshLevel));
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getSendDofs(), feSpace);
!it.end(); it.nextRank())
for (; !it.endDofIter(); it.nextDof())
if (!isPrimal(component, it.getDofIndex()))
if (subDomainIsLocal || subDomainRankDofs[it.getRank()].count(it.getDofIndex()))
stdMpi.getSendData(it.getRank()).push_back(boundaryDofRanks[feSpace][it.getDofIndex()]);
stdMpi.updateSendDataSize();
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace);
!it.end(); it.nextRank())
{
bool recvFromRank = false;
for (; !it.endDofIter(); it.nextDof())
{
if (!isPrimal(component, it.getDofIndex()))
{
if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(it.getDofIndex()))
{
recvFromRank = true;
break;
}
}
}
if (recvFromRank)
stdMpi.recv(it.getRank());
}
stdMpi.startCommunication();
for (DofComm::Iterator it(meshDistributor->getDofComm(mesh, meshLevel).getRecvDofs(), feSpace);
!it.end(); it.nextRank())
{
int i = 0;
for (; !it.endDofIter(); it.nextDof())
{
if (!isPrimal(component, it.getDofIndex()))
{
if (subDomainIsLocal || dofMapSubDomain[feSpace].isRankDof(it.getDofIndex()))
{
boundaryDofRanks[feSpace][it.getDofIndex()] =
stdMpi.getRecvData(it.getRank())[i++];
}
else
{
lagrangeMap[component].insertNonRankDof(it.getDofIndex());
}
}
}
}
// === Reserve for each dual node, on the rank that owns this node, the ===
// === appropriate number of Lagrange constraints. ===
int nRankLagrange = 0;
DofMap& dualMap = dualDofMap[component].getMap();
for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it)
{
if (dofMap[feSpace].isRankDof(it->first))
{
lagrangeMap[component].insertRankDof(it->first, nRankLagrange);
int degree = boundaryDofRanks[feSpace][it->first].size();
nRankLagrange += (degree * (degree - 1)) / 2;
}
else
{
lagrangeMap[component].insertNonRankDof(it->first);
}
}
lagrangeMap[component].nRankDofs = nRankLagrange;
}
void PetscSolverFeti::createAugmentedLagrange(int component)
{
FUNCNAME("PetscSolverFeti::createAugmentedLagrange()");
if (!augmentedLagrange)
return;
}
void PetscSolverFeti::createIndexB(int component)
{
FUNCNAME("PetscSolverFeti::createIndexB()");
const FiniteElemSpace* feSpace = componentSpaces[component];
DOFAdmin* admin = feSpace->getAdmin();
// === To ensure that all interior node on each rank are listen first in ===
// === the global index of all B nodes, insert all interior nodes first, ===
// === without defining a correct index. ===
int nLocalInterior = 0;
for (int i = 0; i < admin->getUsedSize(); i++)
{
if (admin->isDofFree(i) ||
isPrimal(component, i) ||
isDual(component, i) ||
isInterface(component, i) ||
dirichletRows[component].count(i))
continue;
if (meshLevel == 1 && not (*interiorMap)[component].isSet(i))
continue;
if (subDomainIsLocal)
{
localDofMap[component].insertRankDof(i, nLocalInterior);
if (fetiPreconditioner == FETI_DIRICHLET)
interiorDofMap[component].insertRankDof(i, nLocalInterior);
nLocalInterior++;
}
else
{
if (dofMapSubDomain[feSpace].isRankDof(i))
localDofMap[component].insertRankDof(i);
else
localDofMap[component].insertNonRankDof(i);
TEST_EXIT_DBG(fetiPreconditioner == FETI_NONE)
("Not yet implemnted!\n");
}
}
// === And finally, add the global indicies of all dual nodes. ===
for (DofMap::iterator it = dualDofMap[component].getMap().begin();
it != dualDofMap[component].getMap().end(); ++it)
{
if (subDomainIsLocal)
{
localDofMap[component].insertRankDof(it->first);
}
else
{
if (dofMapSubDomain[feSpace].isRankDof(it->first))
localDofMap[component].insertRankDof(it->first);
else
localDofMap[component].insertNonRankDof(it->first);
}
}
}
void PetscSolverFeti::createMatLagrange()
{
FUNCNAME("PetscSolverFeti::createMatLagrange()");
double wtime = MPI::Wtime();
int mpiRank = domainComm.Get_rank();
// === Create distributed matrix for Lagrange constraints. ===
MatCreateAIJ(domainComm,
lagrangeMap.getRankDofs(), localDofMap.getRankDofs(),
lagrangeMap.getOverallDofs(), nGlobalOverallInterior,
2, PETSC_NULL, 2, PETSC_NULL,
&mat_lagrange);
MatSetOption(mat_lagrange, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
Vec vec_scale_lagrange;
createVec(lagrangeMap, vec_scale_lagrange);
// === Create for all duals the corresponding Lagrange constraints. On ===
// === each rank we traverse all pairs (n, m) of ranks, with n < m, ===
// === that contain this node. If the current rank number is r, and ===
// === n == r, the rank sets 1.0 for the corresponding constraint, if ===
// === m == r, than the rank sets -1.0 for the corresponding ===
// === constraint. ===
for (unsigned int component = 0; component < componentSpaces.size(); component++)
{
DofMap& dualMap = dualDofMap[component].getMap();
for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it)
{
TEST_EXIT_DBG(boundaryDofRanks[componentSpaces[component]].count(it->first))
("Should not happen!\n");
// Global index of the first Lagrange constriant for this node.
int index = lagrangeMap.getMatIndex(component, it->first);
// Copy set of all ranks that contain this dual node.
vector<int> W(boundaryDofRanks[componentSpaces[component]][it->first].begin(),
boundaryDofRanks[componentSpaces[component]][it->first].end());
// Number of ranks that contain this dual node.
int degree = W.size();
TEST_EXIT_DBG(degree > 1)("Should not happen!\n");
int counter = 0;
for (int i = 0; i < degree; i++)
{
for (int j = i + 1; j < degree; j++)
{
if (W[i] == mpiRank || W[j] == mpiRank)
{
MatSetValue(mat_lagrange,
index + counter,
localDofMap.getMatIndex(component, it->first) + rStartInterior,
(W[i] == mpiRank ? 1.0 : -1.0),
INSERT_VALUES);
}
counter++;
}
}
// === Create scaling factors for scaling the lagrange matrix, which ===
// === is required for FETI-DP preconditioners. ===
if (dofMap[componentSpaces[component]].isRankDof(it->first))
{
int nConstraints = (degree * (degree - 1)) / 2;
for (int i = 0; i < nConstraints; i++)
{
VecSetValue(vec_scale_lagrange,
index + i,
1.0 / static_cast<double>(degree),
INSERT_VALUES);
}
}
}
}
MatAssemblyBegin(mat_lagrange, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_lagrange, MAT_FINAL_ASSEMBLY);
#if (DEBUG != 0)
{
int nZeroRows = PetscSolverFetiDebug::testZeroRows(mat_lagrange);
int m,n;
MatGetSize(mat_lagrange, &m ,&n);
mpi::globalAdd(domainComm, nZeroRows);
MSG("Lagrange matrix has %d zero rows and global size of %d %d!\n", nZeroRows, m, n);
TEST_EXIT(nZeroRows == 0)("Lagrange matrix has zero rows!\n");
}
#endif
// === If required, create \ref mat_lagrange_scaled ===
VecAssemblyBegin(vec_scale_lagrange);
VecAssemblyEnd(vec_scale_lagrange);
if (fetiPreconditioner != FETI_NONE ||
fetiSolverType == INEXACT ||
stokesMode)
{
MatDuplicate(mat_lagrange, MAT_COPY_VALUES, &mat_lagrange_scaled);
MatDiagonalScale(mat_lagrange_scaled, vec_scale_lagrange, PETSC_NULL);
}
VecDestroy(&vec_scale_lagrange);
// === Print final timings. ===
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 05: %.5f seconds (creation of lagrange constraint matrix)\n",
MPI::Wtime() - wtime);
}
}
bool PetscSolverFeti::testWirebasketEdge(BoundaryObject& edge, const FiniteElemSpace* feSpace)
{
FUNCNAME("PetscSolverFeti::testWirebasketEdge()");
return true;
if (meshDistributor->getMesh()->getDim() == 2)
return true;
if (meshDistributor->getIntBoundary(meshLevel).getDegreeOwn(edge) != 3)
return false;
return true;
Element* el = edge.el;
int i0 = el->getVertexOfEdge(edge.ithObj, 0);
int i1 = el->getVertexOfEdge(edge.ithObj, 1);
DegreeOfFreedom d0 = el->getDof(i0, 0);
DegreeOfFreedom d1 = el->getDof(i1, 0);
WorldVector<double> c0, c1;
el->getMesh()->getDofIndexCoords(d0, feSpace, c0);
el->getMesh()->getDofIndexCoords(d1, feSpace, c1);
bool xe = fabs(c0[0] - c1[0]) < 1e-8;
bool ye = fabs(c0[1] - c1[1]) < 1e-8;
bool ze = fabs(c0[2] - c1[2]) < 1e-8;
int counter = static_cast<int>(xe) + static_cast<int>(ye) + static_cast<int>(ze);
return (counter == 2);
}
vector<vector<BoundaryObject>> PetscSolverFeti::getCoarseEdges()
{
FUNCNAME("PetscSolverFeti::getAugmentedLagrange()");
InteriorBoundary& intBound = meshDistributor->getIntBoundary(meshLevel);
std::set<BoundaryObject> allEdges;
for (InteriorBoundary::iterator it(intBound.getOwn()); !it.end(); ++it)
if (it->rankObj.subObj == EDGE &&
testWirebasketEdge(it->rankObj, feSpaces[0]) &&
allEdges.count(it->rankObj) == 0)
allEdges.insert(it->rankObj);
int nEmptyEdges = 0;
vector<vector<BoundaryObject>> data;
for (std::set<BoundaryObject>::iterator it = allEdges.begin();
it != allEdges.end(); ++it)
{
DofContainer edgeDofs;
it->el->getAllDofs(feSpaces[0], *it, edgeDofs);
if (edgeDofs.size() == 0)
{
nEmptyEdges++;
}
else
{
vector<BoundaryObject> oneBoundary;
oneBoundary.push_back(*it);
data.push_back(oneBoundary);
}
}
int nEdges = allEdges.size();
mpi::globalAdd(nEdges);
mpi::globalAdd(nEmptyEdges);
MSG("Coarse space edges: %d (empty: %d)\n", nEdges, nEmptyEdges);
return data;
}
vector<vector<BoundaryObject>> PetscSolverFeti::getCoarseFaces()
{
FUNCNAME("PetscSolverFeti::getAugmentedLagrange()");
InteriorBoundary& intBound = meshDistributor->getIntBoundary(meshLevel);
map<int, std::set<BoundaryObject>> allFaces;
for (InteriorBoundary::iterator it(intBound.getOwn()); !it.end(); ++it)
if (it->rankObj.subObj == FACE)
allFaces[it.getRank()].insert(it->rankObj);
#if 0
std::set<BoundaryObject> allMyEdges;
TraverseStack stack;
ElInfo* elInfo = stack.traverseFirst(meshDistributor->getMesh(), 0, Mesh::CALL_EL_LEVEL | Mesh::FILL_BOUND);
while (elInfo)
{
Element* el = elInfo->getElement();
for (int i = 0; i < el->getGeo(EDGE); i++)
{
BoundaryObject bobj(el, elInfo->getType(), EDGE, i);
if (intBound.getDegreeOwn(bobj) == 1 && elInfo->getBoundary(EDGE, i) == INTERIOR)
{
allMyEdges.insert(bobj);
}
}
elInfo = stack.traverseNext(elInfo);
}
for (map<int, std::set<BoundaryObject>>::iterator it = allFaces.begin();
it != allFaces.end(); ++it)
{
if (it->second.size() == 2)
{
vector<AtomicBoundary>& bs = intBound.getOwn()[it->first];
for (int i = 0; i < static_cast<int>(bs.size()); i++)
{
if (bs[i].rankObj.subObj == EDGE &&
intBound.getDegreeOwn(bs[i].rankObj) == 1 &&
allMyEdges.count(bs[i].rankObj))
{
MSG("FOUND AN EDGE: %d %d %d\n",
bs[i].rankObj.elIndex, bs[i].rankObj.subObj, bs[i].rankObj.ithObj);
it->second.insert(bs[i].rankObj);
}
}
}
}
#endif
int nEmptyFaces = 0;
vector<vector<BoundaryObject>> data;
for (map<int, std::set<BoundaryObject>>::iterator it = allFaces.begin();
it != allFaces.end(); ++it)
{
vector<BoundaryObject> oneBoundary;
for (std::set<BoundaryObject>::iterator bIt = it->second.begin();
bIt != it->second.end(); ++bIt)
{
DofContainer faceDofs;
bIt->el->getAllDofs(feSpaces[0], *bIt, faceDofs);
if (faceDofs.size())
oneBoundary.push_back(*bIt);
}
if (oneBoundary.size())
data.push_back(oneBoundary);
else
nEmptyFaces++;
}
int nFaces = allFaces.size();
mpi::globalAdd(nFaces);
mpi::globalAdd(nEmptyFaces);
MSG("Coarse space faces: %d (empty: %d)\n", nFaces, nEmptyFaces);
return data;
}
void PetscSolverFeti::createMatAugmentedLagrange()
{
FUNCNAME("PetscSolverFeti::createMatAugmentedLagrange()");
if (!augmentedLagrange)
return;
double wtime = MPI::Wtime();
vector<vector<BoundaryObject>> allEdges = getCoarseEdges();
vector<vector<BoundaryObject>> allFaces = getCoarseFaces();
allEdges.insert(allEdges.end(), allFaces.begin(), allFaces.end());
nRankEdges = allEdges.size();
int rStartEdges = 0;
mpi::getDofNumbering(domainComm, nRankEdges, rStartEdges, nOverallEdges);
MSG("nRankEdges = %d, nOverallEdges = %d\n", nRankEdges, nOverallEdges);
nRankEdges *= componentSpaces.size();
rStartEdges *= componentSpaces.size();
nOverallEdges *= componentSpaces.size();
MatCreateAIJ(domainComm,
nRankEdges, lagrangeMap.getRankDofs(),
nOverallEdges, lagrangeMap.getOverallDofs(),
2, PETSC_NULL, 2, PETSC_NULL,
&mat_augmented_lagrange);
MatSetOption(mat_augmented_lagrange, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
int rowCounter = rStartEdges;
for (vector<vector<BoundaryObject>>::iterator it = allEdges.begin();
it != allEdges.end(); ++it)
{
for (int component = 0; component < static_cast<int>(componentSpaces.size()); component++)
{
for (vector<BoundaryObject>::iterator edgeIt = it->begin();
edgeIt != it->end(); ++edgeIt)
{
DofContainer edgeDofs;
edgeIt->el->getAllDofs(componentSpaces[component], *edgeIt, edgeDofs);
TEST_EXIT(edgeDofs.size())("Should not happen!\n");
for (DofContainer::iterator it = edgeDofs.begin();
it != edgeDofs.end(); ++it)
{
TEST_EXIT(isPrimal(component, **it) == false)
("Should not be primal!\n");
int col = lagrangeMap.getMatIndex(component, **it);
double value = 1.0;
MatSetValue(mat_augmented_lagrange, rowCounter, col, value, INSERT_VALUES);
}
}
rowCounter++;
}
}
MatAssemblyBegin(mat_augmented_lagrange, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_augmented_lagrange, MAT_FINAL_ASSEMBLY);
int nZeroRows = PetscSolverFetiDebug::testZeroRows(mat_augmented_lagrange);
int m,n;
MatGetSize(mat_augmented_lagrange, &m ,&n);
MSG("Augmented lagrange matrix has %d zero rows and global size of %d %d!\n", nZeroRows, m, n);
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 05a: %.5f seconds (creation of augmented lagrange constraint matrix)\n",
MPI::Wtime() - wtime);
}
}
void PetscSolverFeti::createSchurPrimalKsp()
{
FUNCNAME("PetscSolverFeti::createSchurPrimalKsp()");
if (schurPrimalSolver == 0)
{
MSG("Create iterative schur primal solver on level %d!\n", meshLevel);
if (augmentedLagrange == false)
{
schurPrimalData.subSolver = subdomain;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior, &(schurPrimalData.tmp_vec_b));
createVec(primalDofMap, schurPrimalData.tmp_vec_primal);
MatCreateShell(domainComm,
primalDofMap.getRankDofs(),
primalDofMap.getRankDofs(),
primalDofMap.getOverallDofs(),
primalDofMap.getOverallDofs(),
&schurPrimalData,
&mat_schur_primal);
MatShellSetOperation(mat_schur_primal, MATOP_MULT,
(void(*)(void))petscMultMatSchurPrimal);
}
else
{
schurPrimalAugmentedData.subSolver = subdomain;
schurPrimalAugmentedData.nestedVec = true;
createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b0, nGlobalOverallInterior);
createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b1, nGlobalOverallInterior);
createVec(primalDofMap, schurPrimalAugmentedData.tmp_vec_primal);
createVec(lagrangeMap, schurPrimalAugmentedData.tmp_vec_lagrange);
schurPrimalAugmentedData.mat_lagrange = &mat_lagrange;
schurPrimalAugmentedData.mat_augmented_lagrange = &mat_augmented_lagrange;
MatCreateShell(domainComm,
primalDofMap.getRankDofs() + nRankEdges,
primalDofMap.getRankDofs() + nRankEdges,
primalDofMap.getOverallDofs() + nOverallEdges,
primalDofMap.getOverallDofs() + nOverallEdges,
&schurPrimalAugmentedData,
&mat_schur_primal);
MatShellSetOperation(mat_schur_primal, MATOP_MULT,
(void(*)(void))petscMultMatSchurPrimalAugmented);
}
KSPCreate(domainComm, &ksp_schur_primal);
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal);
#else
KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal, SAME_NONZERO_PATTERN);
#endif
KSPSetOptionsPrefix(ksp_schur_primal, "schur_primal_");
KSPSetType(ksp_schur_primal, KSPGMRES);
KSPSetFromOptions(ksp_schur_primal);
}
else
{
MSG("Create direct schur primal solver!\n");
double wtime = MPI::Wtime();
// === Create explicit matrix representation of the Schur primal system. ===
if (!augmentedLagrange)
createMatExplicitSchurPrimal();
else
createMatExplicitAugmentedSchurPrimal();
// === Create KSP solver object and set appropriate solver options. ===
KSPCreate(domainComm, &ksp_schur_primal);
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal);
#else
KSPSetOperators(ksp_schur_primal, mat_schur_primal, mat_schur_primal, SAME_NONZERO_PATTERN);
#endif
KSPSetOptionsPrefix(ksp_schur_primal, "schur_primal_");
KSPSetType(ksp_schur_primal, KSPPREONLY);
PC pc_schur_primal;
KSPGetPC(ksp_schur_primal, &pc_schur_primal);
PCSetType(pc_schur_primal, PCLU);
PCFactorSetMatSolverPackage(pc_schur_primal, MATSOLVERMUMPS);
KSPSetFromOptions(ksp_schur_primal);
// === And finally print timings, if required. ===
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MatInfo minfo;
MatGetInfo(mat_schur_primal, MAT_GLOBAL_SUM, &minfo);
MSG("Schur primal matrix nnz = %f\n", minfo.nz_used);
MSG("FETI-DP timing 06: %.5f seconds (creation of schur primal matrix)\n",
MPI::Wtime() - wtime);
wtime = MPI::Wtime();
KSPSetUp(ksp_schur_primal);
KSPSetUpOnBlocks(ksp_schur_primal);
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 07: %.5f seconds (factorization of primal schur matrix).\n",
MPI::Wtime() - wtime);
}
}
}
void PetscSolverFeti::createMatExplicitSchurPrimal()
{
FUNCNAME("PetscSolverFeti::createMatExplicitSchurPrimal()");
int creationMode = 0;
Parameters::get(name + "->feti->schur primal creation mode", creationMode);
if (creationMode == 0)
{
// matK = inv(A_BB) A_BPi
Mat matK;
petsc_helper::blockMatMatSolve(domainComm,
subdomain->getSolver(),
subdomain->getMatInteriorCoarse(),
matK);
// mat_schur_primal = A_PiPi - A_PiB inv(A_BB) A_BPi
// = A_PiPi - A_PiB matK
MatMatMult(subdomain->getMatCoarseInterior(), matK, MAT_INITIAL_MATRIX,
PETSC_DEFAULT, &mat_schur_primal);
MatAYPX(mat_schur_primal, -1.0, subdomain->getMatCoarse(), DIFFERENT_NONZERO_PATTERN);
MatDestroy(&matK);
}
else
{
schurPrimalData.subSolver = subdomain;
createVec(localDofMap, schurPrimalData.tmp_vec_b, nGlobalOverallInterior);
createVec(primalDofMap, schurPrimalData.tmp_vec_primal);
Mat tmp;
MatCreateShell(domainComm,
primalDofMap.getRankDofs(),
primalDofMap.getRankDofs(),
primalDofMap.getOverallDofs(),
primalDofMap.getOverallDofs(),
&schurPrimalData,
&tmp);
MatShellSetOperation(tmp, MATOP_MULT,
(void(*)(void))petscMultMatSchurPrimal);
MatComputeExplicitOperator(tmp, &mat_schur_primal);
MatDestroy(&tmp);
schurPrimalData.subSolver = NULL;
VecDestroy(&schurPrimalData.tmp_vec_b);
VecDestroy(&schurPrimalData.tmp_vec_primal);
}
}
void PetscSolverFeti::createMatExplicitAugmentedSchurPrimal()
{
FUNCNAME("PetscSolverFeti::createMatExplicitAugmentedSchurPrimal()");
int creationMode = 0;
Parameters::get("parallel->feti->schur primal creation mode", creationMode);
if (creationMode == 0)
{
// qj = -Q J
Mat qj;
MatMatMult(mat_augmented_lagrange, mat_lagrange, MAT_INITIAL_MATRIX,
PETSC_DEFAULT, &qj);
MatScale(qj, -1.0);
// matTmp = inv(A_BB) A_BPi
Mat matTmp;
petsc_helper::blockMatMatSolve(domainComm,
subdomain->getSolver(),
subdomain->getMatInteriorCoarse(),
matTmp);
// mat00 = A_PiPi - A_PiB inv(A_BB) A_BPi
// = A_PiPi - A_PiB matTmp
Mat mat00;
MatMatMult(subdomain->getMatCoarseInterior(), matTmp, MAT_INITIAL_MATRIX,
PETSC_DEFAULT, &mat00);
MatAYPX(mat00, -1.0, subdomain->getMatCoarse(), DIFFERENT_NONZERO_PATTERN);
// mat10 = -Q J inv(A_BB) A_BPi
// = qj matTmp
Mat mat10;
MatMatMult(qj, matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat10);
// matTmp = inv(A_BB) trans(J) trans(Q)
Mat qT, jTqT;
MatTranspose(mat_augmented_lagrange, MAT_INITIAL_MATRIX, &qT);
MatTransposeMatMult(mat_lagrange, qT, MAT_INITIAL_MATRIX, PETSC_DEFAULT,
&jTqT);
petsc_helper::blockMatMatSolve(domainComm,
subdomain->getSolver(),
jTqT,
matTmp);
MatDestroy(&qT);
MatDestroy(&jTqT);
// mat01 = -A_PiB inv(A_BB) trans(J) trans(Q)
// = -A_PiB matTmp
Mat mat01;
MatMatMult(subdomain->getMatCoarseInterior(), matTmp, MAT_INITIAL_MATRIX,
PETSC_DEFAULT, &mat01);
MatScale(mat01, -1.0);
// mat11 = -Q J inv(A_BB) trans(J) trans(Q)
// = qj matTmp
Mat mat11;
MatMatMult(qj, matTmp, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mat11);
MatDestroy(&matTmp);
MatDestroy(&qj);
Mat nestMat[4] = {mat00, mat01, mat10, mat11};
MatCreateNest(PETSC_COMM_WORLD, 2, PETSC_NULL, 2, PETSC_NULL, nestMat, &matTmp);
petsc_helper::matNestConvert(matTmp, mat_schur_primal);
MatDestroy(&mat00);
MatDestroy(&mat01);
MatDestroy(&mat10);
MatDestroy(&mat11);
MatDestroy(&matTmp);
}
else
{
Mat tmp;
schurPrimalAugmentedData.subSolver = subdomain;
schurPrimalAugmentedData.nestedVec = false;
createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b0, nGlobalOverallInterior);
createVec(localDofMap, schurPrimalAugmentedData.tmp_vec_b1, nGlobalOverallInterior);
createVec(primalDofMap, schurPrimalAugmentedData.tmp_vec_primal);
createVec(lagrangeMap, schurPrimalAugmentedData.tmp_vec_lagrange);
schurPrimalAugmentedData.mat_lagrange = &mat_lagrange;
schurPrimalAugmentedData.mat_augmented_lagrange = &mat_augmented_lagrange;
MatCreateShell(domainComm,
primalDofMap.getRankDofs() + nRankEdges,
primalDofMap.getRankDofs() + nRankEdges,
primalDofMap.getOverallDofs() + nOverallEdges,
primalDofMap.getOverallDofs() + nOverallEdges,
&schurPrimalAugmentedData,
&tmp);
MatShellSetOperation(tmp, MATOP_MULT,
(void(*)(void))petscMultMatSchurPrimalAugmented);
MatComputeExplicitOperator(tmp, &mat_schur_primal);
MatDestroy(&tmp);
schurPrimalAugmentedData.subSolver = NULL;
schurPrimalAugmentedData.mat_lagrange = NULL;
schurPrimalAugmentedData.mat_augmented_lagrange = NULL;
VecDestroy(&schurPrimalAugmentedData.tmp_vec_b0);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_b1);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_primal);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_lagrange);
}
}
void PetscSolverFeti::destroySchurPrimalKsp()
{
FUNCNAME("PetscSolverFeti::destroySchurPrimal()");
if (schurPrimalSolver == 0)
{
if (augmentedLagrange == false)
{
schurPrimalData.subSolver = NULL;
VecDestroy(&schurPrimalData.tmp_vec_b);
VecDestroy(&schurPrimalData.tmp_vec_primal);
}
else
{
schurPrimalAugmentedData.subSolver = NULL;
schurPrimalAugmentedData.mat_lagrange = NULL;
schurPrimalAugmentedData.mat_augmented_lagrange = NULL;
VecDestroy(&schurPrimalAugmentedData.tmp_vec_b0);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_b1);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_primal);
VecDestroy(&schurPrimalAugmentedData.tmp_vec_lagrange);
}
}
MatDestroy(&mat_schur_primal);
KSPDestroy(&ksp_schur_primal);
}
void PetscSolverFeti::createFetiKsp()
{
FUNCNAME("PetscSolverFeti::createFetiKsp()");
switch (fetiSolverType)
{
case EXACT:
createFetiExactKsp();
break;
case INEXACT:
createFetiInexactKsp();
break;
case INEXACT_REDUCED:
createFetiInexactReducedKsp();
break;
default:
ERROR_EXIT("Should not happen!\n");
}
}
void PetscSolverFeti::createFetiExactKsp()
{
FUNCNAME("PetscSolverFeti::createFetiExactKsp()");
// === Create FETI-DP solver object. ===
fetiData.mat_lagrange = &mat_lagrange;
fetiData.subSolver = subdomain;
fetiData.ksp_schur_primal = &ksp_schur_primal;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior, &(fetiData.tmp_vec_b0));
createVec(lagrangeMap, fetiData.tmp_vec_lagrange);
createVec(primalDofMap, fetiData.tmp_vec_primal0);
if (stokesMode == false)
{
MatCreateShell(domainComm,
lagrangeMap.getRankDofs(),
lagrangeMap.getRankDofs(),
lagrangeMap.getOverallDofs(),
lagrangeMap.getOverallDofs(),
&fetiData, &mat_feti);
if (augmentedLagrange == false)
{
MatShellSetOperation(mat_feti, MATOP_MULT,
(void(*)(void))petscMultMatFeti);
}
else
{
fetiData.mat_augmented_lagrange = &mat_augmented_lagrange;
createVec(primalDofMap, fetiData.tmp_vec_primal1);
MatShellSetOperation(mat_feti, MATOP_MULT,
(void(*)(void))petscMultMatFetiAugmented);
}
}
else
{
TEST_EXIT_DBG(!augmentedLagrange)("Not yet implemented!\n");
createVec(localDofMap, fetiData.tmp_vec_b1, nGlobalOverallInterior);
createVec(primalDofMap, fetiData.tmp_vec_primal1);
createVec(interfaceDofMap, fetiData.tmp_vec_interface);
MatCreateShell(domainComm,
interfaceDofMap.getRankDofs() + lagrangeMap.getRankDofs(),
interfaceDofMap.getRankDofs() + lagrangeMap.getRankDofs(),
interfaceDofMap.getOverallDofs() + lagrangeMap.getOverallDofs(),
interfaceDofMap.getOverallDofs() + lagrangeMap.getOverallDofs(),
&fetiData, &mat_feti);
MatShellSetOperation(mat_feti, MATOP_MULT,
(void(*)(void))petscMultMatFetiInterface);
}
KSPCreate(domainComm, &ksp_feti);
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(ksp_feti, mat_feti, mat_feti);
#else
KSPSetOperators(ksp_feti, mat_feti, mat_feti, SAME_NONZERO_PATTERN);
#endif
KSPSetOptionsPrefix(ksp_feti, "feti_");
KSPSetType(ksp_feti, KSPGMRES);
KSPSetTolerances(ksp_feti, 0, 1e-8, 1e+3, 1000);
KSPSetFromOptions(ksp_feti);
// === Set KSP monitor. ===
bool monitor = false;
Parameters::get(name + "->feti->monitor", monitor);
if (monitor)
{
if (stokesMode)
KSPMonitorSet(ksp_feti, KSPMonitorFetiStokes, &fetiKspData, PETSC_NULL);
else
KSPMonitorSet(ksp_feti, KSPMonitorTrueResidualNorm, PETSC_NULL, PETSC_NULL);
}
// === Create null space objects. ===
createNullSpace();
switch (fetiPreconditioner)
{
case FETI_DIRICHLET:
KSPGetPC(ksp_feti, &precon_feti);
createFetiPreconDirichlet(precon_feti);
break;
case FETI_LUMPED:
KSPGetPC(ksp_feti, &precon_feti);
createFetiPreconLumped(precon_feti);
break;
default:
break;
}
}
void PetscSolverFeti::createFetiInexactKsp()
{
FUNCNAME("PetscSolverFeti::createFetiInexactKsp()");
// === Init solver ===
int localSize =
localDofMap.getRankDofs() +
primalDofMap.getRankDofs() +
lagrangeMap.getRankDofs();
int globalSize =
nGlobalOverallInterior +
primalDofMap.getOverallDofs() +
lagrangeMap.getOverallDofs();
fetiInexactData.matBB = &(subdomain->getMatInterior());
fetiInexactData.matBPi = &(subdomain->getMatInteriorCoarse());
fetiInexactData.matPiB = &(subdomain->getMatCoarseInterior());
fetiInexactData.matPiPi = &(subdomain->getMatCoarse());
fetiInexactData.mat_lagrange = &mat_lagrange;
createVec(localDofMap, fetiInexactData.tmp_vec_b0);
createVec(localDofMap, fetiInexactData.tmp_vec_b1);
MatCreateShell(domainComm,
localSize, localSize, globalSize, globalSize,
&fetiInexactData, &mat_feti);
MatShellSetOperation(mat_feti, MATOP_MULT,
(void(*)(void))petscMultMatFetiInexact);
KSPCreate(domainComm, &ksp_feti);
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(ksp_feti, mat_feti, mat_feti);
#else
KSPSetOperators(ksp_feti, mat_feti, mat_feti, SAME_NONZERO_PATTERN);
#endif
KSPSetOptionsPrefix(ksp_feti, "feti_");
KSPSetType(ksp_feti, KSPGMRES);
KSPSetTolerances(ksp_feti, 0, 1e-8, 1e+3, 1000);
KSPSetFromOptions(ksp_feti);
// === Init preconditioner ===
fetiInexactPreconData.ksp_schur = ksp_schur_primal;
fetiInexactPreconData.ksp_interior = subdomain->getSolver();
fetiInexactPreconData.matPiB = &(subdomain->getMatCoarseInterior());
fetiInexactPreconData.matBPi = &(subdomain->getMatInteriorCoarse());
fetiInexactPreconData.mat_lagrange = &mat_lagrange;
createVec(localDofMap, fetiInexactPreconData.tmp_vec_b0);
KSPCreate(domainComm, &(fetiInexactPreconData.ksp_pc_feti));
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(fetiInexactPreconData.ksp_pc_feti, mat_lagrange, mat_lagrange);
#else
KSPSetOperators(fetiInexactPreconData.ksp_pc_feti, mat_lagrange, mat_lagrange, SAME_NONZERO_PATTERN);
#endif
KSPGetPC(fetiInexactPreconData.ksp_pc_feti,
&(fetiInexactPreconData.pc_feti));
createFetiPreconLumped(fetiInexactPreconData.pc_feti);
PCSetUp(fetiInexactPreconData.pc_feti);
// === Setup pc object ===
PC pc;
KSPGetPC(ksp_feti, &pc);
PCSetType(pc, PCSHELL);
PCShellSetApply(pc, pcInexactFetiShell);
PCShellSetContext(pc, &fetiInexactPreconData);
}
void PetscSolverFeti::createFetiInexactReducedKsp()
{
FUNCNAME("PetscSolverFeti::createFetiInexactReducedKsp()");
ERROR_EXIT("Not yet implemented!\n");
}
void PetscSolverFeti::createFetiPreconLumped(PC pc)
{
FUNCNAME("PetscSolverFeti::createFetiPreconLumped()");
FetiLumpedPreconData* lumpedData =
(stokesMode ? &fetiInterfaceLumpedPreconData : &fetiLumpedPreconData);
lumpedData->mat_lagrange_scaled = &mat_lagrange_scaled;
lumpedData->mat_duals_duals = &mat_duals_duals;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior, &(lumpedData->tmp_vec_b0));
MatGetVecs(mat_duals_duals, PETSC_NULL,
&(lumpedData->tmp_vec_duals0));
MatGetVecs(mat_duals_duals, PETSC_NULL,
&(lumpedData->tmp_vec_duals1));
for (int component = 0; component < static_cast<int>(componentSpaces.size());
component++)
{
if (stokesMode && component == pressureComponent)
continue;
DofMap& dualMap = dualDofMap[component].getMap();
for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it)
{
DegreeOfFreedom d = it->first;
int matIndexLocal = localDofMap.getLocalMatIndex(component, d);
int matIndexDual = dualDofMap.getLocalMatIndex(component, d);
lumpedData->localToDualMap[matIndexLocal] = matIndexDual;
}
}
if (stokesMode)
{
// === Create mass matrix solver ===
const FiniteElemSpace* pressureFeSpace =
componentSpaces[pressureComponent];
// Create parallel DOF mapping in pressure space.
ParallelDofMapping* massMapping = NULL;
if (massMatrixSolver)
{
massMapping = massMatrixSolver->getDofMapping();
}
else
{
massMapping =
new ParallelDofMapping(COMPONENT_WISE, true);
massMapping->init(pressureFeSpace, pressureFeSpace);
massMapping->setDofComms(meshDistributor->getDofComms(), meshLevel);
massMapping->setMpiComm(meshDistributor->getMeshLevelData().getMpiComm(0));
}
(*massMapping)[0] = interfaceDofMap[pressureComponent];
massMapping->update();
DOFMatrix massMatrix(pressureFeSpace, pressureFeSpace);
Operator op(pressureFeSpace, pressureFeSpace);
Simple_ZOT zot;
op.addTerm(&zot);
massMatrix.assembleOperator(op);
if (!massMatrixSolver)
{
massMatrixSolver = new PetscSolverGlobalMatrix("");
massMatrixSolver->setKspPrefix("mass_");
massMatrixSolver->setMeshDistributor(meshDistributor, meshLevel);
massMatrixSolver->setDofMapping(massMapping);
}
massMatrixSolver->fillPetscMatrix(&massMatrix);
int r, c;
MatGetSize(massMatrixSolver->getMatInterior(), &r, &c);
MatInfo info;
MatGetInfo(massMatrixSolver->getMatInterior(), MAT_GLOBAL_SUM, &info);
MSG("MASS MAT INFO: size = %d x %d nnz = %d\n",
r, c, static_cast<int>(info.nz_used));
fetiInterfaceLumpedPreconData.ksp_mass = massMatrixSolver->getSolver();
// === Create tmp vectors ===
createVec(localDofMap, fetiInterfaceLumpedPreconData.tmp_vec_b1);
createVec(primalDofMap, fetiInterfaceLumpedPreconData.tmp_primal);
fetiInterfaceLumpedPreconData.subSolver = subdomain;
}
// === Set PC object ===
PCSetType(pc, PCSHELL);
if (stokesMode)
{
PCShellSetContext(pc, static_cast<void*>(&fetiInterfaceLumpedPreconData));
PCShellSetApply(pc, petscApplyFetiInterfaceLumpedPrecon);
}
else
{
PCShellSetContext(pc, static_cast<void*>(&fetiLumpedPreconData));
PCShellSetApply(pc, petscApplyFetiLumpedPrecon);
}
}
void PetscSolverFeti::createFetiPreconDirichlet(PC pc)
{
FUNCNAME("PetscSolverFeti::createFetiPreconDirichlet()");
TEST_EXIT(subDomainIsLocal)
("Check for localDofMap.getLocalMatIndex, which should not work for multilevel FETI-DP!\n");
TEST_EXIT(!stokesMode)
("Stokes mode does not yet support the Dirichlet precondition!\n");
KSPCreate(PETSC_COMM_SELF, &ksp_interior);
#if (PETSC_VERSION_MINOR >= 5)
KSPSetOperators(ksp_interior, mat_interior_interior, mat_interior_interior);
#else
KSPSetOperators(ksp_interior, mat_interior_interior, mat_interior_interior, SAME_NONZERO_PATTERN);
#endif
KSPSetOptionsPrefix(ksp_interior, "precon_interior_");
KSPSetType(ksp_interior, KSPPREONLY);
PC pc_interior;
KSPGetPC(ksp_interior, &pc_interior);
if (isSymmetric)
{
PCSetType(pc_interior, PCCHOLESKY);
PCFactorSetMatSolverPackage(pc_interior, MATSOLVERMUMPS);
}
else
{
PCSetType(pc_interior, PCLU);
PCFactorSetMatSolverPackage(pc_interior, MATSOLVERUMFPACK);
}
KSPSetFromOptions(ksp_interior);
fetiDirichletPreconData.mat_lagrange_scaled = &mat_lagrange_scaled;
fetiDirichletPreconData.mat_interior_interior = &mat_interior_interior;
fetiDirichletPreconData.mat_duals_duals = &mat_duals_duals;
fetiDirichletPreconData.mat_interior_duals = &mat_interior_duals;
fetiDirichletPreconData.mat_duals_interior = &mat_duals_interior;
fetiDirichletPreconData.ksp_interior = &ksp_interior;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior, &(fetiDirichletPreconData.tmp_vec_b));
MatGetVecs(mat_duals_duals, PETSC_NULL,
&(fetiDirichletPreconData.tmp_vec_duals0));
MatGetVecs(mat_duals_duals, PETSC_NULL,
&(fetiDirichletPreconData.tmp_vec_duals1));
MatGetVecs(mat_interior_interior, PETSC_NULL,
&(fetiDirichletPreconData.tmp_vec_interior));
TEST_EXIT_DBG(subDomainIsLocal)
("Should not happen, check usage of localDofMap!\n");
for (unsigned int component = 0; component < componentSpaces.size(); component++)
{
DofMap& dualMap = dualDofMap[component].getMap();
for (DofMap::iterator it = dualMap.begin(); it != dualMap.end(); ++it)
{
DegreeOfFreedom d = it->first;
int matIndexLocal = localDofMap.getLocalMatIndex(component, d);
int matIndexDual = dualDofMap.getLocalMatIndex(component, d);
fetiDirichletPreconData.localToDualMap[matIndexLocal] = matIndexDual;
}
}
PCSetType(pc, PCSHELL);
PCShellSetContext(pc, static_cast<void*>(&fetiDirichletPreconData));
PCShellSetApply(pc, petscApplyFetiDirichletPrecon);
// For the case, that we want to print the timings, we force the LU
// factorization of the local problems to be done here explicitly.
if (printTimings)
{
double wtime = MPI::Wtime();
KSPSetUp(ksp_interior);
KSPSetUpOnBlocks(ksp_interior);
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 08: %.5f seconds (factorization of Dirichlet preconditoner matrices)\n",
MPI::Wtime() - wtime);
}
}
void PetscSolverFeti::destroyFetiKsp()
{
FUNCNAME("PetscSolverFeti::destroyFetiKsp()");
switch (fetiSolverType)
{
case EXACT:
destroyFetiExactKsp();
break;
case INEXACT:
destroyFetiInexactKsp();
break;
case INEXACT_REDUCED:
destroyFetiInexactReducedKsp();
break;
default:
ERROR_EXIT("Should not happen!\n");
}
}
void PetscSolverFeti::destroyFetiExactKsp()
{
FUNCNAME("PetscSolverFeti::destroyFetiExactKsp()");
// === Destroy FETI-DP solver object. ===
fetiData.mat_lagrange = PETSC_NULL;
fetiData.subSolver = NULL;
fetiData.ksp_schur_primal = PETSC_NULL;
VecDestroy(&fetiData.tmp_vec_b0);
VecDestroy(&fetiData.tmp_vec_lagrange);
VecDestroy(&fetiData.tmp_vec_primal0);
if (augmentedLagrange)
{
fetiData.mat_augmented_lagrange = PETSC_NULL;
VecDestroy(&fetiData.tmp_vec_primal1);
}
if (stokesMode)
{
VecDestroy(&fetiData.tmp_vec_b1);
VecDestroy(&fetiData.tmp_vec_primal1);
VecDestroy(&fetiData.tmp_vec_interface);
}
MatDestroy(&mat_feti);
KSPDestroy(&ksp_feti);
// === Destroy FETI-DP preconditioner object. ===
switch (fetiPreconditioner)
{
case FETI_DIRICHLET:
KSPDestroy(&ksp_interior);
fetiDirichletPreconData.mat_lagrange_scaled = NULL;
fetiDirichletPreconData.mat_interior_interior = NULL;
fetiDirichletPreconData.mat_duals_duals = NULL;
fetiDirichletPreconData.mat_interior_duals = NULL;
fetiDirichletPreconData.mat_duals_interior = NULL;
fetiDirichletPreconData.ksp_interior = NULL;
VecDestroy(&fetiDirichletPreconData.tmp_vec_b);
VecDestroy(&fetiDirichletPreconData.tmp_vec_duals0);
VecDestroy(&fetiDirichletPreconData.tmp_vec_duals1);
VecDestroy(&fetiDirichletPreconData.tmp_vec_interior);
MatDestroy(&mat_lagrange_scaled);
break;
case FETI_LUMPED:
{
FetiLumpedPreconData& lumpedData =
(stokesMode ? fetiInterfaceLumpedPreconData : fetiLumpedPreconData);
lumpedData.mat_lagrange_scaled = NULL;
lumpedData.mat_duals_duals = NULL;
VecDestroy(&lumpedData.tmp_vec_b0);
VecDestroy(&lumpedData.tmp_vec_duals0);
VecDestroy(&lumpedData.tmp_vec_duals1);
}
break;
default:
break;
}
}
void PetscSolverFeti::destroyFetiInexactKsp()
{
FUNCNAME("PetscSolverFeti::destroyFetiInexactKsp()");
VecDestroy(&(fetiInexactData.tmp_vec_b0));
VecDestroy(&(fetiInexactData.tmp_vec_b1));
MatDestroy(&mat_feti);
KSPDestroy(&ksp_feti);
VecDestroy(&(fetiInexactPreconData.tmp_vec_b0));
KSPDestroy(&(fetiInexactPreconData.ksp_pc_feti));
}
void PetscSolverFeti::destroyFetiInexactReducedKsp()
{
FUNCNAME("PetscSolverFeti::destroyFetiInexactReducedKsp()");
}
void PetscSolverFeti::createNullSpace()
{
FUNCNAME("PetscSolverFeti::createNullSpace()");
if (!stokesMode)
return;
const FiniteElemSpace* pressureFeSpace = componentSpaces[pressureComponent];
Vec ktest0, ktest1;
createLocalVec(localDofMap, ktest0);
createLocalVec(localDofMap, ktest1);
DofMap& m = localDofMap[pressureComponent].getMap();
for (DofMap::iterator it = m.begin(); it != m.end(); ++it)
{
if (dofMap[pressureFeSpace].isRankDof(it->first))
{
int index = localDofMap.getLocalMatIndex(pressureComponent, it->first);
VecSetValue(ktest0, index, 1.0, INSERT_VALUES);
}
}
VecAssemblyBegin(ktest0);
VecAssemblyEnd(ktest0);
MatMult(subdomain->getMatInterior(), ktest0, ktest1);
PetscScalar* valarray;
Vec ktest2, ktest3;
VecGetArray(ktest1, &valarray);
VecCreateMPIWithArray(PETSC_COMM_WORLD, 1,
localDofMap.getRankDofs(), nGlobalOverallInterior,
valarray, &ktest2);
createVec(localDofMap, ktest3, nGlobalOverallInterior);
Vec vecArray[2];
createVec(interfaceDofMap, vecArray[0]);
createVec(lagrangeMap, vecArray[1]);
VecSet(vecArray[0], 1.0);
MatMult(subdomain->getMatInteriorCoarse(1), vecArray[0], ktest3);
VecAXPY(ktest3, 1.0, ktest2);
MatMult(mat_lagrange_scaled, ktest3, vecArray[1]);
VecScale(vecArray[1], -1.0);
Vec nullSpaceBasis;
VecCreateNest(domainComm, 2, PETSC_NULL, vecArray, &nullSpaceBasis);
#if (DEBUG != 0)
PetscSolverFetiDebug::writeNullSpace(*this, nullSpaceBasis);
#endif
MatNullSpace matNullSpace;
MatNullSpaceCreate(domainComm, PETSC_FALSE, 1, &nullSpaceBasis,
&matNullSpace);
MatSetNullSpace(mat_feti, matNullSpace);
KSPSetNullSpace(ksp_feti, matNullSpace);
MatNullSpaceDestroy(&matNullSpace);
VecDestroy(&ktest0);
VecDestroy(&ktest1);
VecDestroy(&ktest2);
VecDestroy(&ktest3);
VecDestroy(&(vecArray[0]));
VecDestroy(&(vecArray[1]));
VecDestroy(&nullSpaceBasis);
}
void PetscSolverFeti::dbgMatrix(Matrix<DOFMatrix*>* mat)
{
FUNCNAME("PetscSolverFeti::dbgMatrix()");
if (levelMode == 2 && meshLevel == 0)
{
MSG("WARNING: MAKE MORE GENERAL!\n");
return;
}
#if (DEBUG != 0)
PetscInt nRow, nCol;
MatGetLocalSize(subdomain->getMatInterior(), &nRow, &nCol);
mpi::globalAdd(nRow);
mpi::globalAdd(nCol);
MatInfo minfo;
MatGetInfo(subdomain->getMatInterior(), MAT_GLOBAL_SUM, &minfo);
int nnz = static_cast<int>(minfo.nz_used);
mpi::globalAdd(nnz);
MSG("Interior matrices [%d x %d] nnz = %d\n", nRow, nCol, nnz);
MatGetSize(subdomain->getMatCoarse(), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarse(), MAT_GLOBAL_SUM, &minfo);
MSG("Primal matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatCoarseInterior(), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarseInterior(), MAT_GLOBAL_SUM, &minfo);
MSG("Primal-Interior matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatInteriorCoarse(), &nRow, &nCol);
MatGetInfo(subdomain->getMatInteriorCoarse(), MAT_GLOBAL_SUM, &minfo);
MSG("Interior-Primal matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
if (stokesMode)
{
MatGetSize(subdomain->getMatCoarse(1, 1), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarse(1, 1), MAT_GLOBAL_SUM, &minfo);
MSG("Interface matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatCoarseInterior(1), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarseInterior(1), MAT_GLOBAL_SUM, &minfo);
MSG("Interface-Interior matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatInteriorCoarse(1), &nRow, &nCol);
MatGetInfo(subdomain->getMatInteriorCoarse(1), MAT_GLOBAL_SUM, &minfo);
MSG("Interior-Interface matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatCoarse(1, 0), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarse(1, 0), MAT_GLOBAL_SUM, &minfo);
MSG("Interface-Primal matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
MatGetSize(subdomain->getMatCoarse(0, 1), &nRow, &nCol);
MatGetInfo(subdomain->getMatCoarse(0, 1), MAT_GLOBAL_SUM, &minfo);
MSG("Primal-Interface matrix [%d x %d] nnz = %d\n", nRow, nCol,
static_cast<int>(minfo.nz_used));
}
#endif
int writeInteriorMatrix = -1;
Parameters::get("parallel->debug->write interior matrix",
writeInteriorMatrix);
if (writeInteriorMatrix >= 0 &&
writeInteriorMatrix == MPI::COMM_WORLD.Get_rank())
{
PetscViewer petscView;
PetscViewerBinaryOpen(PETSC_COMM_SELF, "interior.mat",
FILE_MODE_WRITE, &petscView);
MatView(subdomain->getMatInterior(), petscView);
PetscViewerDestroy(&petscView);
}
bool checkInteriorMatrix = false;;
Parameters::get("parallel->debug->check interior matrix",
checkInteriorMatrix);
if (checkInteriorMatrix)
{
int nZeroRows = PetscSolverFetiDebug::testZeroRows(subdomain->getMatInterior());
MSG("Interior matrix has %d zero rows!\n", nZeroRows);
}
bool printDirichlet = false;
Parameters::get("parallel->debug->print dirichlet information",
printDirichlet);
if (printDirichlet)
{
int nComponents = mat->getSize();
for (int component = 0; component < nComponents; component++)
{
DOFMatrix* seqMat = (*mat)[component][component];
if (!seqMat)
continue;
const FiniteElemSpace* feSpace = seqMat->getRowFeSpace();
TEST_EXIT(feSpace)("Should not happen!\n");
std::set<DegreeOfFreedom>& dirichletRows = seqMat->getDirichletRows();
for (std::set<DegreeOfFreedom>::iterator it = dirichletRows.begin();
it != dirichletRows.end(); ++it)
{
if (localDofMap[component].isSet(*it))
{
MSG("Dirichlet dof %d in component %d with interior mat index %d\n",
*it, component, localDofMap.getMatIndex(component, *it));
}
}
}
}
int writeCoarseMatrix = 0;
Parameters::get("parallel->debug->write coarse matrix",
writeCoarseMatrix);
if (writeCoarseMatrix > 0)
{
PetscViewer petscView;
PetscViewerBinaryOpen(PETSC_COMM_WORLD, "coarse.mat",
FILE_MODE_WRITE, &petscView);
MatView(subdomain->getMatCoarse(), petscView);
PetscViewerDestroy(&petscView);
}
int writeSchurPrimalMatrix = 0;
Parameters::get("parallel->debug->write schur primal matrix",
writeSchurPrimalMatrix);
if (writeSchurPrimalMatrix)
{
PetscViewer petscView;
PetscViewerBinaryOpen(PETSC_COMM_WORLD, "schurprimal.mat",
FILE_MODE_WRITE, &petscView);
MatView(mat_schur_primal, petscView);
PetscViewerDestroy(&petscView);
}
}
void PetscSolverFeti::recoverSolution(Vec& vec_sol_b,
Vec& vec_sol_primal,
SystemVector& vec)
{
FUNCNAME("PetscSolverFeti::recoverSolution()");
// === Get local part of the solution for B variables. ===
PetscScalar* localSolB;
VecGetArray(vec_sol_b, &localSolB);
PetscInt bsize;
VecGetLocalSize(vec_sol_b, &bsize);
// === Create scatter to get solutions of all primal nodes that are ===
// === contained in rank's domain. ===
unsigned int nComponents = vec.getSize();
vector<PetscInt> globalIsIndex, localIsIndex;
globalIsIndex.reserve(primalDofMap.getLocalDofs());
localIsIndex.reserve(primalDofMap.getLocalDofs());
{
int cnt = 0;
for (unsigned int component = 0; component < nComponents; component++)
{
DofMap& dofMap = primalDofMap[component].getMap();
for (DofMap::iterator it = dofMap.begin(); it != dofMap.end(); ++it)
{
globalIsIndex.push_back(primalDofMap.getMatIndex(component, it->first));
localIsIndex.push_back(cnt++);
}
}
TEST_EXIT_DBG(cnt == primalDofMap.getLocalDofs())
("Should not happen!\n");
}
IS globalIs, localIs;
ISCreateGeneral(PETSC_COMM_SELF,
globalIsIndex.size(),
&(globalIsIndex[0]),
PETSC_USE_POINTER,
&globalIs);
ISCreateGeneral(PETSC_COMM_SELF,
localIsIndex.size(),
&(localIsIndex[0]),
PETSC_USE_POINTER,
&localIs);
Vec local_sol_primal;
VecCreateSeq(PETSC_COMM_SELF, localIsIndex.size(), &local_sol_primal);
VecScatter primalScatter;
VecScatterCreate(vec_sol_primal, globalIs, local_sol_primal, localIs, &primalScatter);
VecScatterBegin(primalScatter, vec_sol_primal, local_sol_primal,
INSERT_VALUES, SCATTER_FORWARD);
VecScatterEnd(primalScatter, vec_sol_primal, local_sol_primal,
INSERT_VALUES, SCATTER_FORWARD);
ISDestroy(&globalIs);
ISDestroy(&localIs);
VecScatterDestroy(&primalScatter);
PetscScalar* localSolPrimal;
VecGetArray(local_sol_primal, &localSolPrimal);
// === And copy from PETSc local vectors to the DOF vectors. ===
int cnt = 0;
for (unsigned int component = 0; component < nComponents; component++)
{
DOFVector<double>& dofVec = *(vec.getDOFVector(component));
for (DofMap::iterator it = localDofMap[component].getMap().begin();
it != localDofMap[component].getMap().end(); ++it)
{
if (subDomainIsLocal)
{
int petscIndex = localDofMap.getLocalMatIndex(component, it->first);
dofVec[it->first] = localSolB[petscIndex];
}
else
{
if (dofMapSubDomain[componentSpaces[component]].isRankDof(it->first))
{
int petscIndex = localDofMap.getLocalMatIndex(component, it->first);
TEST_EXIT(petscIndex < bsize)("Should not happen!\n");
dofVec[it->first] = localSolB[petscIndex];
}
}
}
for (DofMap::iterator it = primalDofMap[component].getMap().begin();
it != primalDofMap[component].getMap().end(); ++it)
dofVec[it->first] = localSolPrimal[cnt++];
}
VecRestoreArray(vec_sol_b, &localSolB);
VecRestoreArray(local_sol_primal, &localSolPrimal);
VecDestroy(&local_sol_primal);
}
void PetscSolverFeti::recoverInterfaceSolution(Vec& vecInterface, SystemVector& vec)
{
FUNCNAME("PetscSolverFeti::recoverInterfaceSolution()");
if (!stokesMode)
return;
vector<PetscInt> globalIsIndex, localIsIndex;
globalIsIndex.reserve(interfaceDofMap.getLocalDofs());
localIsIndex.reserve(interfaceDofMap.getLocalDofs());
int cnt = 0;
DofMap& dofMap = interfaceDofMap[pressureComponent].getMap();
for (DofMap::iterator it = dofMap.begin(); it != dofMap.end(); ++it)
{
globalIsIndex.push_back(interfaceDofMap.getMatIndex(pressureComponent,
it->first));
localIsIndex.push_back(cnt++);
}
IS globalIs, localIs;
ISCreateGeneral(PETSC_COMM_SELF,
globalIsIndex.size(),
&(globalIsIndex[0]),
PETSC_USE_POINTER,
&globalIs);
ISCreateGeneral(PETSC_COMM_SELF,
localIsIndex.size(),
&(localIsIndex[0]),
PETSC_USE_POINTER,
&localIs);
Vec local_sol_interface;
VecCreateSeq(PETSC_COMM_SELF, localIsIndex.size(), &local_sol_interface);
VecScatter interfaceScatter;
VecScatterCreate(vecInterface, globalIs, local_sol_interface, localIs, &interfaceScatter);
VecScatterBegin(interfaceScatter, vecInterface, local_sol_interface,
INSERT_VALUES, SCATTER_FORWARD);
VecScatterEnd(interfaceScatter, vecInterface, local_sol_interface,
INSERT_VALUES, SCATTER_FORWARD);
ISDestroy(&globalIs);
ISDestroy(&localIs);
VecScatterDestroy(&interfaceScatter);
PetscScalar* localSolInterface;
VecGetArray(local_sol_interface, &localSolInterface);
// === And copy from PETSc local vectors to the DOF vectors. ===
cnt = 0;
DOFVector<double>& dofVec = *(vec.getDOFVector(pressureComponent));
for (DofMap::iterator it = interfaceDofMap[pressureComponent].getMap().begin();
it != interfaceDofMap[pressureComponent].getMap().end(); ++it)
{
dofVec[it->first] = localSolInterface[cnt++];
}
VecRestoreArray(local_sol_interface, &localSolInterface);
VecDestroy(&local_sol_interface);
}
void PetscSolverFeti::fillPetscMatrix(Matrix<DOFMatrix*>* mat)
{
FUNCNAME("PetscSolverFeti::fillPetscMatrix()");
// === Create all sets and indices. ===
initialize();
createDirichletData(*mat);
createFetiData();
// === Create matrices for the FETI-DP method. ===
if (printTimings)
MPI::COMM_WORLD.Barrier();
double wtime = MPI::Wtime();
subdomain->fillPetscMatrix(mat);
// === SUPER TRICK ===
if (meshLevel == 1)
{
MSG("START MAT TRICK!\n");
mlSubdomain = new PetscSolverGlobalMatrix("");
mlSubdomain->setSymmetric(isSymmetric);
mlSubdomain->setHandleDirichletRows(dirichletMode == 0);
mlSubdomain->setMeshDistributor(meshDistributor, meshLevel);
mlSubdomain->init(componentSpaces, feSpaces);
mlSubdomain->setDofMapping(interiorMap);
mlSubdomain->setCoarseSpaceDofMapping(coarseSpaceMap[0]);
mlSubdomain->fillPetscMatrix(mat);
this->mat = mlSubdomain->getMat();
MSG("END MAT TRICK!\n");
}
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 02: %.5f seconds (creation of interior matrices)\n",
MPI::Wtime() - wtime);
// For the case, that we want to print the timings, we force the LU
// factorization of the local problems to be done here explicitly.
wtime = MPI::Wtime();
KSPSetUp(subdomain->getSolver());
KSPSetUpOnBlocks(subdomain->getSolver());
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 04: %.5f seconds (factorization of subdomain matrices)\n",
MPI::Wtime() - wtime);
}
// === Create matrices for FETI-DP preconditioner. ===
createPreconditionerMatrix(mat);
// === Create and fill PETSc matrix for Lagrange constraints. ===
createMatLagrange();
// === ===
createMatAugmentedLagrange();
// === Create PETSc solver for the Schur complement on primal variables. ===
createSchurPrimalKsp();
// === Create PETSc solver for the FETI-DP operator. ===
createFetiKsp();
// === If required, run debug tests. ===
dbgMatrix(mat);
}
void PetscSolverFeti::fillPetscRhs(SystemVector* vec)
{
FUNCNAME("PetscSolverFeti::fillPetscRhs()");
subdomain->fillPetscRhs(vec);
if (meshLevel == 1)
{
MSG("START VEC TRICK!\n");
mlSubdomain->fillPetscRhs(vec);
this->vecRhs = mlSubdomain->getVecRhs();
MSG("END VEC TRICK!\n");
}
}
void PetscSolverFeti::createPreconditionerMatrix(Matrix<DOFMatrix*>* mat)
{
FUNCNAME("PetscSolverFeti::createPreconditionerMatrix()");
if (fetiPreconditioner == FETI_NONE && fetiSolverType == EXACT)
return;
double wtime = MPI::Wtime();
int nRowsDual = dualDofMap.getRankDofs();
MatCreateSeqAIJ(PETSC_COMM_SELF,
nRowsDual, nRowsDual, 100, PETSC_NULL,
&mat_duals_duals);
MatSetOption(mat_duals_duals, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
if (fetiPreconditioner == FETI_DIRICHLET)
{
int nRowsInterior = interiorDofMap.getRankDofs();
MatCreateSeqAIJ(PETSC_COMM_SELF,
nRowsInterior, nRowsInterior, 100, PETSC_NULL,
&mat_interior_interior);
MatSetOption(mat_interior_interior,
MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
MatCreateSeqAIJ(PETSC_COMM_SELF,
nRowsInterior, nRowsDual, 100, PETSC_NULL,
&mat_interior_duals);
MatSetOption(mat_interior_duals,
MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
MatCreateSeqAIJ(PETSC_COMM_SELF,
nRowsDual, nRowsInterior, 100, PETSC_NULL,
&mat_duals_interior);
MatSetOption(mat_duals_interior,
MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);
}
// === Prepare traverse of sequentially created matrices. ===
using mtl::tag::row;
using mtl::tag::nz;
using mtl::begin;
using mtl::end;
namespace traits = mtl::traits;
typedef DOFMatrix::base_matrix_type Matrix;
typedef traits::range_generator<row, Matrix>::type cursor_type;
typedef traits::range_generator<nz, cursor_type>::type icursor_type;
vector<int> colsLocal, colsLocalOther;
vector<double> valuesLocal, valuesLocalOther;
colsLocal.reserve(300);
colsLocalOther.reserve(300);
valuesLocal.reserve(300);
valuesLocalOther.reserve(300);
// === Traverse all sequentially created matrices and add the values to ===
// === the global PETSc matrices. ===
int nComponents = mat->getSize();
for (int rowComponent = 0; rowComponent < nComponents; rowComponent++)
{
for (int colComponent = 0; colComponent < nComponents; colComponent++)
{
DOFMatrix* dofMat = (*mat)[rowComponent][colComponent];
if (!dofMat)
continue;
TEST_EXIT_DBG(dofMat->getRowFeSpace() == componentSpaces[rowComponent])
("Wrong matrix row FE space!\n");
TEST_EXIT_DBG(dofMat->getColFeSpace() == componentSpaces[colComponent])
("Wrong matrix col FE space!!\n");
if (stokesMode &&
(rowComponent == pressureComponent ||
colComponent == pressureComponent))
continue;
// const FiniteElemSpace *rowFeSpace = dofMat->getRowFeSpace();
// const FiniteElemSpace *colFeSpace = dofMat->getColFeSpace();
traits::col<Matrix>::type col(dofMat->getBaseMatrix());
traits::const_value<Matrix>::type value(dofMat->getBaseMatrix());
// Traverse all rows.
for (cursor_type cursor = begin<row>(dofMat->getBaseMatrix()),
cend = end<row>(dofMat->getBaseMatrix()); cursor != cend; ++cursor)
{
if (dirichletRows[rowComponent].count(cursor.value()))
continue;
if (isPrimal(rowComponent, cursor.value()))
continue;
if (fetiPreconditioner == FETI_DIRICHLET)
{
colsLocal.clear();
colsLocalOther.clear();
valuesLocal.clear();
valuesLocalOther.clear();
// Traverse all columns.
for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor);
icursor != icend; ++icursor)
{
if (dirichletRows[colComponent].count(col(*icursor)))
continue;
if (isPrimal(colComponent, col(*icursor)))
continue;
if (!isDual(rowComponent, cursor.value()))
{
if (!isDual(colComponent, col(*icursor)))
{
int colIndex =
interiorDofMap.getLocalMatIndex(colComponent, col(*icursor));
colsLocal.push_back(colIndex);
valuesLocal.push_back(value(*icursor));
}
else
{
int colIndex =
dualDofMap.getLocalMatIndex(colComponent, col(*icursor));
colsLocalOther.push_back(colIndex);
valuesLocalOther.push_back(value(*icursor));
}
}
else
{
if (!isDual(colComponent, col(*icursor)))
{
int colIndex =
interiorDofMap.getLocalMatIndex(colComponent, col(*icursor));
colsLocalOther.push_back(colIndex);
valuesLocalOther.push_back(value(*icursor));
}
else
{
int colIndex =
dualDofMap.getLocalMatIndex(colComponent, col(*icursor));
colsLocal.push_back(colIndex);
valuesLocal.push_back(value(*icursor));
}
}
} // for each nnz in row
if (!isDual(rowComponent, cursor.value()))
{
int rowIndex =
interiorDofMap.getLocalMatIndex(rowComponent, cursor.value());
MatSetValues(mat_interior_interior, 1, &rowIndex, colsLocal.size(),
&(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES);
if (colsLocalOther.size())
MatSetValues(mat_interior_duals, 1, &rowIndex, colsLocalOther.size(),
&(colsLocalOther[0]), &(valuesLocalOther[0]), INSERT_VALUES);
}
else
{
int rowIndex =
dualDofMap.getLocalMatIndex(rowComponent, cursor.value());
MatSetValues(mat_duals_duals, 1, &rowIndex, colsLocal.size(),
&(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES);
if (colsLocalOther.size())
MatSetValues(mat_duals_interior, 1, &rowIndex, colsLocalOther.size(),
&(colsLocalOther[0]), &(valuesLocalOther[0]), INSERT_VALUES);
}
}
if (fetiPreconditioner == FETI_LUMPED || fetiSolverType == INEXACT)
{
if (!isDual(rowComponent, cursor.value()))
continue;
colsLocal.clear();
valuesLocal.clear();
// Traverse all columns.
for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor);
icursor != icend; ++icursor)
{
if (dirichletRows[colComponent].count(col(*icursor)))
continue;
if (!isDual(colComponent, col(*icursor)))
continue;
int colIndex =
dualDofMap.getLocalMatIndex(colComponent, col(*icursor));
colsLocal.push_back(colIndex);
valuesLocal.push_back(value(*icursor));
}
int rowIndex = dualDofMap.getLocalMatIndex(rowComponent, cursor.value());
MatSetValues(mat_duals_duals, 1, &rowIndex, colsLocal.size(),
&(colsLocal[0]), &(valuesLocal[0]), INSERT_VALUES);
}
}
}
}
// === Start global assembly procedure for preconditioner matrices. ===
if (fetiPreconditioner == FETI_LUMPED || fetiSolverType == INEXACT)
{
MatAssemblyBegin(mat_duals_duals, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_duals_duals, MAT_FINAL_ASSEMBLY);
}
if (fetiPreconditioner == FETI_DIRICHLET)
{
MatAssemblyBegin(mat_interior_interior, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_interior_interior, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(mat_duals_duals, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_duals_duals, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(mat_interior_duals, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_interior_duals, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(mat_duals_interior, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(mat_duals_interior, MAT_FINAL_ASSEMBLY);
}
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 03: %.5f seconds (creation of preconditioner matrices)\n",
MPI::Wtime() - wtime);
}
}
void PetscSolverFeti::solveFeti(Vec& rhsInterior, Vec& rhsCoarse,
Vec& solInterior, Vec& solCoarse)
{
FUNCNAME("PetscSolverFeti::solveFeti()");
switch (fetiSolverType)
{
case EXACT:
solveFetiExact(rhsInterior, rhsCoarse, solInterior, solCoarse);
break;
case INEXACT:
solveFetiInexact(rhsInterior, rhsCoarse, solInterior, solCoarse);
break;
case INEXACT_REDUCED:
solveFetiInexactReduced(rhsInterior, rhsCoarse, solInterior, solCoarse);
break;
default:
ERROR_EXIT("Should not happen!\n");
}
}
void PetscSolverFeti::solveFetiExact(Vec& rhsInterior, Vec& rhsCoarse,
Vec& solInterior, Vec& solCoarse)
{
FUNCNAME("PetscSolverFeti::solveFetiExact()");
// === Some temporary vectors. ===
Vec tmp_b1;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior, &tmp_b1);
Vec tmp_primal1;
createVec(primalDofMap, tmp_primal1);
Vec tmp_lagrange;
MatGetVecs(mat_lagrange, PETSC_NULL, &tmp_lagrange);
// === Create RHS and solution vectors. ===
Vec vecRhs, vecSol;
Vec vecRhsLagrange, vecSolLagrange;
MatGetVecs(mat_lagrange, PETSC_NULL, &vecRhsLagrange);
MatGetVecs(mat_lagrange, PETSC_NULL, &vecSolLagrange);
vecRhs = vecRhsLagrange;
vecSol = vecSolLagrange;
VecDuplicate(vecSol, &fetiKspData.draft);
// === Create reduced RHS ===
double wtime = MPI::Wtime();
// d = L inv(K_BB) f_B - L inv(K_BB) K_BPi inv(S_PiPi) [f_Pi - K_PiB inv(K_BB) f_B]
// vecRhs = L * inv(K_BB) * f_B
subdomain->solveGlobal(rhsInterior, solInterior);
MatMult(mat_lagrange, solInterior, vecRhsLagrange);
// solCoarse = M_PiB * inv(K_BB) * f_B
MatMult(subdomain->getMatCoarseInterior(), solInterior, solCoarse);
// solCoarse = f_Pi - M_PiB * inv(K_BB) * f_B
VecAXPBY(solCoarse, 1.0, -1.0, rhsCoarse);
double wtime2 = MPI::Wtime();
// solCoarse = inv(S_PiPi) (f_Pi - M_PiB * inv(K_BB) * f_B)
KSPSolve(ksp_schur_primal, solCoarse, solCoarse);
if (printTimings)
{
MSG("FETI-DP timing 09a: %.5f seconds (create rhs vector)\n",
MPI::Wtime() - wtime2);
}
MatMult(subdomain->getMatInteriorCoarse(), solCoarse, solInterior);
subdomain->solveGlobal(solInterior, solInterior);
MatMult(mat_lagrange, solInterior, tmp_lagrange);
VecAXPY(vecRhsLagrange, -1.0, tmp_lagrange);
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 09: %.5f seconds (create rhs vector)\n",
MPI::Wtime() - wtime);
wtime = MPI::Wtime();
FetiTimings::reset();
}
// === Optionally run some debug procedures on the FETI-DP system. ===
PetscSolverFetiDebug::debugFeti(*this, vecRhs);
// === Solve with FETI-DP operator. ===
KSPSolve(ksp_feti, vecRhs, vecSol);
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 10: %.5f seconds (application of FETI-DP operator)\n",
MPI::Wtime() - wtime);
wtime = MPI::Wtime();
MSG("FETI-DP timing 10a: %.5f [ %.5f %.5f ] seconds (FETI-DP KSP Solve)\n",
FetiTimings::fetiSolve, FetiTimings::fetiSolve01, FetiTimings::fetiSolve02);
MSG("FETI-DP timing 10b: %.5f seconds (FETI-DP KSP Solve)\n",
FetiTimings::fetiPreconditioner);
}
// === Solve for u_primals. ===
MatMultTranspose(mat_lagrange, vecSol, solInterior);
VecAYPX(solInterior, -1.0, rhsInterior);
subdomain->solveGlobal(solInterior, tmp_b1);
MatMult(subdomain->getMatCoarseInterior(), tmp_b1, solCoarse);
VecAYPX(solCoarse, -1.0, rhsCoarse);
KSPSolve(ksp_schur_primal, solCoarse, solCoarse);
// === Solve for u_b. ===
MatMult(subdomain->getMatInteriorCoarse(), solCoarse, tmp_b1);
VecAXPY(solInterior, -1.0, tmp_b1);
subdomain->solveGlobal(solInterior, solInterior);
// === Print timings and delete data. ===
if (printTimings)
{
MPI::COMM_WORLD.Barrier();
MSG("FETI-DP timing 11: %.5f seconds (Inner solve and solution recovery)\n",
MPI::Wtime() - wtime);
}
VecDestroy(&vecRhs);
VecDestroy(&vecSol);
VecDestroy(&tmp_b1);
VecDestroy(&tmp_lagrange);
VecDestroy(&tmp_primal1);
}
void PetscSolverFeti::solveFetiInexact(Vec& rhsInterior, Vec& rhsCoarse,
Vec& solInterior, Vec& solCoarse)
{
FUNCNAME("PetscSolverFeti::solveFetiInexact()");
Vec tmpLagrange0, tmpLagrange1;
createVec(lagrangeMap, tmpLagrange0);
createVec(lagrangeMap, tmpLagrange1);
VecSet(tmpLagrange0, 0.0);
VecSet(tmpLagrange1, 0.0);
Vec nestVecRhs[3];
nestVecRhs[0] = rhsInterior;
nestVecRhs[1] = rhsCoarse;
nestVecRhs[2] = tmpLagrange0;
Vec nestVecSol[3];
nestVecSol[0] = solInterior;
nestVecSol[1] = solCoarse;
nestVecSol[2] = tmpLagrange1;
Vec vecRhs, vecSol;
VecCreateNest(domainComm, 3, PETSC_NULL, nestVecRhs, &vecRhs);
VecCreateNest(domainComm, 3, PETSC_NULL, nestVecSol, &vecSol);
KSPSolve(ksp_feti, vecRhs, vecSol);
VecDestroy(&vecRhs);
VecDestroy(&vecSol);
VecDestroy(&tmpLagrange0);
VecDestroy(&tmpLagrange1);
}
void PetscSolverFeti::solveFetiInexactReduced(Vec& rhsInterior, Vec& rhsCoarse,
Vec& solInterior, Vec& solCoarse)
{
FUNCNAME("PetscSolverFeti::solveFetiInexactReduced()");
ERROR_EXIT("Not yet implemented!\n");
}
void PetscSolverFeti::destroyMatrixData()
{
FUNCNAME("PetscSolverFeti::destroyMatrixData()");
MatDestroy(&mat_lagrange);
if (augmentedLagrange)
MatDestroy(&mat_augmented_lagrange);
// === Destroy preconditioner data structures. ===
if (fetiPreconditioner != FETI_NONE)
MatDestroy(&mat_duals_duals);
if (fetiPreconditioner == FETI_DIRICHLET)
{
MatDestroy(&mat_interior_interior);
MatDestroy(&mat_interior_duals);
MatDestroy(&mat_duals_interior);
}
destroySchurPrimalKsp();
destroyFetiKsp();
subdomain->destroyMatrixData();
}
void PetscSolverFeti::destroyVectorData()
{
FUNCNAME("PetscSolverFeti::destroyVectorData()");
subdomain->destroyVectorData();
}
void PetscSolverFeti::solvePetscMatrix(SystemVector& vec, AdaptInfo& adaptInfo)
{
FUNCNAME("PetscSolverFeti::solvePetscMatrix()");
Vec solInterior;
VecCreateMPI(meshDistributor->getMeshLevelData().getMpiComm(meshLevel),
localDofMap.getRankDofs(),
nGlobalOverallInterior,
&solInterior);
Vec solCoarse;
createVec(primalDofMap, solCoarse);
solveFeti(subdomain->getVecRhsInterior(),
subdomain->getVecRhsCoarse(),
solInterior,
solCoarse);
// === And recover AMDiS solution vectors. ===
recoverSolution(solInterior, solCoarse, vec);
VecDestroy(&solInterior);
VecDestroy(&solCoarse);
MeshDistributor::globalMeshDistributor->synchVector(vec);
}
void PetscSolverFeti::solveGlobal(Vec& rhs, Vec& sol)
{
FUNCNAME("PetscSolverFeti::solveGlobal()");
Vec rhsInterior, rhsCoarse, solInterior, solCoarse;
VecCreateMPI(domainComm,
localDofMap.getRankDofs(),
nGlobalOverallInterior,
&rhsInterior);
createVec(primalDofMap, rhsCoarse);
VecDuplicate(rhsInterior, &solInterior);
VecDuplicate(rhsCoarse, &solCoarse);
int offset = 0;
{
int domainLocal = 0, nSuperLocal = 0;
if (domainComm.Get_rank() == 0)
domainLocal = interiorMap->getOverallDofs();
mpi::getDofNumbering(meshDistributor->getMpiComm(meshLevel - 1),
domainLocal, offset, nSuperLocal);
int tmp = 0;
if (domainComm.Get_rank() == 0)
tmp = offset;
domainComm.Allreduce(&tmp, &offset, 1, MPI_INT, MPI_SUM);
}
vector<int> localFromRhs, coarseFromRhs;
vector<int> rhsToLocal, rhsToCoarse;
int nComponents = componentSpaces.size();
for (int i = 0; i < nComponents; i++)
{
DofMap& dMap = localDofMap[i].getMap();
for (DofMap::iterator it = dMap.begin(); it != dMap.end(); ++it)
{
int matL = localDofMap.getMatIndex(i, it->first) + rStartInterior;
int matI = interiorMap->getMatIndex(i, it->first) + offset;
localFromRhs.push_back(matL);
rhsToLocal.push_back(matI);
}
}
for (int i = 0; i < nComponents; i++)
{
DofMap& dMap = primalDofMap[i].getMap();
for (DofMap::iterator it = dMap.begin(); it != dMap.end(); ++it)
{
int matL = primalDofMap.getMatIndex(i, it->first);
int matI = interiorMap->getMatIndex(i, it->first) + offset;
coarseFromRhs.push_back(matL);
rhsToCoarse.push_back(matI);
}
}
copyVec(rhs, rhsInterior, rhsToLocal, localFromRhs);
copyVec(rhs, rhsCoarse, rhsToCoarse, coarseFromRhs);
solveFeti(rhsInterior, rhsCoarse, solInterior, solCoarse);
copyVec(solInterior, sol, localFromRhs, rhsToLocal);
copyVec(solCoarse, sol, coarseFromRhs, rhsToCoarse);
MPI::COMM_WORLD.Barrier();
VecDestroy(&rhsInterior);
VecDestroy(&rhsCoarse);
VecDestroy(&solInterior);
VecDestroy(&solCoarse);
}
}
} // end namespaces
| 33.683502 | 121 | 0.602279 | spraetor |
4eca6a6280a9c00c8567b67e506ae22dc21604c6 | 13,055 | cpp | C++ | src/UIController.cpp | nselikoff/Cinder-MinimalUI | f5ace74b8e514a372869d7211e5d76122d573241 | [
"MIT"
] | 6 | 2015-03-12T12:33:49.000Z | 2018-04-20T18:30:28.000Z | src/UIController.cpp | nselikoff/Cinder-MinimalUI | f5ace74b8e514a372869d7211e5d76122d573241 | [
"MIT"
] | null | null | null | src/UIController.cpp | nselikoff/Cinder-MinimalUI | f5ace74b8e514a372869d7211e5d76122d573241 | [
"MIT"
] | 3 | 2020-04-20T21:34:16.000Z | 2020-05-06T19:24:42.000Z | #include "UIController.h"
#include "UIElement.h"
#include "Slider.h"
#include "Button.h"
#include "Label.h"
#include "Image.h"
#include "Graph.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace MinimalUI;
class FontStyleExc;
int UIController::DEFAULT_PANEL_WIDTH = 216;
int UIController::DEFAULT_MARGIN_LARGE = 10;
int UIController::DEFAULT_MARGIN_SMALL = 4;
int UIController::DEFAULT_UPDATE_FREQUENCY = 2;
int UIController::DEFAULT_FBO_WIDTH = 2048;
ci::ColorA UIController::DEFAULT_STROKE_COLOR = ci::ColorA( 0.07f, 0.26f, 0.29f, 1.0f );
ci::ColorA UIController::ACTIVE_STROKE_COLOR = ci::ColorA( 0.19f, 0.66f, 0.71f, 1.0f );
ci::ColorA UIController::DEFAULT_NAME_COLOR = ci::ColorA( 0.14f, 0.49f, 0.54f, 1.0f );
ci::ColorA UIController::DEFAULT_BACKGROUND_COLOR = ci::ColorA( 0.0f, 0.0f, 0.0f, 1.0f );
UIController::UIController( app::WindowRef aWindow, const string &aParamString )
: mWindow( aWindow ), mParamString( aParamString )
{
JsonTree params( mParamString );
mVisible = params.hasChild( "visible" ) ? params["visible"].getValue<bool>() : true;
mAlpha = mVisible ? 1.0f : 0.0f;
mWidth = params.hasChild( "width" ) ? params["width"].getValue<int>() : DEFAULT_PANEL_WIDTH;
mX = params.hasChild( "x" ) ? params["x"].getValue<int>() : 0;
mY = params.hasChild( "y" ) ? params["y"].getValue<int>() : 0;
if ( params.hasChild( "height" ) ) {
mHeightSpecified = true;
mHeight = params["height"].getValue<int>();
} else {
mHeightSpecified = false;
mHeight = getWindow()->getHeight();
}
mCentered = params.hasChild( "centered" ) ? params["centered"].getValue<bool>() : false;
mDepth = params.hasChild( "depth" ) ? params["depth"].getValue<int>() : 0;
mForceInteraction = params.hasChild( "forceInteraction" ) ? params["forceInteraction"].getValue<bool>() : false;
mMarginLarge = params.hasChild( "marginLarge" ) ? params["marginLarge"].getValue<int>() : DEFAULT_MARGIN_LARGE;
// JSON doesn't support hex literals...
std::stringstream str;
string panelColor = params.hasChild( "panelColor" ) ? params["panelColor"].getValue<string>() : "0xCC000000";
str << panelColor;
uint32_t hexValue;
str >> std::hex >> hexValue;
mPanelColor = ColorA::hexA( hexValue );
if ( params.hasChild( "defaultStrokeColor" ) )
{
string strValue = params["defaultStrokeColor"].getValue<string>();
str.clear();
str << strValue;
str >> std::hex >> hexValue;
UIController::DEFAULT_STROKE_COLOR = ColorA::hexA( hexValue );
}
if ( params.hasChild( "activeStrokeColor" ) )
{
string strValue = params["activeStrokeColor"].getValue<string>();
str.clear();
str << strValue;
str >> std::hex >> hexValue;
UIController::ACTIVE_STROKE_COLOR = ColorA::hexA( hexValue );
}
if ( params.hasChild( "defaultNameColor" ) )
{
string strValue = params["defaultNameColor"].getValue<string>();
str.clear();
str << strValue;
str >> std::hex >> hexValue;
UIController::DEFAULT_NAME_COLOR = ColorA::hexA( hexValue );
}
if ( params.hasChild( "defaultBackgroundColor" ) )
{
string strValue = params["defaultBackgroundColor"].getValue<string>();
str.clear();
str << strValue;
str >> std::hex >> hexValue;
UIController::DEFAULT_BACKGROUND_COLOR = ColorA::hexA( hexValue );
}
resize();
mCbMouseDown = mWindow->getSignalMouseDown().connect( mDepth + 99, std::bind( &UIController::mouseDown, this, std::placeholders::_1 ) );
// set default fonts
setFont( "label", Font( "Arial", 16 * 2 ) );
setFont( "smallLabel", Font( "Arial", 12 * 2 ) );
setFont( "icon", Font( "Arial", 22 * 2 ) );
setFont( "header", Font( "Arial", 48 * 2 ) );
setFont( "body", Font( "Arial", 19 * 2 ) );
setFont( "footer", Font( "Arial Italic", 14 * 2 ) );
mInsertPosition = Vec2i( mMarginLarge, mMarginLarge );
mFboNumSamples = params.hasChild( "fboNumSamples" ) ? params["fboNumSamples"].getValue<int>() : 0;
if (params.hasChild("backgroundImage")) {
mBackgroundTexture = gl::Texture(loadImage(loadAsset(params["backgroundImage"].getValue<string>())));
}
setupFbo();
}
UIControllerRef UIController::create( const string &aParamString, app::WindowRef aWindow )
{
return shared_ptr<UIController>( new UIController( aWindow, aParamString ) );
}
void UIController::resize()
{
Vec2i size;
if ( mCentered ) {
size = Vec2i( mWidth, mHeight );
mPosition = getWindow()->getCenter() - size / 2;
} else if ( mHeightSpecified ) {
size = Vec2i( mWidth, mHeight );
mPosition = Vec2i( mX, mY );
} else {
size = Vec2i( mWidth, getWindow()->getHeight() );
mPosition = Vec2i( mX, mY );
}
mBounds = Area( Vec2i::zero(), size );
}
void UIController::mouseDown( MouseEvent &event )
{
if ( mVisible ) {
if ( (mBounds + mPosition).contains( event.getPos() ) || mForceInteraction )
{
event.setHandled();
}
}
}
void UIController::drawBackground()
{
gl::pushMatrices();
gl::color(Color::white());
// draw the background texture if it's defined
if (mBackgroundTexture) gl::draw(mBackgroundTexture, mBounds);
gl::popMatrices();
}
void UIController::draw()
{
if (!mVisible)
return;
// save state
gl::pushMatrices();
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_LINE_BIT | GL_CURRENT_BIT);
// disable depth read (otherwise any 3d drawing done after this will be obscured by the FBO; not exactly sure why)
gl::disableDepthRead();
// optimization
if (getElapsedFrames() % DEFAULT_UPDATE_FREQUENCY == 0) {
// start drawing to the Fbo
mFbo.bindFramebuffer();
gl::lineWidth(toPixels(2.0f));
gl::enable(GL_LINE_SMOOTH);
gl::enableAlphaBlending();
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// clear and set viewport and matrices
gl::clear(ColorA(0.0f, 0.0f, 0.0f, 0.0f));
gl::setViewport(toPixels(mBounds + mPosition));
gl::setMatricesWindow(toPixels(mBounds.getSize()), false);
// draw backing panel
gl::color(mPanelColor);
gl::drawSolidRect(toPixels(mBounds));
// draw the background
drawBackground();
// draw elements
for (unsigned int i = 0; i < mUIElements.size(); i++) {
mUIElements[i]->draw();
}
// finish drawing to the Fbo
mFbo.unbindFramebuffer();
}
// reset the matrices and blending
gl::setViewport( toPixels( getWindow()->getBounds() ) );
gl::setMatricesWindow( toPixels( getWindow()->getSize() ) );
gl::enableAlphaBlending( true );
// if forcing interaction, draw an overlay over the whole window
if ( mForceInteraction ) {
gl::color(ColorA( 0.0f, 0.0f, 0.0f, 0.5f * mAlpha));
gl::drawSolidRect( toPixels( getWindow()->getBounds() ) );
}
// draw the FBO to the screen
gl::color( ColorA( mAlpha, mAlpha, mAlpha, mAlpha ) );
gl::draw( mFbo.getTexture() );
gl::disableAlphaBlending();
// restore state
glPopAttrib();
gl::popMatrices();
}
void UIController::update()
{
if ( !mVisible )
return;
if ( getElapsedFrames() % DEFAULT_UPDATE_FREQUENCY == 0 ) {
for (unsigned int i = 0; i < mUIElements.size(); i++) {
mUIElements[i]->update();
}
}
}
void UIController::show()
{
mVisible = true;
timeline().apply( &mAlpha, 1.0f, 0.25f );
}
void UIController::hide()
{
timeline().apply( &mAlpha, 0.0f, 0.25f ).finishFn( [&]{ mVisible = false; } );
}
UIElementRef UIController::addSlider( const string &aName, float *aValueToLink, const string &aParamString )
{
UIElementRef sliderRef = Slider::create( this, aName, aValueToLink, aParamString );
addElement( sliderRef );
return sliderRef;
}
UIElementRef UIController::addButton( const string &aName, const function<void( bool )> &aEventHandler, const string &aParamString )
{
UIElementRef buttonRef = Button::create( this, aName, aEventHandler, aParamString );
addElement( buttonRef );
return buttonRef;
}
UIElementRef UIController::addLinkedButton( const string &aName, const function<void( bool )> &aEventHandler, bool *aLinkedState, const string &aParamString )
{
UIElementRef linkedButtonRef = LinkedButton::create( this, aName, aEventHandler, aLinkedState, aParamString );
addElement( linkedButtonRef );
return linkedButtonRef;
}
UIElementRef UIController::addLabel( const string &aName, const string &aParamString )
{
UIElementRef labelRef = Label::create( this, aName, aParamString );
addElement( labelRef );
return labelRef;
}
UIElementRef UIController::addImage( const string &aName, ImageSourceRef aImage, const string &aParamString )
{
UIElementRef imageRef = Image::create( this, aName, aImage, aParamString );
addElement( imageRef );
return imageRef;
}
UIElementRef UIController::addSlider2D( const string &aName, Vec2f *aValueToLink, const string &aParamString )
{
UIElementRef slider2DRef = Slider2D::create( this, aName, aValueToLink, aParamString );
addElement( slider2DRef );
return slider2DRef;
}
UIElementRef UIController::addSliderCallback( const std::string &aName, float *aValueToLink, const std::function<void ()> &aEventHandler, const std::string &aParamString )
{
UIElementRef sliderCallbackRef = SliderCallback::create( this, aName, aValueToLink, aEventHandler, aParamString );
addElement( sliderCallbackRef );
return sliderCallbackRef;
}
UIElementRef UIController::addToggleSlider( const string &aSliderName, float *aValueToLink, const string &aButtonName, const function<void (bool)> &aEventHandler, const string &aSliderParamString, const string &aButtonParamString )
{
// create the slider
UIElementRef toggleSliderRef = Slider::create( this, aSliderName, aValueToLink, aSliderParamString );
// add the slider to the controller
addElement( toggleSliderRef );
// create the button
UIElementRef newButtonRef = Button::create( this, aButtonName, aEventHandler, aButtonParamString );
// add an additional event handler to link the button to the slider
std::shared_ptr<class Button> newButton = std::static_pointer_cast<class Button>(newButtonRef);
newButton->addEventHandler( std::bind(&Slider::setLocked, toggleSliderRef, std::placeholders::_1 ) );
// add the button to the controller
addElement( newButton );
return toggleSliderRef;
}
// without event handler
UIElementRef UIController::addMovingGraph(const string &aName, float *aValueToLink, const string &aParamString)
{
UIElementRef movingGraphRef = MovingGraph::create(this, aName, aValueToLink, aParamString);
addElement(movingGraphRef);
return movingGraphRef;
}
// with event handler
// note: this would be an overloaded addMovingGraph function for consistency, were it not for a visual studio compiler defect (see http://cplusplus.github.io/LWG/lwg-active.html#2132)
UIElementRef UIController::addMovingGraphButton(const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString)
{
UIElementRef movingGraphRef = MovingGraph::create(this, aName, aValueToLink, aEventHandler, aParamString);
addElement(movingGraphRef);
return movingGraphRef;
}
void UIController::releaseGroup( const string &aGroup )
{
for (unsigned int i = 0; i < mUIElements.size(); i++) {
if (mUIElements[i]->getGroup() == aGroup ) {
mUIElements[i]->release();
}
}
}
void UIController::selectGroupElementByName(const std::string &aGroup, const std::string &aName)
{
for (unsigned int i = 0; i < mUIElements.size(); i++) {
if ( mUIElements[i]->getGroup() == aGroup ) {
if ( mUIElements[i]->getName() == aName ) {
mUIElements[i]->press();
} else {
mUIElements[i]->release();
}
}
}
}
void UIController::setLockedByGroup( const std::string &aGroup, const bool &locked )
{
for (unsigned int i = 0; i < mUIElements.size(); i++) {
if (mUIElements[i]->getGroup() == aGroup ) {
mUIElements[i]->setLocked( locked );
}
}
}
void UIController::setPressedByGroup( const std::string &aGroup, const bool &pressed )
{
for (unsigned int i = 0; i < mUIElements.size(); i++) {
if (mUIElements[i]->getGroup() == aGroup ) {
pressed ? mUIElements[i]->press() : mUIElements[i]->release();
}
}
}
Font UIController::getFont( const string &aStyle )
{
if ( aStyle == "label" ) {
return mLabelFont;
} else if ( aStyle == "icon" ) {
return mIconFont;
} else if ( aStyle == "header" ) {
return mHeaderFont;
} else if ( aStyle == "body" ) {
return mBodyFont;
} else if ( aStyle == "footer" ) {
return mFooterFont;
} else if ( aStyle == "smallLabel" ) {
return mSmallLabelFont;
} else {
throw FontStyleExc( aStyle );
}
}
void UIController::setFont( const string &aStyle, const ci::Font &aFont )
{
if ( aStyle == "label" ) {
mLabelFont = aFont;
} else if ( aStyle == "icon" ) {
mIconFont = aFont;
} else if ( aStyle == "header" ) {
mHeaderFont = aFont;
} else if ( aStyle == "body" ) {
mBodyFont = aFont;
} else if ( aStyle == "footer" ) {
mFooterFont = aFont;
} else if ( aStyle == "smallLabel" ) {
mSmallLabelFont = aFont;
} else {
throw FontStyleExc( aStyle );
}
}
void UIController::setupFbo()
{
mFormat.enableDepthBuffer( false );
mFormat.setSamples( mFboNumSamples );
mFbo = gl::Fbo( DEFAULT_FBO_WIDTH, DEFAULT_FBO_WIDTH, mFormat );
mFbo.bindFramebuffer();
gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) );
mFbo.unbindFramebuffer();
} | 31.841463 | 231 | 0.704175 | nselikoff |
4ecf3705018615222bf6a218551f06d534fbf648 | 24,170 | hpp | C++ | code/vpp/docs/conceptual/headers/vppContainers.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | code/vpp/docs/conceptual/headers/vppContainers.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | code/vpp/docs/conceptual/headers/vppContainers.hpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright 2016-2018 SOFT-ERG, Przemek Kuczmierczyk (www.softerg.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// -----------------------------------------------------------------------------
namespace vpp {
// -----------------------------------------------------------------------------
/** \brief Generic STL-style vector allocating memory on the GPU.
\ref gvector is general purpose container for GPU data. Depending on the
USAGE template parameter, it can be used for various data buffers used
in graphics and compute shaders. Single \ref gvector instance may have multiple
uses, hence the parameter is bitwise OR of following values:
- Buf::VERTEX - vertex attributes array.
- Buf::INDIRECT - buffer holding indirect draw ranges.
- Buf::INDEX - vertex index array for indexed primitives.
- Buf::UNIFORM - read-only common data (uniform buffer).
- Buf::STORAGE - read & write array (storage buffer).
- Buf::UNITEX - read-only formatted data (uniform texel buffer).
- Buf::STORTEX - read & write formatted data (storage texel buffer).
- Buf::SOURCE - source buffer for transfer operations.
- Buf::TARGET - target buffer for transfer operations.
The vector usually allocates memory on GPU side, but it is also accessible
on CPU side in a way depending on the value of memProfile parameter
of the constructor. This parameter can have the following values:
- MemProfile::DEVICE_STATIC - most frequently used, also known as staging buffer
mode. There are two physical memory blocks allocated: one on the device
side and another one on host size. The data is synchronized on demand.
The access to the memory on both sides is fastest among available modes,
but on-demand synchronization takes additional time.
- MemProfile::DEVICE_DYNAMIC - single memory block shared between a device and host.
Prefferably allocated on device side, or on host side as a fallback.
Automatically synchronized by hardware. Efficient on architectures where
CPU and GPU memory is common.
- MemProfile::DEVICE_FEEDBACK - similar to DEVICE_DYNAMIC, but always allocated on host
and visible to the device.
- MemProfile::HOST_STATIC - like DEVICE_FEEDBACK, allocated on host, may be also cached
on host. Used internally by DEVICE_STATIC for host-side part of the buffer.
Typically just use DEVICE_STATIC.
Object of this class is reference-counted and may be passed by value. Generally,
functions accepting a buffer, bound buffer and certain kinds of views, do accept
a gvector instance as well. Therefore you can fill a \ref gvector with e.g. vertex,
index, indirect or uniform data and bind it directly. Texel buffers require
creating a view explicitly but this view also accepts gvector as data source.
*/
template< typename ItemT, unsigned int USAGE >
class gvector :
public Buffer< USAGE >,
public MemoryBinding< Buffer< USAGE >, DeviceMemory >
{
public:
/** \brief Random access iterator. */
typedef ItemT* iterator;
/** \brief Random access const iterator. */
typedef const ItemT* const_iterator;
/** \brief Constructor.
The vector has fixed capacity, but varying number of valid elements (size).
*/
gvector (
size_t maxItemCount,
MemProfile::ECharacteristic memProfile,
const Device& hDevice );
/** \brief Iterator to begin of the vector. */
iterator begin() { return d_pBegin; }
/** \brief Iterator to the end of the valid range (but not whole area). */
iterator end() { return d_pBegin + d_size; }
/** \brief Const iterator to begin of the vector. */
const_iterator cbegin() const { return d_pBegin; }
/** \brief Const iterator to the end of the valid range (but not whole area). */
const_iterator cend() const { return d_pBegin + d_size; }
/** \brief Checks whether the valid range is empty. */
bool empty() const { return d_size == 0; }
/** \brief Returns the size of the valid range. */
size_t size() const { return d_size; }
/** \brief Returns the size of the whole allocated area (maximum number of elements). */
size_t capacity() const { return d_capacity; }
/** \brief Adds element to the end of the valid range. */
void push_back ( const ItemT& item );
/** \brief Constructs element in place at the end of the valid range. */
template< typename ... ArgsT >
void emplace_back ( ArgsT... args );
/** \brief Allocates space for new item without constructing it. */
ItemT* allocate_back();
/** \brief Resizes the vector in proper way (constructing/destructing elements).
This does not allocate/deallocate any memory nor invalidate iterators.
The capacity of the vector is static. Resizing it only affects the number
of valid items inside the vector.
*/
void resize ( size_t newSize, const ItemT& value = ItemT() );
/** \brief Resizes the vector in dumb way (just setting the size without initialization).
Use for numeric or vector types only.
*/
void setSize ( size_t newSize );
/** \brief Empties the valid range. */
void clear();
/** \brief Access to indexed element. */
ItemT& operator[] ( size_t index )
/** \brief Access to const indexed element. */
const ItemT& operator[] ( size_t index ) const;
/** \brief Generates a command ensuring that valid elements have been synchronized
from host to device. Optionally can be restricted to a range.
*/
void cmdCommit (
CommandBuffer cmdBuffer,
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Generates a command ensuring that entire memory area has been
synchronized from host to device. Optionally can be restricted to a range.
*/
void cmdCommitAll (
CommandBuffer cmdBuffer,
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Generates a command (to implicit context) which ensures valid elements
has been synchronized from host to device.
*/
void cmdCommit (
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Generates a command (to implicit context) which ensures that
entire buffer area has been synchronized from host to device.
*/
void cmdCommitAll (
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Generates a command ensuring that valid elements have been synchronized
from device to host. Optionally can be restricted to a range.
Caution: the vector must explicitly list Buf::SOURCE flag in order to be able
to use this function.
*/
void cmdLoad (
CommandBuffer cmdBuffer,
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Generates a command (to implicit context) which ensures valid elements
have been synchronized from device to host.
Caution: the vector must explicitly list Buf::SOURCE flag in order to be able
to use this function.
*/
void cmdLoad (
size_t firstItem = 0,
size_t nItems = std::numeric_limits< size_t >::max() );
/** \brief Synchronizes entire buffer from host to device.
Submits a command to specified queue. Does not wait for completion,
uses specified semaphores and fence.
*/
void commit (
EQueueType eQueue = Q_GRAPHICS,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore() );
/** \brief Synchronizes entire buffer from host to device and waits for completion.
*/
void commitAndWait (
EQueueType eQueue = Q_GRAPHICS );
/** \brief Synchronizes entire buffer from device to host.
Submits a command to specified queue. Does not wait for completion,
uses specified semaphores and fence.
Caution: the vector must explicitly list Buf::SOURCE flag in order to be able
to use this function.
*/
void load (
EQueueType eQueue = Q_GRAPHICS,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore() );
/** \brief Synchronizes entire buffer from device to host and waits for completion.
Caution: the vector must explicitly list Buf::SOURCE flag in order to be able
to use this function.
*/
void loadAndWait (
EQueueType eQueue = Q_GRAPHICS );
/** \brief Generates a command to copy the buffer contents to specified image.
Caution: may generate other auxiliary commands as well. The vector must explicitly
list Buf::SOURCE flag in order to be able to use this function.
*/
void cmdCopyToImage (
CommandBuffer hCmdBuffer,
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command (to the default context) to copy
the buffer contents to specified image.
Caution: may generate other auxiliary commands as well. The vector must explicitly
list Buf::SOURCE flag in order to be able to use this function.
*/
void cmdCopyToImage (
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents to specified image.
Caution: may generate other auxiliary commands as well. The vector must explicitly
list Buf::SOURCE flag in order to be able to use this function.
*/
void copyToImage (
EQueueType eQueue,
const Img& img,
VkImageLayout targetLayout,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore(),
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents to specified image,
waits for completion.
Caution: may generate other auxiliary commands as well. The vector must explicitly
list Buf::SOURCE flag in order to be able to use this function.
*/
void copyToImageAndWait (
EQueueType eQueue,
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command to copy the buffer contents from specified image.
Caution: may generate other auxiliary commands as well. Changes the layout of
the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL.
*/
void cmdCopyFromImage (
CommandBuffer hCmdBuffer,
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command (to the default context) to copy the buffer
contents from specified image.
Caution: may generate other auxiliary commands as well. Changes the layout of
the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL.
*/
void cmdCopyFromImage (
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents from specified image.
Caution: may generate other auxiliary commands as well. Changes the layout of
the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL.
*/
void copyFromImage (
EQueueType eQueue,
const Img& img,
VkImageLayout sourceImageLayout,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore(),
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents from specified image.
Waits for completion.
Caution: may generate other auxiliary commands as well. Changes the layout of
the image from \c sourceImageLayout to \c VK_IMAGE_LAYOUT_GENERAL.
*/
void copyFromImageAndWait (
EQueueType eQueue,
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
};
// -----------------------------------------------------------------------------
/**
\brief Utility subclass representing a vector of indirect draw ranges.
This object is reference-counted and may be passed by value.
*/
class IndirectCommands :
public gvector< VkDrawIndirectCommand, Buf::INDIRECT >
{
public:
IndirectCommands (
size_t maxItemCount,
MemProfile::ECharacteristic memProfile,
Device hDevice );
};
// -----------------------------------------------------------------------------
/**
\brief Utility subclass representing a vector of indexed indirect draw ranges.
This object is reference-counted and may be passed by value.
*/
class IndexedIndirectCommands :
public gvector< VkDrawIndexedIndirectCommand, Buf::INDIRECT >
{
public:
IndexedIndirectCommands (
size_t maxItemCount,
MemProfile::ECharacteristic memProfile,
Device hDevice );
};
// -----------------------------------------------------------------------------
/**
\brief Utility subclass representing a vector of indirect dispatch ranges.
This object is reference-counted and may be passed by value.
*/
class DispatchIndirectCommands :
public gvector< VkDispatchIndirectCommand, Buf::INDIRECT >
{
public:
DispatchIndirectCommands (
size_t maxItemCount,
MemProfile::ECharacteristic memProfile,
Device hDevice );
};
// -----------------------------------------------------------------------------
/**
\brief Utility subclass representing a vector of indices for indexed draws.
This object is reference-counted and may be passed by value.
*/
class Indices :
public gvector< std::uint32_t, Buf::INDEX >
{
public:
Indices (
size_t maxItemCount,
MemProfile::ECharacteristic memProfile,
Device hDevice );
};
// -----------------------------------------------------------------------------
/**
\brief Array allocated entirely on GPU side, without any mapping to the CPU side.
Use this class for buffers of data which are generated and consumed entirely
on GPU side, without a need to transfer to/from CPU. Such transfers
are still possible but require explicit transfer command to be issued. This
vector class does not offer a staging buffer functionality, therefore has
less memory overhead than gvector (no buffer copy on CPU side).
Use for best performance during multiple-staged GPU computations.
*/
template< typename ItemT, unsigned int USAGE >
class dgvector :
public Buffer< USAGE >,
public MemoryBinding< Buffer< USAGE >, DeviceMemory >
{
public:
dgvector ( size_t maxItemCount, const Device& hDevice );
/** \brief Generates a command to copy the buffer contents to specified image. */
void cmdCopyToImage (
CommandBuffer hCmdBuffer,
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command (to the implicit context) to copy
the buffer contents to specified image. */
void cmdCopyToImage (
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents to specified image. */
void copyToImage (
EQueueType eQueue,
const Img& img,
VkImageLayout targetLayout,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore(),
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents to specified image,
waits for completion.
*/
void copyToImageAndWait (
EQueueType eQueue,
const Img& img,
VkImageLayout targetLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command to copy the buffer contents from specified image. */
void cmdCopyFromImage (
CommandBuffer hCmdBuffer,
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Generates a command (to the implicit context) to copy the buffer
contents from specified image. */
void cmdCopyFromImage (
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents from specified image. */
void copyFromImage (
EQueueType eQueue,
const Img& img,
VkImageLayout sourceImageLayout,
const Fence& signalFenceOnEnd = Fence(),
const Semaphore& waitOnBegin = Semaphore(),
const Semaphore& signalOnEnd = Semaphore(),
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
/** \brief Submits a command to copy the buffer contents from specified image.
Waits for completion.
*/
void copyFromImageAndWait (
EQueueType eQueue,
const Img& img,
VkImageLayout sourceImageLayout,
std::uint32_t mipLevel = 0,
std::uint32_t layer = 0,
const VkOffset3D& imageOffset = VkOffset3D { 0, 0, 0 },
const VkExtent3D& imageExtent = VkExtent3D { 0, 0, 0 },
VkDeviceSize bufferOffset = 0,
std::uint32_t bufferRowLength = 0,
std::uint32_t bufferImageHeight = 0 );
};
// -----------------------------------------------------------------------------
} // namespace vpp
// -----------------------------------------------------------------------------
| 40.690236 | 94 | 0.631485 | maikebing |
4ed8a96a4bd9643062f1c037ba2a03316ae436d7 | 7,229 | cpp | C++ | src/notifybyaudio_canberra.cpp | pasnox/knotifications | ef2871b2a485be5abe393e61c6cd93867420f896 | [
"BSD-3-Clause"
] | 1 | 2019-11-02T03:54:16.000Z | 2019-11-02T03:54:16.000Z | src/notifybyaudio_canberra.cpp | pasnox/knotifications | ef2871b2a485be5abe393e61c6cd93867420f896 | [
"BSD-3-Clause"
] | 2 | 2019-10-27T23:06:33.000Z | 2020-01-11T00:44:07.000Z | src/notifybyaudio_canberra.cpp | brute4s99/knotifications | bc01688f99fcbdc2d3ceb4ad9475da1359441408 | [
"BSD-3-Clause"
] | null | null | null | /* This file is part of the KDE libraries
Copyright (C) 2014-2015 by Martin Klapetek <[email protected]>
Copyright (C) 2018 Kai Uwe Broulik <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "notifybyaudio_canberra.h"
#include "debug_p.h"
#include <QGuiApplication>
#include <QFile>
#include <QFileInfo>
#include <QIcon>
#include <QString>
#include "knotifyconfig.h"
#include "knotification.h"
#include <canberra.h>
NotifyByAudio::NotifyByAudio(QObject *parent)
: KNotificationPlugin(parent)
{
qRegisterMetaType<uint32_t>("uint32_t");
int ret = ca_context_create(&m_context);
if (ret != CA_SUCCESS) {
qCWarning(LOG_KNOTIFICATIONS) << "Failed to initialize canberra context for audio notification:" << ca_strerror(ret);
m_context = nullptr;
return;
}
QString desktopFileName = QGuiApplication::desktopFileName();
// handle apps which set the desktopFileName property with filename suffix,
// due to unclear API dox (https://bugreports.qt.io/browse/QTBUG-75521)
if (desktopFileName.endsWith(QLatin1String(".desktop"))) {
desktopFileName.chop(8);
}
ret = ca_context_change_props(m_context,
CA_PROP_APPLICATION_NAME, qUtf8Printable(qApp->applicationDisplayName()),
CA_PROP_APPLICATION_ID, qUtf8Printable(desktopFileName),
CA_PROP_APPLICATION_ICON_NAME, qUtf8Printable(qApp->windowIcon().name()),
nullptr);
if (ret != CA_SUCCESS) {
qCWarning(LOG_KNOTIFICATIONS) << "Failed to set application properties on canberra context for audio notification:" << ca_strerror(ret);
}
}
NotifyByAudio::~NotifyByAudio()
{
if (m_context) {
ca_context_destroy(m_context);
}
m_context = nullptr;
}
void NotifyByAudio::notify(KNotification *notification, KNotifyConfig *config)
{
const QString soundFilename = config->readEntry(QStringLiteral("Sound"));
if (soundFilename.isEmpty()) {
qCWarning(LOG_KNOTIFICATIONS) << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification";
finish(notification);
return;
}
QUrl soundURL;
const auto dataLocations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
for (const QString &dataLocation : dataLocations) {
soundURL = QUrl::fromUserInput(soundFilename,
dataLocation + QStringLiteral("/sounds"),
QUrl::AssumeLocalFile);
if (soundURL.isLocalFile() && QFileInfo::exists(soundURL.toLocalFile())) {
break;
} else if (!soundURL.isLocalFile() && soundURL.isValid()) {
break;
}
soundURL.clear();
}
if (soundURL.isEmpty()) {
qCWarning(LOG_KNOTIFICATIONS) << "Audio notification requested, but sound file from notifyrc file was not found, aborting audio notification";
finish(notification);
return;
}
// Looping happens in the finishCallback
if (!playSound(m_currentId, soundURL)) {
finish(notification);
return;
}
if (notification->flags() & KNotification::LoopSound) {
m_loopSoundUrls.insert(m_currentId, soundURL);
}
Q_ASSERT(!m_notifications.value(m_currentId));
m_notifications.insert(m_currentId, notification);
++m_currentId;
}
bool NotifyByAudio::playSound(quint32 id, const QUrl &url)
{
if (!m_context) {
qCWarning(LOG_KNOTIFICATIONS) << "Cannot play notification sound without canberra context";
return false;
}
ca_proplist *props = nullptr;
ca_proplist_create(&props);
// We'll also want this cached for a time. volatile makes sure the cache is
// dropped after some time or when the cache is under pressure.
ca_proplist_sets(props, CA_PROP_MEDIA_FILENAME, QFile::encodeName(url.toLocalFile()).constData());
ca_proplist_sets(props, CA_PROP_CANBERRA_CACHE_CONTROL, "volatile");
int ret = ca_context_play_full(m_context, id, props, &ca_finish_callback, this);
ca_proplist_destroy(props);
if (ret != CA_SUCCESS) {
qCWarning(LOG_KNOTIFICATIONS) << "Failed to play sound with canberra:" << ca_strerror(ret);
return false;
}
return true;
}
void NotifyByAudio::ca_finish_callback(ca_context *c, uint32_t id, int error_code, void *userdata)
{
Q_UNUSED(c);
QMetaObject::invokeMethod(static_cast<NotifyByAudio*>(userdata),
"finishCallback",
Q_ARG(uint32_t, id),
Q_ARG(int, error_code));
}
void NotifyByAudio::finishCallback(uint32_t id, int error_code)
{
KNotification *notification = m_notifications.value(id, nullptr);
if (!notification) {
// We may have gotten a late finish callback.
return;
}
if (error_code == CA_SUCCESS) {
// Loop the sound now if we have one
const QUrl soundUrl = m_loopSoundUrls.value(id);
if (soundUrl.isValid()) {
if (!playSound(id, soundUrl)) {
finishNotification(notification, id);
}
return;
}
} else if (error_code != CA_ERROR_CANCELED) {
qCWarning(LOG_KNOTIFICATIONS) << "Playing audio notification failed:" << ca_strerror(error_code);
}
finishNotification(notification, id);
}
void NotifyByAudio::close(KNotification *notification)
{
if (!m_notifications.values().contains(notification)) {
return;
}
const auto id = m_notifications.key(notification);
if (m_context) {
int ret = ca_context_cancel(m_context, id);
if (ret != CA_SUCCESS) {
qCWarning(LOG_KNOTIFICATIONS) << "Failed to cancel canberra context for audio notification:" << ca_strerror(ret);
return;
}
}
// Consider the notification finished. ca_context_cancel schedules a cancel
// but we need to stop using the noficiation immediately or we could access
// a notification past its lifetime (close() may, or indeed must,
// schedule deletion of the notification).
// https://bugs.kde.org/show_bug.cgi?id=398695
finishNotification(notification, id);
}
void NotifyByAudio::finishNotification(KNotification *notification, quint32 id)
{
m_notifications.remove(id);
m_loopSoundUrls.remove(id);
finish(notification);
}
| 34.922705 | 150 | 0.678794 | pasnox |
4de56c2f1e5fa72d6ec33aeb6d98a3908b10cd9f | 844 | cc | C++ | test/test_split.cc | embeddedawesome/cpp-subprocess | 62635b57456baf41547315f4a5a8dd77cdf2c381 | [
"MIT"
] | 331 | 2016-03-19T12:19:14.000Z | 2022-03-31T08:59:01.000Z | test/test_split.cc | mr132001/cpp-subprocess | f1ce916fdc52648da9481a386a24c221bf703f1d | [
"MIT"
] | 50 | 2016-03-21T12:03:46.000Z | 2022-03-15T17:37:31.000Z | test/test_split.cc | mr132001/cpp-subprocess | f1ce916fdc52648da9481a386a24c221bf703f1d | [
"MIT"
] | 79 | 2016-03-20T19:58:10.000Z | 2022-03-31T13:07:53.000Z | #include <iostream>
#include <string>
#include <vector>
std::vector<std::string>
split(const std::string& str, const std::string& delims=" \t")
{
std::vector<std::string> res;
size_t init = 0;
while (true) {
auto pos = str.find_first_of(delims, init);
if (pos == std::string::npos) {
res.emplace_back(str.substr(init, str.length()));
break;
}
res.emplace_back(str.substr(init, pos - init));
pos++;
init = pos;
}
return res;
}
std::string join(const std::vector<std::string>& vec)
{
std::string res;
for (auto& elem : vec) {
res.append(elem + " ");
}
res.erase(--res.end());
return res;
}
int main() {
auto vec = split ("a b c");
for (auto elem : vec) { std::cout << elem << std::endl; }
std::cout << join(vec).length() << std::endl;
return 0;
}
| 19.627907 | 62 | 0.567536 | embeddedawesome |
4de57c438d087a5af5c53c646a0d9761a0d914c3 | 4,587 | cpp | C++ | IPCDemo/IPCPort.cpp | Celemony/ARA_Examples | 24239cf5176b9b230ddd7aa2b9053b6e582cdb2a | [
"Apache-2.0"
] | 2 | 2021-04-27T07:08:07.000Z | 2021-05-20T16:08:51.000Z | IPCDemo/IPCPort.cpp | Celemony/ARA_Examples | 24239cf5176b9b230ddd7aa2b9053b6e582cdb2a | [
"Apache-2.0"
] | null | null | null | IPCDemo/IPCPort.cpp | Celemony/ARA_Examples | 24239cf5176b9b230ddd7aa2b9053b6e582cdb2a | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
//! \file IPCMessage.cpp
//! messaging used for IPC in SDK IPC demo example
//! \project ARA SDK Examples
//! \copyright Copyright (c) 2012-2021, Celemony Software GmbH, All Rights Reserved.
//! \license Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
//------------------------------------------------------------------------------
// This is a brief proof-of-concept demo that hooks up an ARA capable plug-in
// in a separate process using IPC.
// This educational example is not suitable for production code -
// see MainProcess.cpp for a list of issues.
//------------------------------------------------------------------------------
#include "IPCPort.h"
#include "ARA_Library/Debug/ARADebug.h"
// increase to several seconds while debugging so that staying in the debugger does not break program flow
static constexpr auto messageTimeout { 0.1 };
IPCPort::IPCPort (CFMessagePortRef port) :
_port { port }
{}
IPCPort::IPCPort (IPCPort&& other) noexcept
{
*this = std::move (other);
}
IPCPort& IPCPort::operator= (IPCPort&& other) noexcept
{
std::swap (_port, other._port);
return *this;
}
IPCPort::~IPCPort ()
{
if (_port)
{
CFMessagePortInvalidate (_port);
CFRelease (_port);
}
}
CFDataRef IPCPortCallBack (CFMessagePortRef /*port*/, SInt32 /*msgid*/, CFDataRef cfData, void* info)
{
const IPCMessage message { cfData };
return ((IPCPort::Callback) info) (message).createEncodedMessage ();
}
IPCPort IPCPort::createPublishingID (const char* remotePortID, Callback callback)
{
auto portID { CFStringCreateWithCStringNoCopy (kCFAllocatorDefault, remotePortID, kCFStringEncodingASCII, kCFAllocatorNull) };
CFMessagePortContext portContext { 0, (void*) callback, nullptr, nullptr, nullptr };
auto port { CFMessagePortCreateLocal (kCFAllocatorDefault, portID, &IPCPortCallBack, &portContext, nullptr) };
CFRelease (portID);
CFRunLoopSourceRef runLoopSource { CFMessagePortCreateRunLoopSource (kCFAllocatorDefault, port, 0) };
CFRunLoopAddSource (CFRunLoopGetCurrent (), runLoopSource, kCFRunLoopDefaultMode);
CFRelease (runLoopSource);
ARA_INTERNAL_ASSERT (port != nullptr);
return IPCPort { port };
}
IPCPort IPCPort::createConnectedToID (const char* remotePortID)
{
auto timeout { 5.0 };
CFMessagePortRef port {};
// for some reason, the clang analyzer claims a potential leak of port here, even though it's either null or consumed...
#if !defined (__clang_analyzer__)
while (timeout > 0.0)
{
auto portID { CFStringCreateWithCStringNoCopy (kCFAllocatorDefault, remotePortID, kCFStringEncodingASCII, kCFAllocatorNull) };
if ((port = CFMessagePortCreateRemote (kCFAllocatorDefault, portID)))
break;
CFRelease (portID);
constexpr auto waitTime { 0.01 };
CFRunLoopRunInMode (kCFRunLoopDefaultMode, waitTime, false);
timeout -= waitTime;
}
ARA_INTERNAL_ASSERT (port != nullptr);
#endif
return IPCPort { port };
}
void IPCPort::sendWithoutReply (const IPCMessage& message)
{
auto outgoingData { message.createEncodedMessage () };
const auto portSendResult { CFMessagePortSendRequest (_port, 0, outgoingData, messageTimeout, 0.0, nullptr, nullptr) };
CFRelease (outgoingData);
ARA_INTERNAL_ASSERT (portSendResult == kCFMessagePortSuccess);
}
IPCMessage IPCPort::sendAndAwaitReply (const IPCMessage& message)
{
auto outgoingData { message.createEncodedMessage () };
auto incomingData { CFDataRef {} };
const auto portSendResult { CFMessagePortSendRequest (_port, 0, outgoingData, messageTimeout, messageTimeout, kCFRunLoopDefaultMode, &incomingData) };
CFRelease (outgoingData);
ARA_INTERNAL_ASSERT (incomingData && (portSendResult == kCFMessagePortSuccess));
IPCMessage reply { incomingData };
CFRelease (incomingData);
return reply;
}
| 39.205128 | 154 | 0.669937 | Celemony |
4de81c0a7fe7af2277b25493cb4ad06339c8c6ab | 5,053 | cpp | C++ | Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp | sejalsingh417/Open-DSA | dd2228abd3022f0899ded08ff3f710e51b74649f | [
"MIT"
] | 1 | 2021-10-05T15:45:42.000Z | 2021-10-05T15:45:42.000Z | Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp | sejalsingh417/Open-DSA | dd2228abd3022f0899ded08ff3f710e51b74649f | [
"MIT"
] | 17 | 2021-10-05T13:47:01.000Z | 2021-11-06T13:15:42.000Z | Data Structures/Trees/Threaded Binary Tree/Threaded_Binary_Tree_all.cpp | sejalsingh417/Open-DSA | dd2228abd3022f0899ded08ff3f710e51b74649f | [
"MIT"
] | 9 | 2021-10-05T07:21:09.000Z | 2021-10-20T08:31:03.000Z | #include <iostream>
#include <cstdlib>
#define MAX_VALUE 65536
using namespace std;
class N { //node declaration
public:
int k;
N *l, *r;
bool leftTh, rightTh;
};
class ThreadedBinaryTree {
private:
N *root;
public:
ThreadedBinaryTree() { //constructor to initialize the variables
root= new N();
root->r= root->l= root;
root->leftTh = true;
root->k = MAX_VALUE;
}
void makeEmpty() { //clear tree
root= new N();
root->r = root->l = root;
root->leftTh = true;
root->k = MAX_VALUE;
}
void insert(int key) {
N *p = root;
for (;;) {
if (p->k< key) { / /move to right thread
if (p->rightTh)
break;
p = p->r;
} else if (p->k > key) { // move to left thread
if (p->leftTh)
break;
p = p->l;
} else {
return;
}
}
N *temp = new N();
temp->k = key;
temp->rightTh= temp->leftTh= true;
if (p->k < key) {
temp->r = p->r;
temp->l= p;
p->r = temp;
p->rightTh= false;
} else {
temp->r = p;
temp->l = p->l;
p->l = temp;
p->leftTh = false;
}
}
bool search(int key) {
N *temp = root->l;
for (;;) {
if (temp->k < key) { //search in left thread
if (temp->rightTh)
return false;
temp = temp->r;
} else if (temp->k > key) { //search in right thread
if (temp->leftTh)
return false;
temp = temp->l;
} else {
return true;
}
}
}
void Delete(int key) {
N *dest = root->l, *p = root;
for (;;) { //find Node and its parent.
if (dest->k < key) {
if (dest->rightTh)
return;
p = dest;
dest = dest->r;
} else if (dest->k > key) {
if (dest->leftTh)
return;
p = dest;
dest = dest->l;
} else {
break;
}
}
N *target = dest;
if (!dest->rightTh && !dest->leftTh) {
p = dest; //has two children
target = dest->l; //largest node at left child
while (!target->rightTh) {
p = target;
target = target->r;
}
dest->k= target->k; //replace mode
}
if (p->k >= target->k) { //only left child
if (target->rightTh && target->leftTh) {
p->l = target->l;
p->leftTh = true;
} else if (target->rightTh) {
N*largest = target->l;
while (!largest->rightTh) {
largest = largest->r;
}
largest->r = p;
p->l= target->l;
} else {
N *smallest = target->r;
while (!smallest->leftTh) {
smallest = smallest->l;
}
smallest->l = target->l;
p->l = target->r;
}
} else {//only right child
if (target->rightTh && target->leftTh) {
p->r= target->r;
p->rightTh = true;
} else if (target->rightTh) {
N *largest = target->l;
while (!largest->rightTh) {
largest = largest->r;
}
largest->r= target->r;
p->r = target->l;
} else {
N *smallest = target->r;
while (!smallest->leftTh) {
smallest = smallest->l;
}
smallest->l= p;
p->r= target->r;
}
}
}
void displayTree() { //print the tree
N *temp = root, *p;
for (;;) {
p = temp;
temp = temp->r;
if (!p->rightTh) {
while (!temp->leftTh) {
temp = temp->l;
}
}
if (temp == root)
break;
cout<<temp->k<<" ";
}
cout<<endl;
}
};
int main() {
ThreadedBinaryTree tbt;
cout<<"ThreadedBinaryTree\n";
char ch;
int c, v;
while(1) {
cout<<"1. Insert "<<endl;
cout<<"2. Delete"<<endl;
cout<<"3. Search"<<endl;
cout<<"4. Clear"<<endl;
cout<<"5. Display"<<endl;
cout<<"6. Exit"<<endl;
cout<<"Enter Your Choice: ";
cin>>c;
//perform switch operation
switch (c) {
case 1 :
cout<<"Enter integer element to insert: ";
cin>>v;
tbt.insert(v);
break;
case 2 :
cout<<"Enter integer element to delete: ";
cin>>v;
tbt.Delete(v);
break;
case 3 :
cout<<"Enter integer element to search: ";
cin>>v;
if (tbt.search(v) == true)
cout<<"Element "<<v<<" found in the tree"<<endl;
else
cout<<"Element "<<v<<" not found in the tree"<<endl;
break;
case 4 :
cout<<"\nTree Cleared\n";
tbt.makeEmpty();
break;
case 5:
cout<<"Display tree: \n ";
tbt.displayTree();
break;
case 6:
exit(1);
default:
cout<<"\nInvalid type! \n";
}
}
cout<<"\n";
return 0;
}
| 24.293269 | 67 | 0.435385 | sejalsingh417 |
4de9be458ee5e8a5a1fbceee7a061b00ba7112cf | 633 | cpp | C++ | GummiShip/lazer.cpp | fonicartist/GummiShip | 1977f3b4360321fc78da0b124ce1e57797e8911c | [
"MIT"
] | null | null | null | GummiShip/lazer.cpp | fonicartist/GummiShip | 1977f3b4360321fc78da0b124ce1e57797e8911c | [
"MIT"
] | null | null | null | GummiShip/lazer.cpp | fonicartist/GummiShip | 1977f3b4360321fc78da0b124ce1e57797e8911c | [
"MIT"
] | null | null | null | #include "lazer.h"
Lazer::Lazer(float pos, float x, float y, int direction) {
sprite.setPosition(pos, 640);
velocity = sf::Vector2f(x, y);
hit = false;
printf("New lazer created at (%d,%d).\n", pos, 700);
loadAssets(direction);
}
void Lazer::loadAssets(int direction) {
texture.loadFromFile("..\\assets\\sprites\\lazer.png");
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(25 * direction, 0, 25, 53));
sprite.setOrigin(13.f, 0.f);
//sprite.setPosition(220, -60);
sprite.setScale(sf::Vector2f(0.90f, 0.90f));
}
void Lazer::update() {
if (getY() > -100)
sprite.move(velocity);
}
Lazer::~Lazer() {
} | 21.1 | 63 | 0.666667 | fonicartist |
4deb7026a232745d63f2132aa2f8693ead309392 | 577 | cpp | C++ | runtime/fpga/software/runtime/run_elf_zcu102.cpp | caesr-uwaterloo/MapleBoard | 4687854d230ef6ca16270fc0168f8c627c7e7eac | [
"MIT"
] | 1 | 2022-02-19T13:12:08.000Z | 2022-02-19T13:12:08.000Z | runtime/fpga/software/runtime/run_elf_zcu102.cpp | caesr-uwaterloo/MapleBoard | 4687854d230ef6ca16270fc0168f8c627c7e7eac | [
"MIT"
] | null | null | null | runtime/fpga/software/runtime/run_elf_zcu102.cpp | caesr-uwaterloo/MapleBoard | 4687854d230ef6ca16270fc0168f8c627c7e7eac | [
"MIT"
] | null | null | null | #include "common.h"
#include <iostream>
#include <cstring>
#include "loguru.hpp"
using namespace std::chrono_literals;
int main(int argc, char** argv) {
_argc = argc;
_argv = argv;
std::cout << "ZCU102 Real Board" << std::endl;
int exit_code;
// NOTE: this function will launch a new thread
test_main(&exit_code);
auto handlerFuture = handlerDoneSignal.get_future();
// auto status = handlerFuture.wait_for(10000ms);
handlerFuture.wait();
exitSignal.set_value();
handler_thread.join();
LOG_F(WARNING, "Exit Code: %d", exit_code);
return 0;
}
| 19.233333 | 54 | 0.691508 | caesr-uwaterloo |
4ded86b2ab65bb903d7588cb593b902c90bf6c66 | 3,049 | cxx | C++ | Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | 1 | 2015-10-12T00:14:09.000Z | 2015-10-12T00:14:09.000Z | Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | Modules/Numerics/Statistics/test/itkProbabilityDistributionTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkProbabilityDistribution.h"
namespace itk {
namespace Statistics {
class ProbabilityDistributionTestingHelper : public ProbabilityDistribution
{
public:
typedef ProbabilityDistributionTestingHelper Self;
typedef ProbabilityDistribution Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
itkTypeMacro(ProbabilityDistributionTestingHelper, ProbabilityDistribution);
itkNewMacro(Self);
virtual SizeValueType GetNumberOfParameters() const { return 42; }
virtual double EvaluatePDF(double ) const { return 42.0; }
virtual double EvaluatePDF(double , const ParametersType&) const { return 42.0; }
virtual double EvaluateCDF(double ) const { return 42.0; }
virtual double EvaluateCDF(double , const ParametersType&) const { return 42.0; }
virtual double EvaluateInverseCDF(double ) const { return 42.0; }
virtual double EvaluateInverseCDF(double , const ParametersType&) const { return 42.0; }
virtual bool HasMean() const { return true; }
virtual bool HasVariance() const { return true; }
virtual double GetMean() const { return 42.0; }
virtual double GetVariance() const { return 42.0; }
void RunTests()
{
std::cout << "Superclass name = " << this->Superclass::GetNameOfClass() << std::endl;
std::cout << "Parameters = " << this->Superclass::GetParameters() << std::endl;
}
};
}
}
int itkProbabilityDistributionTest(int, char* [] )
{
std::cout << "itkProbabilityDistributionTest Test \n \n";
typedef itk::Statistics::ProbabilityDistributionTestingHelper DistributionType;
DistributionType::Pointer distributionFunction = DistributionType::New();
std::cout << "GetNameOfClass() = " << distributionFunction->GetNameOfClass() << std::endl;
std::cout << "HasMean() = " << distributionFunction->HasMean() << std::endl;
std::cout << "HasVariance() = " << distributionFunction->HasVariance() << std::endl;
std::cout << "Number of parameters = " << distributionFunction->GetNumberOfParameters() << std::endl;
distributionFunction->Print( std::cout );
distributionFunction->RunTests();
return EXIT_SUCCESS;
}
| 38.1125 | 103 | 0.677927 | itkvideo |
4df15c604af1d762325a2f9c0a991157880794fb | 9,012 | hpp | C++ | include/xll/detail/type_text.hpp | jbuonagurio/libxll | 2e91163dbcbeeef3644add6ac583ee98a37b5aac | [
"BSL-1.0"
] | 1 | 2021-03-23T12:40:56.000Z | 2021-03-23T12:40:56.000Z | include/xll/detail/type_text.hpp | jbuonagurio/libxll | 2e91163dbcbeeef3644add6ac583ee98a37b5aac | [
"BSL-1.0"
] | 1 | 2022-03-15T04:23:18.000Z | 2022-03-15T04:23:56.000Z | include/xll/detail/type_text.hpp | jbuonagurio/libxll | 2e91163dbcbeeef3644add6ac583ee98a37b5aac | [
"BSL-1.0"
] | null | null | null | // Copyright 2020 John Buonagurio
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#pragma once
/**
* \file type_text.hpp
* Compile-time mapping from primitive type to pxTypeText identifier wchar array.
* \sa https://docs.microsoft.com/en-us/office/client-developer/excel/xlfregister-form-1#data-types
*/
#include <xll/config.hpp>
#include <xll/attributes.hpp>
#include <xll/fp12.hpp>
#include <xll/xloper.hpp>
#include <xll/pstring.hpp>
#include <xll/detail/type_traits.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/function.hpp>
#include <array>
#include <cstdint>
#include <functional>
#include <tuple>
#include <type_traits>
namespace xll {
namespace detail {
template<typename T>
struct is_array_type : std::false_type {};
template<std::size_t N>
struct is_array_type<static_fp12<N> *> : std::true_type {};
// Variable-type worksheet values and arrays (XLOPER12)
template<class T, class U = void>
struct type_text_arg {
static_assert(!std::is_base_of_v<detail::variant_common_type, T>, "invalid operand type");
static constexpr std::array<wchar_t, 1> value = { L'Q' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, variant *>>> {
static constexpr std::array<wchar_t, 1> value = { L'Q' };
};
// Asynchronous call handle (XLOPER12, xlTypeBigData)
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, handle *>>> {
static constexpr std::array<wchar_t, 1> value = { L'X' };
};
// Larger grid floating-point array structure (FP12)
template<class T>
struct type_text_arg<T, std::enable_if_t<is_array_type<T>::value>> {
static constexpr std::array<wchar_t, 2> value = { L'K', L'%' };
};
// Asynchronous UDF return type
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, void>>> {
static constexpr std::array<wchar_t, 1> value = { L'>' };
};
// Integral types
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, bool>>> {
static constexpr std::array<wchar_t, 1> value = { L'A' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, bool *>>> {
static constexpr std::array<wchar_t, 1> value = { L'L' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, uint16_t>>> {
static constexpr std::array<wchar_t, 1> value = { L'H' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int16_t>>> {
static constexpr std::array<wchar_t, 1> value = { L'I' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int16_t *>>> {
static constexpr std::array<wchar_t, 1> value = { L'M' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int32_t>>> {
static constexpr std::array<wchar_t, 1> value = { L'J' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, int32_t *>>> {
static constexpr std::array<wchar_t, 1> value = { L'N' };
};
// Floating-point types
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, double>>> {
static constexpr std::array<wchar_t, 1> value = { L'B' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, double *>>> {
static constexpr std::array<wchar_t, 1> value = { L'E' };
};
// Null-terminated ASCII byte string (max. 256 characters)
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, char *>>> {
static constexpr std::array<wchar_t, 1> value = { L'C' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, const char *>>> {
static constexpr std::array<wchar_t, 1> value = { L'C' };
};
// Null-terminated Unicode wide-character string (max. 32767 characters)
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, wchar_t *>>> {
static constexpr std::array<wchar_t, 2> value = { L'C', L'%' };
};
template<class T>
struct type_text_arg<T, std::enable_if_t<std::is_same_v<T, const wchar_t *>>> {
static constexpr std::array<wchar_t, 2> value = { L'C', L'%' };
};
template<class A>
struct attribute_text_arg;
// Function attributes
template<>
struct attribute_text_arg<tag::cluster_safe> {
static constexpr std::array<wchar_t, 1> value = { L'&' };
};
template<>
struct attribute_text_arg<tag::volatile_> {
static constexpr std::array<wchar_t, 1> value = { L'!' };
};
template<>
struct attribute_text_arg<tag::thread_safe> {
static constexpr std::array<wchar_t, 1> value = { L'$' };
};
template<>
struct attribute_text_arg<tag::macro_sheet_equivalent> {
static constexpr std::array<wchar_t, 1> value = { L'#' };
};
// Get a pxTypeText wchar array for a callable type. Concatenates the
// pxTypeText wchar arrays for the return type, arguments and attributes
// at compile-time using tuples.
//
// Requires compiler support for std::tuple_cat with std::array, and C++17
// for std::apply and std::invoke_result_t.
//
// Attributes:
// - Asynchronous
// - Cannot be combined with Cluster Safe
// - One 'X' parameter to store the async call handle (xlTypeBigData)
// - void return type, '>'
// - Cluster Safe
// - Cannot be combined with Asynchronous
// - No XLOPER12 arguments that support range references (type 'U').
// - Add '&' to end of type text
// - Volatile
// - Add '!' to end of type text
// - Thread Safe
// - Add '$' to end of type text
// - Macro Sheet Equivalent
// - Cannot be combined with Thread Safe or Cluster Safe
// - Handled as Volatile when using type 'R' or type 'U' arguments.
// - Add '#' to end of type text
template<class Result, class... Args, class... Tags>
constexpr auto type_text_impl(attribute_set<Tags...>)
{
using namespace boost::mp11;
using async_handle_count = mp_count<mp_list<Args...>, handle *>;
using is_asynchronous = mp_to_bool<async_handle_count>;
using has_void_return = std::is_void<Result>;
using is_cluster_safe = mp_contains<mp_list<Tags...>, tag::cluster_safe>;
using is_thread_safe = mp_contains<mp_list<Tags...>, tag::thread_safe>;
using is_macro_sheet_equivalent = mp_contains<mp_list<Tags...>, tag::macro_sheet_equivalent>;
static_assert(!mp_any<std::is_void<Args>...>::value,
"arguments cannot be void");
static_assert(mp_less<async_handle_count, mp_size_t<2>>::value,
"multiple async handles in argument list");
static_assert(!mp_all<is_asynchronous, mp_not<has_void_return>>::value,
"async functions must have void return type");
static_assert(!mp_all<is_asynchronous, is_cluster_safe>::value,
"async functions cannot be cluster-safe");
static_assert(!mp_all<is_macro_sheet_equivalent, is_thread_safe>::value,
"macro sheet equivalent functions cannot be thread-safe");
static_assert(!mp_all<is_macro_sheet_equivalent, is_cluster_safe>::value,
"macro sheet equivalent functions cannot be cluster-safe");
// Construct tuple using std::tuple_cat specialization for std:array.
constexpr auto tuple = std::tuple_cat(
type_text_arg<extern_c_type_t<Result>>::value,
type_text_arg<extern_c_type_t<Args>>::value...,
attribute_text_arg<Tags>::value...
);
// Construct wchar array from the flat tuple.
constexpr auto make_array = [](auto&& ...x) {
return std::array{x...};
};
return std::apply(make_array, tuple);
}
// Overloads for various calling conventions and attributes.
#if BOOST_ARCH_X86_32
template<class F, class... Args, class... Tags>
constexpr auto type_text(F (__cdecl *)(Args...), attribute_set<Tags...> attrs)
{
using result_t = std::invoke_result_t<F(Args...), Args...>;
return detail::type_text_impl<result_t, Args...>(attrs);
}
template<class F, class... Args, class... Tags>
constexpr auto type_text(F (__stdcall *)(Args...), attribute_set<Tags...> attrs)
{
using result_t = std::invoke_result_t<F(Args...), Args...>;
return detail::type_text_impl<result_t, Args...>(attrs);
}
template<class F, class... Args, class... Tags>
constexpr auto type_text(F (__fastcall *)(Args...), attribute_set<Tags...> attrs)
{
using result_t = std::invoke_result_t<F(Args...), Args...>;
return detail::type_text_impl<result_t, Args...>(attrs);
}
template<class F, class... Args, class... Tags>
constexpr auto type_text(F (__vectorcall *)(Args...), attribute_set<Tags...> attrs)
{
using result_t = std::invoke_result_t<F(Args...), Args...>;
return detail::type_text_impl<result_t, Args...>(attrs);
}
#else
template<class F, class... Args, class... Tags>
constexpr auto type_text(F (*)(Args...), attribute_set<Tags...> attrs)
{
using result_t = std::invoke_result_t<F(Args...), Args...>;
return detail::type_text_impl<result_t, Args...>(attrs);
}
#endif // BOOST_ARCH_X86_32
} // namespace detail
} // namespace xll | 32.770909 | 99 | 0.694075 | jbuonagurio |
4df22f2837c6aee3c237eb2f94000fe2612f137c | 477 | cpp | C++ | Main.cpp | shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman | 6c7f6a260553a55bd95b400d286de4a76615429a | [
"MIT"
] | null | null | null | Main.cpp | shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman | 6c7f6a260553a55bd95b400d286de4a76615429a | [
"MIT"
] | null | null | null | Main.cpp | shaCode256/Cpp-Ex1-Do-You-Want-To-Code-A-Snowman | 6c7f6a260553a55bd95b400d286de4a76615429a | [
"MIT"
] | null | null | null | /**
* Main Demo program for snowman exercise.
*
* Author: Shavit Luzon
* Since : 2021-03
*/
#include "snowman.hpp"
#include <iostream>
#include <stdexcept>
using namespace std;
using namespace ariel;
int main() {
int number;
cout << "Type a number which represent a snowman: "; // Type a number and press enter
cin >> number; // Get user input from the keyboard
cout << "Your snowman is: " << snowman(number) << endl; // Display the input value
} | 22.714286 | 86 | 0.654088 | shaCode256 |
4df3827815083eaaad9b713dbca753c12115665f | 304 | cpp | C++ | C++ STL/Memberfunction_template_OutsideClass.cpp | junior-geek04/C-Stl | d7731c52616810f5067162453557075b524690a5 | [
"Apache-2.0"
] | 2 | 2021-05-27T12:18:32.000Z | 2021-05-27T17:33:03.000Z | C++ STL/Memberfunction_template_OutsideClass.cpp | junior-geek04/C-Stl | d7731c52616810f5067162453557075b524690a5 | [
"Apache-2.0"
] | null | null | null | C++ STL/Memberfunction_template_OutsideClass.cpp | junior-geek04/C-Stl | d7731c52616810f5067162453557075b524690a5 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
template<class t>
class enjoy
{public:
t data;
enjoy(t a)
{
data=a;
}
void display();
};
template<class t>
void enjoy<t>::display()
{
cout<<data;
}
int main()
{
enjoy<int> e(94);
cout<<e.data<<"\n";
e.display();
} | 12.16 | 25 | 0.546053 | junior-geek04 |
4df446b0d6258e7c84e7ea316ebba019ed3867cd | 973 | cpp | C++ | libhydrosphere/source/common/compiler/memcpy.cpp | Kaenbyo/Hydrosphere | 123143da54329dc678eea3ac3451bd9275a5513d | [
"Apache-2.0",
"MIT"
] | 17 | 2019-08-05T07:11:04.000Z | 2019-11-27T11:55:04.000Z | libhydrosphere/source/common/compiler/memcpy.cpp | Kaenbyo/Hydrosphere | 123143da54329dc678eea3ac3451bd9275a5513d | [
"Apache-2.0",
"MIT"
] | 1 | 2019-09-15T11:42:50.000Z | 2019-09-15T11:42:50.000Z | libhydrosphere/source/common/compiler/memcpy.cpp | Kaenbyo/Hydrosphere | 123143da54329dc678eea3ac3451bd9275a5513d | [
"Apache-2.0",
"MIT"
] | 3 | 2019-08-27T09:54:38.000Z | 2019-09-11T09:50:08.000Z | /*
* Copyright (c) 2019 Hydrosphère Developers
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
#include <stddef.h>
#include <hs/hs_macro.hpp>
// We define memcpy as we don't have any libraries that can provide it.
// If there is any, as this is weak, it's going to be discared.
extern "C" __HS_ATTRIBUTE_WEAK void *memcpy(
void *dst, const void *src, size_t len) {
const char *from = (const char *)src;
char *to = reinterpret_cast<char *>(dst);
while (len-- > 0) *to++ = *from++;
return dst;
}
extern "C" __HS_ATTRIBUTE_WEAK void *memset(
void *s, int c, size_t n) {
unsigned char *p = reinterpret_cast<unsigned char *>(s);
while (n--) *p++ = (unsigned char)c;
return s;
}
| 31.387097 | 71 | 0.67112 | Kaenbyo |
15006fe04e62b248d130fe4904f72e3bfa5b0bdb | 5,635 | cpp | C++ | pikoc/src/Frontend/PipeASTVisitor.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | 15 | 2015-05-19T08:23:26.000Z | 2021-11-26T02:59:36.000Z | pikoc/src/Frontend/PipeASTVisitor.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | null | null | null | pikoc/src/Frontend/PipeASTVisitor.cpp | piko-dev/piko-public | 8d7ab461de155992ca75e839f406670279fb6bad | [
"BSD-3-Clause"
] | 4 | 2015-10-06T15:14:43.000Z | 2020-02-20T13:17:11.000Z | #include "Frontend/clangUtilities.hpp"
#include "Frontend/PipeASTVisitor.hpp"
#include "Frontend/StageASTVisitor.hpp"
bool PipeASTVisitor::VisitCXXRecordDecl(clang::CXXRecordDecl *decl) {
// Stop if errors have occurred in compilation
if(context.getDiagnostics().hasErrorOccurred()) {
llvm::errs() << "Compilation errors have occurred. "
<< "Please resolve the above error messages.\n";
exit(5);
return false;
}
if(pipeFound)
return true;
if(!decl->hasDefinition())
return true;
clang::CXXRecordDecl *defn = decl->getDefinition();
if(!isPikoPipe(defn))
{
return true;
}
pipeFound = true;
psum->name = defn->getIdentifier()->getName();
bool constState_type_found = false;
bool mutableState_type_found = false;
bool input_type_found = false;
//Add Stages to Pipe
for(clang::RecordDecl::field_iterator
bf = defn->field_begin(), ef = defn->field_end(); bf != ef; ++bf)
{
std::string var_name = bf->getNameAsString();
if(var_name == "constState_")
{
if(bf->getType()->isPointerType())
{
const clang::QualType& qt = bf->getType()->getPointeeType();
psum->constState_type = qt.getAsString();
printf("Found constant state type %s\n", psum->constState_type.c_str());
constState_type_found = true;
}
else
{
__DEB;
}
}
if(var_name == "mutableState_")
{
if(bf->getType()->isPointerType())
{
const clang::QualType& qt = bf->getType()->getPointeeType();
psum->mutableState_type = qt.getAsString();
printf("Found mutable state type %s\n", psum->mutableState_type.c_str());
mutableState_type_found = true;
}
else
{
__DEB;
}
}
if(!bf->getType()->isRecordType())
continue;
clang::CXXRecordDecl *fieldClass = bf->getType()->getAsCXXRecordDecl();
if(var_name == "h_input")
{
if(fieldClass->getNameAsString() == "PikoArray")
{
assert(llvm::isa<clang::TemplateSpecializationType>(bf->getType()));
const clang::TemplateSpecializationType* temptype =
llvm::cast<clang::TemplateSpecializationType>(bf->getType());
assert(temptype->getNumArgs() == 1);
psum->input_type =
temptype->getArgs()[0].getAsType()->getAsCXXRecordDecl()->getNameAsString();
printf("Found input type %s\n", psum->input_type.c_str());
input_type_found = true;
}
else
{
__DEB;
}
}
if(!StageASTVisitor::isPikoStage(fieldClass))
continue;
if(!fieldClass->hasDefinition())
{
llvm::errs() <<
"No definition for stage " << fieldClass->getNameAsString() <<
" used in pipe " << psum->name << "\n";
return false;
}
clang::CXXRecordDecl *fieldClassDefn = fieldClass->getDefinition();
if(!addStageToPipe(fieldClassDefn, *bf)) {
llvm::errs() << "Unable to add stage \"" << bf->getNameAsString()
<< "\" of type \"" << fieldClass->getNameAsString()
<< "\" to pipe \"" << psum->name << "\"\n";
return false;
}
printf("Added stage %s\n", bf->getNameAsString().c_str());
}
assert(constState_type_found && mutableState_type_found && input_type_found);
//Find pikoConnect calls
//for(CXXRecordDecl::ctor_iterator
// bc = defn->ctor_begin(), ec = defn->ctor_end(); bc != ec; ++bc) {
//}
clang::Stmt *ctorBody = defn->ctor_begin()->getBody();
for(clang::Stmt::child_range child = ctorBody->children(); child; ++child)
{
//(*child)->dump();
if(!llvm::isa<clang::CallExpr>(*child))
{
//printf(" exiting early\n");
continue;
}
else
{
}
clang::CallExpr *pikoConn = llvm::cast<clang::CallExpr>(*child);
if(getFuncName(pikoConn->getDirectCallee()) != "pikoConnect")
{
continue;
}
else
{
}
clang::MemberExpr *outStage =
llvm::cast<clang::MemberExpr>(unrollCasts(pikoConn->getArg(0)));
clang::MemberExpr *inStage =
llvm::cast<clang::MemberExpr>(unrollCasts(pikoConn->getArg(1)));
std::string outStageName = outStage->getMemberNameInfo().getAsString();
std::string inStageName = inStage->getMemberNameInfo().getAsString();
stageSummary *outStageSum = psum->findStageByName(outStageName);
stageSummary *inStageSum = psum->findStageByName(inStageName);
llvm::APSInt outPortInt;
llvm::APSInt inPortInt;
if(!pikoConn->getArg(2)->EvaluateAsInt(outPortInt, context)
|| !pikoConn->getArg(3)->EvaluateAsInt(inPortInt, context))
{
llvm::errs() << "pikoConnect port number arguments must "
<< "be compile-time constants\n";
return false;
}
int outPortNum = outPortInt.getSExtValue();
int inPortNum = inPortInt.getSExtValue();
outStageSum->nextStageNames.push_back(inStageSum->name);
outStageSum->nextStagesByPort[outPortNum].push_back(inStageSum);
outStageSum->outPortTypes[outPortNum] = inStageSum->typeNumber;
}
psum->processLinks();
return true;
}
// Must pass in definition
bool PipeASTVisitor::addStageToPipe(clang::CXXRecordDecl *d, clang::FieldDecl *field) {
stageSummary ssum = (*stageMap)[d->getNameAsString()];
ssum.name = field->getNameAsString();
ssum.fullType = field->getType().getAsString();
psum->stages.push_back(ssum);
return true;
}
// Must pass in definition
bool PipeASTVisitor::isPikoPipe(clang::CXXRecordDecl *d) {
for(clang::CXXRecordDecl::base_class_iterator
bbc = d->bases_begin(), ebc = d->bases_end(); bbc != ebc; ++bbc)
{
if(bbc->getType().getAsString() == "class PikoPipe")
{
return true;
}
}
return false;
}
int PipeASTVisitor::getPortNumber(std::string portName) {
if(portName == "out0") return 0;
else if(portName == "out1") return 1;
else if(portName == "out2") return 2;
else if(portName == "out3") return 3;
else if(portName == "out4") return 4;
else return -1;
}
| 24.714912 | 87 | 0.670453 | piko-dev |
1501554ff5b6f85c1379ffba8a4dee83c4c569a2 | 4,266 | cpp | C++ | TestSuite/url_unittest.cpp | w20089527/Net | ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584 | [
"MIT"
] | 1 | 2019-08-10T20:29:13.000Z | 2019-08-10T20:29:13.000Z | TestSuite/url_unittest.cpp | whrool/Net | ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584 | [
"MIT"
] | null | null | null | TestSuite/url_unittest.cpp | whrool/Net | ca40f0d4a5aa94c64abb8ccc7306bc66bdf12584 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright(c) 2015 huan.wang
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files(the "Software"),
// to deal in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "stdafx.h"
#include "CppUnitTest.h"
#include "net/base/url.h"
using namespace net::http;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestSuite
{
TEST_CLASS(Url_Test)
{
public:
TEST_METHOD(Test_Parse)
{
std::string strUrl = "http://www.google.com/?q=abc#frag";
auto url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme() == "http");
Assert::IsTrue(url.GetHost() == "www.google.com");
Assert::IsTrue(url.GetPath() == "/");
Assert::IsTrue(url.GetRawQuery() == "q=abc");
Assert::IsTrue(url.GetFragment() == "frag");
strUrl = "http://www.google.com:8080?q=abc#frag";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme() == "http");
Assert::IsTrue(url.GetHost() == "www.google.com");
Assert::IsTrue(url.GetPath() == "/");
Assert::IsTrue(url.GetPort() == 8080);
Assert::IsTrue(url.GetRawQuery() == "q=abc");
Assert::IsTrue(url.GetFragment() == "frag");
strUrl = "file:///usr/home/r.txt";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme() == "file");
Assert::IsTrue(url.GetHost().empty());
Assert::IsTrue(url.GetPath() == "/usr/home/r.txt");
strUrl = ":///usr/home/r.txt";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme().empty());
Assert::IsTrue(url.GetHost().empty());
Assert::IsTrue(url.GetPath().empty());
strUrl = "/usr/home/r.txt";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme().empty());
Assert::IsTrue(url.GetHost().empty());
Assert::IsTrue(url.GetPath() == strUrl);
strUrl = "http:/usr/home/r.txt";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme() == "http");
Assert::IsTrue(url.GetHost().empty());
Assert::IsTrue(url.GetPath().empty());
strUrl = "//www.google.com/search?q=r";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme().empty());
Assert::IsTrue(url.GetHost() == "www.google.com");
Assert::IsTrue(url.GetPath() == "/search");
Assert::IsTrue(url.GetRawQuery() == "q=r");
strUrl = "mailto:[email protected]";
url = Url::Parse(strUrl);
Assert::IsTrue(url.GetScheme() == "mailto");
Assert::IsTrue(url.GetHost().empty());
Assert::IsTrue(url.GetPath().empty());
Assert::IsTrue(url.GetOpaque() == "[email protected]");
}
TEST_METHOD(Test_ResolveReference_ToString)
{
Url baseUrl = Url::Parse("http://www.google.com/search?q=q");
auto resolveUrl = baseUrl.ResolveReference("../../../hello?q=b#f");
Assert::IsTrue(resolveUrl.ToString() == "http://www.google.com/hello/?q=b#f");
Assert::IsTrue(Url::Parse("mailto:[email protected]").ToString() == "mailto:[email protected]");
}
};
} | 42.66 | 129 | 0.592827 | w20089527 |
1503c4b0cda665eac97f9160dbf3473cf56e5229 | 14,328 | cpp | C++ | src/tool/editor_file/editor.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/tool/editor_file/editor.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/tool/editor_file/editor.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | #include "editor.hpp"
#include "../../engine/mlib/mlib.hpp"
#include "../../version.h"
#include <wx/notebook.h>
#define L_TEXT_X 3
#define L_TEXT_Y 3
#define E_V1 0x31307645
#define ENTITY_VERSION 0x32307645
#define ENGINE_SFML_VERSION "SFML v2.4.1"
BEGIN_EVENT_TABLE(Editor, wxFrame)
EVT_BUTTON(ID_BTN_AS_NEW, Editor::as_new)
EVT_BUTTON(ID_BTN_AS_LOAD, Editor::as_load)
EVT_BUTTON(ID_BTN_AS_SAVE, Editor::as_save)
EVT_BUTTON(ID_BTN_AS_SAVEAS, Editor::as_saveas)
EVT_BUTTON(ID_BTN_D_NEW, Editor::d_new)
EVT_BUTTON(ID_BTN_D_LOAD, Editor::d_load)
EVT_BUTTON(ID_BTN_D_SAVE, Editor::d_save)
EVT_BUTTON(ID_BTN_D_SAVEAS, Editor::d_saveas)
EVT_BUTTON(ID_BTN_DP_LOAD, Editor::dp_load)
EVT_BUTTON(ID_BTN_DP_BUILD, Editor::dp_build)
EVT_BUTTON(ID_BTN_DP_IMPORT, Editor::dp_import)
EVT_BUTTON(ID_BTN_DP_EXPORT, Editor::dp_export)
END_EVENT_TABLE()
Editor::Editor(const wxString& title) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(400, 500), wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN)
{
wxFrame::SetIcon(wxIcon(_T("MAINICON")));
Out.setFile("log_file_editor.txt", true);
Out.setOutput(false, true);
Out = std::string("EG Engine v") + AutoVersion::STATUS + " " + AutoVersion::FULLVERSION_STRING + "\n";
Out = std::string("File Editor Build - ") + ENGINE_SFML_VERSION + "\n";
wxBoxSizer *sizer_vertical = new wxBoxSizer(wxVERTICAL);
SetSizer(sizer_vertical);
mainsizer = new wxPanel(this);
sizer_vertical->Add(mainsizer, 10, wxEXPAND, 0);
wxNotebook *tabs = new wxNotebook(mainsizer, -1, wxPoint(0, 0), wxSize(400, 500), wxNB_TOP | wxNB_MULTILINE, _T("TEST"));
tabs->AddPage(new wxPanel(tabs), _T("Animated Sprite"));
tabs->AddPage(new wxPanel(tabs), _T("Drawable"));
tabs->AddPage(new wxPanel(tabs), _T("Build data pack"));
tabs->SetSize(GetClientRect());
tabs->Refresh();
wxPanel* current_panel;
// animated sprite tab
current_panel = (wxPanel*)tabs->GetPage(0);
new wxButton(current_panel, ID_BTN_AS_NEW, _T("New"), wxPoint(5,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_AS_LOAD, _T("Load"), wxPoint(60,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_AS_SAVE, _T("Save"), wxPoint(115,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_AS_SAVEAS, _T("Save as"), wxPoint(170,0), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("File"), wxPoint(5+L_TEXT_X,25+L_TEXT_Y));
as_file = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,25), wxSize(330, 23));
new wxStaticText(current_panel, -1, _T("Sprite width"), wxPoint(5+L_TEXT_X,50+L_TEXT_Y));
as_w = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(100,50), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("Sprite height"), wxPoint(155+L_TEXT_X,50+L_TEXT_Y));
as_h = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(250,50), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("Frame count"), wxPoint(5+L_TEXT_X,75+L_TEXT_Y));
as_fc = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(100,75), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("Frame time (ms)"), wxPoint(155+L_TEXT_X,75+L_TEXT_Y));
as_ft = new wxTextCtrl(current_panel, -1, _T("0"), wxPoint(250,75), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("Sprite"), wxPoint(5+L_TEXT_X,100+L_TEXT_Y));
as_sprite = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,100), wxSize(180, 23));
// drawable
current_panel = (wxPanel*)tabs->GetPage(1);
new wxButton(current_panel, ID_BTN_D_NEW, _T("New"), wxPoint(5,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_D_LOAD, _T("Load"), wxPoint(60,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_D_SAVE, _T("Save"), wxPoint(115,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_D_SAVEAS, _T("Save as"), wxPoint(170,0), wxSize(50, 23));
new wxStaticText(current_panel, -1, _T("File"), wxPoint(5+L_TEXT_X,25+L_TEXT_Y));
d_file = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,25), wxSize(330, 23));
new wxStaticText(current_panel, -1, _T("String"), wxPoint(5+L_TEXT_X,50+L_TEXT_Y));
d_draw = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(50,50), wxSize(150, 23));
new wxStaticText(current_panel, -1, _T("Type"), wxPoint(5+L_TEXT_X,75+L_TEXT_Y));
d_type = new wxChoice(current_panel, -1, wxPoint(50,75), wxSize(150, 23));
d_type->Freeze();
d_type->Append(_T("Undefined"));
d_type->Append(_T("RichText"));
d_type->Append(_T("sf::Sprite"));
d_type->Append(_T("Animated Sprite"));
d_type->Append(_T("sf::RectangleShape"));
d_type->Append(_T("sf::CircleShape"));
d_type->Append(_T("sf::Text"));
d_type->Append(_T("GameText"));
d_type->Thaw();
d_type->SetSelection(0);
// data pack
current_panel = (wxPanel*)tabs->GetPage(2);
new wxButton(current_panel, ID_BTN_DP_LOAD, _T("Load folder"), wxPoint(0,0), wxSize(100, 23));
new wxButton(current_panel, ID_BTN_DP_BUILD, _T("Build list"), wxPoint(105,0), wxSize(100, 23));
new wxButton(current_panel, ID_BTN_DP_IMPORT, _T("Import"), wxPoint(210,0), wxSize(50, 23));
new wxButton(current_panel, ID_BTN_DP_EXPORT, _T("Export"), wxPoint(265,0), wxSize(50, 23));
dp_folder = new wxStaticText(current_panel, -1, _T(""), wxPoint(L_TEXT_X,25+L_TEXT_Y));
dp_list = new wxTextCtrl(current_panel, -1, _T(""), wxPoint(5, 50), wxSize(375, 375), wxTE_MULTILINE);
mainsizer->Show();
}
Editor::~Editor()
{
}
void Editor::as_new(wxCommandEvent &event)
{
if(wxMessageBox(_T("Current data will be cleared. Continue ?"), _T("Confirm"), wxNO) == wxNO)
return;
as_file->SetValue(_T(""));
as_w->SetValue(_T("0"));
as_h->SetValue(_T("0"));
as_fc->SetValue(_T("0"));
as_ft->SetValue(_T("0"));
as_sprite->SetValue(_T(""));
}
void Editor::as_load(wxCommandEvent &event)
{
wxFileDialog openFileDialog(this, _("Load animated sprite"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST);
if(openFileDialog.ShowModal() == wxID_CANCEL) return;
std::string path = std::string(openFileDialog.GetPath().mb_str());
std::ifstream f(path.c_str(), std::ios::in | std::ios::binary);
if(!f)
{
wxMessageBox(_T("Load failed"));
return;
}
char c;
int32_t tmp32;
std::string str;
do
{
if(!f.good())
{
wxMessageBox(_T("Load failed"));
return;
}
f.read(&c, 1);
if(c != 0x00) str += c;
}while(c != 0x00);
as_sprite->SetValue(wxString(str.c_str(), wxConvUTF8));
f.read((char*)&tmp32, 4);
as_w->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8));
f.read((char*)&tmp32, 4);
as_h->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8));
f.read((char*)&tmp32, 4);
as_fc->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8));
f.read((char*)&tmp32, 4);
as_ft->SetValue(wxString(mlib::int2str(tmp32).c_str(), wxConvUTF8));
as_file->SetValue(wxString(path.c_str(), wxConvUTF8));
}
void Editor::as_save(wxCommandEvent &event)
{
if(!as_stdsave(std::string(as_file->GetValue().mb_str()))) wxMessageBox(_T("Save failed"));
else wxMessageBox(_T("Save success"));
}
void Editor::as_saveas(wxCommandEvent &event)
{
wxFileDialog saveFileDialog(this, _T("Save animated sprite"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
if (saveFileDialog.ShowModal() == wxID_CANCEL)
return; // the user changed idea...
if(!as_stdsave(std::string(saveFileDialog.GetPath().mb_str())))
{
wxMessageBox(_T("Save failed"));
}
else
{
wxMessageBox(_T("Save success"));
as_file->SetValue(saveFileDialog.GetPath());
}
}
bool Editor::as_stdsave(std::string path)
{
std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if(!f) return false;
char c;
int32_t tmp32;
std::string str = std::string(as_sprite->GetValue().mb_str());
for(size_t i = 0; i < str.size(); ++i)
f.write(&(str[i]), 1);
c = 0;
f.write(&c, 1);
str = std::string(as_w->GetValue().mb_str());
if(!mlib::isNumber(str)) tmp32 = 0;
else tmp32 = mlib::str2long(str) % 0x100000000;
f.write((char*)&tmp32, 4);
str = std::string(as_h->GetValue().mb_str());
if(!mlib::isNumber(str)) tmp32 = 0;
else tmp32 = mlib::str2long(str) % 0x100000000;
f.write((char*)&tmp32, 4);
str = std::string(as_fc->GetValue().mb_str());
if(!mlib::isNumber(str)) tmp32 = 0;
else tmp32 = mlib::str2long(str) % 0x100000000;
f.write((char*)&tmp32, 4);
str = std::string(as_ft->GetValue().mb_str());
if(!mlib::isNumber(str)) tmp32 = 0;
else tmp32 = mlib::str2long(str) % 0x100000000;
f.write((char*)&tmp32, 4);
return true;
}
void Editor::d_new(wxCommandEvent &event)
{
if(wxMessageBox(_T("Current data will be cleared. Continue ?"), _T("Confirm"), wxNO) == wxNO)
return;
d_file->SetValue(_T(""));
d_draw->SetValue(_T(""));
d_type->SetSelection(0);
}
void Editor::d_load(wxCommandEvent &event)
{
wxFileDialog openFileDialog(this, _("Load drawable"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST);
if(openFileDialog.ShowModal() == wxID_CANCEL) return;
std::string path = std::string(openFileDialog.GetPath().mb_str());
std::ifstream f(path.c_str(), std::ios::in | std::ios::binary);
if(!f)
{
wxMessageBox(_T("Load failed"));
return;
}
char c;
std::string str;
f.read(&c, 1);
d_type->SetSelection(c);
do
{
if(!f.good())
{
wxMessageBox(_T("Load failed"));
return;
}
f.read(&c, 1);
if(c != 0x00) str += c;
}while(c != 0x00);
d_draw->SetValue(wxString(str.c_str(), wxConvUTF8));
d_file->SetValue(openFileDialog.GetPath());
}
void Editor::d_save(wxCommandEvent &event)
{
if(!d_stdsave(std::string(d_file->GetValue().mb_str()))) wxMessageBox(_T("Save failed"));
else wxMessageBox(_T("Save success"));
}
void Editor::d_saveas(wxCommandEvent &event)
{
wxFileDialog saveFileDialog(this, _T("Save drawable"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
if (saveFileDialog.ShowModal() == wxID_CANCEL)
return; // the user changed idea...
if(!d_stdsave(std::string(saveFileDialog.GetPath().mb_str())))
{
wxMessageBox(_T("Save failed"));
}
else
{
wxMessageBox(_T("Save success"));
d_file->SetValue(saveFileDialog.GetPath());
}
}
bool Editor::d_stdsave(std::string path)
{
std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if(!f) return false;
char c;
std::string str;
c = d_type->GetSelection();
f.write(&c, 1);
str = std::string(d_draw->GetValue().mb_str());
for(size_t i = 0; i < str.size(); ++i)
f.write(&(str[i]), 1);
c = 0;
f.write(&c, 1);
return true;
}
void Editor::dp_load(wxCommandEvent &event)
{
wxDirDialog dlg(NULL, _T("Choose the base directory"), wxGetCwd(), wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dlg.ShowModal() == wxID_CANCEL)
return;
size_t size = dlg.GetPath().size()+1;
dp_folder->SetLabel(dlg.GetPath());
wxArrayString array;
wxDir::GetAllFiles(dlg.GetPath(), &array, _T(""), wxDIR_FILES|wxDIR_DIRS);
dp_list->Freeze();
dp_list->Clear();
for(size_t i = 0; i < array.size(); ++i)
{
array[i] = array[i].substr(size, array[i].size()-size);
for(size_t j = 0; j < array[i].size(); ++j)
if(array[i][j] == '\\') array[i][j] = '/';
dp_list->AppendText(array[i]);
if(i < array.size() - 1) dp_list->AppendText(_T("\n"));
}
dp_list->Thaw();
}
void Editor::dp_build(wxCommandEvent &event)
{
wxString cwd = wxGetCwd();
wxSetWorkingDirectory(dp_folder->GetLabel());
wxString tmp = dp_list->GetValue();
wxString out;
for(size_t i = 0; i < tmp.size(); ++i)
{
if(tmp[i] != '\n') out += tmp[i];
else out += _T(" ");
}
wxString command = _T("\"") + cwd + _T("\\pack_builder.exe\" \"") + cwd + _T("\\data.pack\" ") + out;
long errCount = wxExecute(command, wxEXEC_SYNC);
wxSetWorkingDirectory(cwd);
Out = std::string(command.mb_str()) + "\n";
wxMessageBox(wxString(std::string("Done.\nError count: " + mlib::long2str(errCount)).c_str(), wxConvUTF8));
}
void Editor::dp_import(wxCommandEvent &event)
{
wxFileDialog openFileDialog(this, _("Import file list"), _T(""), _T(""), _T(""), wxFD_OPEN|wxFD_FILE_MUST_EXIST);
if(openFileDialog.ShowModal() == wxID_CANCEL) return;
std::string path = std::string(openFileDialog.GetPath().mb_str());
std::ifstream f(path.c_str(), std::ios::in | std::ios::binary);
if(!f) return;
char c;
wxString tmp;
do
{
f.read(&c, 1);
if(c != '\n' && f.good()) tmp += c;
}while(c != '\n' && f.good());
dp_folder->SetLabel(tmp);
tmp.clear();
dp_list->Freeze();
dp_list->Clear();
while(f.good())
{
f.read(&c, 1);
if(f.good())
{
if(c == '\n')
{
dp_list->AppendText(tmp);
dp_list->AppendText(_T("\n"));
tmp.clear();
}
else tmp += c;
}
}
if(!tmp.empty()) dp_list->AppendText(tmp);
dp_list->Thaw();
wxMessageBox(_T("List imported"));
}
void Editor::dp_export(wxCommandEvent &event)
{
wxFileDialog saveFileDialog(this, _T("Export file list"), _T(""), _T(""), _T(""), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
if (saveFileDialog.ShowModal() == wxID_CANCEL)
return;
std::string path = std::string(saveFileDialog.GetPath().mb_str());
std::ofstream f(path.c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if(!f) return;
std::string tmp;
tmp = std::string(dp_folder->GetLabel().mb_str());
for(size_t i = 0; i < tmp.size(); ++i)
f.write(&tmp[i], 1);
f.write("\n", 1);
tmp = std::string(dp_list->GetValue().mb_str());
for(size_t i = 0; i < tmp.size(); ++i)
f.write(&tmp[i], 1);
wxMessageBox(_T("List exported"));
}
| 33.633803 | 166 | 0.624023 | FoFabien |
1509db1e1ae5ea5bcc9111b295734a2cb8ce4779 | 1,242 | hpp | C++ | includes/Dataset.hpp | arghyatiger/HighPerformanceCNN | 166701ae53885199c4f06c97e127cba688cbe1c3 | [
"MIT"
] | null | null | null | includes/Dataset.hpp | arghyatiger/HighPerformanceCNN | 166701ae53885199c4f06c97e127cba688cbe1c3 | [
"MIT"
] | null | null | null | includes/Dataset.hpp | arghyatiger/HighPerformanceCNN | 166701ae53885199c4f06c97e127cba688cbe1c3 | [
"MIT"
] | null | null | null | #pragma once
#include <Layer.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class DataSet : public Layer {
public:
explicit DataSet(std::string data_path, bool shuffle = false); //constructor
void reset(); //setting train indexes to zero
void forward(int batch_size, bool is_train); //get new batch and push it to model
bool has_next(bool is_train); //check is there are more batches left
int get_height() { return this->height; }
int get_width() { return this->width; }
Container* get_label() { return this->output_label.get(); }
private:
unsigned int reverse_int(unsigned int i); // big endian
void read_images(std::string file_name, std::vector<std::vector<float>>& output); //read dataset file and store images in output
void read_labels(std::string file_name, std::vector<unsigned char>& output); //read dataset file and store labels in output
std::vector<std::vector<float>> train_data;
std::vector<unsigned char> train_label;
int train_data_index;
std::vector<std::vector<float>> test_data;
std::vector<unsigned char> test_label;
int test_data_index;
int height;
int width;
bool shuffle;
std::unique_ptr<Container> output_label;
};
| 30.292683 | 130 | 0.728663 | arghyatiger |
150bc8341f423db902b170fbbeae552438b65b85 | 8,010 | cpp | C++ | src/lunar-master/precess2.cpp | TehSnappy/lib_lunar_ex | a4cd4a3cdec44c2adaefbf1791b8863db568cbbd | [
"MIT"
] | 1 | 2019-03-11T14:46:04.000Z | 2019-03-11T14:46:04.000Z | lib/net/src/nrun/astro/precess2.cpp | lcityd/paragon | 47a43872a5656a8c431c774d353ed214f9d0ed1d | [
"MIT"
] | null | null | null | lib/net/src/nrun/astro/precess2.cpp | lcityd/paragon | 47a43872a5656a8c431c774d353ed214f9d0ed1d | [
"MIT"
] | 1 | 2019-10-12T03:23:41.000Z | 2019-10-12T03:23:41.000Z | /* precess2.cpp: (deprecated version of) functions for computing
Earth precession; see precess.cpp for current version, and
'changes.txt' for info on why this is deprecated
Copyright (C) 2010, Project Pluto
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#include <math.h>
#include <string.h>
#include <stdio.h>
#include "watdefs.h"
#include "afuncs.h"
#include "lunar.h" /* for obliquity( ) prototype */
#define PI 3.1415926535897932384626433832795028841971693993751058209749445923
/* setup_precession fills a 3x3 orthonormal matrix for precessing positions FROM */
/* year t1 TO year t2, where t1 and t2 are Julian YEARS. */
int DLL_FUNC setup_precession( double DLLPTR *matrix, double t1,
double t2)
{
double zeta, z, theta, czeta, cz, ctheta, szeta, sz, stheta;
double ka, kb;
static double t1_old = -PI, t2_old;
static double curr_matrix[9];
int going_backward = 0;
if( fabs( t1 - t2) < 1.e-5) /* dates sensibly equal; spare the tedium */
{ /* of doing pointless math */
set_identity_matrix( matrix);
return( 0);
}
/* Ideally, precessing from t1 to t2 back to t1 should get your */
/* original point. To ensure that this happens, we handle only */
/* the case t2 > t1; otherwise, we swap the times and invert */
/* the resulting matrix. */
/* The reason is that the following precession formula uses */
/* cubic polynomials to approximate zeta, theta, and z. If */
/* you feed it (t2, t1), it does _not_ create a matrix that is */
/* the exact inverse of (t1, t2); there is some accumulated */
/* error. Doing it this way avoids having that show. Also, */
/* there is a performance advantage: if you _do_ call (t1, t2), */
/* then (t2, t1), it's faster to invert the previous result */
/* than it would be to do all the math. */
if( t1 < t2)
{
double temp = t1;
t1 = t2;
t2 = temp;
going_backward = 1;
}
/* It's pretty common to precess a few zillion data points. So */
/* it helps to cache the most recently computed precession matrix */
/* so that repeated calls don't result in repeated computation. */
if( t1 == t1_old && t2 == t2_old)
{
FMEMCPY( matrix, curr_matrix, 9 * sizeof( double));
if( going_backward)
invert_orthonormal_matrix( matrix);
return( 0);
}
t1_old = t1;
t2_old = t2;
t2 = (t2 - t1) / 100.;
t1 = (t1 - 2000.) / 100.;
ka = 2306.2181 + 1.39656 * t1 - .000139 * t1 * t1;
kb = 2004.3109 - 0.85330 * t1 - .000217 * t1 * t1;
zeta = t2 * (ka + t2 * ( .30188 - .000345 * t1 + .017998 * t2));
z = t2 * (ka + t2 * (1.09468 + .000066 * t1 + .018203 * t2));
theta = t2 * (kb + t2 * (-.42665 - .000217 * t1 - .041833 * t2));
theta *= (PI / 180.) / 3600.;
z *= (PI / 180.) / 3600.;
zeta *= (PI / 180.) / 3600.;
czeta = cos( zeta);
szeta = sin( zeta);
cz = cos( z);
sz = sin( z);
ctheta = cos( theta);
stheta = sin( theta);
*matrix++ = czeta * ctheta * cz - szeta * sz;
*matrix++ = -szeta * ctheta * cz - czeta * sz;
*matrix++ = -stheta * cz;
*matrix++ = czeta * ctheta * sz + szeta * cz;
*matrix++ = -szeta * ctheta * sz + czeta * cz;
*matrix++ = -stheta * sz;
*matrix++ = czeta * stheta;
*matrix++ = -szeta * stheta;
*matrix++ = ctheta;
matrix -= 9;
FMEMCPY( curr_matrix, matrix, 9 * sizeof( double));
if( going_backward)
invert_orthonormal_matrix( matrix);
return( 0);
}
static const double sin_obliq_2000 = 0.397777155931913701597179975942380896684;
static const double cos_obliq_2000 = 0.917482062069181825744000384639406458043;
void DLL_FUNC equatorial_to_ecliptic( double *vect)
{
double temp;
temp = vect[2] * cos_obliq_2000 - vect[1] * sin_obliq_2000;
vect[1] = vect[1] * cos_obliq_2000 + vect[2] * sin_obliq_2000;
vect[2] = temp;
}
void DLL_FUNC ecliptic_to_equatorial( double *vect)
{
double temp;
temp = vect[2] * cos_obliq_2000 + vect[1] * sin_obliq_2000;
vect[1] = vect[1] * cos_obliq_2000 - vect[2] * sin_obliq_2000;
vect[2] = temp;
}
int DLL_FUNC precess_vector( const double DLLPTR *matrix,
const double DLLPTR *v1,
double DLLPTR *v2)
{
int i = 3;
while( i--)
{
*v2++ = matrix[0] * v1[0] + matrix[1] * v1[1] + matrix[2] * v1[2];
matrix += 3;
}
return( 0);
}
int DLL_FUNC deprecess_vector( const double DLLPTR *matrix,
const double DLLPTR *v1,
double DLLPTR *v2)
{
int i = 3;
while( i--)
{
*v2++ = matrix[0] * v1[0] + matrix[3] * v1[1] + matrix[6] * v1[2];
matrix++;
}
return( 0);
}
int DLL_FUNC precess_ra_dec( const double DLLPTR *matrix,
double DLLPTR *p_out,
const double DLLPTR *p_in, int backward)
{
double v1[3], v2[3];
const double old_ra = p_in[0];
v1[0] = cos( p_in[0]) * cos( p_in[1]);
v1[1] = sin( p_in[0]) * cos( p_in[1]);
v1[2] = sin( p_in[1]);
if( backward)
deprecess_vector( matrix, v1, v2);
else
precess_vector( matrix, v1, v2);
if( v2[1] || v2[0])
p_out[0] = atan2( v2[1], v2[0]);
else
p_out[0] = 0.;
p_out[1] = asine( v2[2]);
while( p_out[0] - old_ra > PI)
p_out[0] -= PI * 2.;
while( p_out[0] - old_ra <-PI)
p_out[0] += PI * 2.;
return( 0);
}
/* setup_ecliptic_precession fills a 3x3 orthonormal matrix for precessing */
/* positions _in ecliptic coordinates_ FROM year t1 TO year t2, where t1 */
/* and t2 are Julian YEARS... much as setup_precession( ) does for RA/dec */
/* 30 May 2002: change 'obliquity#' to '-obliquity#' to fix a bug reported */
/* by Jordi Mas, probably in place since the code was written. */
int DLL_FUNC setup_ecliptic_precession( double DLLPTR *matrix, const double t1,
const double t2)
{
const double obliquity1 = mean_obliquity( (t1 - 2000.) / 100.);
const double obliquity2 = mean_obliquity( (t2 - 2000.) / 100.);
setup_precession( matrix, t1, t2);
pre_spin_matrix( matrix + 1, matrix + 2, -obliquity1);
spin_matrix( matrix + 3, matrix + 6, -obliquity2);
return( 0);
}
#ifdef TEST_MAIN
#include <stdio.h>
#include <stdlib.h>
int main( const int argc, const char **argv)
{
double t1, t2, matrix[9];
double p[2];
int i;
t1 = atof( argv[1]);
t2 = atof( argv[2]);
if( argc > 3)
{
p[0] = atof( argv[3]) * PI / 180.;
p[1] = atof( argv[4]) * PI / 180.;
}
if( argc < 6)
setup_precession( matrix, t1, t2);
else
setup_ecliptic_precession( matrix, t1, t2);
for( i = 0; i < 9; i++)
printf( "%15.11lf%s", matrix[i], (i % 3 == 2) ? "\n" : " ");
if( argc > 3)
{
precess_ra_dec( matrix, p, p, 0);
printf( "%lf %lf\n", p[0] * 180. / PI, p[1] * 180. / PI);
precess_ra_dec( matrix, p, p, 1);
printf( "%lf %lf\n", p[0] * 180. / PI, p[1] * 180. / PI);
}
}
#endif
| 32.693878 | 83 | 0.576404 | TehSnappy |
150f91c9bdd785d55e82bf1dec95e6a732972e20 | 377 | cpp | C++ | DataStructures/Graphs/Union_Find.cpp | allenli873/USACO_Materials | 62540bf22268619283863e624d06b2588961e0a4 | [
"MIT"
] | 2 | 2020-05-30T22:24:43.000Z | 2020-05-30T23:35:15.000Z | DataStructures/Graphs/Union_Find.cpp | allenli873/USACO_Materials | 62540bf22268619283863e624d06b2588961e0a4 | [
"MIT"
] | null | null | null | DataStructures/Graphs/Union_Find.cpp | allenli873/USACO_Materials | 62540bf22268619283863e624d06b2588961e0a4 | [
"MIT"
] | null | null | null | template<int SZ> struct DSU {
int par[SZ], ranks[SZ];
DSU() {
iota(par, par + SZ, 0);
}
int find(int curr) {
return par[curr] == curr ? curr : (par[curr] = find(par[curr]));
}
void unite(int n1, int n2) {
int f1 = find(n1);
int f2 = find(n2);
if(ranks[f1] > ranks[f2]) {
par[f2] = f1;
ranks[f1]++;
} else {
par[f1] = f2;
ranks[f2]++;
}
}
}
| 15.708333 | 66 | 0.517241 | allenli873 |
15190683b6207230f0df6041ffdcfaf3ecfb50af | 1,109 | cpp | C++ | CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlugin/Source/CsCore/Public/Managers/Pool/Payload/CsPayload_PooledObjectImpl.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/Pool/Payload/CsPayload_PooledObjectImpl.h"
#include "Containers/CsInterfaceMap.h"
const FName NCsPooledObject::NPayload::FImpl::Name = FName("NCsPooledObject::NPayload::FImpl");
namespace NCsPooledObject
{
namespace NPayload
{
FImpl::FImpl() :
// ICsGetInterfaceMap
InterfaceMap(nullptr),
// IPayload
bAllocated(false),
UpdateType(NCsPooledObject::EUpdate::Manager),
Instigator(nullptr),
Owner(nullptr),
Parent(nullptr),
Time(),
PreserveChangesFromDefaultMask(0)
{
// ICsGetInterfaceMap
InterfaceMap = new FCsInterfaceMap();
InterfaceMap->SetRoot<FImpl>(this);
InterfaceMap->Add<IPayload>(static_cast<IPayload*>(this));
}
FImpl::~FImpl()
{
// ICsGetInterfaceMap
delete InterfaceMap;
}
// IPayload
#pragma region
void FImpl::Reset()
{
// IPayload
bAllocated = false;
UpdateType = NCsPooledObject::EUpdate::Manager;
Instigator = nullptr;
Owner = nullptr;
Parent = nullptr;
Time.Reset();
}
#pragma endregion IPayload
}
} | 20.163636 | 95 | 0.699729 | closedsum |
151deaa252ded8f32e97a3a98dcf327dcbb26263 | 3,763 | cpp | C++ | vlcdemo/vlc/vlc.cpp | liyuzhao/QWidgetDemo | a056894da7b7385e37a523ea4825cea48c82d297 | [
"MulanPSL-1.0"
] | 3,095 | 2019-10-11T03:00:33.000Z | 2022-03-31T08:15:13.000Z | vlcdemo/vlc/vlc.cpp | liyuzhao/QWidgetDemo | a056894da7b7385e37a523ea4825cea48c82d297 | [
"MulanPSL-1.0"
] | 28 | 2019-11-12T07:24:06.000Z | 2022-02-28T02:04:48.000Z | vlcdemo/vlc/vlc.cpp | liyuzhao/QWidgetDemo | a056894da7b7385e37a523ea4825cea48c82d297 | [
"MulanPSL-1.0"
] | 1,023 | 2019-10-09T12:54:07.000Z | 2022-03-30T04:02:07.000Z | #include "vlc.h"
VlcThread::VlcThread(QObject *parent) : QThread(parent)
{
setObjectName("VlcThread");
stopped = false;
isPlay = false;
url = "rtsp://192.168.1.200:554/1";
vlcInst = NULL;
vlcMedia = NULL;
vlcPlayer = NULL;
static bool isInit = false;
if (!isInit) {
isInit = true;
qDebug() << TIMEMS << "init vlc lib ok" << " version:" << libvlc_get_version();
}
}
void VlcThread::run()
{
while (!stopped) {
msleep(1);
}
//线程结束后释放资源
free();
stopped = false;
isPlay = false;
//qDebug() << TIMEMS << "stop vlc1 thread";
}
void VlcThread::setUrl(const QString &url)
{
this->url = url;
}
void VlcThread::setOption(const QString &option)
{
if (vlcMedia != NULL) {
QByteArray data = option.toUtf8();
const char *arg = data.constData();
libvlc_media_add_option(vlcMedia, arg);
}
}
bool VlcThread::init()
{
const char *tempArg = "";
const char *vlc_args[9] = {"-I", "dummy", "--no-osd", "--no-stats", "--ignore-config", "--no-video-on-top", "--no-video-title-show", "--no-snapshot-preview", tempArg};
vlcInst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
if (vlcInst == NULL) {
return false;
}
vlcMedia = libvlc_media_new_location(vlcInst, url.toUtf8().constData());
vlcPlayer = libvlc_media_player_new_from_media(vlcMedia);
if (vlcPlayer == NULL) {
return false;
}
//设置播放句柄
VlcWidget *w = (VlcWidget *)this->parent();
#if defined(Q_OS_WIN)
libvlc_media_player_set_hwnd(vlcPlayer, (void *)w->winId());
#elif defined(Q_OS_LINUX)
libvlc_media_player_set_xwindow(vlcPlayer, w->winId());
#elif defined(Q_OS_MAC)
libvlc_media_player_set_nsobject(vlcPlayer, (void *)w->winId());
#endif
//设置硬件加速 none auto any d3d11va dxva2
setOption(QString(":avcodec-hw=%1").arg("none"));
//设置通信协议 tcp udp
setOption(QString(":rtsp-%1").arg("tcp"));
//设置缓存时间 默认500毫秒
setOption(QString(":network-caching=%1").arg(300));
libvlc_media_player_play(vlcPlayer);
//qDebug() << TIMEMS << "init vlc finsh";
return true;
}
void VlcThread::play()
{
isPlay = true;
this->init();
}
void VlcThread::pause()
{
if (vlcPlayer != NULL) {
libvlc_media_player_pause(vlcPlayer);
}
}
void VlcThread::next()
{
if (vlcPlayer != NULL) {
libvlc_media_player_pause(vlcPlayer);
}
}
void VlcThread::free()
{
if (vlcInst != NULL) {
libvlc_release(vlcInst);
vlcInst = NULL;
}
if (vlcMedia != NULL) {
libvlc_media_release(vlcMedia);
vlcMedia = NULL;
}
if (vlcPlayer != NULL) {
libvlc_media_player_release(vlcPlayer);
vlcPlayer = NULL;
}
//qDebug() << TIMEMS << "close vlc ok";
}
void VlcThread::stop()
{
stopped = true;
}
//实时视频显示窗体类
VlcWidget::VlcWidget(QWidget *parent) : QWidget(parent)
{
thread = new VlcThread(this);
}
VlcWidget::~VlcWidget()
{
close();
}
void VlcWidget::setUrl(const QString &url)
{
thread->setUrl(url);
}
void VlcWidget::open()
{
//qDebug() << TIMEMS << "open video" << objectName();
clear();
thread->play();
thread->start();
}
void VlcWidget::pause()
{
thread->pause();
}
void VlcWidget::next()
{
thread->next();
}
void VlcWidget::close()
{
//qDebug() << TIMEMS << "close video" << objectName();
if (thread->isRunning()) {
thread->stop();
thread->quit();
thread->wait(3000);
}
QTimer::singleShot(5, this, SLOT(clear()));
}
void VlcWidget::restart()
{
//qDebug() << TIMEMS << "restart video" << objectName();
close();
QTimer::singleShot(10, this, SLOT(open()));
}
void VlcWidget::clear()
{
update();
}
| 19.805263 | 171 | 0.597661 | liyuzhao |
151f3dd67175a7f64d3fbc91bb474512ea823b11 | 457 | cpp | C++ | chapter_05/BitLevelOperations.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | chapter_05/BitLevelOperations.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | 31 | 2021-05-14T03:37:24.000Z | 2022-03-13T17:38:32.000Z | chapter_05/BitLevelOperations.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | // Exercise 5.46 - Computer Architecture: Bit-level operations
// I am not sure of this solution it is not mine I need to understand this program.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int value, mask = 1, temp, bit;
std::cin >> value;
std::cout << "The bits are ";
for (int i = 15; i >= 0; i--)
{
temp = value >> i;
bit = temp & mask;
std::cout << bit;
}
return 0;
}
| 21.761905 | 83 | 0.553611 | Kevin-Oudai |
151f6553975810ceb7a1cebbc794e9528eaeaac5 | 418 | cpp | C++ | Competitive Programming/leetcode/Number-of-Good-Pairs.cpp | JcsnP/My-Playground | 683600bd32ee7050bbe2cfca8eaf96eb1cdf039c | [
"Unlicense"
] | 2 | 2020-12-31T09:30:57.000Z | 2021-03-15T05:04:18.000Z | Competitive Programming/leetcode/Number-of-Good-Pairs.cpp | JcsnP/My-Playground | 683600bd32ee7050bbe2cfca8eaf96eb1cdf039c | [
"Unlicense"
] | null | null | null | Competitive Programming/leetcode/Number-of-Good-Pairs.cpp | JcsnP/My-Playground | 683600bd32ee7050bbe2cfca8eaf96eb1cdf039c | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int numIdenticalPairs(vector<int>& nums){
unsigned int pairs = 0;
for(unsigned int i = 0; i < nums.size(); i++){
for(unsigned int j = 0; j < nums.size(); j++){
if(nums[i] == nums[j] and i < j){
++pairs;
}
}
}
return pairs;
}
int main(){
vector<int> nums = {1,2,3,1,1,3};
//call function
cout << numIdenticalPairs(nums);
}
| 19 | 50 | 0.552632 | JcsnP |
1526cf54858f8c6ff963783c1a303c91e54e44a7 | 653 | hpp | C++ | cpp/include/core/https/HttpsClient.hpp | nawbar23/fleetmgr | e5f93877fa373841845941dacf37cfcd4364f69c | [
"MIT"
] | null | null | null | cpp/include/core/https/HttpsClient.hpp | nawbar23/fleetmgr | e5f93877fa373841845941dacf37cfcd4364f69c | [
"MIT"
] | null | null | null | cpp/include/core/https/HttpsClient.hpp | nawbar23/fleetmgr | e5f93877fa373841845941dacf37cfcd4364f69c | [
"MIT"
] | null | null | null | #ifndef FM_CORE_HTTPS_HTTPSCLIENT_HPP
#define FM_CORE_HTTPS_HTTPSCLIENT_HPP
#include <string>
namespace fm
{
namespace core
{
namespace https {
/**
* Created by: Bartosz Nawrot
* Date: 2018-11-27
* Description:
*/
class HttpsClient
{
public:
enum Method
{
POST,
PUT,
GET,
DELETE,
};
HttpsClient(const std::string&, const int, const std::string&);
std::string execute(const std::string&, const Method, const std::string&);
protected:
const std::string host;
const int port;
const std::string apiKey;
};
} // https
} // core
} // fm
#endif // FM_CORE_HTTPS_IHTTPSCLIENT_HPP
| 13.604167 | 78 | 0.644717 | nawbar23 |
1530acbd09e58deb3f6305bdb938900452df6334 | 528 | hpp | C++ | examples/02Physics/LevelEnd.hpp | Galhad/firestorm | 3c1584b1e5b95f21d963b9cf226f6ec1a469d7af | [
"MIT"
] | null | null | null | examples/02Physics/LevelEnd.hpp | Galhad/firestorm | 3c1584b1e5b95f21d963b9cf226f6ec1a469d7af | [
"MIT"
] | null | null | null | examples/02Physics/LevelEnd.hpp | Galhad/firestorm | 3c1584b1e5b95f21d963b9cf226f6ec1a469d7af | [
"MIT"
] | null | null | null |
#ifndef FIRESTORM_LEVELEND_HPP
#define FIRESTORM_LEVELEND_HPP
#include "scene/SceneNode.hpp"
#include <memory>
namespace fs::scene
{
class LevelEnd : public SceneNode
{
public:
LevelEnd() = default;
~LevelEnd() override = default;
void create(io::InputManager& inputManager, physics::PhysicsManager& physicsManager, const core::Vector2f& point1,
const core::Vector2f& point2);
void destroy() override;
};
typedef std::unique_ptr<LevelEnd> LevelEndPtr;
}
#endif //FIRESTORM_LEVELEND_HPP
| 18.206897 | 118 | 0.725379 | Galhad |
15322fdd0929ad0f55e4421424f3146d31247b4c | 4,211 | cpp | C++ | modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kharunova_a_algorithm_of_strongin/main.cpp | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Kharunova Alina
#include <gtest/gtest.h>
#include "./algorithm_of_strongin.h"
#include <gtest-mpi-listener.hpp>
TEST(Parallel_Operations_MPI, parallel_sum_in_10_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 10, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 10, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
TEST(Parallel_Operations_MPI, parallel_sum_in_100_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 100, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 100, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
TEST(Parallel_Operations_MPI, parallel_sum_in_1000_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 1000, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 1000, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
TEST(Parallel_Operations_MPI, parallel_sum_in_500_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 500, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 500, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
TEST(Parallel_Operations_MPI, parallel_sum_in_474_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 474, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 474, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
TEST(Parallel_Operations_MPI, parallel_sum_in_50_elements_matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double start, end, timeLin, timeParal;
if (rank == 0) {
start = MPI_Wtime();
linAlgorithm(1, 50, 0.01);
end = MPI_Wtime();
timeLin = end - start;
std::cout << "Linear " << timeLin << std::endl;
start = MPI_Wtime();
}
paralAlgorithm(1, 50, 0.01);
if (rank == 0) {
end = MPI_Wtime();
timeParal = end - start;
std::cout << "Paral " << timeParal << std::endl;
std::cout << "Effective " << timeLin / timeParal << std::endl;
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 28.452703 | 76 | 0.625742 | Gurgen-Arm |
15343d244e983291fce531f0643c5f70262e8831 | 571 | hpp | C++ | upgrade/boot_loader/VerifierRsa.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 54 | 2019-04-02T14:42:54.000Z | 2022-03-20T23:02:19.000Z | upgrade/boot_loader/VerifierRsa.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 32 | 2019-03-26T06:57:29.000Z | 2022-03-25T00:04:44.000Z | upgrade/boot_loader/VerifierRsa.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 20 | 2019-03-25T15:49:49.000Z | 2022-03-20T23:02:22.000Z | #ifndef UPGRADE_VERIFIER_RSA_HPP
#define UPGRADE_VERIFIER_RSA_HPP
#include "upgrade/boot_loader/Verifier.hpp"
namespace application
{
class VerifierRsa
: public Verifier
{
public:
VerifierRsa(infra::ConstByteRange publicKeyN, infra::ConstByteRange publicKeyE);
virtual bool IsValid(hal::SynchronousFlash& flash, const hal::SynchronousFlash::Range& signature, const hal::SynchronousFlash::Range& data) const override;
private:
infra::ConstByteRange publicKeyN;
infra::ConstByteRange publicKeyE;
};
}
#endif
| 24.826087 | 163 | 0.730298 | oguzcanphilips |
15361ff688031e211c11b637af0b229804760345 | 2,494 | cpp | C++ | src/Services/FunctionManagementService.cpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | src/Services/FunctionManagementService.cpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | src/Services/FunctionManagementService.cpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | #include "ECSS_Configuration.hpp"
#ifdef SERVICE_FUNCTION
#include "Services/FunctionManagementService.hpp"
void FunctionManagementService::call(Message& msg) {
msg.resetRead();
ErrorHandler::assertRequest(msg.packetType == Message::TC, msg,
ErrorHandler::AcceptanceErrorType::UnacceptableMessage);
ErrorHandler::assertRequest(msg.messageType == FunctionManagementService::MessageType::PerformFunction, msg,
ErrorHandler::AcceptanceErrorType::UnacceptableMessage);
ErrorHandler::assertRequest(msg.serviceType == FunctionManagementService::ServiceType, msg,
ErrorHandler::AcceptanceErrorType::UnacceptableMessage);
uint8_t funcName[ECSSFunctionNameLength] = { 0 }; // the function's name
uint8_t funcArgs[ECSSFunctionMaxArgLength] = { 0 }; // arguments for the function
msg.readString(funcName, ECSSFunctionNameLength);
msg.readString(funcArgs, ECSSFunctionMaxArgLength);
if (msg.dataSize > (ECSSFunctionNameLength + ECSSFunctionMaxArgLength)) {
ErrorHandler::reportError(msg,
ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError); // report failed
// start of execution as requested by the standard
return;
}
// locate the appropriate function pointer
String<ECSSFunctionNameLength> name(funcName);
FunctionMap::iterator iter = funcPtrIndex.find(name);
void (*selected)(String<ECSSFunctionMaxArgLength>);
if (iter != funcPtrIndex.end()) {
selected = *iter->second;
} else {
ErrorHandler::reportError(msg, ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError);
return;
}
// execute the function if there are no obvious flaws (defined in the standard, pg.158)
selected(funcArgs);
}
void FunctionManagementService::include(String<ECSSFunctionNameLength> funcName,
void (* ptr)(String<ECSSFunctionMaxArgLength>)) {
if (not funcPtrIndex.full()) { // CAUTION: etl::map won't check by itself if it's full
// before attempting to insert a key-value pair, causing segmentation faults. Check first!
funcName.append(ECSSFunctionNameLength - funcName.length(), 0);
funcPtrIndex.insert(std::make_pair(funcName, ptr));
} else {
ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType::MapFull);
}
}
void FunctionManagementService::execute(Message& message) {
switch (message.messageType) {
case PerformFunction:
call(message); // TC[8,1]
break;
default:
ErrorHandler::reportInternalError(ErrorHandler::OtherMessageType);
break;
}
}
#endif
| 37.223881 | 112 | 0.761427 | ACubeSAT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.