hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b2207ddb588860a7cbda8fe9b2e844b701cb641 | 7,396 | cpp | C++ | app/bin/miner/xmr-stak/xmrstak/backend/cpu/crypto/cryptonight_common.cpp | chrisknepper/electron-gui-crypto-miner | e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2 | [
"MIT"
] | 2 | 2018-01-25T04:29:57.000Z | 2020-02-13T15:30:55.000Z | app/bin/miner/xmr-stak/xmrstak/backend/cpu/crypto/cryptonight_common.cpp | chrisknepper/electron-gui-crypto-miner | e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2 | [
"MIT"
] | 1 | 2019-05-26T17:51:57.000Z | 2019-05-26T17:51:57.000Z | app/bin/miner/xmr-stak/xmrstak/backend/cpu/crypto/cryptonight_common.cpp | chrisknepper/electron-gui-crypto-miner | e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2 | [
"MIT"
] | 5 | 2018-02-17T11:32:37.000Z | 2021-02-26T22:26:07.000Z | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with OpenSSL (or a modified version of that library), containing parts
* covered by the terms of OpenSSL License and SSLeay License, the licensors
* of this Program grant you additional permission to convey the resulting work.
*
*/
extern "C"
{
#include "c_groestl.h"
#include "c_blake256.h"
#include "c_jh.h"
#include "c_skein.h"
}
#include "cryptonight.h"
#include "cryptonight_aesni.h"
#include "xmrstak/backend/cryptonight.hpp"
#include "xmrstak/jconf.hpp"
#include <stdio.h>
#include <stdlib.h>
#ifdef __GNUC__
#include <mm_malloc.h>
#else
#include <malloc.h>
#endif // __GNUC__
#if defined(__APPLE__)
#include <mach/vm_statistics.h>
#endif
#ifdef _WIN32
#include <windows.h>
#include <ntsecapi.h>
#else
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#endif // _WIN32
void do_blake_hash(const void* input, size_t len, char* output) {
blake256_hash((uint8_t*)output, (const uint8_t*)input, len);
}
void do_groestl_hash(const void* input, size_t len, char* output) {
groestl((const uint8_t*)input, len * 8, (uint8_t*)output);
}
void do_jh_hash(const void* input, size_t len, char* output) {
jh_hash(32 * 8, (const uint8_t*)input, 8 * len, (uint8_t*)output);
}
void do_skein_hash(const void* input, size_t len, char* output) {
skein_hash(8 * 32, (const uint8_t*)input, 8 * len, (uint8_t*)output);
}
void (* const extra_hashes[4])(const void *, size_t, char *) = {do_blake_hash, do_groestl_hash, do_jh_hash, do_skein_hash};
#ifdef _WIN32
BOOL bRebootDesirable = FALSE; //If VirtualAlloc fails, suggest a reboot
BOOL AddPrivilege(TCHAR* pszPrivilege)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
BOOL status;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, pszPrivilege, &tp.Privileges[0].Luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
status = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
if (!status || (GetLastError() != ERROR_SUCCESS))
return FALSE;
CloseHandle(hToken);
return TRUE;
}
BOOL AddLargePageRights()
{
HANDLE hToken;
PTOKEN_USER user = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) == TRUE)
{
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof(TOKEN_ELEVATION);
BOOL bIsElevated = FALSE;
if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize))
bIsElevated = Elevation.TokenIsElevated;
DWORD size = 0;
GetTokenInformation(hToken, TokenUser, NULL, 0, &size);
if (size > 0 && bIsElevated)
{
user = (PTOKEN_USER)LocalAlloc(LPTR, size);
GetTokenInformation(hToken, TokenUser, user, size, &size);
}
CloseHandle(hToken);
}
if (!user)
return FALSE;
LSA_HANDLE handle;
LSA_OBJECT_ATTRIBUTES attributes;
ZeroMemory(&attributes, sizeof(attributes));
BOOL result = FALSE;
if (LsaOpenPolicy(NULL, &attributes, POLICY_ALL_ACCESS, &handle) == 0)
{
LSA_UNICODE_STRING lockmem;
lockmem.Buffer = L"SeLockMemoryPrivilege";
lockmem.Length = 42;
lockmem.MaximumLength = 44;
PLSA_UNICODE_STRING rights = NULL;
ULONG cnt = 0;
BOOL bHasRights = FALSE;
if (LsaEnumerateAccountRights(handle, user->User.Sid, &rights, &cnt) == 0)
{
for (size_t i = 0; i < cnt; i++)
{
if (rights[i].Length == lockmem.Length &&
memcmp(rights[i].Buffer, lockmem.Buffer, 42) == 0)
{
bHasRights = TRUE;
break;
}
}
LsaFreeMemory(rights);
}
if(!bHasRights)
result = LsaAddAccountRights(handle, user->User.Sid, &lockmem, 1) == 0;
LsaClose(handle);
}
LocalFree(user);
return result;
}
#endif
size_t cryptonight_init(size_t use_fast_mem, size_t use_mlock, alloc_msg* msg)
{
#ifdef _WIN32
if(use_fast_mem == 0)
return 1;
if(AddPrivilege(TEXT("SeLockMemoryPrivilege")) == 0)
{
if(AddLargePageRights())
{
msg->warning = "Added SeLockMemoryPrivilege to the current account. You need to reboot for it to work";
bRebootDesirable = TRUE;
}
else
msg->warning = "Obtaning SeLockMemoryPrivilege failed.";
return 0;
}
bRebootDesirable = TRUE;
return 1;
#else
return 1;
#endif // _WIN32
}
cryptonight_ctx* cryptonight_alloc_ctx(size_t use_fast_mem, size_t use_mlock, alloc_msg* msg)
{
size_t hashMemSize;
if(::jconf::inst()->IsCurrencyMonero())
{
hashMemSize = MONERO_MEMORY;
}
else
{
hashMemSize = AEON_MEMORY;
}
cryptonight_ctx* ptr = (cryptonight_ctx*)_mm_malloc(sizeof(cryptonight_ctx), 4096);
if(use_fast_mem == 0)
{
// use 2MiB aligned memory
ptr->long_state = (uint8_t*)_mm_malloc(hashMemSize, hashMemSize);
ptr->ctx_info[0] = 0;
ptr->ctx_info[1] = 0;
return ptr;
}
#ifdef _WIN32
SIZE_T iLargePageMin = GetLargePageMinimum();
if(hashMemSize > iLargePageMin)
iLargePageMin *= 2;
ptr->long_state = (uint8_t*)VirtualAlloc(NULL, iLargePageMin,
MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
if(ptr->long_state == NULL)
{
_mm_free(ptr);
if(bRebootDesirable)
msg->warning = "VirtualAlloc failed. Reboot might help.";
else
msg->warning = "VirtualAlloc failed.";
return NULL;
}
else
{
ptr->ctx_info[0] = 1;
return ptr;
}
#else
#if defined(__APPLE__)
ptr->long_state = (uint8_t*)mmap(0, hashMemSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
#elif defined(__FreeBSD__)
ptr->long_state = (uint8_t*)mmap(0, hashMemSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER | MAP_PREFAULT_READ, -1, 0);
#else
ptr->long_state = (uint8_t*)mmap(0, hashMemSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, 0, 0);
#endif
if (ptr->long_state == MAP_FAILED)
{
_mm_free(ptr);
msg->warning = "mmap failed";
return NULL;
}
ptr->ctx_info[0] = 1;
if(madvise(ptr->long_state, hashMemSize, MADV_RANDOM|MADV_WILLNEED) != 0)
msg->warning = "madvise failed";
ptr->ctx_info[1] = 0;
if(use_mlock != 0 && mlock(ptr->long_state, hashMemSize) != 0)
msg->warning = "mlock failed";
else
ptr->ctx_info[1] = 1;
return ptr;
#endif // _WIN32
}
void cryptonight_free_ctx(cryptonight_ctx* ctx)
{
size_t hashMemSize;
if(::jconf::inst()->IsCurrencyMonero())
{
hashMemSize = MONERO_MEMORY;
}
else
{
hashMemSize = AEON_MEMORY;
}
if(ctx->ctx_info[0] != 0)
{
#ifdef _WIN32
VirtualFree(ctx->long_state, 0, MEM_RELEASE);
#else
if(ctx->ctx_info[1] != 0)
munlock(ctx->long_state, hashMemSize);
munmap(ctx->long_state, hashMemSize);
#endif // _WIN32
}
else
_mm_free(ctx->long_state);
_mm_free(ctx);
}
| 24.409241 | 123 | 0.70768 | chrisknepper |
8b25238e89a48ce19f3ed57de0a4692b7f8ce2c5 | 50,386 | cpp | C++ | CloakCompiler/MeshCompiler.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakCompiler/MeshCompiler.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakCompiler/MeshCompiler.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "CloakCompiler/Mesh.h"
#include "CloakEngine/Files/ExtendedBuffers.h"
#include "Engine/TempHandler.h"
#include "Engine/BoundingVolume.h"
#include <assert.h>
#include <sstream>
//#define DEBUG_ENFORCE_STRIPS
//#define DEBUG_ENFORCE_NO_STRIPS
#define ALLOW_STRIP_LIST_MIX
#define STRIP_FUNC(name) size_t name(In size_t triID, In size_t swapEdge, In const CE::List<HalfEdge>& edges, In const CE::List<Triangle>& faces, In uint64_t floodFillVisited, In bool firstCall)
#define PRINT_STRIPS
namespace CloakCompiler {
namespace API {
namespace Mesh {
typedef std::function<void(const RespondeInfo&)> RespondeFunc;
constexpr float g_floatDelta = 0.0001f;
constexpr size_t STRIP_CUT_VALUE = 0xFFFFFFFF;
constexpr size_t STRIP_CUT_VALUE_16 = 0xFFFF;
constexpr size_t MAX_IB16_SIZE = 1 << 16;
//Minimum required number of single triangles to not use them as strip
// Since draw calls have a cost, we prefere to have a bit longer index buffers than additional
// draw calls with a few triangles. This value is just a guess, so it might change in future
constexpr size_t MIN_TRI_COUNT = 128;
enum class IndexBufferType {
IB16,
IB16ShortCut,
IB32,
};
struct FinalVertex {
CloakEngine::Global::Math::Vector Position;
CloakEngine::Global::Math::Vector Normal;
CloakEngine::Global::Math::Vector Binormal;
CloakEngine::Global::Math::Vector Tangent;
size_t MaterialID;
TexCoord TexCoord;
Bone Bones[4];
bool CLOAK_CALL CompareForIndex(In const FinalVertex& b) const
{
bool r = Position == b.Position;
r = r && Normal == b.Normal;
r = r && Binormal == b.Binormal;
r = r && Tangent == b.Tangent;
r = r && abs(TexCoord.U - b.TexCoord.U) < g_floatDelta;
r = r && abs(TexCoord.V - b.TexCoord.V) < g_floatDelta;
for (size_t a = 0; a < 4 && r; a++)
{
r = r && Bones[a].BoneID == b.Bones[a].BoneID;
r = r && abs(Bones[a].Weight - b.Bones[a].Weight) < g_floatDelta;
}
return r;
}
};
struct MaterialRange {
size_t MaterialID;
size_t ListCount;
size_t StripCount;
};
constexpr size_t VertexSize = sizeof(FinalVertex) - sizeof(size_t);
constexpr CloakEngine::Files::FileType g_TempFileType{ "MeshTemp","CEMT",1000 };
namespace Strips {
//Number of indices the triangle-list index buffer should at least include to justify the additional draw call:
constexpr size_t MIN_TRIANGLE_LIST_SIZE = 128;
//Percentage of indices (relative to the triangle-strip index buffer) the triangle-list index buffer should at least include to justify the additional draw call:
constexpr float MIN_TRIANGLE_LIST_PERCENTAGE = 0.1f;
struct HalfEdge {
size_t Vertex;
size_t OppositeEdge;
};
struct Triangle {
size_t Edge;
size_t AdjacentCount;
size_t MaterialID;
uint64_t FloodFillVisited;
};
CLOAK_FORCEINLINE constexpr size_t TriangleByEdge(In size_t edgeID)
{
return edgeID / 3;
}
CLOAK_FORCEINLINE constexpr size_t FirstEdgeOfTrinalge(In size_t edgeID)
{
return edgeID * 3;
}
CLOAK_FORCEINLINE constexpr size_t NextEdge(In size_t edgeID)
{
const size_t tID = TriangleByEdge(edgeID);
return (3 * tID) + ((edgeID + 1) % 3);
}
CLOAK_FORCEINLINE constexpr size_t PrevEdge(In size_t edgeID)
{
const size_t tID = TriangleByEdge(edgeID);
return (3 * tID) + ((edgeID + 2) % 3);
}
inline size_t CLOAK_CALL AdjacentTriangleCount(In size_t triangleID, In const CE::List<HalfEdge>& edges, In const CE::List<Triangle>& faces, In uint64_t floodFillVisited)
{
if (triangleID >= edges.size() / 3) { return 0; }
size_t res = 0;
for (size_t a = 0; a < 3; a++)
{
const size_t i = (3 * triangleID) + a;
const size_t j = edges[i].OppositeEdge;
if (j < edges.size() && faces[TriangleByEdge(j)].MaterialID == faces[TriangleByEdge(j)].MaterialID && faces[TriangleByEdge(j)].FloodFillVisited != floodFillVisited) { res++; }
}
return res;
}
inline void CLOAK_CALL UpdateVisited(In size_t triangleID, In const CE::List<HalfEdge>& edges, Inout CE::List<Triangle>* faces, In uint64_t floodFillVisited)
{
faces->at(triangleID).FloodFillVisited = floodFillVisited;
for (size_t a = 0, b = FirstEdgeOfTrinalge(triangleID); a < 3; a++, b = NextEdge(b))
{
const size_t e = edges[b].OppositeEdge;
if (e != edges.size())
{
const size_t t = TriangleByEdge(e);
faces->at(t).AdjacentCount = AdjacentTriangleCount(t, edges, *faces, floodFillVisited);
}
}
}
typedef STRIP_FUNC((*StripFunc));
STRIP_FUNC(LNLS)
{
size_t bstEdge = edges.size();
size_t adjNum = static_cast<size_t>(-1);
for (size_t a = FirstEdgeOfTrinalge(triID), b = 0; b < 3; b++, a = NextEdge(a))
{
const size_t opEdge = edges[a].OppositeEdge;
if (opEdge < edges.size() && faces[TriangleByEdge(opEdge)].FloodFillVisited != floodFillVisited)
{
const size_t adjTri = TriangleByEdge(opEdge);
const size_t adj = AdjacentTriangleCount(adjTri, edges, faces, floodFillVisited);
//Check if edge require swap:
const bool swap = !firstCall && a == swapEdge;
if (adj < adjNum || (adj == adjNum && swap == false))
{
adjNum = adj;
bstEdge = a;
}
}
}
return bstEdge;
}
STRIP_FUNC(LNLN)
{
size_t bstEdge = edges.size();
size_t adjNum = static_cast<size_t>(-1);
size_t adjNumSec = static_cast<size_t>(-1);
for (size_t a = FirstEdgeOfTrinalge(triID), b = 0; b < 3; b++, a = NextEdge(a))
{
const size_t opEdge = edges[a].OppositeEdge;
if (opEdge < edges.size() && faces[TriangleByEdge(opEdge)].FloodFillVisited != floodFillVisited)
{
const size_t adjTri = TriangleByEdge(opEdge);
const size_t adj = AdjacentTriangleCount(adjTri, edges, faces, floodFillVisited);
const bool swap = !firstCall && a == swapEdge;
size_t adjSec = static_cast<size_t>(-1);
if (adj <= adjNum)
{
//Look one step ahead:
for (size_t c = adjTri * 3, d = 0; d < 3; d++, c = NextEdge(c))
{
const size_t opSec = edges[c].OppositeEdge;
if (opSec < edges.size() && opSec != a && faces[TriangleByEdge(opSec)].FloodFillVisited != floodFillVisited)
{
const size_t adjTriSec = TriangleByEdge(opSec);
const size_t sadj = AdjacentTriangleCount(adjTriSec, edges, faces, floodFillVisited);
adjSec = min(adjSec, sadj);
}
}
}
if (adj < adjNum || (adj == adjNum && adjSec < adjNumSec) || (adj == adjNum && adjSec == adjNumSec && swap == false))
{
adjNum = adj;
adjNumSec = adjSec;
bstEdge = a;
}
}
}
return bstEdge;
}
constexpr StripFunc Functions[] = { LNLS, LNLN };
inline bool CLOAK_CALL CalculateIndexBufferStrips(In const CE::List<size_t>& indexBaseBuffer, Inout CE::List<size_t>* indexBuffer, Inout CloakEngine::List<MaterialRange>* materialRanges)
{
bool res = false;
size_t firstIndexPos = 0;
#ifndef DEBUG_ENFORCE_NO_STRIPS
#ifdef DEBUG_ENFORCE_STRIPS
indexBuffer->clear();
#endif
//Create half-edge structure:
CE::List<Triangle> faces(indexBaseBuffer.size() / 3);
CE::List<HalfEdge> edges(faces.size() * 3);
//This array allows to find an edge by two entries of an index buffer:
CE::FlatMap<std::pair<size_t, size_t>, size_t> vertexToEdge;
//To test whether we included an face already in our new index buffer, we use a flood fill counter
uint64_t floodFillVisited = 1;
#define VERTEX_TO_EDGE(v0, v1) vertexToEdge[std::make_pair((v0),(v1))]
#define VERTEX_EDGE_EXIST(v0, v1) (vertexToEdge.find(std::make_pair((v0), (v1))) != vertexToEdge.end())
//Calculate edges:
for (size_t a = 0; a < indexBaseBuffer.size(); a += 3)
{
size_t vli = a + 2;
for (size_t b = 0; b < 3; b++)
{
const size_t vni = a + b;
const size_t vl = indexBaseBuffer[vli];
const size_t vn = indexBaseBuffer[vni];
edges[vni].Vertex = vl;
edges[vni].OppositeEdge = edges.size();
VERTEX_TO_EDGE(vl, vn) = vni;
vli = vni;
}
}
//Initialize face values:
for (size_t a = 0; a < faces.size(); a++)
{
faces[a].Edge = a * 3;
faces[a].FloodFillVisited = 0;
faces[a].AdjacentCount = 0;
faces[a].MaterialID = ~0;
}
//Initialize material IDs:
size_t firstEdge = 0;
for (size_t a = 0; a < materialRanges->size(); a++)
{
CLOAK_ASSUME(materialRanges->at(a).StripCount == 0);
const size_t lastEdge = min(firstEdge + materialRanges->at(a).ListCount, edges.size());
CLOAK_ASSUME(lastEdge % 3 == 0);
for (size_t c = firstEdge; c < lastEdge; c += 3)
{
const size_t t = TriangleByEdge(c);
faces[t].MaterialID = materialRanges->at(a).MaterialID;
}
firstEdge = lastEdge;
}
//Calculate opposite edges:
for (size_t a = 0; a < indexBaseBuffer.size(); a += 3)
{
size_t vli = a + 2;
for (size_t b = 0; b < 3; b++)
{
const size_t vni = a + b;
const size_t vl = indexBaseBuffer[vli];
const size_t vn = indexBaseBuffer[vni];
const size_t eM = VERTEX_TO_EDGE(vl, vn);
if (VERTEX_EDGE_EXIST(vn, vl))
{
const size_t eO = VERTEX_TO_EDGE(vn, vl);
const size_t tM = TriangleByEdge(eM);
const size_t tO = TriangleByEdge(eO);
if (faces[tM].MaterialID == faces[tO].MaterialID)
{
edges[eM].OppositeEdge = eO;
vli = vni;
continue;
}
}
edges[eM].OppositeEdge = edges.size();
vli = vni;
}
}
CE::List<size_t> newIBStrip;
CE::List<size_t> newIBList;
firstEdge = 0;
for (size_t a = 0; a < materialRanges->size(); a++)
{
CLOAK_ASSUME(materialRanges->at(a).StripCount == 0);
if (materialRanges->at(a).ListCount < 3) { continue; }
const size_t lastEdge = min(firstEdge + materialRanges->at(a).ListCount, edges.size());
CLOAK_ASSUME(lastEdge % 3 == 0);
//Calculate triangle strips:
for (size_t b = 0; b < ARRAYSIZE(Functions); b++)
{
//Main Algorithm:
do {
//Find best face (with lowest adjacent count) to start with:
size_t face = faces.size();
size_t bstAdjC = ~0;
for (size_t c = firstEdge; c < lastEdge; c += 3)
{
const size_t t = TriangleByEdge(c);
faces[t].AdjacentCount = AdjacentTriangleCount(t, edges, faces, floodFillVisited);
if (faces[t].FloodFillVisited != floodFillVisited && faces[t].AdjacentCount < bstAdjC)
{
bstAdjC = faces[t].AdjacentCount;
face = t;
}
}
if (face == faces.size()) { break; } // No more faces
UpdateVisited(face, edges, &faces, floodFillVisited);
size_t edge = Functions[b](face, edges.size(), edges, faces, floodFillVisited, true);
if (edge == edges.size())
{
//Single triangle, all adjacent triangles were already used:
edge = FirstEdgeOfTrinalge(face);
#ifdef ALLOW_STRIP_LIST_MIX
newIBList.push_back(edges[edge].Vertex);
edge = NextEdge(edge);
newIBList.push_back(edges[edge].Vertex);
edge = NextEdge(edge);
newIBList.push_back(edges[edge].Vertex);
#else
newIBStrip.push_back(edges[edge].Vertex);
edge = NextEdge(edge);
newIBStrip.push_back(edges[edge].Vertex);
edge = NextEdge(edge);
newIBStrip.push_back(edges[edge].Vertex);
newIBStrip.push_back(STRIP_CUT_VALUE);
#endif
}
else
{
const size_t startEdge = edge;
bool extendSecondDir = false;
//Insert first triangle:
newIBStrip.push_back(edges[PrevEdge(edge)].Vertex);
newIBStrip.push_back(edges[edge].Vertex);
size_t curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
newIBStrip.push_back(edges[curEdge].Vertex);
//Walk along strip:
do {
insert_ccw_triangle:
size_t swapEdge = NextEdge(curEdge);
face = TriangleByEdge(curEdge);
UpdateVisited(face, edges, &faces, floodFillVisited);
edge = Functions[b](face, swapEdge, edges, faces, floodFillVisited, false);
if (edge == edges.size())
{
//Strip ended (insert strip cut twice to enforce even number of indices)
newIBStrip.push_back(edges[PrevEdge(curEdge)].Vertex);
newIBStrip.push_back(STRIP_CUT_VALUE);
newIBStrip.push_back(STRIP_CUT_VALUE);
break;
}
else if (edge == swapEdge)
{
//Swap
newIBStrip.push_back(edges[edge].Vertex);
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
newIBStrip.push_back(edges[curEdge].Vertex);
goto insert_ccw_triangle;
}
else
{
newIBStrip.push_back(edges[edge].Vertex);
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
}
insert_cw_triangle:
swapEdge = PrevEdge(curEdge);
face = TriangleByEdge(curEdge);
UpdateVisited(face, edges, &faces, floodFillVisited);
edge = Functions[b](face, swapEdge, edges, faces, floodFillVisited, false);
if (edge == edges.size())
{
//Strip ended
newIBStrip.push_back(edges[PrevEdge(curEdge)].Vertex);
newIBStrip.push_back(STRIP_CUT_VALUE);
break;
}
else if (edge == swapEdge)
{
//Swap
newIBStrip.push_back(edges[curEdge].Vertex);
newIBStrip.push_back(edges[edge].Vertex);
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
goto insert_cw_triangle;
}
else
{
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
newIBStrip.push_back(edges[curEdge].Vertex);
}
} while (true);
//Try to extend in second direction:
if (extendSecondDir == false)
{
extendSecondDir = true;
size_t swapEdge = NextEdge(startEdge);
face = TriangleByEdge(startEdge);
edge = Functions[b](face, swapEdge, edges, faces, floodFillVisited, false);
if (edge < edges.size())
{
//Remove last strip cuts from strip:
while (newIBStrip.empty() == false && newIBStrip.back() == STRIP_CUT_VALUE) { newIBStrip.pop_back(); }
//Reverse strip:
// To reverse the strip, we need an even amount of indices in the strip. Otherwise, we would also reverse face directions
if (newIBStrip.size() % 2 != 0) { newIBStrip.push_back(newIBStrip.back()); }
for (size_t a = 0; a < newIBStrip.size() >> 1; a++) { std::swap(newIBStrip[a], newIBStrip[newIBStrip.size() - (a + 1)]); }
if (edge == swapEdge)
{
newIBStrip.pop_back();
newIBStrip.push_back(edges[edge].Vertex);
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
newIBStrip.push_back(edges[curEdge].Vertex);
goto insert_ccw_triangle;
}
else
{
curEdge = edges[edge].OppositeEdge;
CLOAK_ASSUME(curEdge < edges.size());
goto insert_cw_triangle;
}
}
}
}
} while (true);
//If the number of single triangles in the list does not justify a second draw call, we will merge it into the strips:
if (newIBStrip.size() > 0 && (newIBList.size() < MIN_TRIANGLE_LIST_SIZE || newIBList.size() < static_cast<size_t>(newIBStrip.size() * MIN_TRIANGLE_LIST_PERCENTAGE)))
{
for (size_t a = 0; a < newIBList.size(); a += 3)
{
newIBStrip.push_back(newIBList[a + 0]);
newIBStrip.push_back(newIBList[a + 1]);
newIBStrip.push_back(newIBList[a + 2]);
newIBStrip.push_back(STRIP_CUT_VALUE);
}
newIBList.clear();
}
//Remove last strip cuts from strip:
while (newIBStrip.empty() == false && newIBStrip.back() == STRIP_CUT_VALUE) { newIBStrip.pop_back(); }
//Compare and copy new index buffer:
#ifndef DEBUG_ENFORCE_STRIPS
if (newIBStrip.size() + newIBList.size() < materialRanges->at(a).ListCount + materialRanges->at(a).StripCount)
#else
if (b == 0 || newIBStrip.size() + newIBList.size() < materialRanges->at(a).ListCount + materialRanges->at(a).StripCount)
#endif
{
res = true;
materialRanges->at(a).ListCount = newIBList.size();
materialRanges->at(a).StripCount = newIBStrip.size();
CLOAK_ASSUME(firstIndexPos + newIBList.size() + newIBStrip.size() <= indexBuffer->size());
#ifndef DEBUG_ENFORCE_STRIPS
size_t p = firstIndexPos;
for (size_t b = 0; b < newIBStrip.size(); b++, p++) { indexBuffer->at(p) = newIBStrip[b]; }
for (size_t b = 0; b < newIBList.size(); b++, p++) { indexBuffer->at(p) = newIBList[b]; }
#else
indexBuffer->resize(firstIndexPos);
for (size_t b = 0; b < newIBStrip.size(); b++) { indexBuffer->push_back(newIBStrip[b]); }
for (size_t b = 0; b < newIBList.size(); b++) { indexBuffer->push_back(newIBList[b]); }
#endif
}
newIBStrip.clear();
newIBList.clear();
floodFillVisited++;
}
firstIndexPos += materialRanges->at(a).ListCount + materialRanges->at(a).StripCount;
firstEdge = lastEdge;
}
indexBuffer->resize(firstIndexPos);
#undef VERTEX_TO_EDGE
#endif
#ifdef PRINT_STRIPS
CE::Global::Log::WriteToLog("Final index buffer (" + std::to_string(indexBuffer->size()) + " Indices):");
firstIndexPos = 0;
for (size_t a = 0; a < materialRanges->size(); a++)
{
CE::Global::Log::WriteToLog("\tMaterial " + std::to_string(a));
for (size_t b = 0, s = 0; b < materialRanges->at(a).StripCount; s++)
{
std::stringstream r;
r << "\t\tStrip " << s << ": ";
if (indexBuffer->at(firstIndexPos + b) != STRIP_CUT_VALUE)
{
r << indexBuffer->at(firstIndexPos + b++);
while (b < materialRanges->at(a).StripCount && indexBuffer->at(firstIndexPos + b) != STRIP_CUT_VALUE) { r << " | " << indexBuffer->at(firstIndexPos + b++); }
}
while (b < materialRanges->at(a).StripCount && indexBuffer->at(firstIndexPos + b) == STRIP_CUT_VALUE) { r << " | CUT"; b++; }
CE::Global::Log::WriteToLog(r.str());
}
if (materialRanges->at(a).ListCount > 0)
{
std::stringstream r;
r << "\t\tList: " << indexBuffer->at(firstIndexPos + materialRanges->at(a).StripCount);
for (size_t b = 1; b < materialRanges->at(a).ListCount; b++) { r << " | " << indexBuffer->at(firstIndexPos + materialRanges->at(a).StripCount + b); }
CE::Global::Log::WriteToLog(r.str());
}
firstIndexPos += materialRanges->at(a).ListCount + materialRanges->at(a).StripCount;
}
#endif
return res;
}
}
inline void CLOAK_CALL SendResponse(In RespondeFunc func, In RespondeCode code, In size_t Polygon, In_opt size_t Vertex = 0, In_opt std::string msg = "")
{
RespondeInfo info;
info.Code = code;
info.Polygon = Polygon;
info.Vertex = Vertex;
info.Msg = msg;
func(info);
}
inline void CLOAK_CALL SendResponse(In RespondeFunc func, In RespondeCode code, In_opt std::string msg = "")
{
SendResponse(func, code, 0, 0, msg);
}
inline void CLOAK_CALL CopyVertex(In const Vertex& a, In const CloakEngine::Global::Math::Vector& normal, In const CloakEngine::Global::Math::Vector& binormal, In const CloakEngine::Global::Math::Vector& tangent, In uint32_t material, Out FinalVertex* b)
{
Bone tb[4];
//Remove bones with same ID
for (size_t c = 0; c < 4; c++)
{
if (a.Bones[c].Weight > 0)
{
bool f = false;
for (size_t d = 0; d < c && f == false; d++)
{
if (tb[d].Weight > 0 && tb[d].BoneID == a.Bones[c].BoneID)
{
f = true;
tb[d].Weight += a.Bones[c].Weight;
}
}
if (f == false)
{
tb[c].BoneID = a.Bones[c].BoneID;
tb[c].Weight = a.Bones[c].Weight;
}
else
{
tb[c].BoneID = 0;
tb[c].Weight = 0;
}
}
else
{
tb[c].BoneID = 0;
tb[c].Weight = 0;
}
}
float wNorm = 0;
//Normalize bone weights
for (size_t c = 0; c < 4; c++)
{
if (tb[c].Weight > 0) { wNorm += tb[c].Weight; }
}
//Set final vertex
b->Position = a.Position;
b->TexCoord = a.TexCoord;
b->Normal = normal;
b->Binormal = binormal;
b->Tangent = tangent;
b->MaterialID = material;
for (size_t c = 0; c < 4; c++)
{
if (tb[c].Weight > 0)
{
b->Bones[c].BoneID = tb[c].BoneID;
b->Bones[c].Weight = tb[c].Weight / wNorm;
}
else
{
b->Bones[c].BoneID = 0;
b->Bones[c].Weight = 0;
}
}
}
inline void CLOAK_CALL CalculatePolygonVertices(In const Vertex& a, In const Vertex& b, In const Vertex& c, In bool calcNorms, In size_t material, Out FinalVertex res[3])
{
TexCoord tex[2];
tex[0].U = b.TexCoord.U - a.TexCoord.U;
tex[0].V = b.TexCoord.V - a.TexCoord.V;
tex[1].U = c.TexCoord.U - a.TexCoord.U;
tex[1].V = c.TexCoord.V - a.TexCoord.V;
CloakEngine::Global::Math::Vector vec[2];
vec[0] = static_cast<const CloakEngine::Global::Math::Vector>(b.Position) - a.Position;
vec[1] = static_cast<const CloakEngine::Global::Math::Vector>(c.Position) - a.Position;
float det = (tex[0].U*tex[1].V) - (tex[1].U*tex[0].V);
if (fabsf(det) < 1e-4f)
{
tex[0].U = 1;
tex[0].V = 0;
tex[1].U = 1;
tex[1].V = -1;
det = -1;
}
const float den = 1.0f / det;
CloakEngine::Global::Math::Vector tangent = (den * ((tex[1].V * vec[0]) - (tex[0].V * vec[1]))).Normalize();
CloakEngine::Global::Math::Vector binormal = (den * ((tex[0].U * vec[1]) - (tex[1].U * vec[0]))).Normalize();
if (calcNorms)
{
CloakEngine::Global::Math::Vector normal = tangent.Cross(binormal).Normalize();
tangent -= binormal * (binormal.Dot(tangent));
if (normal.Cross(tangent).Dot(binormal) < 0) { tangent = -tangent; }
tangent = tangent.Normalize();
CopyVertex(a, normal, binormal, tangent, static_cast<uint32_t>(material), &res[0]);
CopyVertex(b, normal, binormal, tangent, static_cast<uint32_t>(material), &res[1]);
CopyVertex(c, normal, binormal, tangent, static_cast<uint32_t>(material), &res[2]);
}
else
{
const CloakEngine::Global::Math::Vector an = static_cast<CloakEngine::Global::Math::Vector>(a.Normal).Normalize();
const CloakEngine::Global::Math::Vector bn = static_cast<CloakEngine::Global::Math::Vector>(b.Normal).Normalize();
const CloakEngine::Global::Math::Vector cn = static_cast<CloakEngine::Global::Math::Vector>(c.Normal).Normalize();
const CloakEngine::Global::Math::Vector at = (tangent - (an.Dot(tangent)*an)).Normalize();
const CloakEngine::Global::Math::Vector bt = (tangent - (bn.Dot(tangent)*bn)).Normalize();
const CloakEngine::Global::Math::Vector ct = (tangent - (cn.Dot(tangent)*cn)).Normalize();
const CloakEngine::Global::Math::Vector ab = (binormal - ((an.Dot(binormal)*an) + (at.Dot(binormal)*at))).Normalize();
const CloakEngine::Global::Math::Vector bb = (binormal - ((bn.Dot(binormal)*bn) + (bt.Dot(binormal)*bt))).Normalize();
const CloakEngine::Global::Math::Vector cb = (binormal - ((cn.Dot(binormal)*cn) + (ct.Dot(binormal)*ct))).Normalize();
CopyVertex(a, a.Normal, ab, at, static_cast<uint32_t>(material), &res[0]);
CopyVertex(b, b.Normal, bb, bt, static_cast<uint32_t>(material), &res[1]);
CopyVertex(c, c.Normal, cb, ct, static_cast<uint32_t>(material), &res[2]);
}
}
inline IndexBufferType CLOAK_CALL CalculateIndexBuffer(In const FinalVertex* vb, In size_t vbs, Out CE::List<size_t>* ib, Out CE::List<bool>* usedVB, Out CloakEngine::List<MaterialRange>* materialRanges)
{
usedVB->resize(vbs);
ib->clear();
ib->reserve(vbs);
materialRanges->clear();
//Create Index Reference Buffer:
CE::List<size_t> irb(vbs);
for (size_t a = 0; a < vbs; a++)
{
const FinalVertex& v = vb[a];
for (size_t b = 0; b < a; b++)
{
const FinalVertex& i = vb[irb[b]];
if (v.CompareForIndex(i))
{
usedVB->at(a) = false;
irb[a] = irb[b];
goto irb_found_index;
}
}
usedVB->at(a) = true;
irb[a] = a;
irb_found_index:
continue;
}
//Create rebased index buffer:
CE::List<size_t> ibb(vbs);
ibb[0] = 0;
for (size_t a = 1; a < vbs; a++)
{
if (usedVB->at(a) == true) { ibb[a] = ibb[a - 1] + 1; }
else { ibb[a] = ibb[a - 1]; }
}
for (size_t a = 0; a < vbs; a++)
{
size_t p = a;
while (p != irb[p])
{
CLOAK_ASSUME(usedVB->at(p) == false);
p = irb[p];
}
ibb[a] = ibb[p];
}
#ifdef PRINT_STRIPS
CE::Global::Log::WriteToLog("Simple Index Buffer ("+std::to_string(ibb.size())+" Indices):");
#endif
size_t ibStart = 0;
for (size_t a = 0; a < vbs; a++)
{
ib->push_back(ibb[a]);
#ifdef PRINT_STRIPS
CE::Global::Log::WriteToLog("\tIB[" + std::to_string(a) + "] = " + std::to_string(ibb[a]));
#endif
if (a > 0 && vb[a].MaterialID != vb[a - 1].MaterialID)
{
MaterialRange mr;
mr.ListCount = a - ibStart;
mr.StripCount = 0;
mr.MaterialID = vb[a - 1].MaterialID;
materialRanges->push_back(mr);
ibStart = a;
}
}
//Add last material range:
MaterialRange mr;
mr.ListCount = vbs - ibStart;
mr.StripCount = 0;
mr.MaterialID = vb[vbs - 1].MaterialID;
materialRanges->push_back(mr);
//Calculate triangle strips:
IndexBufferType res;
if (Strips::CalculateIndexBufferStrips(ibb, ib, materialRanges) == false)
{
res = ib->size() < MAX_IB16_SIZE ? IndexBufferType::IB16 : IndexBufferType::IB32;
}
else
{
res = ib->size() < MAX_IB16_SIZE ? IndexBufferType::IB16 : IndexBufferType::IB32;
if (res == IndexBufferType::IB16)
{
for (size_t a = 0; a < ib->size(); a++)
{
if (ib->at(a) == STRIP_CUT_VALUE) { res = IndexBufferType::IB16ShortCut; }
}
}
}
return res;
}
inline bool CLOAK_CALL CheckFloat(In CloakEngine::Files::IReader* r, In const float& f)
{
const float i = static_cast<float>(r->ReadDouble(32));
return abs(i - f) < g_floatDelta;
}
inline bool CLOAK_CALL CheckVector(In CloakEngine::Files::IReader* r, In const CloakEngine::Global::Math::Vector& v)
{
CloakEngine::Global::Math::Point p(v);
return CheckFloat(r, p.X) && CheckFloat(r, p.Y) && CheckFloat(r, p.Z);
}
inline void CLOAK_CALL WriteVector(In CloakEngine::Files::IWriter* w, In const CloakEngine::Global::Math::Vector& v)
{
CloakEngine::Global::Math::Point p(v);
w->WriteDouble(32, p.X);
w->WriteDouble(32, p.Y);
w->WriteDouble(32, p.Z);
}
inline bool CLOAK_CALL CheckTemp(In CloakEngine::Files::IWriter* output, In const EncodeDesc& encode, In const Desc& desc, In RespondeFunc func)
{
bool suc = false;
if ((encode.flags & EncodeFlags::NO_TEMP_READ) == EncodeFlags::NONE)
{
CloakEngine::Files::IReader* read = nullptr;
CREATE_INTERFACE(CE_QUERY_ARGS(&read));
if (read != nullptr)
{
const std::u16string tmpPath = encode.tempPath;
suc = read->SetTarget(tmpPath, g_TempFileType, false, true) == g_TempFileType.Version;
if (suc) { SendResponse(func, RespondeCode::CHECK_TMP); }
if (suc) { suc = !Engine::TempHandler::CheckGameID(read, encode.targetGameID); }
if (suc) { suc = static_cast<BoundingVolume>(read->ReadBits(8)) == desc.Bounding; }
if (suc) { suc = read->ReadDynamic() == desc.Vertices.size(); }
if (suc) { suc = read->ReadDynamic() == desc.Polygons.size(); }
if (suc)
{
for (size_t a = 0; a < desc.Polygons.size() && suc; a++)
{
const Polygon& p = desc.Polygons[a];
suc = suc && ((read->ReadBits(1) == 1) == p.AutoGenerateNormal);
suc = suc && (read->ReadBits(32) == p.Material);
suc = suc && (read->ReadBits(32) == p.Point[0]);
suc = suc && (read->ReadBits(32) == p.Point[1]);
suc = suc && (read->ReadBits(32) == p.Point[2]);
}
}
if (suc)
{
for (size_t a = 0; a < desc.Vertices.size() && suc; a++)
{
const Vertex& v = desc.Vertices[a];
suc = suc && CheckVector(read, v.Position);
suc = suc && CheckVector(read, v.Normal);
suc = suc && CheckFloat(read, v.TexCoord.U);
suc = suc && CheckFloat(read, v.TexCoord.V);
for (size_t b = 0; b < 4 && suc; b++)
{
suc = suc && (read->ReadBits(32) == v.Bones[b].BoneID);
suc = suc && CheckFloat(read, v.Bones[b].Weight);
}
}
}
if (suc)
{
uint32_t bys = static_cast<uint32_t>(read->ReadBits(32));
uint8_t bis = static_cast<uint8_t>(read->ReadBits(3));
for (uint32_t a = 0; a < bys; a++) { output->WriteBits(8, read->ReadBits(8)); }
if (bis > 0) { output->WriteBits(bis, read->ReadBits(bis)); }
}
}
SAVE_RELEASE(read);
}
return !suc;
}
inline void CLOAK_CALL WriteTemp(In CloakEngine::Files::IVirtualWriteBuffer* data, In uint32_t bys, In uint8_t bis, In const EncodeDesc& encode, In const Desc& desc, In RespondeFunc response)
{
if ((encode.flags & EncodeFlags::NO_TEMP_WRITE) == EncodeFlags::NONE)
{
SendResponse(response, RespondeCode::WRITE_TMP);
CloakEngine::Files::IWriter* write = nullptr;
CREATE_INTERFACE(CE_QUERY_ARGS(&write));
write->SetTarget(encode.tempPath, g_TempFileType, CloakEngine::Files::CompressType::NONE);
Engine::TempHandler::WriteGameID(write, encode.targetGameID);
write->WriteBits(8, static_cast<uint8_t>(desc.Bounding));
write->WriteDynamic(desc.Vertices.size());
write->WriteDynamic(desc.Polygons.size());
for (size_t a = 0; a < desc.Polygons.size(); a++)
{
const Polygon& p = desc.Polygons[a];
write->WriteBits(1, p.AutoGenerateNormal ? 1 : 0);
write->WriteBits(32, p.Material);
write->WriteBits(32, p.Point[0]);
write->WriteBits(32, p.Point[1]);
write->WriteBits(32, p.Point[2]);
}
for (size_t a = 0; a < desc.Vertices.size(); a++)
{
const Vertex& v = desc.Vertices[a];
WriteVector(write, v.Position);
WriteVector(write, v.Normal);
write->WriteDouble(32, v.TexCoord.U);
write->WriteDouble(32, v.TexCoord.V);
for (size_t b = 0; b < 4; b++)
{
write->WriteBits(32, v.Bones[b].BoneID);
write->WriteDouble(32, v.Bones[b].Weight);
}
}
write->WriteBits(32, bys);
write->WriteBits(3, bis);
write->WriteBuffer(data, bys, bis);
SAVE_RELEASE(write);
}
}
inline void CLOAK_CALL WriteSingleVertex(In CloakEngine::Files::IWriter* write, In const FinalVertex& v, In bool saveBones)
{
WriteVector(write, v.Position);
WriteVector(write, v.Normal);
WriteVector(write, v.Binormal);
WriteVector(write, v.Tangent);
write->WriteDouble(32, v.TexCoord.U);
write->WriteDouble(32, v.TexCoord.V);
if (saveBones)
{
size_t bc = 0;
for (size_t a = 0; a < 4; a++)
{
if (v.Bones[a].Weight > 0)
{
bc++;
}
}
write->WriteBits(2, bc);
for (size_t a = 0; a < 4; a++)
{
if (v.Bones[a].Weight > 0)
{
write->WriteBits(32, v.Bones[a].BoneID);
write->WriteDouble(32, v.Bones[a].Weight);
}
}
}
}
#ifdef _DEBUG
inline void CLOAK_CALL __DBG_PrintVertex(In const FinalVertex& v)
{
CloakEngine::Global::Math::Point h(v.Position);
CloakDebugLog("\tPosition = [" + std::to_string(h.X) + "|" + std::to_string(h.Y) + "|" + std::to_string(h.Z) + "]");
h = static_cast<CloakEngine::Global::Math::Point>(v.Normal);
CloakDebugLog("\tNormal = [" + std::to_string(h.X) + "|" + std::to_string(h.Y) + "|" + std::to_string(h.Z) + "]");
h = static_cast<CloakEngine::Global::Math::Point>(v.Binormal);
CloakDebugLog("\tBinormal = [" + std::to_string(h.X) + "|" + std::to_string(h.Y) + "|" + std::to_string(h.Z) + "]");
h = static_cast<CloakEngine::Global::Math::Point>(v.Tangent);
CloakDebugLog("\tTangent = [" + std::to_string(h.X) + "|" + std::to_string(h.Y) + "|" + std::to_string(h.Z) + "]");
CloakDebugLog("\tTexCoord = [" + std::to_string(v.TexCoord.U) + "|" + std::to_string(v.TexCoord.V) + "]");
}
#define PrintVertex(v) __DBG_PrintVertex(v)
#else
#define PrintVertex(v)
#endif
inline void CLOAK_CALL WriteIndexVertexBuffer(In CloakEngine::Files::IWriter* write, In size_t size, In size_t boneCount, In_reads(size) const FinalVertex* vertexBuffer, In_reads(size) const CE::List<bool>& used)
{
#ifdef _DEBUG
size_t vertI = 0;
#endif
for (size_t a = 0; a < size; a++)
{
if (used[a] == true)
{
#ifdef _DEBUG
CloakDebugLog("Write vertex " + std::to_string(a) + " at index " + std::to_string(vertI));
PrintVertex(vertexBuffer[a]);
vertI++;
#endif
WriteSingleVertex(write, vertexBuffer[a], boneCount > 0);
}
}
}
inline void CLOAK_CALL WriteBoneUsage(In CloakEngine::Files::IWriter* write, In size_t begin, In size_t end, In size_t boneCount, In_reads(end) const FinalVertex* vertexBuffer)
{
if (boneCount > 0)
{
bool* usage = new bool[boneCount];
for (size_t a = 0; a < boneCount; a++) { usage[a] = false; }
for (size_t a = begin; a < end; a++)
{
const FinalVertex& v = vertexBuffer[a];
for (size_t b = 0; b < 4; b++)
{
if (v.Bones[b].Weight > 0)
{
usage[v.Bones[b].BoneID] = true;
}
}
}
for (size_t a = 0; a < boneCount; a++) { write->WriteBits(1, usage[a] ? 1 : 0); }
delete[] usage;
}
}
inline void CLOAK_CALL WriteIndexBuffer(In CloakEngine::Files::IWriter* write, In size_t ibsl, In bool shortStripCut, In size_t boneCount, In_reads(size) const FinalVertex* vertexBuffer, In_reads(size) const CE::List<size_t>& indexBuffer, In const CloakEngine::List<MaterialRange>& matRanges)
{
for (size_t a = 0, b = 0; a < indexBuffer.size() && b < matRanges.size(); b++)
{
const MaterialRange& mr = matRanges[b];
const size_t cS = min(mr.StripCount, indexBuffer.size() - a);
const size_t cL = min(mr.ListCount, indexBuffer.size() - (a + cS));
CloakDebugLog("Write material " + std::to_string(mr.MaterialID) + " (" + std::to_string(cS) + " triangle strip vertices, " + std::to_string(cL) + " triangle list vertices)");
write->WriteBits(32, cS);
write->WriteBits(32, cL);
write->WriteBits(32, mr.MaterialID);
WriteBoneUsage(write, a, a + cS + cL, boneCount, vertexBuffer);
for (size_t c = 0; c < cS; a++, c++)
{
CLOAK_ASSUME(a < indexBuffer.size());
CloakDebugLog("Write Index[" + std::to_string(a) + "]: " + (indexBuffer[a] == STRIP_CUT_VALUE ? "Strip Cut" : std::to_string(indexBuffer[a])));
if (shortStripCut == true && indexBuffer[a] == STRIP_CUT_VALUE) { write->WriteBits(ibsl, STRIP_CUT_VALUE_16); }
else { write->WriteBits(ibsl, indexBuffer[a]); }
}
for (size_t c = 0; c < cL; a++, c++)
{
CLOAK_ASSUME(a < indexBuffer.size());
CloakDebugLog("Write Index[" + std::to_string(a) + "]: " + (indexBuffer[a] == STRIP_CUT_VALUE ? "Strip Cut" : std::to_string(indexBuffer[a])));
write->WriteBits(ibsl, indexBuffer[a]);
}
}
}
inline void CLOAK_CALL WriteRawVertexBuffer(In CloakEngine::Files::IWriter* write, In size_t size, In size_t boneCount, In_reads(size) const FinalVertex* vertexBuffer)
{
size_t s = 0;
size_t lMat = 0;
for (size_t a = 0; a < size; a++, s++)
{
if (a == 0) { lMat = vertexBuffer[a].MaterialID; }
else if (lMat != vertexBuffer[a].MaterialID)
{
CloakDebugLog("Write material " + std::to_string(lMat) + " (" + std::to_string(s) + " vertices)");
write->WriteBits(32, s);
write->WriteBits(32, lMat);
WriteBoneUsage(write, a - s, a, boneCount, vertexBuffer);
for (size_t b = a - s; b < a; b++)
{
CloakDebugLog("Write vertex " + std::to_string(b));
PrintVertex(vertexBuffer[b]);
const FinalVertex& v = vertexBuffer[b];
WriteSingleVertex(write, v, boneCount > 0);
}
lMat = vertexBuffer[a].MaterialID;
s = 0;
}
}
CloakDebugLog("Write material " + std::to_string(lMat) + " (" + std::to_string(s) + " vertices)");
write->WriteBits(32, s);
write->WriteBits(32, lMat);
WriteBoneUsage(write, size - s, size, boneCount, vertexBuffer);
for (size_t b = size - s; b < size; b++)
{
CloakDebugLog("Write vertex " + std::to_string(b));
PrintVertex(vertexBuffer[b]);
const FinalVertex& v = vertexBuffer[b];
WriteSingleVertex(write, v, boneCount > 0);
}
}
CLOAKCOMPILER_API Vector::Vector()
{
X = Y = Z = W = 0;
}
CLOAKCOMPILER_API Vector::Vector(In const CloakEngine::Global::Math::Vector& v)
{
CloakEngine::Global::Math::Point p(v);
X = p.X;
Y = p.Y;
Z = p.Z;
W = p.W;
}
CLOAKCOMPILER_API Vector& Vector::operator=(In const Vector& p)
{
X = p.X;
Y = p.Y;
Z = p.Z;
W = p.W;
return *this;
}
CLOAKCOMPILER_API Vector& Vector::operator=(In const CloakEngine::Global::Math::Vector& v)
{
CloakEngine::Global::Math::Point p(v);
X = p.X;
Y = p.Y;
Z = p.Z;
W = p.W;
return *this;
}
CLOAKCOMPILER_API Vector::operator CloakEngine::Global::Math::Vector()
{
return CloakEngine::Global::Math::Vector(X, Y, Z, W);
}
CLOAKCOMPILER_API Vector::operator const CloakEngine::Global::Math::Vector() const
{
return CloakEngine::Global::Math::Vector(X, Y, Z, W);
}
CLOAKCOMPILER_API void CLOAK_CALL EncodeToFile(In CloakEngine::Files::IWriter* output, In const EncodeDesc& encode, In const Desc& desc, In std::function<void(const RespondeInfo&)> response)
{
bool suc = true;
if (CheckTemp(output, encode, desc, response))
{
CloakEngine::Files::IVirtualWriteBuffer* wrBuf = CloakEngine::Files::CreateVirtualWriteBuffer();
CloakEngine::Files::IWriter* write = nullptr;
CREATE_INTERFACE(CE_QUERY_ARGS(&write));
write->SetTarget(wrBuf);
const size_t vbs = desc.Polygons.size() * 3;
FinalVertex* vb = NewArray(FinalVertex, vbs);
size_t matCount = 0;
const size_t polS = desc.Polygons.size();
//Check polygon-vertex aviability
for (size_t a = 0; a < desc.Polygons.size() && suc == true; a++)
{
const Polygon& p = desc.Polygons[a];
for (size_t b = 0; b < 3 && suc == true; b++)
{
if (p.Point[b] >= desc.Vertices.size())
{
SendResponse(response, RespondeCode::ERROR_VERTEXREF, a, p.Point[b], "Polygon " + std::to_string(a) + " refers to vertex " + std::to_string(p.Point[b]) + " but there are only " + std::to_string(desc.Vertices.size()) + " vertices!");
suc = false;
}
}
}
if (suc == true)
{
//Write required minimum of bones in animation skeleton
SendResponse(response, RespondeCode::CALC_BONES);
size_t maxBone = 0;
for (size_t a = 0; a < desc.Vertices.size(); a++)
{
const Vertex& v = desc.Vertices[a];
for (size_t b = 0; b < 4; b++)
{
if (v.Bones[b].Weight > 0)
{
maxBone = max(maxBone, v.Bones[b].BoneID);
}
}
}
const size_t boneCount = maxBone > 0 ? maxBone + 1 : 0;
write->WriteBits(32, boneCount);
//Sort polygons by material
SendResponse(response, RespondeCode::CALC_SORT);
size_t* const sortHeap = NewArray(size_t, polS * 2);
size_t* sorted[2] = { &sortHeap[0],&sortHeap[polS] };
size_t count[16];
for (size_t a = 0; a < polS; a++) { sorted[0][a] = a; }
for (uint32_t a = 0xf, b = 0; b < 8; a <<= 4, b++)
{
for (size_t c = 0; c < 16; c++) { count[c] = 0; }
for (size_t c = 0; c < polS; c++) { count[(desc.Polygons[sorted[0][c]].Material & a) >> (4 * b)]++; }
for (size_t c = 1; c < 16; c++) { count[c] += count[c - 1]; }
for (size_t c = polS; c > 0; c--)
{
const size_t p = (desc.Polygons[sorted[0][c - 1]].Material & a) >> (4 * b);
sorted[1][count[p] - 1] = sorted[0][c - 1];
count[p]--;
}
size_t* t = sorted[0];
sorted[0] = sorted[1];
sorted[1] = t;
}
//Remap material ids to zero-based array indices
SendResponse(response, RespondeCode::CALC_MATERIALS);
uint32_t lastMat;
for (size_t a = 0, b = 0; a < polS; a++)
{
const Polygon& p = desc.Polygons[sorted[0][a]];
if (a == 0) { lastMat = p.Material; }
else if (lastMat != p.Material)
{
lastMat = p.Material;
b++;
matCount = max(matCount, b + 1);
}
}
matCount = max(1, matCount);
//Calculate binormals/tangents & copy vertex data
SendResponse(response, RespondeCode::CALC_BINORMALS);
for (size_t a = 0; a < polS; a++)
{
const Polygon& p = desc.Polygons[sorted[0][a]];
CalculatePolygonVertices(desc.Vertices[p.Point[0]], desc.Vertices[p.Point[1]], desc.Vertices[p.Point[2]], p.AutoGenerateNormal, p.Material, &vb[3 * a]);
}
if (suc == true)
{
if (boneCount == 0)
{
//Calculate bounding volume for full mesh
if (desc.Bounding != BoundingVolume::None) { SendResponse(response, RespondeCode::CALC_BOUNDING); }
const size_t posSize = desc.Vertices.size();
uint8_t* poslHeap = new uint8_t[(sizeof(CloakEngine::Global::Math::Vector)*posSize) + 15];
CloakEngine::Global::Math::Vector* posl = reinterpret_cast<CloakEngine::Global::Math::Vector*>((reinterpret_cast<uintptr_t>(poslHeap) + 15) & ~static_cast<uintptr_t>(0xF));
for (size_t a = 0; a < posSize; a++) { posl[a] = desc.Vertices[a].Position; }
switch (desc.Bounding)
{
case BoundingVolume::None:
{
write->WriteBits(2, 0);
break;
}
case BoundingVolume::OOBB:
{
Engine::BoundingVolume::BoundingOOBB bound = Engine::BoundingVolume::CalculateBoundingOOBB(posl, posSize);
if (bound.Enabled)
{
SendResponse(response, RespondeCode::WRITE_BOUNDING);
write->WriteBits(2, 1);
WriteVector(write, bound.Center);
for (size_t a = 0; a < 3; a++) { WriteVector(write, bound.Axis[a]); }
for (size_t a = 0; a < 3; a++) { write->WriteDouble(32, bound.HalfSize[a]); }
CloakEngine::Global::Math::Point cen(bound.Center);
CloakDebugLog("Bounding Box center: " + std::to_string(cen.X) + " | " + std::to_string(cen.Y) + " | " + std::to_string(cen.Z));
for (size_t a = 0; a < 3; a++)
{
CloakEngine::Global::Math::Point p(bound.Axis[a]);
CloakDebugLog("Bounding Box axis[" + std::to_string(a) + "]: " + std::to_string(p.X) + " | " + std::to_string(p.Y) + " | " + std::to_string(p.Z));
}
for (size_t a = 0; a < 3; a++)
{
CloakDebugLog("Bounding Box axis[" + std::to_string(a) + "] scale: " + std::to_string(bound.HalfSize[a]));
}
break;
}
else
{
SendResponse(response, RespondeCode::ERROR_BOUNDING, "Failed to calculate OOBB, switch to bounding-Volume: sphere");
}
//Fall through
}
case BoundingVolume::Sphere:
{
Engine::BoundingVolume::BoundingSphere bound = Engine::BoundingVolume::CalculateBoundingSphere(posl, posSize);
if (bound.Enabled)
{
SendResponse(response, RespondeCode::WRITE_BOUNDING);
write->WriteBits(2, 2);
WriteVector(write, bound.Center);
write->WriteDouble(32, bound.Radius);
CloakEngine::Global::Math::Point cen(bound.Center);
CloakDebugLog("Bounding Sphere center: " + std::to_string(cen.X) + " | " + std::to_string(cen.Y) + " | " + std::to_string(cen.Z));
CloakDebugLog("Bounding Sphere radius: " + std::to_string(bound.Radius));
break;
}
else
{
SendResponse(response, RespondeCode::ERROR_BOUNDING, "Failed to calculate bounding sphere!");
suc = false;
}
break;
}
default:
suc = false;
SendResponse(response, RespondeCode::ERROR_BOUNDING, "Unknown bounding volume type");
break;
}
delete[] poslHeap;
}
else
{
std::vector<std::vector<size_t>> boneToVertex(boneCount);
for (size_t a = 0; a < vbs; a++)
{
const FinalVertex& v = vb[a];
for (size_t b = 0; b < 4; b++)
{
if (v.Bones[b].Weight > 0)
{
boneToVertex[v.Bones[b].BoneID].push_back(a);
}
}
}
for (size_t a = 0; a < boneCount; a++)
{
if (boneToVertex[a].size() == 0) { continue; }
//TODO: per-Bone bounding volume
//TODO: Find solution to interpolated vertices (vertices between bones -> weight of one bone < 1)
SendResponse(response, RespondeCode::ERROR_BOUNDING, "Bounding volume calculation for animated objects is not yet implemented!");
suc = false;
}
}
}
if (suc == true)
{
bool useIndexBuffer = false;
if (desc.UseIndexBuffer)
{
//Calculate index buffer
SendResponse(response, RespondeCode::CALC_INDICES);
CE::List<bool> vbUsed(vbs);
CE::List<size_t> ib;
CloakEngine::List<MaterialRange> matRanges;
const IndexBufferType stripCut = CalculateIndexBuffer(vb, vbs, &ib, &vbUsed, &matRanges);
size_t finVbs = 0;
for (size_t a = 0; a < vbs; a++)
{
if (vbUsed[a] == true) { finVbs++; }
}
const size_t ibsL = stripCut == IndexBufferType::IB32 ? 4 : 2;
CloakDebugLog("IB Comparison: IB = " + std::to_string((finVbs*VertexSize) + (ib.size()*ibsL)) + " (" + std::to_string(finVbs) + " Vertices) Raw = " + std::to_string(vbs*VertexSize) + " (" + std::to_string(vbs) + " Vertices)");
//Test whether we use an index buffer at all:
if ((vbs - finVbs)*VertexSize > (ib.size()*ibsL))
{
useIndexBuffer = true;
//Write all vertices + sorted per material indices
SendResponse(response, RespondeCode::WRITE_VERTICES);
write->WriteBits(16, matRanges.size() - 1);
write->WriteBits(32, finVbs);
write->WriteBits(1, 1); //Use index buffer
write->WriteBits(1, ibsL == 2 ? 0 : 1); //16 or 32 bit index buffer size
if (ibsL == 2) { write->WriteBits(1, stripCut == IndexBufferType::IB16ShortCut ? 1 : 0); } //short strip cuts?
write->WriteBits(32, ib.size());
CloakDebugLog("Write Index + Vertex Buffer");
WriteIndexVertexBuffer(write, vbs, boneCount, vb, vbUsed);
WriteIndexBuffer(write, ibsL << 3, stripCut == IndexBufferType::IB16ShortCut, boneCount, vb, ib, matRanges);
}
}
if (useIndexBuffer == false)
{
//Write vertices, sorted and seperated by materials
SendResponse(response, RespondeCode::WRITE_VERTICES);
write->WriteBits(16, matCount - 1);
write->WriteBits(32, vbs);
write->WriteBits(1, 0);
CloakDebugLog("Write raw vertex buffer");
WriteRawVertexBuffer(write, vbs, boneCount, vb);
}
}
DeleteArray(sortHeap);
}
DeleteArray(vb);
const uint32_t bys = static_cast<uint32_t>(write->GetPosition());
const uint8_t bis = static_cast<uint8_t>(write->GetBitPosition());
write->Save();
if (suc)
{
output->WriteBuffer(wrBuf, bys, bis);
WriteTemp(wrBuf, bys, bis, encode, desc, response);
}
SAVE_RELEASE(write);
SAVE_RELEASE(wrBuf);
}
SendResponse(response, suc ? RespondeCode::FINISH_SUCCESS : RespondeCode::FINISH_ERROR);
}
}
}
} | 38.462595 | 296 | 0.575934 | Bizzarrus |
8b25b5b117dea936c9867a72fb89755fa9461ee2 | 1,870 | cc | C++ | examples/mdc2250_example.cc | GAVLab/mdc2250 | dfbdda0827d0a798f50ca4dea733a78c961062de | [
"Unlicense"
] | 1 | 2018-07-24T20:12:27.000Z | 2018-07-24T20:12:27.000Z | examples/mdc2250_example.cc | GAVLab/mdc2250 | dfbdda0827d0a798f50ca4dea733a78c961062de | [
"Unlicense"
] | null | null | null | examples/mdc2250_example.cc | GAVLab/mdc2250 | dfbdda0827d0a798f50ca4dea733a78c961062de | [
"Unlicense"
] | null | null | null | #include <iostream>
#include "mdc2250/mdc2250.h"
#include "mdc2250/decode.h"
void telemetry_callback(const std::string &telemetry) {
std::cout << "Got telemetry: " << telemetry << std::endl;
}
int run() {
mdc2250::MDC2250 my_mdc2250(true);
my_mdc2250.connect("/dev/tty.USA49Wfd122P1.1");
// Disable echo
my_mdc2250.setEcho(true);
// Disable watchdog
my_mdc2250.setWatchdog(10000);
// Setup telemetry
size_t period = 25;
my_mdc2250.setTelemetry("C,V,C,A", period, telemetry_callback);
my_mdc2250.setTelemetry("C,V,C,A", period, telemetry_callback);
// Move both motors for 4 seconds
my_mdc2250.commandMotor(1, 1000);
my_mdc2250.commandMotor(2, -1000);
boost::this_thread::sleep(boost::posix_time::milliseconds(4000));
// Stop both motors for 1 second
my_mdc2250.commandMotor(1);
my_mdc2250.commandMotor(2, 0);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
// Move both motors for 1 second, but estop (they shouldn't move)
my_mdc2250.commandMotors(-1000, 1000);
std::cout << "E-stopping!" << std::endl;
my_mdc2250.estop();
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
// Stop both motors for 1 second, and clear the estop
my_mdc2250.commandMotors();
my_mdc2250.commandMotors(0); // Same thing
my_mdc2250.clearEstop();
// Have to redo telemetry after an estop
my_mdc2250.setTelemetry("C,V,C,A", period, telemetry_callback);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
// Move both motors for 4 seconds
my_mdc2250.commandMotors(-1000, 1000);
boost::this_thread::sleep(boost::posix_time::milliseconds(4000));
// Stop both motors
my_mdc2250.commandMotors();
return 0;
}
int main(void) {
try {
return run();
} catch (std::exception &e) {
std::cerr << "Unhandled Exception: " << e.what() << std::endl;
return 1;
}
}
| 31.166667 | 67 | 0.705348 | GAVLab |
8b2633dcefee9dc0b5ad9a4b7878986a5675fb66 | 927 | cc | C++ | below2.1/busyschedule.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/busyschedule.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/busyschedule.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <utility>
using namespace std;
int main(){
int n;
while (true)
{
cin>>n;
cin.ignore(255,'\n');
if(n == 0){
break;
}
string s;
pair<string,int> arr[n];
string raw[n];
for (int i = 0; i < n; i++)
{
getline(cin,s);
raw[i] = s;
if(s.length() == 9){
s = "0"+s;
}
if(s[0] == '1' && s[1] == '2'){
s[0] = '0';
s[1] = '0';
}
string dpn = s.substr(0,5);
string blkg = s.substr(6,1);
s = blkg+dpn;
arr[i] = make_pair(s,i);
}
sort(arr,arr+n);
for (int i = 0; i < n; i++)
{
cout<<raw[arr[i].second]<<"\n";
}
cout<<'\n';
}
return 0;
} | 20.152174 | 43 | 0.332255 | danzel-py |
8b2643b2dcbd8408f37c51fda66b99addd961d6e | 3,478 | hpp | C++ | libs/core/futures/include/hpx/futures/detail/future_transforms.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 1,822 | 2015-01-03T11:22:37.000Z | 2022-03-31T14:49:59.000Z | libs/core/futures/include/hpx/futures/detail/future_transforms.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 3,288 | 2015-01-05T17:00:23.000Z | 2022-03-31T18:49:41.000Z | libs/core/futures/include/hpx/futures/detail/future_transforms.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 431 | 2015-01-07T06:22:14.000Z | 2022-03-31T14:50:04.000Z | // Copyright (c) 2017 Denis Blank
//
// SPDX-License-Identifier: BSL-1.0
// 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
#include <hpx/functional/deferred_call.hpp>
#include <hpx/futures/traits/acquire_future.hpp>
#include <hpx/futures/traits/acquire_shared_state.hpp>
#include <hpx/futures/traits/detail/future_traits.hpp>
#include <hpx/futures/traits/is_future.hpp>
#include <hpx/util/detail/reserve.hpp>
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vector>
namespace hpx { namespace lcos { namespace detail {
// Returns true when the given future is ready,
// the future is deferred executed if possible first.
template <typename T,
typename std::enable_if<traits::is_future<
typename std::decay<T>::type>::value>::type* = nullptr>
bool async_visit_future(T&& current)
{
// Check for state right away as the element might not be able to
// produce a shared state (even if it's ready).
if (current.is_ready())
{
return true;
}
auto const& state =
traits::detail::get_shared_state(std::forward<T>(current));
if (state.get() == nullptr)
{
return true;
}
// Execute_deferred might make the future ready
state->execute_deferred();
// Detach the context if the future isn't ready
return state->is_ready();
}
// Attach the continuation next to the given future
template <typename T, typename N,
typename std::enable_if<traits::is_future<
typename std::decay<T>::type>::value>::type* = nullptr>
void async_detach_future(T&& current, N&& next)
{
auto const& state =
traits::detail::get_shared_state(std::forward<T>(current));
// Attach a continuation to this future which will
// re-evaluate it and continue to the next argument (if any).
state->set_on_completed(util::deferred_call(std::forward<N>(next)));
}
// Acquire a future range from the given begin and end iterator
template <typename Iterator,
typename Container =
std::vector<typename future_iterator_traits<Iterator>::type>>
Container acquire_future_iterators(Iterator begin, Iterator end)
{
Container lazy_values;
auto difference = std::distance(begin, end);
if (difference > 0)
traits::detail::reserve_if_reservable(
lazy_values, static_cast<std::size_t>(difference));
std::transform(begin, end, std::back_inserter(lazy_values),
traits::acquire_future_disp());
return lazy_values; // Should be optimized by RVO
}
// Acquire a future range from the given
// begin iterator and count
template <typename Iterator,
typename Container =
std::vector<typename future_iterator_traits<Iterator>::type>>
Container acquire_future_n(Iterator begin, std::size_t count)
{
Container values;
traits::detail::reserve_if_reservable(values, count);
traits::acquire_future_disp func;
for (std::size_t i = 0; i != count; ++i)
values.push_back(func(*begin++));
return values; // Should be optimized by RVO
}
}}} // namespace hpx::lcos::detail
| 33.442308 | 80 | 0.648936 | Andrea-MariaDB-2 |
8b269b265fdd89139337633dad2b80e826f3aed2 | 1,461 | cc | C++ | chromium/content/browser/devtools/devtools_manager.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/content/browser/devtools/devtools_manager.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/content/browser/devtools/devtools_manager.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/devtools/devtools_manager.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
#include "content/browser/devtools/devtools_netlog_observer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
namespace content {
// static
DevToolsManager* DevToolsManager::GetInstance() {
return base::Singleton<DevToolsManager>::get();
}
DevToolsManager::DevToolsManager()
: delegate_(GetContentClient()->browser()->GetDevToolsManagerDelegate()),
attached_hosts_count_(0) {
}
DevToolsManager::~DevToolsManager() {
DCHECK(!attached_hosts_count_);
}
void DevToolsManager::AgentHostStateChanged(
DevToolsAgentHostImpl* agent_host, bool attached) {
if (attached) {
if (!attached_hosts_count_) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&DevToolsNetLogObserver::Attach));
}
++attached_hosts_count_;
} else {
--attached_hosts_count_;
if (!attached_hosts_count_) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&DevToolsNetLogObserver::Detach));
}
}
}
} // namespace content
| 28.096154 | 77 | 0.721424 | wedataintelligence |
8b29b1ce9bcceb73f0e8bd0d279e333787967fe9 | 1,696 | cc | C++ | src/lib/TileSet.cc | jube/libtmx | 495d94ddb11d10b3dd2e7707b2c57916675a9f2b | [
"0BSD"
] | 5 | 2015-04-29T14:05:30.000Z | 2021-03-26T19:27:13.000Z | src/lib/TileSet.cc | jube/libtmx | 495d94ddb11d10b3dd2e7707b2c57916675a9f2b | [
"0BSD"
] | 1 | 2015-03-24T08:57:28.000Z | 2015-03-24T08:57:28.000Z | src/lib/TileSet.cc | jube/libtmx | 495d94ddb11d10b3dd2e7707b2c57916675a9f2b | [
"0BSD"
] | 4 | 2015-03-23T23:42:37.000Z | 2020-07-09T08:23:13.000Z | /*
* Copyright (c) 2013-2014, Julien Bernard
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <tmx/TileSet.h>
namespace tmx {
const Tile *TileSet::getTile(unsigned id) const noexcept {
for (auto tile : *this) {
if (tile->getId() == id) {
return tile;
}
}
return nullptr;
}
Rect TileSet::getCoords(unsigned id, Size size) const noexcept {
unsigned width = (size.width - 2 * m_margin + m_spacing) / (m_tilewidth + m_spacing); // number of tiles
unsigned height = (size.height - 2 * m_margin + m_spacing) / (m_tileheight + m_spacing); // number of tiles
unsigned tu = id % width;
unsigned tv = id / width;
assert(tv < height);
unsigned du = m_margin + tu * m_spacing + m_x;
unsigned dv = m_margin + tv * m_spacing + m_y;
assert((tu + 1) * m_tilewidth + du <= size.width);
assert((tv + 1) * m_tileheight + dv <= size.height);
return { tu * m_tilewidth + du, tv * m_tileheight + dv, m_tilewidth, m_tileheight };
}
}
| 36.085106 | 111 | 0.685142 | jube |
8b29f915938cd201b214ed8f2c2c872c9525dd05 | 4,619 | cpp | C++ | src/is_slam/src/slam_odom.cpp | chenjianqu/is_slam | 519664c1c32d53119d5e3b36f5acc06e338495fb | [
"MIT"
] | 2 | 2021-12-29T12:35:04.000Z | 2021-12-30T09:10:54.000Z | src/is_slam/src/slam_odom.cpp | chenjianqu/is_slam | 519664c1c32d53119d5e3b36f5acc06e338495fb | [
"MIT"
] | null | null | null | src/is_slam/src/slam_odom.cpp | chenjianqu/is_slam | 519664c1c32d53119d5e3b36f5acc06e338495fb | [
"MIT"
] | null | null | null | /*******************************************************
* Copyright (C) 2022, Chen Jianqu, Shanghai University
*
* This file is part of is_slam.
*
* Licensed under the MIT License;
* you may not use this file except in compliance with the License.
*******************************************************/
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <chrono>
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <tf/transform_broadcaster.h>
#include <tf_conversions/tf_eigen.h>
#include <std_msgs/Time.h>
#include <opencv2/core/core.hpp>
#include <opencv2/core/eigen.hpp>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <Eigen/Dense>
#include"System.h"
using namespace std;
class ImageGrabber
{
public:
ImageGrabber(ORB_SLAM2::System* pSLAM);
void GrabRGBD(const sensor_msgs::ImageConstPtr& msgRGB,const sensor_msgs::ImageConstPtr& msgD);
void SetPublisher(image_transport::Publisher* pub_rgb_,image_transport::Publisher* pub_depth_);
protected:
ORB_SLAM2::System* mpSLAM;
tf::TransformBroadcaster* br;
image_transport::Publisher* pub_rgb;
image_transport::Publisher* pub_depth;
unsigned long counter;
void MatToTransform(cv::Mat &Tcw,tf::Transform &m);
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "orb_slam_node");//初始化节点
ros::start();//启动节点
if(argc != 3)
{
cout<<"需要传入参数:视觉词典路径 配置文件路径" << endl;
ros::shutdown();//关闭节点
return 1;
}
//初始化ORB-SLAM2
ORB_SLAM2::System SLAM(argv[1],argv[2],ORB_SLAM2::System::RGBD,true);
ImageGrabber igb(&SLAM);
ros::NodeHandle nh;
//接受RGB图和深度图
message_filters::Subscriber<sensor_msgs::Image> rgb_sub(nh, "/camera/rgb/image_raw", 1);
message_filters::Subscriber<sensor_msgs::Image> depth_sub(nh, "/camera/depth_registered/image_raw", 1);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image> sync_pol;
message_filters::Synchronizer<sync_pol> sync(sync_pol(10), rgb_sub,depth_sub);
sync.registerCallback(boost::bind(&ImageGrabber::GrabRGBD,&igb,_1,_2));
image_transport::ImageTransport it(nh);
image_transport::Publisher pub_rgb = it.advertise("/orbslam2/rgb", 1);
image_transport::Publisher pub_depth = it.advertise("/orbslam2/depth", 1);
igb.SetPublisher(&pub_rgb,&pub_depth);
ros::spin();
SLAM.Shutdown();
SLAM.SaveKeyFrameTrajectoryTUM("KeyFrameTrajectory.txt");
ros::shutdown();
return 0;
}
ImageGrabber::ImageGrabber(ORB_SLAM2::System* pSLAM):
mpSLAM(pSLAM),
counter(0)
{
br=new tf::TransformBroadcaster();
}
void ImageGrabber::SetPublisher(image_transport::Publisher* pub_rgb_,image_transport::Publisher* pub_depth_)
{
pub_rgb=pub_rgb_;
pub_depth=pub_depth_;
}
void ImageGrabber::MatToTransform(cv::Mat &Tcw,tf::Transform &m)
{
//设置平移
m.setOrigin(
tf::Vector3(
Tcw.at<float>(0,3),
Tcw.at<float>(1,3),
Tcw.at<float>(2,3)
)
);
//设置旋转
tf::Matrix3x3 Rcw;
Rcw.setValue( //Mat转换为Matrix
Tcw.at<float>(0,0),Tcw.at<float>(0,1),Tcw.at<float>(0,2),
Tcw.at<float>(1,0),Tcw.at<float>(1,1),Tcw.at<float>(1,2),
Tcw.at<float>(2,0),Tcw.at<float>(2,1),Tcw.at<float>(2,2)
);
tf::Quaternion q;
Rcw.getRotation(q);
m.setRotation(q);
}
void ImageGrabber::GrabRGBD(const sensor_msgs::ImageConstPtr& msgRGB,const sensor_msgs::ImageConstPtr& msgD)
{
ros::Time timestamp= msgRGB->header.stamp;
// Copy the ros image message to cv::Mat.
cv_bridge::CvImageConstPtr cv_ptrRGB;
try{
cv_ptrRGB = cv_bridge::toCvShare(msgRGB);
}
catch (cv_bridge::Exception& e){
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv_bridge::CvImageConstPtr cv_ptrD;
try{
cv_ptrD = cv_bridge::toCvShare(msgD);
}
catch (cv_bridge::Exception& e){
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
//调用ORB-SLAM2
cv::Mat Tcw=mpSLAM->TrackRGBD(cv_ptrRGB->image,cv_ptrD->image,cv_ptrRGB->header.stamp.toSec());
//如果不是关键帧,就退出吧
if(!mpSLAM->GetIsKeyFrame())
return;
tf::Transform m;
MatToTransform(Tcw,m);
//发布rgb和深度图
pub_rgb->publish(msgRGB);
pub_depth->publish(msgD);
//cout<<"RGB Time:"<<msgRGB->header.stamp<<endl;
//cout<<"Depth Time:"<<msgD->header.stamp<<endl;
//cout<<Tcw<<endl<<endl;
//发布坐标
br->sendTransform(tf::StampedTransform(m, timestamp, "world", "orb_slam2"));
counter++;
cout<<"发布关键帧序号:"<<counter<<endl;
}
| 25.103261 | 109 | 0.688461 | chenjianqu |
8b2a3bbb1bbd584e4ad0a7ebba277153f87c69d4 | 31,921 | cc | C++ | hoomd/hpmc/UpdaterBoxMC.cc | USF-GT-Molecular-Modeling/hoomd-blue | 2ba2f9e60b0320746d21aa8219bfc9df119c053f | [
"BSD-3-Clause"
] | null | null | null | hoomd/hpmc/UpdaterBoxMC.cc | USF-GT-Molecular-Modeling/hoomd-blue | 2ba2f9e60b0320746d21aa8219bfc9df119c053f | [
"BSD-3-Clause"
] | null | null | null | hoomd/hpmc/UpdaterBoxMC.cc | USF-GT-Molecular-Modeling/hoomd-blue | 2ba2f9e60b0320746d21aa8219bfc9df119c053f | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009-2022 The Regents of the University of Michigan.
// Part of HOOMD-blue, released under the BSD 3-Clause License.
#include "UpdaterBoxMC.h"
#include "hoomd/RNGIdentifiers.h"
#include <numeric>
#include <vector>
/*! \file UpdaterBoxMC.cc
\brief Definition of UpdaterBoxMC
*/
namespace hoomd
{
namespace hpmc
{
UpdaterBoxMC::UpdaterBoxMC(std::shared_ptr<SystemDefinition> sysdef,
std::shared_ptr<Trigger> trigger,
std::shared_ptr<IntegratorHPMC> mc,
std::shared_ptr<Variant> P)
: Updater(sysdef, trigger), m_mc(mc), m_beta_P(P), m_volume_delta(0.0), m_volume_weight(0.0),
m_ln_volume_delta(0.0), m_ln_volume_weight(0.0), m_volume_mode("standard"), m_volume_A1(0.0),
m_volume_A2(0.0), m_length_delta {0.0, 0.0, 0.0},
m_length_weight(0.0), m_shear_delta {0.0, 0.0, 0.0}, m_shear_weight(0.0), m_shear_reduce(0.0),
m_aspect_delta(0.0), m_aspect_weight(0.0)
{
m_exec_conf->msg->notice(5) << "Constructing UpdaterBoxMC" << std::endl;
// initialize stats
resetStats();
// allocate memory for m_pos_backup
unsigned int MaxN = m_pdata->getMaxN();
GPUArray<Scalar4>(MaxN, m_exec_conf).swap(m_pos_backup);
// Connect to the MaxParticleNumberChange signal
m_pdata->getMaxParticleNumberChangeSignal()
.connect<UpdaterBoxMC, &UpdaterBoxMC::slotMaxNChange>(this);
updateChangedWeights();
}
UpdaterBoxMC::~UpdaterBoxMC()
{
m_exec_conf->msg->notice(5) << "Destroying UpdaterBoxMC" << std::endl;
m_pdata->getMaxParticleNumberChangeSignal()
.disconnect<UpdaterBoxMC, &UpdaterBoxMC::slotMaxNChange>(this);
}
/*! Determine if box exceeds a shearing threshold and needs to be lattice reduced.
The maximum amount of shear to allow is somewhat arbitrary, but must be > 0.5. Small values mean
the box is reconstructed more often, making it more confusing to track particle diffusion. Larger
shear values mean parallel box planes can get closer together, reducing the number of cells
possible in the cell list or increasing the number of images that must be checked for small
boxes.
Box is oversheared in direction \f$ \hat{e}_i \f$ if
\f$ \bar{e}_j \cdot \hat{e}_i >= reduce * \left| \bar{e}_i \right| \f$
or
\f$ \bar{e}_j \cdot \bar{e}_i >= reduce * \left| \bar{e}_i \right| ^2 \f$
\f$ = reduce * \bar{e}_i \cdot \bar{e}_i \f$
\returns bool true if box is overly sheared
*/
inline bool UpdaterBoxMC::is_oversheared()
{
if (m_shear_reduce <= 0.5)
return false;
const BoxDim curBox = m_pdata->getGlobalBox();
const Scalar3 x = curBox.getLatticeVector(0);
const Scalar3 y = curBox.getLatticeVector(1);
const Scalar3 z = curBox.getLatticeVector(2);
const Scalar y_x = y.x; // x component of y vector
const Scalar max_y_x = x.x * m_shear_reduce;
const Scalar z_x = z.x; // x component of z vector
const Scalar max_z_x = x.x * m_shear_reduce;
// z_y \left| y \right|
const Scalar z_yy = dot(z, y);
// MAX_SHEAR * left| y \right| ^2
const Scalar max_z_y_2 = dot(y, y) * m_shear_reduce;
if (fabs(y_x) > max_y_x || fabs(z_x) > max_z_x || fabs(z_yy) > max_z_y_2)
return true;
else
return false;
}
/*! Perform lattice reduction.
Remove excessive box shearing by finding a more cubic degenerate lattice
when shearing is more half a lattice vector from cubic. The lattice reduction could make data
needlessly complicated and may break detailed balance, use judiciously.
\returns true if overshear was removed
*/
inline bool UpdaterBoxMC::remove_overshear()
{
bool overshear = false; // initialize return value
const Scalar MAX_SHEAR = Scalar(0.5f); // lattice can be reduced if shearing exceeds this value
BoxDim newBox = m_pdata->getGlobalBox();
Scalar3 x = newBox.getLatticeVector(0);
Scalar3 y = newBox.getLatticeVector(1);
Scalar3 z = newBox.getLatticeVector(2);
Scalar xy = newBox.getTiltFactorXY();
Scalar xz = newBox.getTiltFactorXZ();
Scalar yz = newBox.getTiltFactorYZ();
// Remove one lattice vector of shear if necessary. Only apply once so image doesn't change more
// than one.
const Scalar y_x = y.x; // x component of y vector
const Scalar max_y_x = x.x * MAX_SHEAR;
if (y_x > max_y_x)
{
// Ly * xy_new = Ly * xy_old + sign*Lx --> xy_new = xy_old + sign*Lx/Ly
xy -= x.x / y.y;
y.x = xy * y.y;
overshear = true;
}
if (y_x < -max_y_x)
{
xy += x.x / y.y;
y.x = xy * y.y;
overshear = true;
}
const Scalar z_x = z.x; // x component of z vector
const Scalar max_z_x = x.x * MAX_SHEAR;
if (z_x > max_z_x)
{
// Lz * xz_new = Lz * xz_old + sign*Lx --> xz_new = xz_old + sign*Lx/Lz
xz -= x.x / z.z;
z.x = xz * z.z;
overshear = true;
}
if (z_x < -max_z_x)
{
// Lz * xz_new = Lz * xz_old + sign*Lx --> xz_new = xz_old + sign*Lx/Lz
xz += x.x / z.z;
z.x = xz * z.z;
overshear = true;
}
// z_y \left| y \right|
const Scalar z_yy = dot(z, y);
// MAX_SHEAR * left| y \right| ^2
const Scalar max_z_y_2 = dot(y, y) * MAX_SHEAR;
if (z_yy > max_z_y_2)
{
// Lz * xz_new = Lz * xz_old + sign * y.x --> xz_new = = xz_old + sign * y.x / Lz
xz -= y.x / z.z;
// Lz * yz_new = Lz * yz_old + sign * y.y --> yz_new = yz_old + sign y.y /Lz
yz -= y.y / z.z;
overshear = true;
}
if (z_yy < -max_z_y_2)
{
// Lz * xz_new = Lz * xz_old + sign * y.x --> xz_new = = xz_old + sign * y.x / Lz
xz += y.x / z.z;
// Lz * yz_new = Lz * yz_old + sign * y.y --> yz_new = yz_old + sign y.y /Lz
yz += y.y / z.z;
overshear = true;
}
if (overshear)
{
newBox.setTiltFactors(xy, xz, yz);
m_pdata->setGlobalBox(newBox);
// Use lexical scope to make sure ArrayHandles get cleaned up
{
// Get particle positions and images
ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
access_location::host,
access_mode::readwrite);
ArrayHandle<int3> h_image(m_pdata->getImages(),
access_location::host,
access_mode::readwrite);
unsigned int N = m_pdata->getN();
// move the particles to be inside the new box
for (unsigned int i = 0; i < N; i++)
{
Scalar4 pos = h_pos.data[i];
int3 image = h_image.data[i];
newBox.wrap(pos, image);
h_pos.data[i] = pos;
h_image.data[i] = image;
}
} // end lexical scope
// To get particles into the right domain in MPI, we will store and then reload a snapshot
SnapshotParticleData<Scalar> snap;
m_pdata->takeSnapshot(snap);
// loading from snapshot will load particles into the proper MPI domain
m_pdata->initializeFromSnapshot(snap);
// we've moved the particles, communicate those changes
m_mc->communicate(true);
}
return overshear;
}
//! Try new box with particle positions scaled from previous box.
/*! If new box generates overlaps, restore original box and particle positions.
\param Lx new Lx value
\param Ly new Ly value
\param Lz new Lz value
\param xy new xy value
\param xz new xz value
\param yz new yz value
\param timestep current simulation step
\returns bool True if box resize was accepted
If box is excessively sheared, subtract lattice vectors to make box more cubic.
*/
inline bool UpdaterBoxMC::box_resize_trial(Scalar Lx,
Scalar Ly,
Scalar Lz,
Scalar xy,
Scalar xz,
Scalar yz,
uint64_t timestep,
Scalar deltaE,
hoomd::RandomGenerator& rng)
{
// Make a backup copy of position data
unsigned int N_backup = m_pdata->getN();
{
ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
access_location::host,
access_mode::read);
ArrayHandle<Scalar4> h_pos_backup(m_pos_backup,
access_location::host,
access_mode::overwrite);
memcpy(h_pos_backup.data, h_pos.data, sizeof(Scalar4) * N_backup);
}
BoxDim curBox = m_pdata->getGlobalBox();
if (m_mc->getPatchEnergy())
{
// energy of old configuration
deltaE -= m_mc->computePatchEnergy(timestep);
}
// Attempt box resize and check for overlaps
BoxDim newBox = m_pdata->getGlobalBox();
newBox.setL(make_scalar3(Lx, Ly, Lz));
newBox.setTiltFactors(xy, xz, yz);
bool allowed = m_mc->attemptBoxResize(timestep, newBox);
if (allowed && m_mc->getPatchEnergy())
{
deltaE += m_mc->computePatchEnergy(timestep);
}
if (allowed && m_mc->getExternalField())
{
ArrayHandle<Scalar4> h_pos_backup(m_pos_backup,
access_location::host,
access_mode::readwrite);
Scalar ext_energy
= m_mc->getExternalField()->calculateDeltaE(timestep, h_pos_backup.data, NULL, curBox);
// The exponential is a very fast function and we may do better to add pseudo-Hamiltonians
// and exponentiate only once...
deltaE += ext_energy;
}
double p = hoomd::detail::generate_canonical<double>(rng);
if (allowed && p < fast::exp(-deltaE))
{
return true;
}
else
{
// Restore original box and particle positions
{
ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
access_location::host,
access_mode::readwrite);
ArrayHandle<Scalar4> h_pos_backup(m_pos_backup,
access_location::host,
access_mode::read);
unsigned int N = m_pdata->getN();
if (N != N_backup)
{
this->m_exec_conf->msg->error()
<< "update.boxmc"
<< ": Number of particles mismatch when rejecting box resize" << std::endl;
throw std::runtime_error("Error resizing box");
// note, this error should never appear (because particles are not migrated after a
// box resize), but is left here as a sanity check
}
memcpy(h_pos.data, h_pos_backup.data, sizeof(Scalar4) * N);
}
m_pdata->setGlobalBox(curBox);
// we have moved particles, communicate those changes
m_mc->communicate(false);
return false;
}
}
inline bool UpdaterBoxMC::safe_box(const Scalar newL[3], const unsigned int& Ndim)
{
// Scalar min_allowed_size = m_mc->getMaxTransMoveSize(); // This is dealt with elsewhere
const Scalar min_allowed_size(0.0); // volume must be kept positive
for (unsigned int j = 0; j < Ndim; j++)
{
if ((newL[j]) < min_allowed_size)
{
// volume must be kept positive
m_exec_conf->msg->notice(10)
<< "Box unsafe because dimension " << j << " would be negative." << std::endl;
return false;
}
}
return true;
}
/*! Perform Metropolis Monte Carlo box resizes and shearing
\param timestep Current time step of the simulation
*/
void UpdaterBoxMC::update(uint64_t timestep)
{
Updater::update(timestep);
m_count_step_start = m_count_total;
m_exec_conf->msg->notice(10) << "UpdaterBoxMC: " << timestep << std::endl;
// Create a prng instance for this timestep
hoomd::RandomGenerator rng(
hoomd::Seed(hoomd::RNGIdentifier::UpdaterBoxMC, timestep, m_sysdef->getSeed()),
hoomd::Counter(m_instance));
// Choose a move type
auto const weight_total = m_weight_partial_sums.back();
if (weight_total == 0.0)
{
// Attempt to execute with all move weights equal to zero.
m_exec_conf->msg->warning()
<< "No move types with non-zero weight. UpdaterBoxMC has nothing to do." << std::endl;
return;
}
// Generate a number between (0, weight_total]
auto const selected = hoomd::detail::generate_canonical<Scalar>(rng) * weight_total;
// Select the first move type whose partial sum of weights is greater than
// or equal to the generated value.
auto const move_type_select = std::distance(
m_weight_partial_sums.cbegin(),
std::lower_bound(m_weight_partial_sums.cbegin(), m_weight_partial_sums.cend(), selected));
// Attempt and evaluate a move
// This section will need to be updated when move types are added.
if (move_type_select == 0)
{
// Isotropic volume change
m_exec_conf->msg->notice(8) << "Volume move performed at step " << timestep << std::endl;
update_V(timestep, rng);
}
else if (move_type_select == 1)
{
// Isotropic volume change in logarithmic steps
m_exec_conf->msg->notice(8) << "lnV move performed at step " << timestep << std::endl;
update_lnV(timestep, rng);
}
else if (move_type_select == 2)
{
// Volume change in distribution of box lengths
m_exec_conf->msg->notice(8)
<< "Box length move performed at step " << timestep << std::endl;
update_L(timestep, rng);
}
else if (move_type_select == 3)
{
// Shear change
m_exec_conf->msg->notice(8) << "Box shear move performed at step " << timestep << std::endl;
update_shear(timestep, rng);
}
else if (move_type_select == 4)
{
// Volume conserving aspect change
m_exec_conf->msg->notice(8)
<< "Box aspect move performed at step " << timestep << std::endl;
update_aspect(timestep, rng);
}
else
{
// Should not reach this point
m_exec_conf->msg->warning()
<< "UpdaterBoxMC selected an unassigned move type. Selected " << move_type_select
<< " from range " << weight_total << std::endl;
return;
}
if (is_oversheared())
{
while (remove_overshear()) { }; // lattice reduction, possibly in several steps
m_exec_conf->msg->notice(5)
<< "Lattice reduction performed at step " << timestep << std::endl;
}
}
void UpdaterBoxMC::update_L(uint64_t timestep, hoomd::RandomGenerator& rng)
{
// Get updater parameters for current timestep
Scalar P = (*m_beta_P)(timestep);
// Get current particle data and box lattice parameters
assert(m_pdata);
unsigned int Ndim = m_sysdef->getNDimensions();
unsigned int Nglobal = m_pdata->getNGlobal();
BoxDim curBox = m_pdata->getGlobalBox();
Scalar curL[3];
Scalar newL[3]; // Lx, Ly, Lz
newL[0] = curL[0] = curBox.getLatticeVector(0).x;
newL[1] = curL[1] = curBox.getLatticeVector(1).y;
newL[2] = curL[2] = curBox.getLatticeVector(2).z;
Scalar newShear[3]; // xy, xz, yz
newShear[0] = curBox.getTiltFactorXY();
newShear[1] = curBox.getTiltFactorXZ();
newShear[2] = curBox.getTiltFactorYZ();
// Volume change
// Choose a lattice vector if non-isotropic volume changes
unsigned int nonzero_dim = 0;
for (unsigned int i = 0; i < Ndim; ++i)
if (m_length_delta[i] != 0.0)
nonzero_dim++;
if (nonzero_dim == 0)
{
// all dimensions have delta==0, just count as accepted and return
m_count_total.volume_accept_count++;
return;
}
unsigned int chosen_nonzero_dim = hoomd::UniformIntDistribution(nonzero_dim - 1)(rng);
unsigned int nonzero_dim_count = 0;
unsigned int i = 0;
for (unsigned int j = 0; j < Ndim; ++j)
{
if (m_length_delta[j] != 0.0)
{
if (nonzero_dim_count == chosen_nonzero_dim)
{
i = j;
break;
}
++nonzero_dim_count;
}
}
Scalar dL_max(m_length_delta[i]);
// Choose a length change
Scalar dL = hoomd::UniformDistribution<Scalar>(-dL_max, dL_max)(rng);
// perform volume change by applying a delta to one dimension
newL[i] += dL;
if (!safe_box(newL, Ndim))
{
m_count_total.volume_reject_count++;
}
else
{
// Calculate volume change for 2 or 3 dimensions.
double Vold, dV, Vnew;
Vold = curL[0] * curL[1];
if (Ndim == 3)
Vold *= curL[2];
Vnew = newL[0] * newL[1];
if (Ndim == 3)
Vnew *= newL[2];
dV = Vnew - Vold;
// Calculate Boltzmann factor
double dBetaH = P * dV - Nglobal * log(Vnew / Vold);
// attempt box change
bool accept = box_resize_trial(newL[0],
newL[1],
newL[2],
newShear[0],
newShear[1],
newShear[2],
timestep,
dBetaH,
rng);
if (accept)
{
m_count_total.volume_accept_count++;
}
else
{
m_count_total.volume_reject_count++;
}
}
}
//! Update the box volume in logarithmic steps
void UpdaterBoxMC::update_lnV(uint64_t timestep, hoomd::RandomGenerator& rng)
{
// Get updater parameters for current timestep
Scalar P = (*m_beta_P)(timestep);
// Get current particle data and box lattice parameters
assert(m_pdata);
unsigned int Ndim = m_sysdef->getNDimensions();
unsigned int Nglobal = m_pdata->getNGlobal();
BoxDim curBox = m_pdata->getGlobalBox();
Scalar curL[3];
Scalar newL[3]; // Lx, Ly, Lz
newL[0] = curL[0] = curBox.getLatticeVector(0).x;
newL[1] = curL[1] = curBox.getLatticeVector(1).y;
newL[2] = curL[2] = curBox.getLatticeVector(2).z;
Scalar newShear[3]; // xy, xz, yz
newShear[0] = curBox.getTiltFactorXY();
newShear[1] = curBox.getTiltFactorXZ();
newShear[2] = curBox.getTiltFactorYZ();
// original volume
double V = curL[0] * curL[1];
if (Ndim == 3)
{
V *= curL[2];
}
// Aspect ratios
Scalar A1 = m_volume_A1;
Scalar A2 = m_volume_A2;
// Volume change
Scalar dlnV_max(m_ln_volume_delta);
// Choose a volume change
Scalar dlnV = hoomd::UniformDistribution<Scalar>(-dlnV_max, dlnV_max)(rng);
Scalar new_V = V * exp(dlnV);
// perform isotropic volume change
if (Ndim == 3)
{
newL[0] = pow(A1 * A2 * new_V, (1. / 3.));
newL[1] = newL[0] / A1;
newL[2] = newL[0] / A2;
}
else // Ndim ==2
{
newL[0] = pow(A1 * new_V, (1. / 2.));
newL[1] = newL[0] / A1;
// newL[2] is already assigned to curL[2]
}
if (!safe_box(newL, Ndim))
{
m_count_total.ln_volume_reject_count++;
}
else
{
// Calculate Boltzmann factor
double dBetaH = P * (new_V - V) - (Nglobal + 1) * log(new_V / V);
// attempt box change
bool accept = box_resize_trial(newL[0],
newL[1],
newL[2],
newShear[0],
newShear[1],
newShear[2],
timestep,
dBetaH,
rng);
if (accept)
{
m_count_total.ln_volume_accept_count++;
}
else
{
m_count_total.ln_volume_reject_count++;
}
}
}
void UpdaterBoxMC::update_V(uint64_t timestep, hoomd::RandomGenerator& rng)
{
// Get updater parameters for current timestep
Scalar P = (*m_beta_P)(timestep);
// Get current particle data and box lattice parameters
assert(m_pdata);
unsigned int Ndim = m_sysdef->getNDimensions();
unsigned int Nglobal = m_pdata->getNGlobal();
BoxDim curBox = m_pdata->getGlobalBox();
Scalar curL[3];
Scalar newL[3]; // Lx, Ly, Lz
newL[0] = curL[0] = curBox.getLatticeVector(0).x;
newL[1] = curL[1] = curBox.getLatticeVector(1).y;
newL[2] = curL[2] = curBox.getLatticeVector(2).z;
Scalar newShear[3]; // xy, xz, yz
newShear[0] = curBox.getTiltFactorXY();
newShear[1] = curBox.getTiltFactorXZ();
newShear[2] = curBox.getTiltFactorYZ();
// original volume
double V = curL[0] * curL[1];
if (Ndim == 3)
{
V *= curL[2];
}
// Aspect ratios
Scalar A1 = m_volume_A1;
Scalar A2 = m_volume_A2;
// Volume change
Scalar dV_max(m_volume_delta);
// Choose a volume change
Scalar dV = hoomd::UniformDistribution<Scalar>(-dV_max, dV_max)(rng);
// perform isotropic volume change
if (Ndim == 3)
{
newL[0] = pow((A1 * A2 * (V + dV)), (1. / 3.));
newL[1] = newL[0] / A1;
newL[2] = newL[0] / A2;
}
else // Ndim ==2
{
newL[0] = pow((A1 * (V + dV)), (1. / 2.));
newL[1] = newL[0] / A1;
// newL[2] is already assigned to curL[2]
}
if (!safe_box(newL, Ndim))
{
m_count_total.volume_reject_count++;
}
else
{
// Calculate new volume
double Vnew = newL[0] * newL[1];
if (Ndim == 3)
{
Vnew *= newL[2];
}
// Calculate Boltzmann factor
double dBetaH = P * dV - Nglobal * log(Vnew / V);
// attempt box change
bool accept = box_resize_trial(newL[0],
newL[1],
newL[2],
newShear[0],
newShear[1],
newShear[2],
timestep,
dBetaH,
rng);
if (accept)
{
m_count_total.volume_accept_count++;
}
else
{
m_count_total.volume_reject_count++;
}
}
}
void UpdaterBoxMC::update_shear(uint64_t timestep, hoomd::RandomGenerator& rng)
{
// Get updater parameters for current timestep
// Get current particle data and box lattice parameters
assert(m_pdata);
unsigned int Ndim = m_sysdef->getNDimensions();
// unsigned int Nglobal = m_pdata->getNGlobal();
BoxDim curBox = m_pdata->getGlobalBox();
Scalar curL[3];
Scalar newL[3]; // Lx, Ly, Lz
newL[0] = curL[0] = curBox.getLatticeVector(0).x;
newL[1] = curL[1] = curBox.getLatticeVector(1).y;
newL[2] = curL[2] = curBox.getLatticeVector(2).z;
Scalar newShear[3]; // xy, xz, yz
newShear[0] = curBox.getTiltFactorXY();
newShear[1] = curBox.getTiltFactorXZ();
newShear[2] = curBox.getTiltFactorYZ();
Scalar dA, dA_max;
// Choose a tilt factor and randomly perturb it
unsigned int i(0);
if (Ndim == 3)
{
i = hoomd::UniformIntDistribution(2)(rng);
}
dA_max = m_shear_delta[i];
dA = hoomd::UniformDistribution<Scalar>(-dA_max, dA_max)(rng);
newShear[i] += dA;
// Attempt box resize
bool trial_success = box_resize_trial(newL[0],
newL[1],
newL[2],
newShear[0],
newShear[1],
newShear[2],
timestep,
Scalar(0.0),
rng);
if (trial_success)
{
m_count_total.shear_accept_count++;
}
else
{
m_count_total.shear_reject_count++;
}
}
void UpdaterBoxMC::update_aspect(uint64_t timestep, hoomd::RandomGenerator& rng)
{
// We have not established what ensemble this samples:
// This is not a thermodynamic updater.
// There is also room for improvement in enforcing volume conservation.
// Get updater parameters for current timestep
// Get current particle data and box lattice parameters
assert(m_pdata);
unsigned int Ndim = m_sysdef->getNDimensions();
// unsigned int Nglobal = m_pdata->getNGlobal();
BoxDim curBox = m_pdata->getGlobalBox();
Scalar curL[3];
Scalar newL[3]; // Lx, Ly, Lz
newL[0] = curL[0] = curBox.getLatticeVector(0).x;
newL[1] = curL[1] = curBox.getLatticeVector(1).y;
newL[2] = curL[2] = curBox.getLatticeVector(2).z;
Scalar newShear[3]; // xy, xz, yz
newShear[0] = curBox.getTiltFactorXY();
newShear[1] = curBox.getTiltFactorXZ();
newShear[2] = curBox.getTiltFactorYZ();
// Choose an aspect ratio and randomly perturb it
unsigned int i = hoomd::UniformIntDistribution(Ndim - 1)(rng);
Scalar dA = Scalar(1.0) + hoomd::UniformDistribution<Scalar>(Scalar(0.0), m_aspect_delta)(rng);
if (hoomd::UniformIntDistribution(1)(rng))
{
dA = Scalar(1.0) / dA;
}
newL[i] *= dA;
Scalar lambda = curL[i] / newL[i];
if (Ndim == 3)
{
lambda = sqrt(lambda);
}
for (unsigned int j = 0; j < Ndim; j++)
{
if (i != j)
{
newL[j] = lambda * curL[j];
}
}
// Attempt box resize
bool trial_success = box_resize_trial(newL[0],
newL[1],
newL[2],
newShear[0],
newShear[1],
newShear[2],
timestep,
Scalar(0.0),
rng);
if (trial_success)
{
m_count_total.aspect_accept_count++;
}
else
{
m_count_total.aspect_reject_count++;
}
}
/*! \param mode 0 -> Absolute count, 1 -> relative to the start of the run, 2 -> relative to the
last executed step \return The current state of the acceptance counters
UpdaterBoxMC maintains a count of the number of accepted and rejected moves since instantiation.
getCounters() provides the current value. The parameter *mode* controls whether the returned
counts are absolute, relative to the start of the run, or relative to the start of the last
executed step.
*/
hpmc_boxmc_counters_t UpdaterBoxMC::getCounters(unsigned int mode)
{
hpmc_boxmc_counters_t result;
if (mode == 0)
result = m_count_total;
else if (mode == 1)
result = m_count_total - m_count_run_start;
else
result = m_count_total - m_count_step_start;
// don't MPI_AllReduce counters because all ranks count the same thing
return result;
}
namespace detail
{
void export_UpdaterBoxMC(pybind11::module& m)
{
pybind11::class_<UpdaterBoxMC, Updater, std::shared_ptr<UpdaterBoxMC>>(m, "UpdaterBoxMC")
.def(pybind11::init<std::shared_ptr<SystemDefinition>,
std::shared_ptr<Trigger>,
std::shared_ptr<IntegratorHPMC>,
std::shared_ptr<Variant>>())
.def_property("volume", &UpdaterBoxMC::getVolumeParams, &UpdaterBoxMC::setVolumeParams)
.def_property("length", &UpdaterBoxMC::getLengthParams, &UpdaterBoxMC::setLengthParams)
.def_property("shear", &UpdaterBoxMC::getShearParams, &UpdaterBoxMC::setShearParams)
.def_property("aspect", &UpdaterBoxMC::getAspectParams, &UpdaterBoxMC::setAspectParams)
.def_property("betaP", &UpdaterBoxMC::getBetaP, &UpdaterBoxMC::setBetaP)
.def("getCounters", &UpdaterBoxMC::getCounters)
.def_property("instance", &UpdaterBoxMC::getInstance, &UpdaterBoxMC::setInstance);
pybind11::class_<hpmc_boxmc_counters_t>(m, "hpmc_boxmc_counters_t")
.def_property_readonly("volume",
[](const hpmc_boxmc_counters_t& a)
{
pybind11::tuple result;
result = pybind11::make_tuple(a.volume_accept_count,
a.volume_reject_count);
return result;
})
.def_property_readonly("ln_volume",
[](const hpmc_boxmc_counters_t& a)
{
pybind11::tuple result;
result = pybind11::make_tuple(a.ln_volume_accept_count,
a.ln_volume_reject_count);
return result;
})
.def_property_readonly("aspect",
[](const hpmc_boxmc_counters_t& a)
{
pybind11::tuple result;
result = pybind11::make_tuple(a.aspect_accept_count,
a.aspect_reject_count);
return result;
})
.def_property_readonly("shear",
[](const hpmc_boxmc_counters_t& a)
{
pybind11::tuple result;
result = pybind11::make_tuple(a.shear_accept_count,
a.shear_reject_count);
return result;
});
}
} // end namespace detail
void UpdaterBoxMC::updateChangedWeights()
{
// This line will need to be rewritten or updated when move types are added to the updater.
auto const weights = std::vector<Scalar> {m_volume_weight,
m_ln_volume_weight,
m_length_weight,
m_shear_weight,
m_aspect_weight};
m_weight_partial_sums = std::vector<Scalar>(weights.size());
std::partial_sum(weights.cbegin(), weights.cend(), m_weight_partial_sums.begin());
}
} // end namespace hpmc
} // end namespace hoomd
| 36.068927 | 100 | 0.53717 | USF-GT-Molecular-Modeling |
8b2b4ea1edf1d7f52c6c0a80f5cd2cc24224d672 | 3,489 | inl | C++ | include/base64_decode.inl | bcrist/bengine-util | 398ccedf39ce8d85c15ad0b8334991a6498ac80d | [
"MIT"
] | null | null | null | include/base64_decode.inl | bcrist/bengine-util | 398ccedf39ce8d85c15ad0b8334991a6498ac80d | [
"MIT"
] | null | null | null | include/base64_decode.inl | bcrist/bengine-util | 398ccedf39ce8d85c15ad0b8334991a6498ac80d | [
"MIT"
] | null | null | null | #if !defined(BE_UTIL_STRING_BASE64_DECODE_HPP_) && !defined(DOXYGEN)
#include "base64_decode.hpp"
#elif !defined(BE_UTIL_STRING_BASE64_DECODE_INL_)
#define BE_UTIL_STRING_BASE64_DECODE_INL_
namespace be::util {
namespace detail {
///////////////////////////////////////////////////////////////////////////////
template <char S62, char S63, char P>
UC base64_index(char symbol) {
if (symbol >= 'A' && symbol <= 'Z') {
return UC(symbol - 'A');
} else if (symbol >= 'a' && symbol <= 'z') {
return UC(26 + symbol - 'a');
} else if (symbol >= '0' && symbol <= '9') {
return UC(52 + symbol - '0');
} else if (symbol == S62) {
return 62u;
} else if (symbol == S63) {
return 63u;
} else if (symbol == P) {
return UC(-2);
} else {
return UC(-1);
}
}
///////////////////////////////////////////////////////////////////////////////
inline void base64_decode_3_bytes(UC a, UC b, UC c, UC d, UC* out) {
out[0] = (a << 2) | (b >> 4);
out[1] = (b << 4) | (c >> 2);
out[2] = (c << 6) | d;
}
///////////////////////////////////////////////////////////////////////////////
inline void base64_decode_2_bytes(UC a, UC b, UC c, UC* out) {
out[0] = (a << 2) | (b >> 4);
out[1] = (b << 4) | (c >> 2);
}
///////////////////////////////////////////////////////////////////////////////
inline void base64_decode_1_byte(UC a, UC b, UC* out) {
out[0] = (a << 2) | (b >> 4);
}
///////////////////////////////////////////////////////////////////////////////
template <char S62, char S63, char P>
std::size_t base64_decode(SV encoded_data, UC* out) {
std::size_t remaining_bytes = encoded_data.size();
const char* ptr = &(*encoded_data.begin());
UC* begin = out;
UC indices[4];
UC n_indices = 0;
while (remaining_bytes > 0) {
UC index = base64_index<S62, S63, P>(*ptr);
indices[n_indices] = index;
++ptr;
if (index <= 63u) {
++n_indices;
if (n_indices == 4) {
base64_decode_3_bytes(indices[0], indices[1], indices[2], indices[3], out);
out += 3;
n_indices = 0;
}
} else if (index == UC(-2)) {
break; // if we find a pad character, ignore the rest of the input
}
--remaining_bytes;
}
if (n_indices == 3) {
base64_decode_2_bytes(indices[0], indices[1], indices[2], out);
out += 2;
} else if (n_indices == 2) {
base64_decode_1_byte(indices[0], indices[1], out);
++out;
}
return std::size_t(out - begin);
}
} // be::util::detail
///////////////////////////////////////////////////////////////////////////////
template <char S62, char S63, char P>
S base64_decode_string(SV encoded_data) {
S decoded;
if (encoded_data.empty()) {
return decoded;
}
decoded.resize((encoded_data.size() / 4) * 3 + 3);
std::size_t size = detail::base64_decode<S62, S63, P>(encoded_data, reinterpret_cast<UC*>(&(decoded[0])));
decoded.resize(size);
return decoded;
}
///////////////////////////////////////////////////////////////////////////////
template <char S62, char S63, char P>
Buf<UC> base64_decode_buf(SV encoded_data) {
if (encoded_data.empty()) {
return Buf<UC>();
}
Buf<UC> buf = make_buf<UC>((encoded_data.size() / 4) * 3 + 3);
std::size_t size = detail::base64_decode<S62, S63, P>(encoded_data, buf.get());
buf.release();
return Buf<UC>(buf.get(), size, be::detail::delete_array);
}
} // be::util
#endif
| 28.834711 | 109 | 0.4818 | bcrist |
8b2bb95f3f9879c38eaabd0cf0635e78cb47e11a | 83,980 | cpp | C++ | module-services/service-cellular/ServiceCellular.cpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | null | null | null | module-services/service-cellular/ServiceCellular.cpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | null | null | null | module-services/service-cellular/ServiceCellular.cpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "endpoints/developerMode/event/ATRequest.hpp"
#include "handler/RawATHandler.hpp"
#include "CellularUrcHandler.hpp"
#include "service-cellular/CellularCall.hpp"
#include "service-cellular/CellularMessage.hpp"
#include "service-cellular/CellularServiceAPI.hpp"
#include "service-cellular/ServiceCellular.hpp"
#include "service-cellular/SignalStrength.hpp"
#include "service-cellular/State.hpp"
#include "service-cellular/USSD.hpp"
#include "service-cellular/MessageConstants.hpp"
#include "service-cellular/connection-manager/ConnectionManagerCellularCommands.hpp"
#include "SimCard.hpp"
#include "NetworkSettings.hpp"
#include "service-cellular/RequestFactory.hpp"
#include "service-cellular/CellularRequestHandler.hpp"
#include "system/messages/SentinelRegistrationMessage.hpp"
#include <Audio/AudioCommon.hpp>
#include <BaseInterface.hpp>
#include <CalllogRecord.hpp>
#include <Commands.hpp>
#include <at/ATFactory.hpp>
#include <Common/Common.hpp>
#include <Common/Query.hpp>
#include <MessageType.hpp>
#include <modem/ATCommon.hpp>
#include <modem/ATParser.hpp>
#include <modem/mux/DLCChannel.h>
#include <modem/mux/CellularMux.h>
#include <NotificationsRecord.hpp>
#include <PhoneNumber.hpp>
#include <Result.hpp>
#include <Service/Message.hpp>
#include <Service/Service.hpp>
#include <Timers/TimerFactory.hpp>
#include <Tables/CalllogTable.hpp>
#include <Tables/Record.hpp>
#include <Utils.hpp>
#include <Utility.hpp>
#include <at/cmd/CLCC.hpp>
#include <at/cmd/CFUN.hpp>
#include <at/UrcClip.hpp>
#include <at/UrcCmti.hpp>
#include <at/UrcCreg.hpp>
#include <at/UrcCtze.hpp>
#include <at/UrcCusd.hpp>
#include <at/UrcQind.hpp>
#include <at/UrcCpin.hpp> // for Cpin
#include <at/response.hpp>
#include <bsp/cellular/bsp_cellular.hpp>
#include <EventStore.hpp>
#include <country.hpp>
#include <log/log.hpp>
#include <at/UrcFactory.hpp>
#include <queries/messages/sms/QuerySMSSearchByType.hpp>
#include <queries/notifications/QueryNotificationsIncrement.hpp>
#include <queries/notifications/QueryNotificationsMultipleIncrement.hpp>
#include <projdefs.h>
#include <service-antenna/AntennaMessage.hpp>
#include <service-antenna/AntennaServiceAPI.hpp>
#include <service-antenna/ServiceAntenna.hpp>
#include <service-appmgr/Constants.hpp>
#include <service-appmgr/Controller.hpp>
#include <service-db/agents/settings/SystemSettings.hpp>
#include <service-db/DBServiceAPI.hpp>
#include <service-db/DBNotificationMessage.hpp>
#include <service-db/QueryMessage.hpp>
#include <service-evtmgr/Constants.hpp>
#include <service-evtmgr/EventManagerServiceAPI.hpp>
#include <service-evtmgr/EVMessages.hpp>
#include <service-desktop/DesktopMessages.hpp>
#include <service-desktop/DeveloperModeMessage.hpp>
#include <service-time/service-time/TimeMessage.hpp>
#include <task.h>
#include <ucs2/UCS2.hpp>
#include <utf8/UTF8.hpp>
#include <queries/messages/sms/QuerySMSUpdate.hpp>
#include <queries/messages/sms/QuerySMSAdd.hpp>
#include <algorithm>
#include <bits/exception.h>
#include <cassert>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "checkSmsCenter.hpp"
#include <service-desktop/Constants.hpp>
#include <gsl/util>
#include <ticks.hpp>
#include "ServiceCellularPriv.hpp"
#include <service-cellular/api/request/sim.hpp>
#include <service-cellular/api/notification/notification.hpp>
#include <ctime>
#include <at/cmd/QCFGUsbnet.hpp>
const char *ServiceCellular::serviceName = cellular::service::name;
inline constexpr auto cellularStack = 8000;
using namespace cellular;
using namespace cellular::msg;
using cellular::service::State;
ServiceCellular::ServiceCellular()
: sys::Service(serviceName, "", cellularStack, sys::ServicePriority::Idle),
phoneModeObserver{std::make_unique<sys::phone_modes::Observer>()},
priv{std::make_unique<internal::ServiceCellularPriv>(this)}
{
LOG_INFO("[ServiceCellular] Initializing");
bus.channels.push_back(sys::BusChannel::ServiceCellularNotifications);
bus.channels.push_back(sys::BusChannel::ServiceDBNotifications);
bus.channels.push_back(sys::BusChannel::ServiceEvtmgrNotifications);
bus.channels.push_back(sys::BusChannel::PhoneModeChanges);
callStateTimer = sys::TimerFactory::createPeriodicTimer(
this, "call_state", std::chrono::milliseconds{1000}, [this](sys::Timer &) { CallStateTimerHandler(); });
callEndedRecentlyTimer = sys::TimerFactory::createSingleShotTimer(
this, "callEndedRecentlyTimer", std::chrono::seconds{5}, [this](sys::Timer &timer) {
priv->outSMSHandler.sendMessageIfDelayed();
});
stateTimer = sys::TimerFactory::createPeriodicTimer(
this, "state", std::chrono::milliseconds{1000}, [&](sys::Timer &) { handleStateTimer(); });
ussdTimer = sys::TimerFactory::createPeriodicTimer(
this, "ussd", std::chrono::milliseconds{1000}, [this](sys::Timer &) { handleUSSDTimer(); });
sleepTimer = sys::TimerFactory::createPeriodicTimer(
this, "sleep", constants::sleepTimerInterval, [this](sys::Timer &) { SleepTimerHandler(); });
connectionTimer =
sys::TimerFactory::createPeriodicTimer(this, "connection", std::chrono::seconds{60}, [this](sys::Timer &) {
utility::conditionally_invoke(
[this]() { return phoneModeObserver->isInMode(sys::phone_modes::PhoneMode::Offline); },
[this]() {
if (connectionManager != nullptr)
connectionManager->onTimerTick();
});
});
simTimer = sys::TimerFactory::createSingleShotTimer(
this, "simTimer", std::chrono::milliseconds{6000}, [this](sys::Timer &) { priv->simCard->handleSimTimer(); });
ongoingCall.setStartCallAction([=](const CalllogRecord &rec) {
auto call = DBServiceAPI::CalllogAdd(this, rec);
if (call.ID == DB_ID_NONE) {
LOG_ERROR("CalllogAdd failed");
}
return call;
});
ongoingCall.setEndCallAction([=](const CalllogRecord &rec) {
if (DBServiceAPI::CalllogUpdate(this, rec) && rec.type == CallType::CT_MISSED) {
DBServiceAPI::GetQuery(this,
db::Interface::Name::Notifications,
std::make_unique<db::query::notifications::Increment>(
NotificationsRecord::Key::Calls, rec.phoneNumber));
}
return true;
});
notificationCallback = [this](std::string &data) {
LOG_DEBUG("Notifications callback called with %u data bytes", static_cast<unsigned int>(data.size()));
std::string logStr = utils::removeNewLines(data);
LOG_SENSITIVE(LOGDEBUG, "Data: %s", logStr.c_str());
atURCStream.write(data);
auto vUrc = atURCStream.getURCList();
for (const auto &urc : vUrc) {
std::string message;
auto msg = identifyNotification(urc);
if (msg != std::nullopt) {
bus.sendMulticast(msg.value(), sys::BusChannel::ServiceCellularNotifications);
}
}
};
packetData = std::make_unique<packet_data::PacketData>(*this); /// call in apnListChanged handler
registerMessageHandlers();
}
ServiceCellular::~ServiceCellular()
{
LOG_INFO("[ServiceCellular] Cleaning resources");
}
void ServiceCellular::SleepTimerHandler()
{
auto currentTime = cpp_freertos::Ticks::TicksToMs(cpp_freertos::Ticks::GetTicks());
auto lastCommunicationTimestamp = cmux->getLastCommunicationTimestamp();
auto timeOfInactivity = currentTime >= lastCommunicationTimestamp
? currentTime - lastCommunicationTimestamp
: std::numeric_limits<TickType_t>::max() - lastCommunicationTimestamp + currentTime;
if (!ongoingCall.isValid() && priv->state->get() == State::ST::Ready &&
timeOfInactivity >= constants::enterSleepModeTime.count()) {
cmux->enterSleepMode();
cpuSentinel->ReleaseMinimumFrequency();
}
}
void ServiceCellular::CallStateTimerHandler()
{
LOG_DEBUG("CallStateTimerHandler");
auto msg = std::make_shared<CellularListCallsMessage>();
bus.sendUnicast(std::move(msg), ServiceCellular::serviceName);
}
sys::ReturnCodes ServiceCellular::InitHandler()
{
board = cmux->getBoard();
settings = std::make_unique<settings::Settings>();
settings->init(::service::ServiceProxy(shared_from_this()));
connectionManager = std::make_unique<ConnectionManager>(
utils::getNumericValue<bool>(
settings->getValue(settings::Cellular::offlineMode, settings::SettingsScope::Global)),
static_cast<std::chrono::minutes>(utils::getNumericValue<int>(settings->getValue(
settings->getValue(settings::Offline::connectionFrequency, settings::SettingsScope::Global)))),
std::make_shared<ConnectionManagerCellularCommands>(*this));
priv->state->set(State::ST::WaitForStartPermission);
settings->registerValueChange(
settings::Cellular::volte_on,
[this](const std::string &value) { volteChanged(value); },
::settings::SettingsScope::Global);
settings->registerValueChange(
settings::Cellular::apn_list,
[this](const std::string &value) { apnListChanged(value); },
::settings::SettingsScope::Global);
priv->setInitialMultiPartSMSUID(static_cast<std::uint8_t>(utils::getNumericValue<int>(
settings->getValue(settings::Cellular::currentUID, settings::SettingsScope::Global))));
priv->saveNewMultiPartSMSUIDCallback = [this](std::uint8_t uid) -> void {
settings->setValue(
settings::Cellular::currentUID, std::to_string(static_cast<int>(uid)), settings::SettingsScope::Global);
};
cpuSentinel = std::make_shared<sys::CpuSentinel>(serviceName, this);
ongoingCall.setCpuSentinel(cpuSentinel);
auto sentinelRegistrationMsg = std::make_shared<sys::SentinelRegistrationMessage>(cpuSentinel);
bus.sendUnicast(sentinelRegistrationMsg, ::service::name::system_manager);
cmux->registerCellularDevice();
return sys::ReturnCodes::Success;
}
sys::ReturnCodes ServiceCellular::DeinitHandler()
{
settings->deinit();
return sys::ReturnCodes::Success;
}
void ServiceCellular::ProcessCloseReason(sys::CloseReason closeReason)
{
sendCloseReadyMessage(this);
}
sys::ReturnCodes ServiceCellular::SwitchPowerModeHandler(const sys::ServicePowerMode mode)
{
LOG_INFO("[ServiceCellular] PowerModeHandler: %s", c_str(mode));
switch (mode) {
case sys::ServicePowerMode ::Active:
cmux->exitSleepMode();
break;
case sys::ServicePowerMode ::SuspendToRAM:
case sys::ServicePowerMode ::SuspendToNVM:
cmux->enterSleepMode();
break;
}
return sys::ReturnCodes::Success;
}
void ServiceCellular::registerMessageHandlers()
{
phoneModeObserver->connect(this);
phoneModeObserver->subscribe(
[this](sys::phone_modes::PhoneMode mode) { connectionManager->onPhoneModeChange(mode); });
phoneModeObserver->subscribe([&](sys::phone_modes::Tethering tethering) {
if (tethering == sys::phone_modes::Tethering::On) {
priv->tetheringHandler->enable();
}
else {
priv->tetheringHandler->disable();
logTetheringCalls();
}
});
priv->connectSimCard();
priv->connectNetworkTime();
priv->connectSimContacts();
priv->connectImeiGetHandler();
connect(typeid(CellularStartOperatorsScanMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularStartOperatorsScanMessage *>(request);
return handleCellularStartOperatorsScan(msg);
});
connect(typeid(CellularGetActiveContextsMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularGetActiveContextsMessage *>(request);
return handleCellularGetActiveContextsMessage(msg);
});
connect(typeid(CellularRequestCurrentOperatorNameMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularRequestCurrentOperatorNameMessage *>(request);
return handleCellularRequestCurrentOperatorName(msg);
});
connect(typeid(CellularGetAPNMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularGetAPNMessage *>(request);
return handleCellularGetAPNMessage(msg);
});
connect(typeid(CellularSetAPNMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularSetAPNMessage *>(request);
return handleCellularSetAPNMessage(msg);
});
connect(typeid(CellularNewAPNMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularNewAPNMessage *>(request);
return handleCellularNewAPNMessage(msg);
});
connect(typeid(CellularSetDataTransferMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularSetDataTransferMessage *>(request);
return handleCellularSetDataTransferMessage(msg);
});
connect(typeid(CellularGetDataTransferMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularGetDataTransferMessage *>(request);
return handleCellularGetDataTransferMessage(msg);
});
connect(typeid(CellularActivateContextMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularActivateContextMessage *>(request);
return handleCellularActivateContextMessage(msg);
});
connect(typeid(CellularDeactivateContextMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularDeactivateContextMessage *>(request);
return handleCellularDeactivateContextMessage(msg);
});
connect(typeid(CellularChangeVoLTEDataMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularChangeVoLTEDataMessage *>(request);
volteOn = msg->getVoLTEon();
settings->setValue(settings::Cellular::volte_on, std::to_string(volteOn), settings::SettingsScope::Global);
NetworkSettings networkSettings(*this);
auto vstate = networkSettings.getVoLTEConfigurationState();
if ((vstate != VoLTEState::On) && volteOn) {
LOG_DEBUG("VoLTE On");
if (networkSettings.setVoLTEState(VoLTEState::On) == at::Result::Code::OK) {
priv->modemResetHandler->performSoftReset();
}
}
else if (!volteOn) {
LOG_DEBUG("VoLTE Off");
if (networkSettings.setVoLTEState(VoLTEState::Off) == at::Result::Code::OK) {
priv->modemResetHandler->performSoftReset();
}
}
return std::make_shared<CellularResponseMessage>(true);
});
connect(typeid(CellularSetFlightModeMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularSetFlightModeMessage *>(request);
return handleCellularSetFlightModeMessage(msg);
});
connect(typeid(CellularPowerStateChange), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularPowerStateChange *>(request);
priv->nextPowerState = msg->getNewState();
handle_power_state_change();
return sys::MessageNone{};
});
connect(typeid(sdesktop::developerMode::DeveloperModeRequest), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<sdesktop::developerMode::DeveloperModeRequest *>(request);
if (typeid(*msg->event.get()) == typeid(sdesktop::developerMode::CellularHotStartEvent)) {
priv->simCard->setChannel(nullptr);
priv->networkTime->setChannel(nullptr);
priv->simContacts->setChannel(nullptr);
priv->imeiGetHandler->setChannel(nullptr);
cmux->closeChannels();
///> change state - simulate hot start
handle_power_up_request();
}
if (typeid(*msg->event.get()) == typeid(sdesktop::developerMode::CellularStateInfoRequestEvent)) {
auto event = std::make_unique<sdesktop::developerMode::CellularStateInfoRequestEvent>(priv->state->c_str());
auto message = std::make_shared<sdesktop::developerMode::DeveloperModeRequest>(std::move(event));
bus.sendUnicast(std::move(message), ::service::name::service_desktop);
}
if (typeid(*msg->event.get()) == typeid(sdesktop::developerMode::CellularSleepModeInfoRequestEvent)) {
auto event = std::make_unique<sdesktop::developerMode::CellularSleepModeInfoRequestEvent>(
cmux->isCellularInSleepMode());
auto message = std::make_shared<sdesktop::developerMode::DeveloperModeRequest>(std::move(event));
bus.sendUnicast(std::move(message), ::service::name::service_desktop);
}
if (typeid(*msg->event.get()) == typeid(sdesktop::developerMode::ATResponseEvent)) {
auto channel = cmux->get(CellularMux::Channel::Commands);
assert(channel);
auto handler = cellular::RawATHandler(*channel);
return handler.handle(msg);
}
return sys::MessageNone{};
});
connect(typeid(CellularNewIncomingSMSMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularNewIncomingSMSMessage *>(request);
auto ret = receiveSMS(msg->getData());
return std::make_shared<CellularResponseMessage>(ret);
});
connect(typeid(CellularAnswerIncomingCallMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularAnswerIncomingCallMessage *>(request);
return handleCellularAnswerIncomingCallMessage(msg);
});
connect(typeid(CellularCallRequestMessage), [&](sys::Message *request) -> sys::MessagePointer {
if (phoneModeObserver->isInMode(sys::phone_modes::PhoneMode::Offline)) {
this->bus.sendUnicast(std::make_shared<CellularCallRejectedByOfflineNotification>(),
::service::name::appmgr);
return std::make_shared<CellularResponseMessage>(true);
}
auto msg = static_cast<CellularCallRequestMessage *>(request);
return handleCellularCallRequestMessage(msg);
});
connect(typeid(CellularHangupCallMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularHangupCallMessage *>(request);
handleCellularHangupCallMessage(msg);
return sys::MessageNone{};
});
connect(typeid(CellularDismissCallMessage), [&](sys::Message *request) -> sys::MessagePointer {
handleCellularDismissCallMessage(request);
return sys::MessageNone{};
});
connect(typeid(db::QueryResponse), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<db::QueryResponse *>(request);
return handleDBQueryResponseMessage(msg);
});
connect(typeid(CellularListCallsMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularListCallsMessage *>(request);
return handleCellularListCallsMessage(msg);
});
connect(typeid(db::NotificationMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<db::NotificationMessage *>(request);
return handleDBNotificationMessage(msg);
});
connect(typeid(CellularRingingMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularRingingMessage *>(request);
return handleCellularRingingMessage(msg);
});
connect(typeid(CellularIncominCallMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularIncomingCallMessage(request); });
connect(typeid(CellularCallerIdMessage), [&](sys::Message *request) -> sys::MessagePointer {
auto msg = static_cast<CellularCallerIdMessage *>(request);
return handleCellularCallerIdMessage(msg);
});
connect(typeid(CellularGetIMSIMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetIMSIMessage(request); });
connect(typeid(CellularGetOwnNumberMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetOwnNumberMessage(request); });
connect(typeid(CellularGetNetworkInfoMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetNetworkInfoMessage(request); });
connect(typeid(CellularAntennaRequestMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularSelectAntennaMessage(request); });
connect(typeid(CellularSetScanModeMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularSetScanModeMessage(request); });
connect(typeid(CellularGetScanModeMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetScanModeMessage(request); });
connect(typeid(CellularGetFirmwareVersionMessage), [&](sys::Message *request) -> sys::MessagePointer {
return handleCellularGetFirmwareVersionMessage(request);
});
connect(typeid(sevm::StatusStateMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleEVMStatusMessage(request); });
connect(typeid(CellularGetCsqMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetCsqMessage(request); });
connect(typeid(CellularGetCregMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetCregMessage(request); });
connect(typeid(CellularGetNwinfoMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetNwinfoMessage(request); });
connect(typeid(CellularGetAntennaMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularGetAntennaMessage(request); });
connect(typeid(CellularDtmfRequestMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularDtmfRequestMessage(request); });
connect(typeid(CellularUSSDMessage),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularUSSDMessage(request); });
connect(typeid(cellular::StateChange),
[&](sys::Message *request) -> sys::MessagePointer { return handleStateRequestMessage(request); });
connect(typeid(CellularCallActiveNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleCallActiveNotification(request); });
connect(typeid(CellularCallAbortedNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleCallAbortedNotification(request); });
connect(typeid(CellularPowerUpProcedureCompleteNotification), [&](sys::Message *request) -> sys::MessagePointer {
return handlePowerUpProcedureCompleteNotification(request);
});
connect(typeid(CellularPowerDownDeregisteringNotification), [&](sys::Message *request) -> sys::MessagePointer {
return handlePowerDownDeregisteringNotification(request);
});
connect(typeid(CellularPowerDownDeregisteredNotification), [&](sys::Message *request) -> sys::MessagePointer {
return handlePowerDownDeregisteredNotification(request);
});
connect(typeid(CellularNewIncomingSMSNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleNewIncomingSMSNotification(request); });
connect(typeid(CellularSmsDoneNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleSmsDoneNotification(request); });
connect(typeid(CellularSignalStrengthUpdateNotification), [&](sys::Message *request) -> sys::MessagePointer {
return handleSignalStrengthUpdateNotification(request);
});
connect(typeid(CellularNetworkStatusUpdateNotification), [&](sys::Message *request) -> sys::MessagePointer {
return handleNetworkStatusUpdateNotification(request);
});
connect(typeid(CellularUrcIncomingNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleUrcIncomingNotification(request); });
connect(typeid(CellularRingNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularRingNotification(request); });
connect(typeid(CellularCallerIdNotification),
[&](sys::Message *request) -> sys::MessagePointer { return handleCellularCallerIdNotification(request); });
connect(typeid(CellularSetConnectionFrequencyMessage), [&](sys::Message *request) -> sys::MessagePointer {
return handleCellularSetConnectionFrequencyMessage(request);
});
handle_CellularGetChannelMessage();
}
void ServiceCellular::change_state(cellular::StateChange *msg)
{
assert(msg);
switch (msg->request) {
case State::ST::Idle:
handle_idle();
break;
case State::ST::WaitForStartPermission:
handle_wait_for_start_permission();
break;
case State::ST::PowerUpRequest:
handle_power_up_request();
break;
case State::ST::StatusCheck:
handle_status_check();
break;
case State::ST::PowerUpInProgress:
handle_power_up_in_progress_procedure();
break;
case State::ST::PowerUpProcedure:
handle_power_up_procedure();
break;
case State::ST::BaudDetect:
if (nextPowerStateChangeAwaiting) {
handle_power_state_change();
}
else {
handle_baud_detect();
}
break;
case State::ST::AudioConfigurationProcedure:
handle_audio_conf_procedure();
break;
case State::ST::CellularPrivInit:
handle_cellular_priv_init();
break;
case State::ST::CellularConfProcedure:
handle_start_conf_procedure();
break;
case State::ST::APNConfProcedure:
handle_apn_conf_procedure();
break;
case State::ST::SanityCheck:
handle_sim_sanity_check();
break;
case State::ST::ModemOn:
handle_modem_on();
break;
case State::ST::URCReady:
handle_URCReady();
break;
case State::ST::ModemFatalFailure:
handle_fatal_failure();
break;
case State::ST::Failed:
handle_failure();
break;
case State::ST::Ready:
handle_ready();
break;
case State::ST::PowerDownStarted:
handle_power_down_started();
break;
case State::ST::PowerDownWaiting:
handle_power_down_waiting();
break;
case State::ST::PowerDown:
handle_power_down();
if (nextPowerStateChangeAwaiting) {
handle_power_state_change();
}
break;
};
}
bool ServiceCellular::handle_idle()
{
LOG_DEBUG("Idle");
return true;
}
bool ServiceCellular::handle_wait_for_start_permission()
{
auto msg = std::make_shared<CellularCheckIfStartAllowedMessage>();
bus.sendUnicast(msg, ::service::name::system_manager);
return true;
}
bool ServiceCellular::handle_power_up_request()
{
cmux->selectAntenna(bsp::cellular::antenna::lowBand);
switch (board) {
case bsp::Board::RT1051:
priv->state->set(State::ST::StatusCheck);
break;
case bsp::Board::Linux:
priv->state->set(State::ST::PowerUpProcedure);
break;
case bsp::Board::none:
return false;
break;
}
return true;
}
bool ServiceCellular::handle_power_up_procedure()
{
switch (board) {
case bsp::Board::RT1051: {
LOG_DEBUG("RT1051 - cold start");
cmux->turnOnModem();
// wait for status pin change to change state
break;
}
case bsp::Board::Linux: {
// check baud once to determine if it's already turned on
auto ret = cmux->baudDetectOnce();
if (ret == CellularMux::ConfState::Success) {
// it's on aka hot start.
LOG_DEBUG("Linux - hot start");
priv->state->set(State::ST::CellularConfProcedure);
break;
}
else {
// it's off aka cold start
LOG_DEBUG("Linux - cold start");
LOG_WARN("Press PWR_KEY for 2 sec on modem eval board!");
vTaskDelay(pdMS_TO_TICKS(2000)); // give some 2 secs more for user input
// if it's Linux, then wait for status pin to become active, to align its starting position with RT1051
vTaskDelay(pdMS_TO_TICKS(8000));
priv->state->set(State::ST::PowerUpInProgress);
break;
}
}
case bsp::Board::none:
default:
LOG_FATAL("Board not known!");
assert(0);
break;
}
return true;
}
bool ServiceCellular::handle_power_up_in_progress_procedure(void)
{
if (priv->modemResetHandler->isResetInProgress()) {
constexpr auto msModemUartInitTime = 12000;
vTaskDelay(pdMS_TO_TICKS(msModemUartInitTime));
}
priv->state->set(State::ST::BaudDetect);
return true;
}
bool ServiceCellular::handle_baud_detect()
{
auto ret = cmux->baudDetectProcedure();
if (ret == CellularMux::ConfState::Success) {
priv->state->set(State::ST::CellularConfProcedure);
return true;
}
else {
priv->state->set(State::ST::ModemFatalFailure);
return false;
}
}
bool ServiceCellular::handle_power_down_started()
{
/// we should not send anything to the modem from now on
return true;
}
bool ServiceCellular::handle_power_down_waiting()
{
switch (board) {
case bsp::Board::RT1051:
// wait for pin status become inactive (handled elsewhere)
break;
case bsp::Board::Linux:
// if it's Linux, then wait for status pin to become inactive, to align with RT1051
vTaskDelay(pdMS_TO_TICKS(17000)); // according to docs this shouldn't be needed, but better be safe than Quectel
priv->state->set(State::ST::PowerDown);
break;
default:
LOG_ERROR("Powering 'down an unknown device not handled");
return false;
}
return true;
}
bool ServiceCellular::handle_power_down()
{
LOG_DEBUG("Powered Down");
cmux->closeChannels();
cmux.reset();
cmux = std::make_unique<CellularMux>(PortSpeed_e::PS460800, this);
if (priv->modemResetHandler->isResetInProgress()) {
priv->state->set(State::ST::Idle);
}
return true;
}
bool ServiceCellular::handle_start_conf_procedure()
{
// Start configuration procedure, if it's first run modem will be restarted
auto confRet = cmux->confProcedure();
if (confRet == CellularMux::ConfState::Success) {
priv->state->set(State::ST::AudioConfigurationProcedure);
return true;
}
priv->state->set(State::ST::Failed);
return false;
}
bool ServiceCellular::handle_audio_conf_procedure()
{
auto audioRet = cmux->audioConfProcedure();
if (audioRet == CellularMux::ConfState::ModemNeedsReset) {
priv->modemResetHandler->performReboot();
return false;
}
if (audioRet == CellularMux::ConfState::Success) {
auto cmd = at::factory(at::AT::IPR) + std::to_string(ATPortSpeeds_text[cmux->getStartParams().PortSpeed]);
LOG_DEBUG("Setting baudrate %i baud", ATPortSpeeds_text[cmux->getStartParams().PortSpeed]);
if (!cmux->getParser()->cmd(cmd)) {
LOG_ERROR("Baudrate setup error");
priv->state->set(State::ST::Failed);
return false;
}
cmux->getCellular()->setSpeed(ATPortSpeeds_text[cmux->getStartParams().PortSpeed]);
vTaskDelay(1000);
if (cmux->startMultiplexer() == CellularMux::ConfState::Success) {
LOG_DEBUG("[ServiceCellular] Modem is fully operational");
// open channel - notifications
DLCChannel *notificationsChannel = cmux->get(CellularMux::Channel::Notifications);
if (notificationsChannel != nullptr) {
LOG_DEBUG("Setting up notifications callback");
notificationsChannel->setCallback(notificationCallback);
}
priv->state->set(State::ST::CellularPrivInit);
return true;
}
else {
priv->state->set(State::ST::Failed);
return false;
}
}
else if (audioRet == CellularMux::ConfState::Failure) {
/// restart
priv->state->set(State::ST::AudioConfigurationProcedure);
return true;
}
// Reset procedure started, do nothing here
priv->state->set(State::ST::Idle);
return true;
}
bool ServiceCellular::handle_cellular_priv_init()
{
auto channel = cmux->get(CellularMux::Channel::Commands);
priv->simCard->setChannel(channel);
priv->networkTime->setChannel(channel);
priv->simContacts->setChannel(channel);
priv->imeiGetHandler->setChannel(channel);
if (!priv->tetheringHandler->configure()) {
priv->modemResetHandler->performHardReset();
return true;
}
auto flightMode =
settings->getValue(settings::Cellular::offlineMode, settings::SettingsScope::Global) == "1" ? true : false;
connectionManager->setFlightMode(flightMode);
auto interval = 0;
if (utils::toNumeric(settings->getValue(settings::Offline::connectionFrequency, settings::SettingsScope::Global),
interval)) {
connectionManager->setInterval(std::chrono::minutes{interval});
}
if (!connectionManager->onPhoneModeChange(phoneModeObserver->getCurrentPhoneMode())) {
priv->state->set(State::ST::Failed);
LOG_ERROR("Failed to handle phone mode");
return false;
}
priv->state->set(State::ST::APNConfProcedure);
return true;
}
auto ServiceCellular::handle(db::query::SMSSearchByTypeResult *response) -> bool
{
if (response->getResults().empty()) {
priv->outSMSHandler.handleNoMoreDbRecords();
}
else {
for (auto &rec : response->getResults()) {
if (rec.type == SMSType::QUEUED) {
priv->outSMSHandler.handleIncomingDbRecord(rec, callEndedRecentlyTimer.isActive());
}
}
}
return true;
}
/**
* NOTICE: URC handling function identifyNotification works on different thread, so sending
* any AT commands is not allowed here (also in URC handlers and other functions called from here)
* @return
*/
std::optional<std::shared_ptr<sys::Message>> ServiceCellular::identifyNotification(const std::string &data)
{
CellularUrcHandler urcHandler(*this);
std::string str(data.begin(), data.end());
std::string logStr = utils::removeNewLines(str);
LOG_SENSITIVE(LOGDEBUG, "Notification:: %s", logStr.c_str());
auto urc = at::urc::UrcFactory::Create(str);
urc->Handle(urcHandler);
if (!urc->isHandled()) {
LOG_SENSITIVE(LOGWARN, "Unhandled notification: %s", logStr.c_str());
}
return urcHandler.getResponse();
}
auto ServiceCellular::receiveSMS(std::string messageNumber) -> bool
{
constexpr auto ucscSetMaxRetries = 3;
auto retVal = true;
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel == nullptr) {
retVal = false;
return retVal;
}
auto ucscSetRetries = 0;
while (ucscSetRetries < ucscSetMaxRetries) {
if (!channel->cmd(at::AT::SMS_UCSC2)) {
++ucscSetRetries;
LOG_ERROR("Could not set UCS2 charset mode for TE. Retry %d", ucscSetRetries);
}
else {
break;
}
}
auto _ = gsl::finally([&channel, &retVal, &messageNumber] {
if (!channel->cmd(at::AT::SMS_GSM)) {
LOG_ERROR("Could not set GSM (default) charset mode for TE");
}
// delete message from modem memory
if (retVal && !channel->cmd(at::factory(at::AT::CMGD) + messageNumber)) {
LOG_ERROR("Could not delete SMS from modem");
}
});
bool messageParsed = false;
std::string messageRawBody;
UTF8 receivedNumber;
const auto &cmd = at::factory(at::AT::QCMGR);
auto ret = channel->cmd(cmd + messageNumber, cmd.getTimeout());
if (!ret) {
LOG_ERROR("!!!! Could not read text message !!!!");
retVal = false;
}
else {
for (std::size_t i = 0; i < ret.response.size(); i++) {
if (ret.response[i].find("QCMGR") != std::string::npos) {
std::istringstream ss(ret.response[i]);
std::string token;
std::vector<std::string> tokens;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
tokens[1].erase(std::remove(tokens[1].begin(), tokens[1].end(), '\"'), tokens[1].end());
/*
* tokens:
* [0] - +QCMGR
* [1] - sender number
* [2] - none
* [3] - date YY/MM/DD
* [4] - hour HH/MM/SS/timezone
* concatenaded messages
* [5] - unique concatenated message id
* [6] - current message number
* [7] - total messages count
*
*/
// parse sender number
receivedNumber = UCS2(tokens[1]).toUTF8();
// parse date
tokens[3].erase(std::remove(tokens[3].begin(), tokens[3].end(), '\"'), tokens[3].end());
auto messageDate = std::time(nullptr);
if (tokens.size() == 5) {
LOG_DEBUG("Single message");
messageRawBody = ret.response[i + 1];
messageParsed = true;
}
else if (tokens.size() == 8) {
LOG_DEBUG("Concatenated message");
uint32_t last = 0;
uint32_t current = 0;
try {
last = std::stoi(tokens[7]);
current = std::stoi(tokens[6]);
}
catch (const std::exception &e) {
LOG_ERROR("ServiceCellular::receiveSMS error %s", e.what());
retVal = false;
break;
}
LOG_DEBUG("part %" PRIu32 "from %" PRIu32, current, last);
if (current == last) {
messageParts.push_back(ret.response[i + 1]);
for (std::size_t j = 0; j < messageParts.size(); j++) {
messageRawBody += messageParts[j];
}
messageParts.clear();
messageParsed = true;
}
else {
messageParts.push_back(ret.response[i + 1]);
}
}
if (messageParsed) {
messageParsed = false;
const auto decodedMessage = UCS2(messageRawBody).toUTF8();
const auto record = createSMSRecord(decodedMessage, receivedNumber, messageDate);
if (!dbAddSMSRecord(record)) {
LOG_ERROR("Failed to add text message to db");
retVal = false;
break;
}
}
}
}
}
return retVal;
}
bool ServiceCellular::getOwnNumber(std::string &destination)
{
auto ret = cmux->get(CellularMux::Channel::Commands)->cmd(at::AT::CNUM);
if (ret) {
auto begin = ret.response[0].find(',');
auto end = ret.response[0].rfind(',');
if (begin != std::string::npos && end != std::string::npos) {
std::string number;
try {
number = ret.response[0].substr(begin, end - begin);
}
catch (std::exception &e) {
LOG_ERROR("ServiceCellular::getOwnNumber exception: %s", e.what());
return false;
}
number.erase(std::remove(number.begin(), number.end(), '"'), number.end());
number.erase(std::remove(number.begin(), number.end(), ','), number.end());
destination = number;
return true;
}
}
LOG_ERROR("ServiceCellular::getOwnNumber failed.");
return false;
}
bool ServiceCellular::getIMSI(std::string &destination, bool fullNumber)
{
auto ret = cmux->get(CellularMux::Channel::Commands)->cmd(at::AT::CIMI);
if (ret) {
if (fullNumber) {
destination = ret.response[0];
}
else {
try {
destination = ret.response[0].substr(0, 3);
}
catch (std::exception &e) {
LOG_ERROR("ServiceCellular::getIMSI exception: %s", e.what());
return false;
}
}
return true;
}
LOG_ERROR("ServiceCellular::getIMSI failed.");
return false;
}
std::vector<std::string> ServiceCellular::getNetworkInfo(void)
{
std::vector<std::string> data;
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto resp = channel->cmd(at::AT::CSQ);
if (resp.code == at::Result::Code::OK) {
data.push_back(resp.response[0]);
}
else {
LOG_ERROR("CSQ Error");
data.push_back("");
}
resp = channel->cmd(at::AT::CREG);
if (resp.code == at::Result::Code::OK) {
data.push_back(resp.response[0]);
}
else {
LOG_ERROR("CREG Error");
data.push_back("");
}
resp = channel->cmd(at::AT::QNWINFO);
if (resp.code == at::Result::Code::OK) {
std::string ret;
if (at::response::parseQNWINFO(resp.response[0], ret)) {
data.push_back(ret);
}
else {
data.push_back("");
}
}
else {
LOG_ERROR("QNWINFO Error");
data.push_back("");
}
}
return data;
}
std::vector<std::string> get_last_AT_error(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::CEER);
return std::move(ret.response);
}
void log_last_AT_error(DLCChannel *channel)
{
std::vector<std::string> atErrors(get_last_AT_error(channel));
int i = 1;
for (auto &msg_line : atErrors) {
LOG_ERROR("%d/%d: %s", i, static_cast<int>(atErrors.size()), msg_line.c_str());
i++;
}
}
bool is_SIM_detection_enabled(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::SIM_DET);
if (ret) {
if (ret.response[0].find("+QSIMDET: 1") != std::string::npos) {
LOG_DEBUG("SIM detecition enabled!");
return true;
}
}
else {
LOG_FATAL("Cant check sim detection status!");
log_last_AT_error(channel);
}
return false;
}
bool enable_SIM_detection(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::SIM_DET_ON);
if (!ret) {
log_last_AT_error(channel);
return false;
}
return true;
}
bool is_SIM_status_enabled(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::QSIMSTAT);
if (ret) {
if (ret.response[0].find("+QSIMSTAT: 1") != std::string::npos) {
LOG_DEBUG("SIM swap enabled!");
return true;
}
}
else {
LOG_FATAL("SIM swap status failure! %s", ret.response[0].c_str());
log_last_AT_error(channel);
}
return false;
}
bool enable_SIM_status(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::SIMSTAT_ON);
if (!ret) {
log_last_AT_error(channel);
return false;
}
return true;
}
void save_SIM_detection_status(DLCChannel *channel)
{
auto ret = channel->cmd(at::AT::STORE_SETTINGS_ATW);
if (!ret) {
log_last_AT_error(channel);
}
}
bool sim_check_hot_swap(DLCChannel *channel)
{
assert(channel);
bool reboot_needed = false;
if (!is_SIM_detection_enabled(channel)) {
reboot_needed = true;
}
if (!is_SIM_status_enabled(channel)) {
reboot_needed = true;
}
if (reboot_needed) {
enable_SIM_detection(channel);
enable_SIM_status(channel);
save_SIM_detection_status(channel);
LOG_FATAL("Modem reboot required, Please remove battery!");
}
return !reboot_needed;
}
bool ServiceCellular::handle_sim_sanity_check()
{
auto ret = sim_check_hot_swap(cmux->get(CellularMux::Channel::Commands));
if (ret) {
priv->state->set(State::ST::ModemOn);
}
else {
LOG_ERROR("Sanity check failure - modem has to be rebooted");
priv->modemResetHandler->performHardReset();
}
return ret;
}
bool ServiceCellular::handle_modem_on()
{
auto channel = cmux->get(CellularMux::Channel::Commands);
channel->cmd("AT+CCLK?");
// inform host ap ready
cmux->informModemHostWakeup();
tetheringTurnOnURC();
priv->state->set(State::ST::URCReady);
LOG_DEBUG("AP ready");
return true;
}
bool ServiceCellular::handle_URCReady()
{
auto channel = cmux->get(CellularMux::Channel::Commands);
bool ret = true;
priv->requestNetworkTimeSettings();
ret = ret && channel->cmd(at::AT::ENABLE_NETWORK_REGISTRATION_URC);
bus.sendMulticast<cellular::msg::notification::ModemStateChanged>(cellular::api::ModemState::Ready);
LOG_DEBUG("%s", priv->state->c_str());
return ret;
}
bool ServiceCellular::handleTextMessagesInit()
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel == nullptr) {
LOG_ERROR("Cant configure sim! no Commands channel!");
return false;
}
auto commands = at::getCommadsSet(at::commadsSet::smsInit);
for (const auto &command : commands) {
if (!channel->cmd(command)) {
LOG_ERROR("Text messages init failed!");
return false;
}
}
if (!receiveAllMessages()) {
LOG_ERROR("Receiving all messages from modem failed");
return true; // this is not blocking issue
}
return true;
}
SMSRecord ServiceCellular::createSMSRecord(const UTF8 &decodedMessage,
const UTF8 &receivedNumber,
const time_t messageDate,
const SMSType &smsType) const noexcept
{
SMSRecord record{};
record.body = decodedMessage;
record.number = utils::PhoneNumber::getReceivedNumberView(receivedNumber);
record.type = SMSType::INBOX;
record.date = messageDate;
return record;
}
bool ServiceCellular::dbAddSMSRecord(const SMSRecord &record)
{
return DBServiceAPI::AddSMS(
this, record, db::QueryCallback::fromFunction([this, number = record.number](auto response) {
auto result = dynamic_cast<db::query::SMSAddResult *>(response);
if (result == nullptr || !result->result) {
return false;
}
onSMSReceived(number);
return true;
}));
}
void ServiceCellular::onSMSReceived(const utils::PhoneNumber::View &number)
{
DBServiceAPI::GetQuery(
this,
db::Interface::Name::Notifications,
std::make_unique<db::query::notifications::Increment>(NotificationsRecord::Key::Sms, number));
bus.sendMulticast(std::make_shared<CellularIncomingSMSNotificationMessage>(),
sys::BusChannel::ServiceCellularNotifications);
}
bool ServiceCellular::receiveAllMessages()
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel == nullptr) {
return false;
}
constexpr std::string_view cmd = "CMGL: ";
if (auto ret = channel->cmd(at::AT::LIST_MESSAGES)) {
for (std::size_t i = 0; i < ret.response.size(); i++) {
if (auto pos = ret.response[i].find(cmd); pos != std::string::npos) {
auto startPos = pos + cmd.size();
auto endPos = ret.response[i].find_first_of(',');
if (receiveSMS(ret.response[i].substr(startPos, endPos - startPos))) {
LOG_WARN("Cannot receive text message - %" PRIu32 " / %" PRIu32,
static_cast<uint32_t>(i),
static_cast<uint32_t>(ret.response.size()));
}
}
}
return true;
}
else {
return false;
}
}
bool ServiceCellular::handle_failure()
{
priv->state->set(State::ST::Idle);
bus.sendMulticast<cellular::msg::notification::ModemStateChanged>(cellular::api::ModemState::Fail);
return true;
}
bool ServiceCellular::handle_fatal_failure()
{
LOG_FATAL("Await for death!");
bus.sendMulticast<cellular::msg::notification::ModemStateChanged>(cellular::api::ModemState::Fatal);
while (true) {
vTaskDelay(500);
}
return true;
}
bool ServiceCellular::handle_ready()
{
LOG_DEBUG("%s", priv->state->c_str());
sleepTimer.start();
return true;
}
bool ServiceCellular::SetScanMode(std::string mode)
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto command = at::factory(at::AT::SET_SCANMODE);
auto resp = channel->cmd(command.getCmd() + mode + ",1", command.getTimeout(), 1);
if (resp.code == at::Result::Code::OK) {
return true;
}
}
return false;
}
std::string ServiceCellular::GetScanMode(void)
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto resp = channel->cmd(at::AT::GET_SCANMODE);
if (resp.code == at::Result::Code::OK) {
auto beg = resp.response[0].find(",");
if (beg != std::string::npos) {
auto response = resp.response[0].substr(beg + 1, 1);
return response;
}
}
else {
LOG_ERROR("Unable to get network search mode configuration");
}
}
return {};
}
bool ServiceCellular::transmitDtmfTone(uint32_t digit)
{
auto channel = cmux->get(CellularMux::Channel::Commands);
at::Result resp;
if (channel) {
auto command = at::factory(at::AT::QLDTMF);
std::string dtmfString = "\"" + std::string(1, digit) + "\"";
resp = channel->cmd(command.getCmd() + dtmfString);
if (resp) {
command = at::factory(at::AT::VTS);
resp = channel->cmd(command.getCmd() + dtmfString);
}
}
return resp.code == at::Result::Code::OK;
}
void ServiceCellular::handle_CellularGetChannelMessage()
{
connect(CellularGetChannelMessage(), [&](sys::Message *req) {
auto getChannelMsg = static_cast<CellularGetChannelMessage *>(req);
LOG_DEBUG("Handle request for channel: %s", CellularMux::name(getChannelMsg->dataChannel).c_str());
std::shared_ptr<CellularGetChannelResponseMessage> channelResponsMessage =
std::make_shared<CellularGetChannelResponseMessage>(cmux->get(getChannelMsg->dataChannel));
LOG_DEBUG("channel ptr: %p", channelResponsMessage->dataChannelPtr);
bus.sendUnicast(std::move(channelResponsMessage), req->sender);
return sys::MessageNone{};
});
}
bool ServiceCellular::handle_status_check(void)
{
LOG_INFO("Checking modem status.");
auto modemActive = cmux->isModemActive();
if (modemActive) {
// modem is already turned on, call configutarion procedure
LOG_INFO("Modem is already turned on.");
LOG_DEBUG("RT1051 - hot start");
priv->state->set(State::ST::PowerUpInProgress);
}
else {
priv->state->set(State::ST::PowerUpProcedure);
}
return true;
}
void ServiceCellular::startStateTimer(uint32_t timeout)
{
stateTimeout = timeout;
stateTimer.start();
}
void ServiceCellular::stopStateTimer()
{
stateTimeout = 0;
stateTimer.stop();
}
void ServiceCellular::handleStateTimer(void)
{
stateTimeout--;
if (stateTimeout == 0) {
stopStateTimer();
LOG_FATAL("State %s timeout occured!", priv->state->c_str());
priv->state->set(State::ST::ModemFatalFailure);
}
}
void ServiceCellular::handle_power_state_change()
{
nextPowerStateChangeAwaiting = false;
auto modemActive = cmux->isModemActive();
if (priv->nextPowerState == State::PowerState::On) {
if (priv->state->get() == State::ST::PowerDownWaiting) {
LOG_DEBUG("Powerdown in progress. Powerup request queued.");
nextPowerStateChangeAwaiting = true;
}
else if (priv->state->get() == State::ST::PowerUpProcedure ||
priv->state->get() == State::ST::PowerUpInProgress) {
LOG_DEBUG("Powerup already in progress");
}
else if (priv->state->get() == State::ST::PowerDown ||
priv->state->get() == State::ST::WaitForStartPermission) {
LOG_INFO("Modem Power UP.");
priv->state->set(State::ST::PowerUpRequest);
}
else {
LOG_DEBUG("Modem already powered up.");
}
}
else {
if (priv->state->get() == State::ST::PowerUpProcedure || priv->state->get() == State::ST::PowerUpInProgress) {
LOG_DEBUG("Powerup in progress. Powerdown request queued.");
nextPowerStateChangeAwaiting = true;
}
else if (priv->state->get() == State::ST::PowerDownWaiting) {
LOG_DEBUG("Powerdown already in progress.");
}
else if (priv->state->get() == State::ST::PowerDown) {
LOG_DEBUG("Modem already powered down.");
}
else if (priv->state->get() == State::ST::WaitForStartPermission && !modemActive) {
LOG_DEBUG("Modem already powered down.");
priv->state->set(State::ST::PowerDown);
}
else {
LOG_INFO("Modem Power DOWN.");
cmux->turnOffModem();
priv->state->set(State::ST::PowerDownWaiting);
}
}
}
bool ServiceCellular::handleUSSDRequest(CellularUSSDMessage::RequestType requestType, const std::string &request)
{
constexpr uint32_t commandTimeout = 120000;
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel != nullptr) {
if (requestType == CellularUSSDMessage::RequestType::pullSesionRequest) {
channel->cmd(at::AT::SMS_GSM);
std::string command = at::factory(at::AT::CUSD_SEND) + request + ",15";
auto result = channel->cmd(command, std::chrono::milliseconds(commandTimeout));
if (result.code == at::Result::Code::OK) {
ussdState = ussd::State::pullRequestSent;
setUSSDTimer();
}
}
else if (requestType == CellularUSSDMessage::RequestType::abortSesion) {
ussdState = ussd::State::sesionAborted;
auto result = channel->cmd(at::AT::CUSD_CLOSE_SESSION);
if (result.code == at::Result::Code::OK) {
CellularServiceAPI::USSDRequest(this, CellularUSSDMessage::RequestType::pushSesionRequest);
}
else {
CellularServiceAPI::USSDRequest(this, CellularUSSDMessage::RequestType::abortSesion);
}
}
else if (requestType == CellularUSSDMessage::RequestType::pushSesionRequest) {
ussdState = ussd::State::pushSesion;
auto result = channel->cmd(at::AT::CUSD_OPEN_SESSION);
if (result.code == at::Result::Code::OK) {}
}
return true;
}
return false;
}
void ServiceCellular::handleUSSDTimer(void)
{
if (ussdTimeout > 0) {
ussdTimeout -= 1;
}
else {
LOG_WARN("USSD timeout occured, abotrig current session");
ussdTimer.stop();
CellularServiceAPI::USSDRequest(this, CellularUSSDMessage::RequestType::abortSesion);
}
}
void ServiceCellular::setUSSDTimer(void)
{
switch (ussdState) {
case ussd::State::pullRequestSent:
ussdTimeout = ussd::pullResponseTimeout;
break;
case ussd::State::pullResponseReceived:
ussdTimeout = ussd::pullSesionTimeout;
break;
case ussd::State::pushSesion:
case ussd::State::sesionAborted:
case ussd::State::none:
ussdTimeout = ussd::noTimeout;
break;
}
if (ussdTimeout == ussd::noTimeout) {
ussdTimer.stop();
return;
}
ussdTimer.start();
}
std::shared_ptr<cellular::RawCommandRespAsync> ServiceCellular::handleCellularStartOperatorsScan(
CellularStartOperatorsScanMessage *msg)
{
LOG_INFO("CellularStartOperatorsScan handled");
auto ret = std::make_shared<cellular::RawCommandRespAsync>(CellularMessage::Type::OperatorsScanResult);
NetworkSettings networkSettings(*this);
ret->data = networkSettings.scanOperators(msg->getFullInfo());
bus.sendUnicast(ret, msg->sender);
return ret;
}
bool ServiceCellular::handle_apn_conf_procedure()
{
LOG_DEBUG("APN on modem configuration");
packetData->setupAPNSettings();
priv->state->set(State::ST::SanityCheck);
return true;
}
std::shared_ptr<CellularCurrentOperatorNameResponse> ServiceCellular::handleCellularRequestCurrentOperatorName(
CellularRequestCurrentOperatorNameMessage *msg)
{
LOG_INFO("CellularRequestCurrentOperatorName handled");
NetworkSettings networkSettings(*this);
const auto currentNetworkOperatorName = networkSettings.getCurrentOperatorName();
Store::GSM::get()->setNetworkOperatorName(currentNetworkOperatorName);
return std::make_shared<CellularCurrentOperatorNameResponse>(currentNetworkOperatorName);
}
std::shared_ptr<CellularGetAPNResponse> ServiceCellular::handleCellularGetAPNMessage(CellularGetAPNMessage *msg)
{
std::vector<std::shared_ptr<packet_data::APN::Config>> apns;
if (auto type = msg->getAPNType(); type) {
if (auto apn = packetData->getAPNFirst(*type); apn) {
apns.push_back(*apn);
}
return std::make_shared<CellularGetAPNResponse>(apns);
}
if (auto ctxid = msg->getContextId(); ctxid) {
if (auto apn = packetData->getAPN(*ctxid); apn) {
apns.push_back(*apn);
}
return std::make_shared<CellularGetAPNResponse>(apns);
}
return std::make_shared<CellularGetAPNResponse>(packetData->getAPNs());
}
std::shared_ptr<CellularSetAPNResponse> ServiceCellular::handleCellularSetAPNMessage(CellularSetAPNMessage *msg)
{
auto apn = msg->getAPNConfig();
auto ret = packetData->setAPN(apn);
settings->setValue(settings::Cellular::apn_list, packetData->saveAPNSettings(), settings::SettingsScope::Global);
return std::make_shared<CellularSetAPNResponse>(ret);
}
std::shared_ptr<CellularNewAPNResponse> ServiceCellular::handleCellularNewAPNMessage(CellularNewAPNMessage *msg)
{
auto apn = msg->getAPNConfig();
std::uint8_t newId = 0;
auto ret = packetData->newAPN(apn, newId);
settings->setValue(settings::Cellular::apn_list, packetData->saveAPNSettings(), settings::SettingsScope::Global);
return std::make_shared<CellularNewAPNResponse>(ret, newId);
}
std::shared_ptr<CellularSetDataTransferResponse> ServiceCellular::handleCellularSetDataTransferMessage(
CellularSetDataTransferMessage *msg)
{
packetData->setDataTransfer(msg->getDataTransfer());
return std::make_shared<CellularSetDataTransferResponse>(at::Result::Code::OK);
}
std::shared_ptr<CellularGetDataTransferResponse> ServiceCellular::handleCellularGetDataTransferMessage(
CellularGetDataTransferMessage *msg)
{
return std::make_shared<CellularGetDataTransferResponse>(packetData->getDataTransfer());
}
std::shared_ptr<CellularActivateContextResponse> ServiceCellular::handleCellularActivateContextMessage(
CellularActivateContextMessage *msg)
{
return std::make_shared<CellularActivateContextResponse>(packetData->activateContext(msg->getContextId()),
msg->getContextId());
}
std::shared_ptr<CellularDeactivateContextResponse> ServiceCellular::handleCellularDeactivateContextMessage(
CellularDeactivateContextMessage *msg)
{
return std::make_shared<CellularDeactivateContextResponse>(packetData->deactivateContext(msg->getContextId()),
msg->getContextId());
}
std::shared_ptr<CellularGetActiveContextsResponse> ServiceCellular::handleCellularGetActiveContextsMessage(
CellularGetActiveContextsMessage *msg)
{
return std::make_shared<CellularGetActiveContextsResponse>(packetData->getActiveContexts());
}
std::shared_ptr<CellularSetOperatorAutoSelectResponse> ServiceCellular::handleCellularSetOperatorAutoSelect(
CellularSetOperatorAutoSelectMessage *msg)
{
LOG_INFO("CellularSetOperatorAutoSelect handled");
NetworkSettings networkSettings(*this);
return std::make_shared<CellularSetOperatorAutoSelectResponse>(networkSettings.setOperatorAutoSelect());
}
std::shared_ptr<CellularSetOperatorResponse> ServiceCellular::handleCellularSetOperator(CellularSetOperatorMessage *msg)
{
LOG_INFO("CellularSetOperatorAutoSelect handled");
NetworkSettings networkSettings(*this);
return std::make_shared<CellularSetOperatorResponse>(
networkSettings.setOperator(msg->getMode(), msg->getFormat(), msg->getName()));
}
void ServiceCellular::volteChanged(const std::string &value)
{
if (!value.empty()) {
LOG_INFO("VoLTE setting state changed to '%s'.", value.c_str());
volteOn = utils::getNumericValue<bool>(value);
}
}
void ServiceCellular::apnListChanged(const std::string &value)
{
if (!value.empty()) {
LOG_INFO("apn_list setting state changed to '%s'.", value.c_str());
packetData->loadAPNSettings(value);
}
}
auto ServiceCellular::handleCellularAnswerIncomingCallMessage(CellularMessage *msg)
-> std::shared_ptr<CellularResponseMessage>
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
if (ongoingCall.getType() != CallType::CT_INCOMING) {
return std::make_shared<CellularResponseMessage>(true);
}
auto channel = cmux->get(CellularMux::Channel::Commands);
auto ret = false;
if (channel) {
auto response = channel->cmd(at::AT::ATA);
if (response) {
// Propagate "CallActive" notification into system
bus.sendMulticast(std::make_shared<CellularCallActiveNotification>(),
sys::BusChannel::ServiceCellularNotifications);
ret = true;
}
}
return std::make_shared<CellularResponseMessage>(ret);
}
auto ServiceCellular::handleCellularCallRequestMessage(CellularCallRequestMessage *msg)
-> std::shared_ptr<CellularResponseMessage>
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel == nullptr) {
return std::make_shared<CellularResponseMessage>(false);
}
cellular::RequestFactory factory(
msg->number.getEntered(), *channel, msg->callMode, Store::GSM::get()->simCardInserted());
auto request = factory.create();
CellularRequestHandler handler(*this);
auto result = channel->cmd(request->command());
request->handle(handler, result);
return std::make_shared<CellularResponseMessage>(request->isHandled());
}
void ServiceCellular::handleCellularHangupCallMessage(CellularHangupCallMessage *msg)
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
if (channel->cmd(at::AT::ATH)) {
callManager.hangUp();
callStateTimer.stop();
callEndedRecentlyTimer.start();
if (!ongoingCall.endCall(CellularCall::Forced::True)) {
LOG_ERROR("Failed to end ongoing call");
}
bus.sendMulticast(std::make_shared<CellularResponseMessage>(true, msg->type),
sys::BusChannel::ServiceCellularNotifications);
}
else {
LOG_ERROR("Call not aborted");
bus.sendMulticast(std::make_shared<CellularResponseMessage>(false, msg->type),
sys::BusChannel::ServiceCellularNotifications);
}
}
bus.sendMulticast(std::make_shared<CellularResponseMessage>(false, msg->type),
sys::BusChannel::ServiceCellularNotifications);
}
void ServiceCellular::handleCellularDismissCallMessage(sys::Message *msg)
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
auto message = static_cast<CellularDismissCallMessage *>(msg);
hangUpCall();
if (message->addNotificationRequired()) {
handleCallAbortedNotification(msg);
}
}
auto ServiceCellular::handleDBQueryResponseMessage(db::QueryResponse *msg) -> std::shared_ptr<sys::ResponseMessage>
{
bool responseHandled = false;
auto result = msg->getResult();
if (auto response = dynamic_cast<db::query::SMSSearchByTypeResult *>(result.get())) {
responseHandled = handle(response);
}
else if (result->hasListener()) {
responseHandled = result->handle();
}
if (responseHandled) {
return std::make_shared<sys::ResponseMessage>();
}
else {
return std::make_shared<sys::ResponseMessage>(sys::ReturnCodes::Unresolved);
}
}
auto ServiceCellular::handleCellularListCallsMessage(CellularMessage *msg) -> std::shared_ptr<sys::ResponseMessage>
{
at::cmd::CLCC cmd;
auto base = cmux->get(CellularMux::Channel::Commands)->cmd(cmd);
if (auto response = cmd.parseCLCC(base); response) {
const auto &data = response.getData();
auto it = std::find_if(std::begin(data), std::end(data), [&](const auto &entry) {
return entry.stateOfCall == ModemCall::CallState::Active && entry.mode == ModemCall::CallMode::Voice;
});
if (it != std::end(data)) {
auto notification = std::make_shared<CellularCallActiveNotification>();
bus.sendMulticast(std::move(notification), sys::BusChannel::ServiceCellularNotifications);
callStateTimer.stop();
return std::make_shared<CellularResponseMessage>(true);
}
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleDBNotificationMessage(db::NotificationMessage *msg) -> std::shared_ptr<sys::ResponseMessage>
{
if (msg->interface == db::Interface::Name::SMS &&
(msg->type == db::Query::Type::Create || msg->type == db::Query::Type::Update)) {
priv->outSMSHandler.handleDBNotification();
return std::make_shared<sys::ResponseMessage>();
}
return std::make_shared<sys::ResponseMessage>(sys::ReturnCodes::Failure);
}
auto ServiceCellular::handleCellularRingingMessage(CellularRingingMessage *msg) -> std::shared_ptr<sys::ResponseMessage>
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
return std::make_shared<CellularResponseMessage>(ongoingCall.startCall(msg->number, CallType::CT_OUTGOING));
}
auto ServiceCellular::handleCellularIncomingCallMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
auto ret = true;
auto message = static_cast<CellularIncominCallMessage *>(msg);
if (!ongoingCall.isValid()) {
ret = ongoingCall.startCall(message->number, CallType::CT_INCOMING);
}
return std::make_shared<CellularResponseMessage>(ret);
}
auto ServiceCellular::handleCellularCallerIdMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularCallerIdMessage *>(msg);
ongoingCall.setNumber(message->number);
return sys::MessageNone{};
}
auto ServiceCellular::handleCellularGetIMSIMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
std::string temp;
if (getIMSI(temp)) {
return std::make_shared<CellularResponseMessage>(true, temp);
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetOwnNumberMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
std::string temp;
if (getOwnNumber(temp)) {
return std::make_shared<CellularGetOwnNumberResponseMessage>(true, temp);
}
return std::make_shared<CellularGetOwnNumberResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetNetworkInfoMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = std::make_shared<cellular::RawCommandRespAsync>(CellularMessage::Type::NetworkInfoResult);
message->data = getNetworkInfo();
bus.sendUnicast(message, msg->sender);
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularSelectAntennaMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularAntennaRequestMessage *>(msg);
cmux->selectAntenna(message->antenna);
vTaskDelay(50); // sleep for 50 ms...
auto actualAntenna = cmux->getAntenna();
if (actualAntenna == bsp::cellular::antenna::lowBand) {
LOG_INFO("Low band antenna set");
}
else {
LOG_INFO("High band antenna set");
}
bool changedAntenna = (actualAntenna == message->antenna);
auto notification = std::make_shared<AntennaChangedMessage>();
bus.sendMulticast(notification, sys::BusChannel::AntennaNotifications);
return std::make_shared<CellularResponseMessage>(changedAntenna);
}
auto ServiceCellular::handleCellularSetScanModeMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularSetScanModeMessage *>(msg);
bool ret = SetScanMode(message->data);
return std::make_shared<CellularResponseMessage>(ret);
}
auto ServiceCellular::handleCellularGetScanModeMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto mode = GetScanMode();
if (mode != "") {
auto response = std::make_shared<cellular::RawCommandRespAsync>(CellularMessage::Type::GetScanModeResult);
response->data.push_back(mode);
bus.sendUnicast(response, msg->sender);
return std::make_shared<CellularResponseMessage>(true);
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetFirmwareVersionMessage(sys::Message *msg)
-> std::shared_ptr<sys::ResponseMessage>
{
std::string response;
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto resp = channel->cmd(at::AT::QGMR);
if (resp.code == at::Result::Code::OK) {
response = resp.response[0];
return std::make_shared<CellularResponseMessage>(true, response);
}
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleEVMStatusMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
using namespace bsp::cellular::status;
auto message = static_cast<sevm::StatusStateMessage *>(msg);
auto status_pin = message->state;
if (priv->modemResetHandler->handleStatusPinEvent(status_pin == value::ACTIVE)) {
return std::make_shared<CellularResponseMessage>(true);
}
if (status_pin == value::ACTIVE) {
if (priv->state->get() == State::ST::PowerUpProcedure) {
priv->state->set(State::ST::PowerUpInProgress); // and go to baud detect as usual
}
}
if (status_pin == value::INACTIVE) {
if (priv->state->get() == State::ST::PowerDownWaiting) {
priv->state->set(State::ST::PowerDown);
}
}
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularGetCsqMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto modemResponse = channel->cmd(at::AT::CSQ);
if (modemResponse.code == at::Result::Code::OK) {
return std::make_shared<CellularResponseMessage>(true, modemResponse.response[0]);
}
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetCregMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto resp = channel->cmd(at::AT::CREG);
if (resp.code == at::Result::Code::OK) {
return std::make_shared<CellularResponseMessage>(true, resp.response[0]);
}
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetNwinfoMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel) {
auto resp = channel->cmd(at::AT::QNWINFO);
if (resp.code == at::Result::Code::OK) {
return std::make_shared<CellularResponseMessage>(true, resp.response[0]);
}
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleCellularGetAntennaMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto antenna = cmux->getAntenna();
return std::make_shared<CellularAntennaResponseMessage>(true, antenna, CellularMessage::Type::GetAntenna);
}
auto ServiceCellular::handleCellularDtmfRequestMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularDtmfRequestMessage *>(msg);
auto resp = transmitDtmfTone(message->getDigit());
return std::make_shared<CellularResponseMessage>(resp);
}
auto ServiceCellular::handleCellularUSSDMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularUSSDMessage *>(msg);
return std::make_shared<CellularResponseMessage>(handleUSSDRequest(message->type, message->data));
}
auto ServiceCellular::handleStateRequestMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
change_state(dynamic_cast<cellular::StateChange *>(msg));
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCallActiveNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto ret = std::make_shared<CellularResponseMessage>(ongoingCall.setActive());
NetworkSettings networkSettings(*this);
auto currentNAT = networkSettings.getCurrentNAT();
if (currentNAT) {
auto currentSimpleNAT = NetworkSettings::toSimpleNAT(*currentNAT);
LOG_INFO("Current NAT %s(%s)",
utils::enumToString(*currentNAT).c_str(),
utils::enumToString(currentSimpleNAT).c_str());
if (currentSimpleNAT == NetworkSettings::SimpleNAT::LTE) {
LOG_INFO("VoLTE call");
}
else {
LOG_INFO("Non VoLTE call");
}
}
else {
LOG_WARN("Cannot get current NAT");
}
return ret;
}
auto ServiceCellular::handleCallAbortedNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
callStateTimer.stop();
auto ret = ongoingCall.endCall();
callManager.hangUp();
return std::make_shared<CellularResponseMessage>(ret);
}
auto ServiceCellular::handlePowerUpProcedureCompleteNotification(sys::Message *msg)
-> std::shared_ptr<sys::ResponseMessage>
{
if (board == bsp::Board::Linux) {
priv->state->set(State::ST::CellularConfProcedure);
}
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handlePowerDownDeregisteringNotification(sys::Message *msg)
-> std::shared_ptr<sys::ResponseMessage>
{
if (priv->state->get() != State::ST::PowerDownWaiting) {
priv->state->set(State::ST::PowerDownStarted);
return std::make_shared<CellularResponseMessage>(true);
}
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handlePowerDownDeregisteredNotification(sys::Message *msg)
-> std::shared_ptr<sys::ResponseMessage>
{
priv->state->set(State::ST::PowerDownWaiting);
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleNewIncomingSMSNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto message = static_cast<CellularNewIncomingSMSNotification *>(msg);
auto notification = std::make_shared<CellularNewIncomingSMSMessage>(message->data);
bus.sendUnicast(std::move(notification), msg->sender);
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleSmsDoneNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto resp = handleTextMessagesInit();
return std::make_shared<CellularResponseMessage>(resp);
}
auto ServiceCellular::handleSignalStrengthUpdateNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleNetworkStatusUpdateNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
return std::make_shared<CellularResponseMessage>(false);
}
auto ServiceCellular::handleUrcIncomingNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
// when handling URC, the CPU frequency does not go below a certain level
cpuSentinel->HoldMinimumFrequency(bsp::CpuFrequencyHz::Level_4);
cmux->exitSleepMode();
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularSetFlightModeMessage(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
auto setMsg = static_cast<CellularSetFlightModeMessage *>(msg);
settings->setValue(
settings::Cellular::offlineMode, std::to_string(setMsg->flightModeOn), settings::SettingsScope::Global);
connectionManager->setFlightMode(setMsg->flightModeOn);
connectionManager->onPhoneModeChange(phoneModeObserver->getCurrentPhoneMode());
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularRingNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
LOG_INFO("%s", __PRETTY_FUNCTION__);
if (phoneModeObserver->isTetheringOn() || connectionManager->forceDismissCalls()) {
return std::make_shared<CellularResponseMessage>(hangUpCall());
}
if (!callManager.isIncomingCallPropagated()) {
auto message = static_cast<CellularRingNotification *>(msg);
bus.sendMulticast(std::make_shared<CellularIncominCallMessage>(message->getNubmer()),
sys::BusChannel::ServiceCellularNotifications);
callManager.ring();
}
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularCallerIdNotification(sys::Message *msg) -> std::shared_ptr<sys::ResponseMessage>
{
if (connectionManager->forceDismissCalls()) {
return std::make_shared<CellularResponseMessage>(hangUpCall());
}
auto message = static_cast<CellularCallerIdNotification *>(msg);
if (phoneModeObserver->isTetheringOn()) {
tetheringCalllog.push_back(CalllogRecord{CallType::CT_MISSED, message->getNubmer()});
return std::make_shared<CellularResponseMessage>(hangUpCallBusy());
}
if (!callManager.isCallerInfoComplete()) {
bus.sendMulticast(std::make_shared<CellularCallerIdMessage>(message->getNubmer()),
sys::BusChannel::ServiceCellularNotifications);
callManager.completeCallerInfo();
}
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::handleCellularSetConnectionFrequencyMessage(sys::Message *msg)
-> std::shared_ptr<sys::ResponseMessage>
{
auto setMsg = static_cast<CellularSetConnectionFrequencyMessage *>(msg);
settings->setValue(settings::Offline::connectionFrequency,
std::to_string(setMsg->getConnectionFrequency()),
settings::SettingsScope::Global);
connectionManager->setInterval(std::chrono::minutes{setMsg->getConnectionFrequency()});
connectionManager->onPhoneModeChange(phoneModeObserver->getCurrentPhoneMode());
return std::make_shared<CellularResponseMessage>(true);
}
auto ServiceCellular::hangUpCall() -> bool
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel != nullptr) {
if (channel->cmd(at::factory(at::AT::ATH))) {
callManager.hangUp();
return true;
}
}
LOG_ERROR("Failed to hang up call");
return false;
}
auto ServiceCellular::hangUpCallBusy() -> bool
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel != nullptr) {
if (channel->cmd(at::factory(at::AT::QHUP_BUSY))) {
return true;
}
}
LOG_ERROR("Failed to hang up call");
return false;
}
auto ServiceCellular::tetheringTurnOffURC() -> bool
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel != nullptr) {
if (!channel->cmd(at::factory(at::AT::CSQ_URC_OFF))) {
LOG_ERROR("Failed to stop CSQ URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::ACT_URC_OFF))) {
LOG_ERROR("Failed to stop ACT URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::SMS_URC_OFF))) {
LOG_ERROR("Failed to stop SMS URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::RING_URC_OFF))) {
LOG_ERROR("Failed to stop RING URC");
return false;
}
}
return true;
}
auto ServiceCellular::tetheringTurnOnURC() -> bool
{
auto channel = cmux->get(CellularMux::Channel::Commands);
if (channel != nullptr) {
if (!channel->cmd(at::factory(at::AT::CSQ_URC_ON))) {
LOG_ERROR("Failed to stop CSQ URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::ACT_URC_ON))) {
LOG_ERROR("Failed to stop ACT URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::SMS_URC_ON))) {
LOG_ERROR("Failed to stop SMS URC");
return false;
}
if (!channel->cmd(at::factory(at::AT::RING_URC_ON))) {
LOG_ERROR("Failed to stop RING URC");
return false;
}
}
return true;
}
auto ServiceCellular::logTetheringCalls() -> void
{
if (!tetheringCalllog.empty()) {
for (auto callRecord : tetheringCalllog) {
auto call = DBServiceAPI::CalllogAdd(this, callRecord);
if (call.ID == DB_ID_NONE) {
LOG_ERROR("CalllogAdd failed");
}
}
std::vector<utils::PhoneNumber::View> numbers;
for (auto calllogRecord : tetheringCalllog) {
numbers.push_back(calllogRecord.phoneNumber);
}
DBServiceAPI::GetQuery(
this,
db::Interface::Name::Notifications,
std::make_unique<db::query::notifications::MultipleIncrement>(NotificationsRecord::Key::Calls, numbers));
tetheringCalllog.clear();
}
}
TaskHandle_t ServiceCellular::getTaskHandle()
{
return xTaskGetCurrentTaskHandle();
}
| 36.768827 | 126 | 0.651643 | SP2FET |
8b2bbd9da35d3774d949b40fdc27ec6110b0762c | 20,461 | hpp | C++ | boost/lib/include/boost/asio/impl/compose.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 177 | 2021-02-19T02:01:04.000Z | 2022-03-30T07:31:21.000Z | boost/lib/include/boost/asio/impl/compose.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 188 | 2021-02-19T04:15:55.000Z | 2022-03-26T09:42:15.000Z | boost/lib/include/boost/asio/impl/compose.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 78 | 2021-03-05T03:01:13.000Z | 2022-03-29T07:10:01.000Z | //
// impl/compose.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 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)
//
#ifndef BOOST_ASIO_IMPL_COMPOSE_HPP
#define BOOST_ASIO_IMPL_COMPOSE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_cont_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/detail/variadic_templates.hpp>
#include <boost/asio/execution/executor.hpp>
#include <boost/asio/execution/outstanding_work.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/asio/is_executor.hpp>
#include <boost/asio/system_executor.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail
{
template <typename Executor, typename = void>
class composed_work_guard
{
public:
typedef typename decay<
typename prefer_result<Executor,
execution::outstanding_work_t::tracked_t
>::type
>::type executor_type;
composed_work_guard(const Executor& ex)
: executor_(boost::asio::prefer(ex, execution::outstanding_work.tracked))
{
}
void reset()
{
}
executor_type get_executor() const BOOST_ASIO_NOEXCEPT
{
return executor_;
}
private:
executor_type executor_;
};
#if !defined(BOOST_ASIO_NO_TS_EXECUTORS)
template <typename Executor>
struct composed_work_guard<Executor,
typename enable_if<
!execution::is_executor<Executor>::value
>::type> : executor_work_guard<Executor>
{
composed_work_guard(const Executor& ex)
: executor_work_guard<Executor>(ex)
{
}
};
#endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS)
template <typename>
struct composed_io_executors;
template <>
struct composed_io_executors<void()>
{
composed_io_executors() BOOST_ASIO_NOEXCEPT
: head_(system_executor())
{
}
typedef system_executor head_type;
system_executor head_;
};
inline composed_io_executors<void()> make_composed_io_executors()
{
return composed_io_executors<void()>();
}
template <typename Head>
struct composed_io_executors<void(Head)>
{
explicit composed_io_executors(const Head& ex) BOOST_ASIO_NOEXCEPT
: head_(ex)
{
}
typedef Head head_type;
Head head_;
};
template <typename Head>
inline composed_io_executors<void(Head)>
make_composed_io_executors(const Head& head)
{
return composed_io_executors<void(Head)>(head);
}
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename Head, typename... Tail>
struct composed_io_executors<void(Head, Tail...)>
{
explicit composed_io_executors(const Head& head,
const Tail&... tail) BOOST_ASIO_NOEXCEPT
: head_(head),
tail_(tail...)
{
}
void reset()
{
head_.reset();
tail_.reset();
}
typedef Head head_type;
Head head_;
composed_io_executors<void(Tail...)> tail_;
};
template <typename Head, typename... Tail>
inline composed_io_executors<void(Head, Tail...)>
make_composed_io_executors(const Head& head, const Tail&... tail)
{
return composed_io_executors<void(Head, Tail...)>(head, tail...);
}
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#define BOOST_ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF(n) \
template <typename Head, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
struct composed_io_executors<void(Head, BOOST_ASIO_VARIADIC_TARGS(n))> \
{ \
explicit composed_io_executors(const Head& head, \
BOOST_ASIO_VARIADIC_CONSTREF_PARAMS(n)) BOOST_ASIO_NOEXCEPT \
: head_(head), \
tail_(BOOST_ASIO_VARIADIC_BYVAL_ARGS(n)) \
{ \
} \
\
void reset() \
{ \
head_.reset(); \
tail_.reset(); \
} \
\
typedef Head head_type; \
Head head_; \
composed_io_executors<void(BOOST_ASIO_VARIADIC_TARGS(n))> tail_; \
}; \
\
template <typename Head, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
inline composed_io_executors<void(Head, BOOST_ASIO_VARIADIC_TARGS(n))> \
make_composed_io_executors(const Head& head, \
BOOST_ASIO_VARIADIC_CONSTREF_PARAMS(n)) \
{ \
return composed_io_executors< \
void(Head, BOOST_ASIO_VARIADIC_TARGS(n))>( \
head, BOOST_ASIO_VARIADIC_BYVAL_ARGS(n)); \
} \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF)
#undef BOOST_ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename>
struct composed_work;
template <>
struct composed_work<void()>
{
typedef composed_io_executors<void()> executors_type;
composed_work(const executors_type&) BOOST_ASIO_NOEXCEPT
: head_(system_executor())
{
}
void reset()
{
head_.reset();
}
typedef system_executor head_type;
composed_work_guard<system_executor> head_;
};
template <typename Head>
struct composed_work<void(Head)>
{
typedef composed_io_executors<void(Head)> executors_type;
explicit composed_work(const executors_type& ex) BOOST_ASIO_NOEXCEPT
: head_(ex.head_)
{
}
void reset()
{
head_.reset();
}
typedef Head head_type;
composed_work_guard<Head> head_;
};
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename Head, typename... Tail>
struct composed_work<void(Head, Tail...)>
{
typedef composed_io_executors<void(Head, Tail...)> executors_type;
explicit composed_work(const executors_type& ex) BOOST_ASIO_NOEXCEPT
: head_(ex.head_),
tail_(ex.tail_)
{
}
void reset()
{
head_.reset();
tail_.reset();
}
typedef Head head_type;
composed_work_guard<Head> head_;
composed_work<void(Tail...)> tail_;
};
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#define BOOST_ASIO_PRIVATE_COMPOSED_WORK_DEF(n) \
template <typename Head, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
struct composed_work<void(Head, BOOST_ASIO_VARIADIC_TARGS(n))> \
{ \
typedef composed_io_executors<void(Head, \
BOOST_ASIO_VARIADIC_TARGS(n))> executors_type; \
\
explicit composed_work(const executors_type& ex) BOOST_ASIO_NOEXCEPT \
: head_(ex.head_), \
tail_(ex.tail_) \
{ \
} \
\
void reset() \
{ \
head_.reset(); \
tail_.reset(); \
} \
\
typedef Head head_type; \
composed_work_guard<Head> head_; \
composed_work<void(BOOST_ASIO_VARIADIC_TARGS(n))> tail_; \
}; \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_COMPOSED_WORK_DEF)
#undef BOOST_ASIO_PRIVATE_COMPOSED_WORK_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename Impl, typename Work, typename Handler, typename Signature>
class composed_op;
template <typename Impl, typename Work, typename Handler,
typename R, typename... Args>
class composed_op<Impl, Work, Handler, R(Args...)>
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename Impl, typename Work, typename Handler, typename Signature>
class composed_op
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
{
public:
template <typename I, typename W, typename H>
composed_op(BOOST_ASIO_MOVE_ARG(I) impl,
BOOST_ASIO_MOVE_ARG(W) work,
BOOST_ASIO_MOVE_ARG(H) handler)
: impl_(BOOST_ASIO_MOVE_CAST(I)(impl)),
work_(BOOST_ASIO_MOVE_CAST(W)(work)),
handler_(BOOST_ASIO_MOVE_CAST(H)(handler)),
invocations_(0)
{
}
#if defined(BOOST_ASIO_HAS_MOVE)
composed_op(composed_op&& other)
: impl_(BOOST_ASIO_MOVE_CAST(Impl)(other.impl_)),
work_(BOOST_ASIO_MOVE_CAST(Work)(other.work_)),
handler_(BOOST_ASIO_MOVE_CAST(Handler)(other.handler_)),
invocations_(other.invocations_)
{
}
#endif // defined(BOOST_ASIO_HAS_MOVE)
typedef typename associated_executor<Handler,
typename composed_work_guard<
typename Work::head_type
>::executor_type
>::type executor_type;
executor_type get_executor() const BOOST_ASIO_NOEXCEPT
{
return (get_associated_executor)(handler_, work_.head_.get_executor());
}
typedef typename associated_allocator<Handler,
std::allocator<void> >::type allocator_type;
allocator_type get_allocator() const BOOST_ASIO_NOEXCEPT
{
return (get_associated_allocator)(handler_, std::allocator<void>());
}
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template<typename... T>
void operator()(BOOST_ASIO_MOVE_ARG(T)... t)
{
if (invocations_ < ~0u)
++invocations_;
impl_(*this, BOOST_ASIO_MOVE_CAST(T)(t)...);
}
void complete(Args... args)
{
this->work_.reset();
this->handler_(BOOST_ASIO_MOVE_CAST(Args)(args)...);
}
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
void operator()()
{
if (invocations_ < ~0u)
++invocations_;
impl_(*this);
}
void complete()
{
this->work_.reset();
this->handler_();
}
#define BOOST_ASIO_PRIVATE_COMPOSED_OP_DEF(n) \
template<BOOST_ASIO_VARIADIC_TPARAMS(n)> \
void operator()(BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) \
{ \
if (invocations_ < ~0u) \
++invocations_; \
impl_(*this, BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
\
template<BOOST_ASIO_VARIADIC_TPARAMS(n)> \
void complete(BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) \
{ \
this->work_.reset(); \
this->handler_(BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_COMPOSED_OP_DEF)
#undef BOOST_ASIO_PRIVATE_COMPOSED_OP_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
//private:
Impl impl_;
Work work_;
Handler handler_;
unsigned invocations_;
};
template <typename Impl, typename Work, typename Handler, typename Signature>
inline asio_handler_allocate_is_deprecated
asio_handler_allocate(std::size_t size,
composed_op<Impl, Work, Handler, Signature>* this_handler)
{
#if defined(BOOST_ASIO_NO_DEPRECATED)
boost_asio_handler_alloc_helpers::allocate(size, this_handler->handler_);
return asio_handler_allocate_is_no_longer_used();
#else // defined(BOOST_ASIO_NO_DEPRECATED)
return boost_asio_handler_alloc_helpers::allocate(
size, this_handler->handler_);
#endif // defined(BOOST_ASIO_NO_DEPRECATED)
}
template <typename Impl, typename Work, typename Handler, typename Signature>
inline asio_handler_deallocate_is_deprecated
asio_handler_deallocate(void* pointer, std::size_t size,
composed_op<Impl, Work, Handler, Signature>* this_handler)
{
boost_asio_handler_alloc_helpers::deallocate(
pointer, size, this_handler->handler_);
#if defined(BOOST_ASIO_NO_DEPRECATED)
return asio_handler_deallocate_is_no_longer_used();
#endif // defined(BOOST_ASIO_NO_DEPRECATED)
}
template <typename Impl, typename Work, typename Handler, typename Signature>
inline bool asio_handler_is_continuation(
composed_op<Impl, Work, Handler, Signature>* this_handler)
{
return this_handler->invocations_ > 1 ? true
: boost_asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Function, typename Impl,
typename Work, typename Handler, typename Signature>
inline asio_handler_invoke_is_deprecated
asio_handler_invoke(Function& function,
composed_op<Impl, Work, Handler, Signature>* this_handler)
{
boost_asio_handler_invoke_helpers::invoke(
function, this_handler->handler_);
#if defined(BOOST_ASIO_NO_DEPRECATED)
return asio_handler_invoke_is_no_longer_used();
#endif // defined(BOOST_ASIO_NO_DEPRECATED)
}
template <typename Function, typename Impl,
typename Work, typename Handler, typename Signature>
inline asio_handler_invoke_is_deprecated
asio_handler_invoke(const Function& function,
composed_op<Impl, Work, Handler, Signature>* this_handler)
{
boost_asio_handler_invoke_helpers::invoke(
function, this_handler->handler_);
#if defined(BOOST_ASIO_NO_DEPRECATED)
return asio_handler_invoke_is_no_longer_used();
#endif // defined(BOOST_ASIO_NO_DEPRECATED)
}
template <typename Signature, typename Executors>
class initiate_composed_op
{
public:
typedef typename composed_io_executors<Executors>::head_type executor_type;
template <typename T>
explicit initiate_composed_op(int, BOOST_ASIO_MOVE_ARG(T) executors)
: executors_(BOOST_ASIO_MOVE_CAST(T)(executors))
{
}
executor_type get_executor() const BOOST_ASIO_NOEXCEPT
{
return executors_.head_;
}
template <typename Handler, typename Impl>
void operator()(BOOST_ASIO_MOVE_ARG(Handler) handler,
BOOST_ASIO_MOVE_ARG(Impl) impl) const
{
composed_op<typename decay<Impl>::type, composed_work<Executors>,
typename decay<Handler>::type, Signature>(
BOOST_ASIO_MOVE_CAST(Impl)(impl),
composed_work<Executors>(executors_),
BOOST_ASIO_MOVE_CAST(Handler)(handler))();
}
private:
composed_io_executors<Executors> executors_;
};
template <typename Signature, typename Executors>
inline initiate_composed_op<Signature, Executors> make_initiate_composed_op(
BOOST_ASIO_MOVE_ARG(composed_io_executors<Executors>) executors)
{
return initiate_composed_op<Signature, Executors>(0,
BOOST_ASIO_MOVE_CAST(composed_io_executors<Executors>)(executors));
}
template <typename IoObject>
inline typename IoObject::executor_type
get_composed_io_executor(IoObject& io_object,
typename enable_if<
!is_executor<IoObject>::value
&& !execution::is_executor<IoObject>::value
>::type* = 0)
{
return io_object.get_executor();
}
template <typename Executor>
inline const Executor& get_composed_io_executor(const Executor& ex,
typename enable_if<
is_executor<Executor>::value
|| execution::is_executor<Executor>::value
>::type* = 0)
{
return ex;
}
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename CompletionToken, typename Signature,
typename Implementation, typename... IoObjectsOrExecutors>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature)
async_compose(BOOST_ASIO_MOVE_ARG(Implementation) implementation,
BOOST_ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token,
BOOST_ASIO_MOVE_ARG(IoObjectsOrExecutors)... io_objects_or_executors)
{
return async_initiate<CompletionToken, Signature>(
detail::make_initiate_composed_op<Signature>(
detail::make_composed_io_executors(
detail::get_composed_io_executor(
BOOST_ASIO_MOVE_CAST(IoObjectsOrExecutors)(
io_objects_or_executors))...)),
token, BOOST_ASIO_MOVE_CAST(Implementation)(implementation));
}
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename CompletionToken, typename Signature, typename Implementation>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature)
async_compose(BOOST_ASIO_MOVE_ARG(Implementation) implementation,
BOOST_ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token)
{
return async_initiate<CompletionToken, Signature>(
detail::make_initiate_composed_op<Signature>(
detail::make_composed_io_executors()),
token, BOOST_ASIO_MOVE_CAST(Implementation)(implementation));
}
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR(n) \
BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_##n
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_1 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_2 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_3 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_4 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T4)(x4))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_5 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T4)(x4)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T5)(x5))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_6 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T4)(x4)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T5)(x5)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T6)(x6))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_7 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T4)(x4)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T5)(x5)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T6)(x6)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T7)(x7))
# define BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_8 \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T1)(x1)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T2)(x2)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T3)(x3)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T4)(x4)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T5)(x5)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T6)(x6)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T7)(x7)), \
detail::get_composed_io_executor(BOOST_ASIO_MOVE_CAST(T8)(x8))
#define BOOST_ASIO_PRIVATE_ASYNC_COMPOSE_DEF(n) \
template <typename CompletionToken, typename Signature, \
typename Implementation, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) \
async_compose(BOOST_ASIO_MOVE_ARG(Implementation) implementation, \
BOOST_ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, \
BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) \
{ \
return async_initiate<CompletionToken, Signature>( \
detail::make_initiate_composed_op<Signature>( \
detail::make_composed_io_executors( \
BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR(n))), \
token, BOOST_ASIO_MOVE_CAST(Implementation)(implementation)); \
} \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_ASYNC_COMPOSE_DEF)
#undef BOOST_ASIO_PRIVATE_ASYNC_COMPOSE_DEF
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_1
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_2
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_3
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_4
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_5
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_6
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_7
#undef BOOST_ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_8
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_IMPL_COMPOSE_HPP
| 32.070533 | 80 | 0.740335 | mamil |
8b2dc994901a53642a4b7d3101ba4968a5d21caa | 4,922 | cpp | C++ | GridGenerator/GridGenerator.cpp | Izay0i/SuperMarioBros3 | 46d254aa1ae4396175145d9743932c5c4fbf1763 | [
"MIT"
] | 1 | 2020-11-09T09:08:02.000Z | 2020-11-09T09:08:02.000Z | GridGenerator/GridGenerator.cpp | Izay0i/SuperMarioBros3 | 46d254aa1ae4396175145d9743932c5c4fbf1763 | [
"MIT"
] | null | null | null | GridGenerator/GridGenerator.cpp | Izay0i/SuperMarioBros3 | 46d254aa1ae4396175145d9743932c5c4fbf1763 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
//const unsigned int SCREEN_WIDTH = 256;
//const unsigned int SCREEN_HEIGHT = 224;
const unsigned int SCREEN_WIDTH = 500;
const unsigned int SCREEN_HEIGHT = 500;
const unsigned int CELL_WIDTH = SCREEN_WIDTH;
const unsigned int CELL_HEIGHT = SCREEN_HEIGHT;
//const unsigned int CELL_WIDTH = static_cast<unsigned int>(SCREEN_WIDTH / 2);
//const unsigned int CELL_HEIGHT = static_cast<unsigned int>(SCREEN_HEIGHT / 2);
const unsigned int MAX_FILE_LINE = 5000;
bool wroteTagOnce = false;
unsigned int xCells = 0, yCells = 0;
enum class GridFileSection {
GRIDFILE_SECTION_UNKNOWN,
GRIDFILE_SECTION_SCENESIZE,
GRIDFILE_SECTION_ENTITYDATA
};
std::vector<std::string> SplitStr(std::string line, std::string delimeter = "\t") {
std::vector<std::string> tokens;
size_t last = 0, next = 0;
while ((next = line.find(delimeter, last)) != std::string::npos) {
tokens.push_back(line.substr(last, next - last));
last = next + 1;
}
tokens.push_back(line.substr(last));
return tokens;
}
void ParseSceneSize(std::ofstream& outFile, std::string line) {
std::vector<std::string> tokens = SplitStr(line);
if (tokens.size() < 2) {
return;
}
unsigned int sceneWidth = std::stoul(tokens.at(0));
unsigned int sceneHeight = std::stoul(tokens.at(1));
//Do float division and then ceil the value to get an extra row and column offscreen
//Then cast it to unsigned int to truncate the decimals
xCells = static_cast<unsigned int>(ceil((static_cast<float>(sceneWidth) / CELL_WIDTH)));
yCells = static_cast<unsigned int>(ceil((static_cast<float>(sceneHeight) / CELL_HEIGHT)));
//Be sure to use std::flush or std::endl to flush the buffer
outFile << "[GRIDCELLS]\n";
outFile << xCells << '\t' << yCells << '\n';
outFile << "[/]\n\n";
}
void ParseEntityData(std::ofstream& outFile, std::string line) {
std::vector<std::string> tokens = SplitStr(line);
if (tokens.size() < 5) {
return;
}
float posX = std::stof(tokens.at(3));
float posY = std::stof(tokens.at(4));
unsigned int objectID = std::stoul(tokens.at(0));
//Convert world space to cell space
unsigned int cellPosX = static_cast<unsigned int>(posX / CELL_WIDTH);
unsigned int cellPosY = static_cast<unsigned int>(posY / CELL_HEIGHT);
if (cellPosX < 0) {
cellPosX = 0;
}
else if (cellPosX >= xCells) {
cellPosX = xCells - 1;
}
if (cellPosY < 0) {
cellPosY = 0;
}
else if (cellPosY >= yCells) {
cellPosY = yCells - 1;
}
if (!wroteTagOnce) {
wroteTagOnce = true;
outFile << "#objID" << '\t' << "Cell_X" << '\t' << "Cell_Y\n";
outFile << "[POSITIONS]\n";
}
outFile << objectID << '\t' << cellPosX << '\t' << cellPosY << '\n';
}
int main() {
std::string file = "stage_fortress.txt";
std::ofstream outputFile("grid_stage_fortress.txt");
outputFile.clear();
std::ifstream readFile;
readFile.open(file, std::ios::in);
if (!readFile.is_open()) {
std::cout << "[GRID GENERATOR] Failed to read file\n";
return -1;
}
GridFileSection gridFileSection = GridFileSection::GRIDFILE_SECTION_UNKNOWN;
char str[MAX_FILE_LINE];
while (readFile.getline(str, MAX_FILE_LINE)) {
std::string line(str);
if (line.empty() || line.front() == '#') {
continue;
}
if (line == "[/]") {
gridFileSection = GridFileSection::GRIDFILE_SECTION_UNKNOWN;
continue;
}
if (line == "[SCENESIZE]") {
gridFileSection = GridFileSection::GRIDFILE_SECTION_SCENESIZE;
continue;
}
if (line == "[ENTITYDATA]") {
gridFileSection = GridFileSection::GRIDFILE_SECTION_ENTITYDATA;
continue;
}
switch (gridFileSection) {
case GridFileSection::GRIDFILE_SECTION_SCENESIZE:
ParseSceneSize(outputFile, line);
break;
case GridFileSection::GRIDFILE_SECTION_ENTITYDATA:
ParseEntityData(outputFile, line);
break;
}
}
//Add closing tag
outputFile << "[/]" << std::flush;
readFile.close();
std::cout << xCells << '\t' << yCells << std::endl;
/*unsigned int width = 240;
unsigned int height = 32;
unsigned int offset = 16;
unsigned int starting_x = 1856;
unsigned int starting_y = 752;
char format[] = "231\t34\t247\t50\t%u\t%u\n";
char debug[100];
for (unsigned int i = 0; i < width; i += offset) {
for (unsigned int j = 0; j < height; j += offset) {
sprintf_s(debug, format, starting_x + i, starting_y + j);
OutputDebugStringA(debug);
}
}*/
return 0;
} | 28.287356 | 94 | 0.609102 | Izay0i |
8b303d6788c9887d1bc1f67344ad5b24afa0316d | 8,330 | cpp | C++ | src/mame/drivers/spg2xx_shredmjr.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/spg2xx_shredmjr.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/spg2xx_shredmjr.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Ryan Holtz, David Haywood
#include "emu.h"
#include "includes/spg2xx.h"
class shredmjr_game_state : public spg2xx_game_state
{
public:
shredmjr_game_state(const machine_config &mconfig, device_type type, const char *tag) :
spg2xx_game_state(mconfig, type, tag),
m_porta_data(0x0000),
m_shiftamount(0)
{ }
void shredmjr(machine_config &config);
void taikeegr(machine_config &config);
void taikeegrp(machine_config &config);
void init_taikeegr();
protected:
uint16_t porta_r();
virtual void porta_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0) override;
private:
uint16_t m_porta_data;
int m_shiftamount;
};
// Shredmaster Jr uses the same input order as the regular Taikee Guitar, but reads all inputs through a single multiplexed bit
void shredmjr_game_state::porta_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
if (data != m_porta_data)
{
if ((data & 0x0800) != (m_porta_data & 0x0800))
{
if (data & 0x0800)
{
//logerror("0x0800 low -> high\n");
}
else
{
//logerror("0x0800 high -> low\n");
}
}
if ((data & 0x0200) != (m_porta_data & 0x0200))
{
if (data & 0x0200)
{
//logerror("0x0200 low -> high\n");
m_shiftamount++;
}
else
{
//logerror("0x0200 high -> low\n");
}
}
if ((data & 0x0100) != (m_porta_data & 0x0100))
{
if (data & 0x0100)
{
//logerror("0x0100 low -> high\n");
m_shiftamount = 0;
}
else
{
//logerror("0x0100 high -> low\n");
}
}
}
m_porta_data = data;
}
uint16_t shredmjr_game_state::porta_r()
{
//logerror("porta_r with shift amount %d \n", m_shiftamount);
uint16_t ret = 0x0000;
uint16_t portdata = m_io_p1->read();
portdata = (portdata >> m_shiftamount) & 0x1;
if (portdata)
ret |= 0x0400;
return ret;
}
static INPUT_PORTS_START( taikeegr )
PORT_START("P1")
PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("Strum Bar Down")
PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("Strum Bar Up")
PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_NAME("Whamming Bar")
PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Yellow")
PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_NAME("Green")
PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Red")
PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Blue")
PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_NAME("Pink")
PORT_BIT( 0xff00, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("P2")
PORT_BIT( 0xffff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("P3")
PORT_BIT( 0xffff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
static INPUT_PORTS_START( guitarstp )
PORT_START("P1")
PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_NAME("Strum Bar Down")
PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_NAME("Strum Bar Up")
PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_NAME("Whamming Bar")
PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Yellow")
PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_NAME("Blue")
PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Red")
PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Green")
PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_NAME("Orange")
PORT_BIT( 0xff00, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("P2")
PORT_BIT( 0xffff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("P3")
PORT_BIT( 0xffff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
void shredmjr_game_state::shredmjr(machine_config &config)
{
SPG24X(config, m_maincpu, XTAL(27'000'000), m_screen);
m_maincpu->set_addrmap(AS_PROGRAM, &shredmjr_game_state::mem_map_4m);
spg2xx_base(config);
m_maincpu->porta_in().set(FUNC(shredmjr_game_state::porta_r));
m_maincpu->porta_out().set(FUNC(shredmjr_game_state::porta_w));
}
void shredmjr_game_state::taikeegr(machine_config &config)
{
SPG24X(config, m_maincpu, XTAL(27'000'000), m_screen);
m_maincpu->set_addrmap(AS_PROGRAM, &shredmjr_game_state::mem_map_4m);
spg2xx_base(config);
m_maincpu->porta_in().set_ioport("P1");
}
void shredmjr_game_state::taikeegrp(machine_config &config)
{
taikeegr(config);
m_maincpu->set_pal(true);
m_screen->set_refresh_hz(50);
}
void shredmjr_game_state::init_taikeegr()
{
u16 *src = (u16*)memregion("maincpu")->base();
for (int i = 0x00000; i < 0x800000/2; i++)
{
u16 dat = src[i];
dat = bitswap<16>(dat, 15,14,13,12, 11,10,9,8, 7,6,5,4, 0,1,2,3 );
src[i] = dat;
}
std::vector<u16> buffer(0x800000/2);
for (int i = 0; i < 0x800000/2; i++)
{
int j = 0;
switch (i & 0x00e00)
{
case 0x00000: j = (i & 0xfff1ff) | 0x000; break;
case 0x00200: j = (i & 0xfff1ff) | 0x800; break;
case 0x00400: j = (i & 0xfff1ff) | 0x400; break;
case 0x00600: j = (i & 0xfff1ff) | 0xc00; break;
case 0x00800: j = (i & 0xfff1ff) | 0x200; break;
case 0x00a00: j = (i & 0xfff1ff) | 0xa00; break;
case 0x00c00: j = (i & 0xfff1ff) | 0x600; break;
case 0x00e00: j = (i & 0xfff1ff) | 0xe00; break;
}
buffer[j] = src[i];
}
std::copy(buffer.begin(), buffer.end(), &src[0]);
}
ROM_START( taikeegr )
ROM_REGION( 0x800000, "maincpu", ROMREGION_ERASE00 )
ROM_LOAD16_WORD_SWAP( "taikee_guitar.bin", 0x000000, 0x800000, CRC(8cbe2feb) SHA1(d72e816f259ba6a6260d6bbaf20c5e9b2cf7140b) )
ROM_END
ROM_START( rockstar )
ROM_REGION( 0x800000, "maincpu", ROMREGION_ERASE00 )
ROM_LOAD16_WORD_SWAP( "29gl064.bin", 0x000000, 0x800000, CRC(40de50ff) SHA1(b33ae7a3d32911addf833998d7419f4830be5a07) )
ROM_END
ROM_START( shredmjr )
ROM_REGION( 0x800000, "maincpu", ROMREGION_ERASE00 )
ROM_LOAD16_WORD_SWAP( "shredmasterjr.bin", 0x000000, 0x800000, CRC(95a6dcf1) SHA1(44893cd6ebe6b7f33a73817b72ae7be70c3126dc) )
ROM_END
ROM_START( guitarst )
ROM_REGION( 0x800000, "maincpu", ROMREGION_ERASE00 )
ROM_LOAD16_WORD_SWAP( "guitarstar_s29gl064m11tfir4_0001227e.bin", 0x000000, 0x800000, CRC(feaace47) SHA1(dd426bb4f03a16b1b96b63b4e0d79ea75097bf72) )
ROM_END
ROM_START( guitarstp )
ROM_REGION( 0x800000, "maincpu", ROMREGION_ERASE00 )
ROM_LOAD16_WORD_SWAP( "29gl064.u2", 0x000000, 0x800000, CRC(1dbcff73) SHA1(b179e4da6f38e7d5ec796bf846a63492d30eb0f5) )
ROM_END
// These were all sold as different products, use a different sets of songs / presentation styles (2D or perspective gameplay, modified titlescreens etc.)
// and sometimes even slightly different hardware, so aren't set as clones of each other
// box title not confirmed, Guitar Rock on title screen, has Bon Jovi etc.
CONS( 2007, taikeegr, 0, 0, taikeegrp, taikeegr, shredmjr_game_state, init_taikeegr, "TaiKee", "Guitar Rock (PAL)", MACHINE_IMPERFECT_TIMING | MACHINE_IMPERFECT_SOUND | MACHINE_IMPERFECT_GRAPHICS ) // timing not quite correct yet
// Plug 'N' Play Rockstar Guitar on box, Guitar Rock on title screen, has Manic Street Preachers etc.
CONS( 2007, rockstar, 0, 0, taikeegrp, taikeegr, shredmjr_game_state, init_taikeegr, "Ultimate Products / TaiKee", "Plug 'N' Play Rockstar Guitar / Guitar Rock (PAL)", MACHINE_IMPERFECT_TIMING | MACHINE_IMPERFECT_SOUND | MACHINE_IMPERFECT_GRAPHICS ) // timing not quite correct yet
// dreamGEAR branded presentation, modified hardware (buttons read in a different way) same song seletion as taikeegr
CONS( 2007, shredmjr, 0, 0, shredmjr, taikeegr, shredmjr_game_state, init_taikeegr, "dreamGEAR", "Shredmaster Jr (NTSC)", MACHINE_IMPERFECT_TIMING | MACHINE_IMPERFECT_SOUND | MACHINE_IMPERFECT_GRAPHICS ) // ^
// doesn't have a Senario logo ingame, but does on box. unique song selection
CONS( 200?, guitarst, 0, 0, taikeegr, taikeegr, shredmjr_game_state, init_taikeegr, "Senario", "Guitar Star (US, Senario, NTSC)", MACHINE_IMPERFECT_TIMING | MACHINE_IMPERFECT_SOUND | MACHINE_IMPERFECT_GRAPHICS ) // ^
// This one has the same songs as 'rockstar' but different game style / presentation.
// Unit found in Ireland "imported by Cathay Product Sourcing Ltd." on the box, with address in Ireland
// ITEM #01109 on instruction sheet, no manufacturer named on either box or instructions
CONS( 200?, guitarstp, 0, 0, taikeegrp, guitarstp,shredmjr_game_state, init_taikeegr, "<unknown>", "Guitar Star (Europe, PAL)", MACHINE_IMPERFECT_TIMING | MACHINE_IMPERFECT_SOUND | MACHINE_IMPERFECT_GRAPHICS ) // ^
| 33.32 | 301 | 0.72509 | Robbbert |
8b3114c6134d5018fee2d93708f7a6ce984dc7e6 | 2,625 | cpp | C++ | src/test/pq/notifications.cpp | skaae/taopq | a621cbba1f63c599819466f3da7ef7d352bdaf0d | [
"BSL-1.0"
] | 142 | 2018-12-10T10:12:50.000Z | 2022-03-26T16:01:06.000Z | src/test/pq/notifications.cpp | skaae/taopq | a621cbba1f63c599819466f3da7ef7d352bdaf0d | [
"BSL-1.0"
] | 45 | 2018-11-29T13:13:59.000Z | 2022-01-17T07:03:30.000Z | src/test/pq/notifications.cpp | skaae/taopq | a621cbba1f63c599819466f3da7ef7d352bdaf0d | [
"BSL-1.0"
] | 34 | 2018-11-29T14:03:59.000Z | 2022-03-15T13:08:13.000Z | // Copyright (c) 2016-2021 Daniel Frey and Dr. Colin Hirsch
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include "../getenv.hpp"
#include "../macros.hpp"
#include <tao/pq/connection.hpp>
#if defined( _WIN32 )
#include <winsock.h>
#else
#include <unistd.h>
#endif
std::size_t counter = 0;
void handle_notification( const tao::pq::notification& n )
{
std::cout << "channel '" << n.channel() << "' received '" << n.payload() << "'\n";
++counter;
}
std::size_t foo_counter = 0;
void handle_foo_notification( const char* payload )
{
std::cout << "foo handler received '" << payload << "'\n";
++foo_counter;
}
void run()
{
// overwrite the default with an environment variable if needed
const auto connection_string = tao::pq::internal::getenv( "TAOPQ_TEST_DATABASE", "dbname=template1" );
const auto connection = tao::pq::connection::create( connection_string );
TEST_EXECUTE( connection->set_notification_handler( handle_notification ) );
TEST_EXECUTE( connection->listen( "FOO", handle_foo_notification ) );
TEST_ASSERT( counter == 0 );
TEST_ASSERT( foo_counter == 0 );
TEST_EXECUTE( connection->notify( "FOO" ) );
TEST_ASSERT( counter == 1 );
TEST_ASSERT( foo_counter == 1 );
TEST_ASSERT( connection->notification_handler( "FOO" ) );
TEST_ASSERT( !connection->notification_handler( "BAR" ) );
TEST_EXECUTE( connection->reset_notification_handler( "FOO" ) );
TEST_ASSERT( !connection->notification_handler( "FOO" ) );
TEST_EXECUTE( connection->notify( "FOO", "with payload" ) );
TEST_ASSERT( counter == 2 );
TEST_ASSERT( foo_counter == 1 );
TEST_EXECUTE( connection->unlisten( "FOO" ) );
TEST_EXECUTE( connection->notify( "FOO" ) );
TEST_EXECUTE( connection->get_notifications() );
TEST_ASSERT( counter == 2 );
TEST_ASSERT( connection->notification_handler() );
TEST_EXECUTE( connection->reset_notification_handler() );
TEST_ASSERT( !connection->notification_handler() );
#if defined( _WIN32 )
closesocket( PQsocket( connection->underlying_raw_ptr() ) );
#else
close( PQsocket( connection->underlying_raw_ptr() ) );
#endif
TEST_THROWS( connection->get_notifications() );
}
auto main() -> int // NOLINT(bugprone-exception-escape)
{
try {
run();
}
// LCOV_EXCL_START
catch( const std::exception& e ) {
std::cerr << "exception: " << e.what() << std::endl;
throw;
}
catch( ... ) {
std::cerr << "unknown exception" << std::endl;
throw;
}
// LCOV_EXCL_STOP
}
| 29.166667 | 105 | 0.670095 | skaae |
8b3142098669ae216ebb5d300178f723667b43e8 | 2,955 | hpp | C++ | src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_nhwc.hpp | NomotoKazuhiro/oneDNN | 18795301d6776bc1431ec808cba7bdf83d191bf8 | [
"Apache-2.0"
] | 13 | 2020-05-29T07:39:23.000Z | 2021-11-22T14:01:28.000Z | src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_nhwc.hpp | NomotoKazuhiro/oneDNN | 18795301d6776bc1431ec808cba7bdf83d191bf8 | [
"Apache-2.0"
] | 8 | 2020-09-04T02:05:19.000Z | 2021-12-24T02:18:37.000Z | src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_nhwc.hpp | NomotoKazuhiro/oneDNN | 18795301d6776bc1431ec808cba7bdf83d191bf8 | [
"Apache-2.0"
] | 24 | 2020-08-07T04:21:48.000Z | 2021-12-09T02:03:35.000Z | /*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_X64_LRN_JIT_AVX512_COMMON_LRN_BWD_NHWC_HPP
#define CPU_X64_LRN_JIT_AVX512_COMMON_LRN_BWD_NHWC_HPP
#include "cpu/x64/lrn/jit_avx512_common_lrn_bwd_base.hpp"
#include "cpu/x64/lrn/jit_avx512_common_lrn_utils.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
namespace x64 {
namespace lrn {
using namespace dnnl::impl::status;
using namespace dnnl::impl::utils;
using namespace data_type;
using namespace Xbyak;
using namespace Xbyak::util;
template <data_type_t d_type>
class jit_avx512_common_lrn_kernel_bwd_nhwc_t
: public jit_avx512_common_lrn_kernel_bwd_t<d_type> {
public:
jit_avx512_common_lrn_kernel_bwd_nhwc_t(unsigned C, float alpha, float beta,
int local_size, void *code_ptr = nullptr,
size_t code_size = 1 * Xbyak::DEFAULT_MAX_CODE_SIZE);
DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx512_common_lrn_kernel_bwd_nhwc_t)
private:
void set_up_ker_params();
void execute_compute_loop(unsigned num_full_16c_blocks, unsigned C_tail);
void compute_loop(across_version version, tail_mode tail_proc,
unsigned C_tail = 0, int loop_size_param = 1);
void compute(int loop_size_param, tail_mode tail_proc);
void increment_loop_params(std::size_t offset);
void load_compute_data(
across_version version, tail_mode tail_proc, int loop_size_param);
void store_compute_data(
int loop_size_param, tail_mode tail_m, unsigned C_tail);
void reserve_stack_space(std::size_t space);
void unreserve_stack_space(std::size_t space);
void load_data_to_stack(
unsigned C_tail, across_version version, tail_mode tail_proc);
int get_stack_offset(const Reg64 reg, tail_mode tail_proc);
const std::vector<int> tmp_mask_prev_;
const std::vector<int> tmp_mask_next_;
static constexpr int zmm_size_ = 64;
static constexpr int tmp_load_to_stack_idx_prev_ = 12;
static constexpr int tmp_load_to_stack_idx_tail_ = 13;
static constexpr int tmp_store_from_stack_idx_tail_ = 14;
const Reg64 mask_ = r11;
const Reg64 blockC_ = r12;
const int half_ls_;
};
} // namespace lrn
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
| 35.60241 | 80 | 0.720474 | NomotoKazuhiro |
8b3287ce970f6aea0e3ce65b9b5531055ed91c25 | 875 | cpp | C++ | Problems/rotateImage.cpp | ShivamDureja/Data-Structures-And-Algorithms | 49c8fe18cbb57c54e8af900ca166604f967e7285 | [
"Unlicense"
] | 1 | 2021-11-24T05:25:42.000Z | 2021-11-24T05:25:42.000Z | Problems/rotateImage.cpp | ShivamDureja/Data-Structures-And-Algorithms | 49c8fe18cbb57c54e8af900ca166604f967e7285 | [
"Unlicense"
] | null | null | null | Problems/rotateImage.cpp | ShivamDureja/Data-Structures-And-Algorithms | 49c8fe18cbb57c54e8af900ca166604f967e7285 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <algorithm>
void rotate_image(int a[][4], int n)
{
for (int i = 0; i < n; i++)
{
std::reverse(a[i], a[i] + n);
}
//take transpose
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if(i<j)
std::swap(a[i][j], a[j][i]);
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
std::cout << a[i][j] << " ";
}
std::cout << std::endl;
}
}
int main()
{
int a[4][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
std::cout << a[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Rotated matrix-" << std::endl;
rotate_image(a, 4);
return 0;
} | 19.886364 | 74 | 0.354286 | ShivamDureja |
8b346aa9944149ba6214bd17c7a6126bb21c0115 | 392 | cpp | C++ | kuangbin/1/e.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | kuangbin/1/e.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | kuangbin/1/e.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
int flag, n;
void dfs(unsigned long long x, int k){
if(flag)
return;
if(x % n == 0){
printf("%llu\n", x);
flag = 1;
return;
}
if(k == 19)
return;
dfs(x * 10, k + 1);
dfs(x * 10 + 1, k + 1);
}
int main(){
while(~scanf("%d", &n) && n){
flag = 0;
dfs(1, 0);
}
return 0;
} | 12.645161 | 38 | 0.540816 | tusikalanse |
8b347c3494d34d4d749fdbc9eb8960a8cd5a10da | 31,004 | cpp | C++ | lib/src/AMRTools/QuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 10 | 2018-02-01T20:57:36.000Z | 2022-03-17T02:57:49.000Z | lib/src/AMRTools/QuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 19 | 2018-10-04T21:37:18.000Z | 2022-02-25T16:20:11.000Z | lib/src/AMRTools/QuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 11 | 2019-01-12T23:33:32.000Z | 2021-08-09T15:19:50.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "QuadCFInterp.H"
#include "BoxIterator.H"
#include "QuadCFInterpF_F.H"
#include "LayoutIterator.H"
#include "DataIterator.H"
#include "CH_Timer.H"
#include "CFIVS.H"
#include "TensorCFInterp.H"
#include "NamespaceHeader.H"
using std::endl;
/***********************/
// default constructor
/***********************/
bool QuadCFInterp::newCFInterMode = true;
/**/
void
QuadCFInterp::
interpPhiOnIVS(LevelData<FArrayBox>& a_phif,
const FArrayBox& a_phistar,
const DataIndex& a_datInd,
const int a_idir,
const Side::LoHiSide a_hiorlo,
const IntVectSet& a_interpIVS,
Real a_dxLevel,
Real a_dxCrse,
int a_ncomp)
{
IVSIterator fine_ivsit(a_interpIVS);
FArrayBox& a_phi = a_phif[a_datInd];
Real x1 = a_dxLevel;
Real x2 = 0.5*(3.*a_dxLevel+a_dxCrse);
Real denom = 1.0-((x1+x2)/x1);
Real idenom = 1.0/(denom); // divide is more expensive usually
Real x = 2.*a_dxLevel;
Real xsquared = x*x;
Real m1 = 1/(x1*x1);
Real m2 = 1/(x1*(x1-x2));
Real q1 = 1/(x1-x2);
Real q2 = x1+x2;
int ihilo = sign(a_hiorlo);
IntVect ai = -2*ihilo*BASISV(a_idir);
IntVect bi = - ihilo*BASISV(a_idir);
IntVect ci = ihilo*BASISV(a_idir);
for (fine_ivsit.begin(); fine_ivsit.ok(); ++fine_ivsit)
{
IntVect ivf = fine_ivsit();
// quadratic interpolation
for (int ivar = 0; ivar < a_ncomp; ivar++)
{
Real pa = a_phi(ivf + ai, ivar);
Real pb = a_phi(ivf + bi, ivar);
Real pc = a_phistar(ivf + ci, ivar);
//phi = ax**2 + bx + c, x = 0 at pa
Real a = (pb-pa)*m1 - (pb-pc)*m2;
a *= idenom;
Real b = (pb-pc)*q1 - a*q2;
Real c = pa;
a_phi(ivf,ivar) = a*xsquared + b*x + c;
} //end loop over components
} //end loop over fine intvects
}
/**/
void
QuadCFInterp::
homogeneousCFInterpPhi(LevelData<FArrayBox>& a_phif,
const DataIndex& a_datInd,
int a_idir,
Side::LoHiSide a_hiorlo,
LayoutData<CFIVS> a_loCFIVS[SpaceDim],
LayoutData<CFIVS> a_hiCFIVS[SpaceDim],
Real a_dxLevel,
Real a_dxCrse,
int a_ncomp)
{
const CFIVS* cfivs_ptr = NULL;
if (a_hiorlo == Side::Lo)
cfivs_ptr = &a_loCFIVS[a_idir][a_datInd];
else
cfivs_ptr = &a_hiCFIVS[a_idir][a_datInd];
const IntVectSet& interp_ivs = cfivs_ptr->getFineIVS();
if (!interp_ivs.isEmpty())
{
int ihilo = sign(a_hiorlo);
Box phistarbox = interp_ivs.minBox();
phistarbox.shift(a_idir, ihilo);
FArrayBox phistar(phistarbox, a_ncomp);
//hence the homogeneous...
phistar.setVal(0.);
//given phistar, interpolate on fine ivs to fill ghost cells for phi
interpPhiOnIVS(a_phif, phistar, a_datInd, a_idir, a_hiorlo,
interp_ivs, a_dxLevel, a_dxCrse, a_ncomp);
}
}
/**/
void
QuadCFInterp::
homogeneousCFInterpTanGrad(LevelData<FArrayBox>& a_tanGrad,
const LevelData<FArrayBox>& a_phi,
const DataIndex& a_DatInd,
int a_idir,
Side::LoHiSide a_hiorlo,
Real a_dxLevel,
Real a_dxCrse,
int a_ncomp,
LayoutData<TensorFineStencilSet> a_loTanStencilSets[SpaceDim],
LayoutData<TensorFineStencilSet> a_hiTanStencilSets[SpaceDim])
{
const TensorFineStencilSet* cfstencil_ptr = NULL;
if (a_hiorlo == Side::Lo)
cfstencil_ptr = &a_loTanStencilSets[a_idir][a_DatInd];
else
cfstencil_ptr = &a_hiTanStencilSets[a_idir][a_DatInd];
Real x1 = a_dxLevel;
Real x2 = 0.5*(3.*a_dxLevel+a_dxCrse);
Real denom = 1.0-((x1+x2)/x1);
Real idenom = 1.0/(denom); // divide is more expensive usually
Real x = 2.*a_dxLevel;
Real xsquared = x*x;
Real m1 = 1/(x1*x1);
Real m2 = 1/(x1*(x1-x2));
Real q1 = 1/(x1-x2);
Real q2 = x1+x2;
const FArrayBox& phi = a_phi[a_DatInd];
FArrayBox& tanGrad = a_tanGrad[a_DatInd];
// loop over gradient directions
for (int gradDir = 0; gradDir<SpaceDim; gradDir++)
{
if (gradDir != a_idir)
{
// first do centered stencil
const IntVectSet& centeredIVS =
cfstencil_ptr->getCenteredStencilSet(gradDir);
int ihilo = sign(a_hiorlo);
if (!centeredIVS.isEmpty())
{
// do centered computation
IVSIterator cntrd_ivs(centeredIVS);
// want to average fine-grid gradient with coarse
// grid gradient, which is 0 (which is where the
// extra factor of one-half comes from)
Real gradMult = (0.5/a_dxLevel);
for (cntrd_ivs.begin(); cntrd_ivs.ok(); ++cntrd_ivs)
{
IntVect ivf = cntrd_ivs();
IntVect finePhiLoc = ivf - ihilo*BASISV(a_idir);
IntVect finePhiLoc2 = finePhiLoc - ihilo*BASISV(a_idir);
// loop over variables
for (int ivar = 0; ivar<a_phi.nComp(); ivar++)
{
Real fineHi = phi(finePhiLoc2+BASISV(gradDir),ivar);
Real fineLo = phi(finePhiLoc2-BASISV(gradDir),ivar);
Real fineGrada = gradMult*(fineHi-fineLo);
fineHi = phi(finePhiLoc+BASISV(gradDir),ivar);
fineLo = phi(finePhiLoc-BASISV(gradDir),ivar);
Real fineGradb = gradMult*(fineHi-fineLo);
// homogeneous interp implies that gradc is 0
Real gradc = 0;
int gradComp = TensorCFInterp::gradIndex(ivar,gradDir);
Real a = (fineGradb-fineGrada)*m1 - (fineGradb-gradc)*m2;
a *= idenom;
Real b = (fineGradb-gradc)*q1 - a*q2;
Real c = fineGrada;
tanGrad(ivf,gradComp) = a*xsquared + b*x + c;
}
} // end loop over centered difference cells
} // end if there are centered cells
// now do forward-difference cells
const IntVectSet& forwardIVS =
cfstencil_ptr->getForwardStencilSet(gradDir);
if (!forwardIVS.isEmpty())
{
// do forward-difference computations
IVSIterator fwd_ivs(forwardIVS);
// set up multipliers for gradient; since we want to average
// fine-grid gradient with coarse-grid gradient (which is 0),
// include an extra factor of one-half here.
Real mult0 = -1.5/a_dxLevel;
Real mult1 = 2.0/a_dxLevel;
Real mult2 = -0.5/a_dxLevel;
for (fwd_ivs.begin(); fwd_ivs.ok(); ++fwd_ivs)
{
IntVect ivf = fwd_ivs();
IntVect finePhiLoc = ivf - ihilo*BASISV(a_idir);
IntVect finePhiLoc2 = finePhiLoc - ihilo*BASISV(a_idir);
//now loop overvariables
for (int var= 0; var<a_phi.nComp(); var++)
{
Real fine0 = phi(finePhiLoc2,var);
Real fine1 = phi(finePhiLoc2+BASISV(gradDir),var);
Real fine2 = phi(finePhiLoc2+2*BASISV(gradDir),var);
Real fineGrada = mult0*fine0 +mult1*fine1 +mult2*fine2;
fine0 = phi(finePhiLoc,var);
fine1 = phi(finePhiLoc+BASISV(gradDir),var);
fine2 = phi(finePhiLoc+2*BASISV(gradDir),var);
Real fineGradb = mult0*fine0 +mult1*fine1 +mult2*fine2;
Real gradc = 0.0;
int gradComp = TensorCFInterp::gradIndex(var,gradDir);
// now compute gradient
Real a = (fineGradb-fineGrada)*m1 - (fineGradb-gradc)*m2;
a *= idenom;
Real b = (fineGradb-gradc)*q1 - a*q2;
Real c = fineGrada;
tanGrad(ivf,gradComp) = a*xsquared + b*x + c;
} // end loop over variables
} // end loop over forward-difference locations
} // end if there are forward-difference cells
// now do backward-difference cells
const IntVectSet& backwardIVS =
cfstencil_ptr->getBackwardStencilSet(gradDir);
if (!backwardIVS.isEmpty())
{
IVSIterator back_ivs(backwardIVS);
// set up multipliers for gradient -- since we want to average
// fine-grid gradient with coarse-grid gradient (which is 0),
// include an extra factor of one-half here.
Real mult0 = -1.5/a_dxLevel;
Real mult1 = 2.0/a_dxLevel;
Real mult2 = -0.5/a_dxLevel;
for (back_ivs.begin(); back_ivs.ok(); ++back_ivs)
{
IntVect ivf = back_ivs();
IntVect finePhiLoc = ivf - ihilo*BASISV(a_idir);
IntVect finePhiLoc2 = finePhiLoc - ihilo*BASISV(a_idir);
// now loop over variables
for (int var=0; var<a_phi.nComp(); var++)
{
Real fine0 = phi(finePhiLoc2,var);
Real fine1 = phi(finePhiLoc2-BASISV(gradDir),var);
Real fine2 = phi(finePhiLoc2-2*BASISV(gradDir),var);
Real fineGrada = mult0*fine0 +mult1*fine1 +mult2*fine2;
fine0 = phi(finePhiLoc,var);
fine1 = phi(finePhiLoc-BASISV(gradDir),var);
fine2 = phi(finePhiLoc-2*BASISV(gradDir),var);
Real fineGradb = mult0*fine0 +mult1*fine1 +mult2*fine2;
Real gradc = 0.0;
int gradComp = TensorCFInterp::gradIndex(var,gradDir);
Real a = (fineGradb-fineGrada)*m1 - (fineGradb-gradc)*m2;
a *= idenom;
Real b = (fineGradb-gradc)*q1 - a*q2;
Real c = fineGrada;
tanGrad(ivf,gradComp) = a*xsquared + b*x + c;
} // end loop over variables
} // end loop over backward-difference cells
} // end if there are backward-difference cells
} // end if gradDir is a tangential direction
} // end loop over gradient directions
}
/***********************/
// does homogeneous coarse/fine interpolation
/***********************/
void
QuadCFInterp::
homogeneousCFInterp(LevelData<FArrayBox>& a_phif,
LevelData<FArrayBox>& a_tanGrad,
LayoutData<CFIVS> a_loCFIVS[SpaceDim],
LayoutData<CFIVS> a_hiCFIVS[SpaceDim],
Real a_dxLevel,
Real a_dxCrse,
int a_ncomp,
LayoutData<TensorFineStencilSet> a_loTanStencilSets[SpaceDim],
LayoutData<TensorFineStencilSet> a_hiTanStencilSets[SpaceDim])
{
// need to do this to be sure that tangential derivatives are computed
// correctly
a_phif.exchange(a_phif.interval());
DataIterator dit = a_phif.dataIterator();
for (dit.begin(); dit.ok(); ++dit)
{
const DataIndex& datInd = dit();
// first fill in cells for phi
for (int idir = 0; idir < SpaceDim; idir++)
{
SideIterator sit;
for (sit.begin(); sit.ok(); sit.next())
{
homogeneousCFInterpPhi(a_phif,datInd,idir,sit(),
a_loCFIVS, a_hiCFIVS,
a_dxLevel, a_dxCrse, a_ncomp);
}
}
// now fill in tangential gradient cells
for (int idir = 0; idir<SpaceDim; idir++)
{
SideIterator sit;
for (sit.begin(); sit.ok(); sit.next())
{
homogeneousCFInterpTanGrad(a_tanGrad, a_phif,
datInd,idir,sit(),
a_dxLevel, a_dxCrse, a_ncomp,
a_loTanStencilSets, a_hiTanStencilSets);
}
}
}
}
void
QuadCFInterp::clear()
{
m_isDefined = false;
m_level = -1;
m_dxFine = -1;
}
QuadCFInterp::QuadCFInterp()
{
clear();
}
/***********************/
/***********************/
QuadCFInterp::QuadCFInterp(
const DisjointBoxLayout& a_fineBoxes,
const DisjointBoxLayout* a_coarBoxes,
Real a_dxFine,
int a_refRatio, int a_nComp,
const Box& a_domf)
{
ProblemDomain fineProbDomain(a_domf);
define(a_fineBoxes,a_coarBoxes, a_dxFine,a_refRatio,a_nComp, fineProbDomain);
}
/***********************/
/***********************/
QuadCFInterp::QuadCFInterp(
const DisjointBoxLayout& a_fineBoxes,
const DisjointBoxLayout* a_coarBoxes,
Real a_dxFine,
int a_refRatio, int a_nComp,
const ProblemDomain& a_domf)
{
define(a_fineBoxes,a_coarBoxes, a_dxFine,a_refRatio,a_nComp, a_domf);
}
/***********************/
/***********************/
void
QuadCFInterp::define(
const DisjointBoxLayout& a_fineBoxes,
const DisjointBoxLayout* a_coarBoxesPtr,
Real a_dxLevel,
int a_refRatio, int a_nComp,
const ProblemDomain& a_domf)
{
CH_TIME("QuadCFInterp::define");
clear();
m_isDefined = true;
CH_assert(a_nComp > 0);
CH_assert (!a_domf.isEmpty());
// consistency check
CH_assert (a_fineBoxes.checkPeriodic(a_domf));
m_domainFine = a_domf;
m_dxFine = a_dxLevel;
m_refRatio = a_refRatio;
m_nComp = a_nComp;
m_inputFineLayout = a_fineBoxes;
bool fineCoversCoarse = false;
if (a_coarBoxesPtr != NULL)
{
int factor = D_TERM6(a_refRatio, *a_refRatio, *a_refRatio,
*a_refRatio, *a_refRatio, *a_refRatio);
long long numPts = a_fineBoxes.numCells()/factor;
numPts -= a_coarBoxesPtr->numCells();
if (numPts == 0) fineCoversCoarse = true;
}
m_fineCoversCoarse = fineCoversCoarse;
if (a_coarBoxesPtr == NULL || fineCoversCoarse)
m_level = 0;
else
m_level = 1;
if (m_level > 0)
{
// (DFM) only check for valid refRatio if a coarser level exists
CH_assert(a_refRatio >= 1);
const DisjointBoxLayout& coarBoxes = *a_coarBoxesPtr;
m_inputCoarLayout = coarBoxes;
CH_assert (coarBoxes.checkPeriodic(coarsen(a_domf,a_refRatio)));
for (int idir = 0; idir < SpaceDim; idir++)
{
m_loQCFS[idir].define(a_fineBoxes);
m_hiQCFS[idir].define(a_fineBoxes);
}
//locoarboxes and hicoarboxes are now open
//and have same processor mapping as a_fineboxes
//make boxes for coarse buffers
m_coarBoxes.deepCopy(a_fineBoxes);
m_coarBoxes.coarsen(m_refRatio);
m_coarBoxes.grow(2);
m_coarBoxes.close();
m_coarBuffer.define(m_coarBoxes, m_nComp);
m_copier.define(coarBoxes, m_coarBoxes);
if (!newCFInterMode) //old n^2 algorithm (bvs)
{
//make cfstencils and boxes for coarse buffers
DataIterator dit = a_fineBoxes.dataIterator();
for (dit.begin(); dit.ok(); ++dit)
{
const Box& fineBox = a_fineBoxes[dit()];
for (int idir = 0; idir < SpaceDim; idir++)
{
//low side cfstencil
m_loQCFS[idir][dit()].define(a_domf,
fineBox,
a_fineBoxes,
coarBoxes,
a_refRatio,
idir,
Side::Lo);
//high side cfstencil
m_hiQCFS[idir][dit()].define(a_domf,
fineBox,
a_fineBoxes,
coarBoxes,
a_refRatio,
idir,
Side::Hi);
}
}
} else
{
//new "moving window" version of CF stencil building
Vector<Box> periodicFine;
CFStencil::buildPeriodicVector(periodicFine, a_domf, a_fineBoxes);
Vector<Box> coarsenedFine(periodicFine);
for (int i=0; i<coarsenedFine.size(); ++i)
{
coarsenedFine[i].coarsen(a_refRatio);
}
DataIterator dit = a_fineBoxes.dataIterator();
for (dit.begin(); dit.ok(); ++dit)
{
const Box& fineBox = a_fineBoxes[dit()];
for (int idir = 0; idir < SpaceDim; idir++)
{
//low side cfstencil
m_loQCFS[idir][dit()].define(a_domf,
fineBox,
periodicFine,
coarsenedFine,
coarBoxes,
a_refRatio,
idir,
Side::Lo);
//high side cfstencil
m_hiQCFS[idir][dit()].define(a_domf,
fineBox,
periodicFine,
coarsenedFine,
coarBoxes,
a_refRatio,
idir,
Side::Hi);
}
}
}
}
}
/***********************/
// apply coarse-fine boundary conditions -- assume that phi grids
// are grown by one
/***********************/
void
QuadCFInterp::coarseFineInterp(BaseFab<Real> & a_phif,
const BaseFab<Real> & a_phic,
const QuadCFStencil& a_qcfs,
const Side::LoHiSide a_hiorlo,
const int a_idir,
const Interval& a_variables) const
{
CH_TIME("QuadCFInterp::coarseFineInterp(BaseFab<Real> & a_phif,...)");
CH_assert(isDefined());
//nothing happens if m_level == 0
if (m_level > 0)
{
if (!a_qcfs.isEmpty())
{
BaseFab<Real> phistar;
//first find extended value phistar
//includes finding slopes of coarse solution bar
getPhiStar(phistar, a_phic, a_qcfs, a_hiorlo, a_idir, a_variables);
//given phistar, interpolate on fine ivs
interpOnIVS(a_phif, phistar, a_qcfs, a_hiorlo, a_idir, a_variables);
}
}
}
/***********************/
//get extended phi (lives next to interpivs)
/***********************/
void
QuadCFInterp::getPhiStar(BaseFab<Real> & a_phistar,
const BaseFab<Real> & a_phic,
const QuadCFStencil& a_qcfs,
const Side::LoHiSide a_hiorlo,
const int a_idir,
const Interval& a_variables) const
{
CH_TIMERS("QuadCFInterp::getPhiStar");
//CH_TIMER("QuadCFInterp::computeFirstDerivative", t1st);
//CH_TIMER("QuadCFInterp::computesecondDerivative", t2nd);
//CH_TIMER("QuadCFInterp::computemixedDerivative", tmixed);
CH_TIMER("QuadCFInterp::slopes", tslopes);
CH_TIMER("QuadCFInterp::notPacked", tnp);
CH_TIMER("QuadCFInterp::preamble", tpreamble);
CH_assert(isDefined());
CH_assert(a_qcfs.isDefined());
#if (CH_SPACEDIM > 1)
Real dxf = m_dxFine;
Real dxc = m_refRatio*dxf;
#endif
// if we think of a_idir as the "me" direction, then
// the other directions can be "you1" and "you2"
#if (CH_SPACEDIM == 3)
int you1, you2;
if (a_idir == 0)
{
you1 = 1;
you2 = 2;
}
else if (a_idir == 1)
{
you1 = 0;
you2 = 2;
}
else
{
you1 = 0;
you2 = 1;
}
#else // (CH_SPACEDIM == 2)
int you1;
if (a_idir == 0)
{
you1 = 1;
}
else
{
you1 = 0;
}
#endif
//if cfsten is empty, nothing to interpolate.
if (!a_qcfs.isEmpty())
{
CH_START(tpreamble);
CH_assert(m_level > 0);
const IntVectSet& interp_ivs = a_qcfs.getFineIVS();
const IntVectSet& coarsl_ivs = a_qcfs.getCoarIVS();
if (!coarsl_ivs.isDense())
{
MayDay::Error("What the hell?? TreeIntVectSet ???");
}
if (!interp_ivs.isDense())
{
MayDay::Error("What the hell?? TreeIntVectSet ???");
}
Box coarinterpbox = coarsl_ivs.minBox();
int ncomp = a_phic.nComp();
CH_assert(ncomp == m_nComp);
CH_assert(a_phic.box().contains((coarinterpbox)));
// allocate phistar here
int ihilo = sign(a_hiorlo);
Box phistarbox = interp_ivs.minBox();
phistarbox.shift(a_idir, ihilo);
a_phistar.define(phistarbox, ncomp);
CH_STOP(tpreamble);
for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++)
{
CH_START(tslopes);
//phi = phino + slope*x + half*x*x*curvature
BaseFab<Real> coarslope(coarinterpbox, SpaceDim);
BaseFab<Real> coarcurva(coarinterpbox, SpaceDim);
#if (CH_SPACEDIM == 3)
BaseFab<Real> coarmixed(coarinterpbox, 1);
#endif
// coarslope.setVal(0.);
//first find extended value phistar. get slopes of coarse solution
IVSIterator coar_ivsit(coarsl_ivs);
for (coar_ivsit.begin(); coar_ivsit.ok(); ++coar_ivsit)
{
// this isn't relevant for 1D
#if (CH_SPACEDIM > 1)
const IntVect& coariv = coar_ivsit();
// coarslope(coariv, a_idir) = 0.0;
// coarcurva(coariv, a_idir) = 0.0;
coarslope(coariv, you1) =
a_qcfs.computeFirstDerivative (a_phic, you1, ivar, coariv, dxc);
coarcurva(coariv, you1) =
a_qcfs.computeSecondDerivative(a_phic, you1, ivar, coariv, dxc);
#endif
#if (CH_SPACEDIM == 3)
coarslope(coariv, you2) =
a_qcfs.computeFirstDerivative (a_phic, you2, ivar, coariv, dxc);
coarcurva(coariv, you2) =
a_qcfs.computeSecondDerivative(a_phic, you2, ivar, coariv, dxc);
coarmixed(coariv) =
a_qcfs.computeMixedDerivative(a_phic, ivar, coariv, dxc);
#endif
} //end loop over coarse intvects
CH_STOP(tslopes);
if (a_qcfs.finePacked() && CH_SPACEDIM==3)
{
const IntVect& iv = phistarbox.smallEnd();
IntVect civ(iv);
civ.coarsen(m_refRatio);
Box region = a_qcfs.packedBox();
#if (CH_SPACEDIM == 3)
FORT_PHISTAR(CHF_FRA_SHIFT(a_phistar, iv),
CHF_BOX_SHIFT(region, iv),
CHF_CONST_FRA_SHIFT(a_phic, civ),
CHF_FRA_SHIFT(coarslope, civ),
CHF_FRA_SHIFT(coarcurva, civ),
CHF_FRA_SHIFT(coarmixed, civ),
CHF_CONST_REAL(dxf),
CHF_CONST_INT(ivar),
CHF_CONST_INT(a_idir),
CHF_CONST_INT(ihilo),
CHF_CONST_INT(m_refRatio));
#endif
}
else
{
CH_START(tnp);
IntVect ivf, ivc, ivstar;
// ifdef is here to prevent unused variable wasrnings in 1D
#if (CH_SPACEDIM > 1)
int jf, jc;
Real xf, xc, x1;
#endif
Real pc, update1=0, update2=0, update3=0;
IVSIterator fine_ivsit(interp_ivs);
for (fine_ivsit.begin(); fine_ivsit.ok(); ++fine_ivsit)
{
ivf = fine_ivsit();
ivc = coarsen(ivf, m_refRatio);
ivstar = ivf;
ivstar.shift(a_idir, ihilo);
pc = a_phic(ivc,ivar);
// for 1D, none of this is necessary -- just copy
// coarse value into phiStar
#if (CH_SPACEDIM > 1)
jf = ivf[you1];
jc = ivc[you1];
xf = (jf+0.5)*dxf;
xc = (jc+0.5)*dxc;
x1 = xf-xc;
update1= x1*coarslope(ivc, you1) + 0.5*x1*x1*coarcurva(ivc, you1);
#endif
#if (CH_SPACEDIM==3)
Real x2;
jf = ivf[you2];
jc = ivc[you2];
xf = (jf+0.5)*dxf;
xc = (jc+0.5)*dxc;
x2 = xf-xc;
update2 = x2*coarslope(ivc, you2) + 0.5*x2*x2*coarcurva(ivc, you2);
//add in mixed derivative component
update3 = x1*x2*coarmixed(ivc);
#endif
a_phistar(ivstar, ivar) = pc+update1+update2+update3;
} //end loop over fine intvects
CH_STOP(tnp);
} // end if for not packed optimization
}//end loop over variables
} //end if (level>0 && !hocfs.isempty())
} //end function getphistar
/***********************/
/***********************/
bool
QuadCFInterp::isDefined() const
{
return m_isDefined;
}
void
QuadCFInterp::interpOnIVS(BaseFab<Real> & a_phif,
const BaseFab<Real> & a_phistar,
const QuadCFStencil& a_qcfs,
const Side::LoHiSide a_hiorlo,
const int a_idir,
const Interval& a_variables) const
{
CH_TIME("QuadCFInterp::interpOnIVS");
CH_assert(isDefined());
CH_assert(a_qcfs.isDefined());
//if cfsten is empty, nothing to interpolate.
if (!a_qcfs.isEmpty())
{
//if there IS something to interpolate, the level ident
//had better be greater than zero. Otherwise a null
//was sent in as coarse grids on construction
CH_assert(m_level > 0);
const IntVectSet& interp_ivs = a_qcfs.getFineIVS();
int ihilo = sign(a_hiorlo);
int nref = m_refRatio;
if (!a_qcfs.finePacked())
{
IVSIterator fine_ivsit(interp_ivs);
CH_assert(a_phistar.nComp() == a_phif.nComp());
CH_assert(a_phistar.nComp() == m_nComp);
for (fine_ivsit.begin(); fine_ivsit.ok(); ++fine_ivsit)
{
IntVect ivf = fine_ivsit();
// quadratic interpolation
for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++)
{
Real pa = a_phif (ivf -2*ihilo*BASISV(a_idir), ivar);
Real pb = a_phif (ivf - ihilo*BASISV(a_idir), ivar);
Real ps = a_phistar(ivf + ihilo*BASISV(a_idir), ivar);
//phi = ax**2 + bx + c, x = 0 at pa
Real h = m_dxFine;
Real a = (2./h/h)*(2.*ps + pa*(nref+1.0) -pb*(nref+3.0))/
(nref*nref + 4*nref + 3.0);
Real b = (pb-pa)/h - a*h;
Real c = pa;
Real x = 2.*h;
a_phif (ivf,ivar) = a*x*x + b*x + c;
} //end loop over components
} //end loop over fine intvects
} else
{ // data is packed, just call Fortran
int b=a_variables.begin();
int e=a_variables.end();
FORT_QUADINTERP(CHF_FRA(a_phif),
CHF_CONST_FRA(a_phistar),
CHF_BOX(a_qcfs.packedBox()),
CHF_CONST_INT(ihilo),
CHF_CONST_REAL(m_dxFine),
CHF_CONST_INT(a_idir),
CHF_CONST_INT(b),
CHF_CONST_INT(e),
CHF_CONST_INT(nref));
}
} //end if (level>0 && !oscfs.isempty())
} //end function interponivs
/***********************/
// apply coarse-fine boundary conditions -- assume that phi grids
// are grown by one
/***********************/
void
QuadCFInterp::coarseFineInterp(LevelData<FArrayBox>& a_phif,
const LevelData<FArrayBox>& a_phic)
{
CH_TIME("QuadCFInterp::coarseFineInterp");
CH_assert(isDefined());
Interval variables = a_phic.interval();
if (m_level > 0)
{
CH_assert(a_phif.nComp() == m_nComp);
CH_assert(a_phic.nComp() == m_nComp);
CH_assert(a_phif.ghostVect() >= IntVect::Unit);
CH_assert(a_phic.boxLayout() == m_inputCoarLayout);
CH_assert(a_phif.boxLayout() == m_inputFineLayout);
a_phic.copyTo(a_phic.interval(), m_coarBuffer, m_coarBuffer.interval(),
m_copier);
for (int idir = 0; idir < SpaceDim; idir++)
{
DataIterator ditFine = a_phif.dataIterator();
for (ditFine.begin(); ditFine.ok(); ++ditFine)
{
DataIndex datIndGlo =ditFine();
BaseFab<Real> & phif = a_phif[datIndGlo];
const BaseFab<Real> & phiC = m_coarBuffer[datIndGlo];
//lo side cfinterp
//recall that buffers have fine processor mapping
{
const QuadCFStencil& loQCFS = m_loQCFS[idir][datIndGlo];
coarseFineInterp(phif, phiC ,loQCFS, Side::Lo, idir, variables);
}
//hi side cfinterp
{
const QuadCFStencil& hiQCFS = m_hiQCFS[idir][datIndGlo];
coarseFineInterp(phif, phiC, hiQCFS, Side::Hi, idir, variables);
}
}//end iteration over boxes in fine grid
} //end iteration over directions
}
}
/***********************/
/***********************/
QuadCFInterp::~QuadCFInterp()
{
clear();
}
#include "NamespaceFooter.H"
| 34.564103 | 89 | 0.505967 | rmrsk |
8b3656201ca82e44df019eb542cb94d58c49daca | 2,195 | hpp | C++ | include/memoria/context/fixedsize_stack.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2021-07-30T16:54:24.000Z | 2021-09-08T15:48:17.000Z | include/memoria/context/fixedsize_stack.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | null | null | null | include/memoria/context/fixedsize_stack.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2020-03-14T15:15:25.000Z | 2020-06-15T11:26:56.000Z |
// Copyright Oliver Kowalke 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef MEMORIA_CONTEXT_FIXEDSIZE_H
#define MEMORIA_CONTEXT_FIXEDSIZE_H
#include <cstddef>
#include <cstdlib>
#include <new>
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <memoria/context/detail/config.hpp>
#include <memoria/context/stack_context.hpp>
#include <memoria/context/stack_traits.hpp>
#if defined(MEMORIA_CONTEXT_USE_MAP_STACK)
extern "C" {
#include <sys/mman.h>
}
#endif
#if defined(BOOST_USE_VALGRIND)
#include <valgrind/valgrind.h>
#endif
namespace memoria {
namespace context {
template< typename traitsT >
class basic_fixedsize_stack {
private:
std::size_t size_;
public:
typedef traitsT traits_type;
basic_fixedsize_stack( std::size_t size = traits_type::default_size() ) noexcept :
size_( size) {
}
stack_context allocate() {
#if defined(MEMORIA_CONTEXT_USE_MAP_STACK)
void * vp = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
if ( vp == MAP_FAILED) {
throw std::bad_alloc();
}
#else
void * vp = std::malloc( size_);
if ( ! vp) {
throw std::bad_alloc();
}
#endif
stack_context sctx;
sctx.size = size_;
sctx.sp = static_cast< char * >( vp) + sctx.size;
#if defined(BOOST_USE_VALGRIND)
sctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( sctx.sp, vp);
#endif
return sctx;
}
void deallocate( stack_context & sctx) noexcept {
BOOST_ASSERT( sctx.sp);
#if defined(BOOST_USE_VALGRIND)
VALGRIND_STACK_DEREGISTER( sctx.valgrind_stack_id);
#endif
void * vp = static_cast< char * >( sctx.sp) - sctx.size;
#if defined(MEMORIA_CONTEXT_USE_MAP_STACK)
::munmap( vp, sctx.size);
#else
std::free( vp);
#endif
}
};
typedef basic_fixedsize_stack< stack_traits > fixedsize_stack;
# if ! defined(MEMORIA_USE_SEGMENTED_STACKS)
typedef fixedsize_stack default_stack;
# endif
}}
#endif // MEMORIA_CONTEXT_FIXEDSIZE_H
| 23.858696 | 105 | 0.680182 | victor-smirnov |
8b37b2b67143965ce4f2db5fdd9c67c1cba7e4e4 | 579 | hpp | C++ | include/uitsl/chrono/TimeGuard.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 15 | 2020-07-31T23:06:09.000Z | 2022-01-13T18:05:33.000Z | include/uitsl/chrono/TimeGuard.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 137 | 2020-08-13T23:32:17.000Z | 2021-10-16T04:00:40.000Z | include/uitsl/chrono/TimeGuard.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 3 | 2020-08-09T01:52:03.000Z | 2020-10-02T02:13:47.000Z | #pragma once
#ifndef UITSL_CHRONO_TIMEGUARD_HPP_INCLUDE
#define UITSL_CHRONO_TIMEGUARD_HPP_INCLUDE
#include <chrono>
namespace uitsl {
template<typename DurationType, typename Clock=std::chrono::steady_clock>
class TimeGuard {
DurationType &dest;
const std::chrono::time_point<Clock> start;
public:
explicit TimeGuard(DurationType &dest_)
: dest{dest_}
, start{Clock::now()}
{ ; }
~TimeGuard() {
dest = std::chrono::duration_cast<DurationType>( Clock::now() - start );
}
};
} // namespace uitsl
#endif // #ifndef UITSL_CHRONO_TIMEGUARD_HPP_INCLUDE
| 18.09375 | 76 | 0.732297 | mmore500 |
8b3807485cad4609617e9017bb5fcb8d213dbb88 | 8,241 | cpp | C++ | CSGOSimple/helpers/utils.cpp | Tyler-Admin/CSGOSimple | 99a659a1368ed9445b9ccf8ec4514d25d9bf81d6 | [
"MIT"
] | 400 | 2018-10-30T14:52:13.000Z | 2022-03-29T11:46:24.000Z | CSGOSimple/helpers/utils.cpp | Tyler-Admin/CSGOSimple | 99a659a1368ed9445b9ccf8ec4514d25d9bf81d6 | [
"MIT"
] | 126 | 2018-12-03T15:54:57.000Z | 2022-03-23T17:11:53.000Z | CSGOSimple/helpers/utils.cpp | Tyler-Admin/CSGOSimple | 99a659a1368ed9445b9ccf8ec4514d25d9bf81d6 | [
"MIT"
] | 316 | 2018-11-09T22:38:38.000Z | 2022-03-25T13:35:09.000Z | #include "Utils.hpp"
#define NOMINMAX
#include <Windows.h>
#include <stdio.h>
#include <string>
#include <vector>
#include "../valve_sdk/csgostructs.hpp"
#include "Math.hpp"
HANDLE _out = NULL, _old_out = NULL;
HANDLE _err = NULL, _old_err = NULL;
HANDLE _in = NULL, _old_in = NULL;
namespace Utils {
std::vector<char> HexToBytes(const std::string& hex) {
std::vector<char> res;
for (auto i = 0u; i < hex.length(); i += 2) {
std::string byteString = hex.substr(i, 2);
char byte = (char)strtol(byteString.c_str(), NULL, 16);
res.push_back(byte);
}
return res;
}
std::string BytesToString(unsigned char* data, int len) {
constexpr char hexmap[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
std::string res(len * 2, ' ');
for (int i = 0; i < len; ++i) {
res[2 * i] = hexmap[(data[i] & 0xF0) >> 4];
res[2 * i + 1] = hexmap[data[i] & 0x0F];
}
return res;
}
std::vector<std::string> Split(const std::string& str, const char* delim) {
std::vector<std::string> res;
char* pTempStr = _strdup(str.c_str());
char* context = NULL;
char* pWord = strtok_s(pTempStr, delim, &context);
while (pWord != NULL) {
res.push_back(pWord);
pWord = strtok_s(NULL, delim, &context);
}
free(pTempStr);
return res;
}
unsigned int FindInDataMap(datamap_t *pMap, const char *name) {
while (pMap) {
for (int i = 0; i<pMap->dataNumFields; i++) {
if (pMap->dataDesc[i].fieldName == NULL)
continue;
if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
return pMap->dataDesc[i].fieldOffset[TD_OFFSET_NORMAL];
if (pMap->dataDesc[i].fieldType == FIELD_EMBEDDED) {
if (pMap->dataDesc[i].td) {
unsigned int offset;
if ((offset = FindInDataMap(pMap->dataDesc[i].td, name)) != 0)
return offset;
}
}
}
pMap = pMap->baseMap;
}
return 0;
}
/*
* @brief Create console
*
* Create and attach a console window to the current process
*/
void AttachConsole()
{
_old_out = GetStdHandle(STD_OUTPUT_HANDLE);
_old_err = GetStdHandle(STD_ERROR_HANDLE);
_old_in = GetStdHandle(STD_INPUT_HANDLE);
::AllocConsole() && ::AttachConsole(GetCurrentProcessId());
_out = GetStdHandle(STD_OUTPUT_HANDLE);
_err = GetStdHandle(STD_ERROR_HANDLE);
_in = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(_out,
ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
SetConsoleMode(_in,
ENABLE_INSERT_MODE | ENABLE_EXTENDED_FLAGS |
ENABLE_PROCESSED_INPUT | ENABLE_QUICK_EDIT_MODE);
}
/*
* @brief Detach console
*
* Detach and destroy the attached console
*/
void DetachConsole()
{
if(_out && _err && _in) {
FreeConsole();
if(_old_out)
SetStdHandle(STD_OUTPUT_HANDLE, _old_out);
if(_old_err)
SetStdHandle(STD_ERROR_HANDLE, _old_err);
if(_old_in)
SetStdHandle(STD_INPUT_HANDLE, _old_in);
}
}
/*
* @brief Print to console
*
* Replacement to printf that works with the newly created console
*/
bool ConsolePrint(const char* fmt, ...)
{
if(!_out)
return false;
char buf[1024];
va_list va;
va_start(va, fmt);
_vsnprintf_s(buf, 1024, fmt, va);
va_end(va);
return !!WriteConsoleA(_out, buf, static_cast<DWORD>(strlen(buf)), nullptr, nullptr);
}
/*
* @brief Blocks execution until a key is pressed on the console window
*
*/
char ConsoleReadKey()
{
if(!_in)
return false;
auto key = char{ 0 };
auto keysread = DWORD{ 0 };
ReadConsoleA(_in, &key, 1, &keysread, nullptr);
return key;
}
/*
* @brief Wait for all the given modules to be loaded
*
* @param timeout How long to wait
* @param modules List of modules to wait for
*
* @returns See WaitForSingleObject return values.
*/
int WaitForModules(std::int32_t timeout, const std::initializer_list<std::wstring>& modules)
{
bool signaled[32] = { 0 };
bool success = false;
std::uint32_t totalSlept = 0;
if(timeout == 0) {
for(auto& mod : modules) {
if(GetModuleHandleW(std::data(mod)) == NULL)
return WAIT_TIMEOUT;
}
return WAIT_OBJECT_0;
}
if(timeout < 0)
timeout = INT32_MAX;
while(true) {
for(auto i = 0u; i < modules.size(); ++i) {
auto& module = *(modules.begin() + i);
if(!signaled[i] && GetModuleHandleW(std::data(module)) != NULL) {
signaled[i] = true;
//
// Checks if all modules are signaled
//
bool done = true;
for(auto j = 0u; j < modules.size(); ++j) {
if(!signaled[j]) {
done = false;
break;
}
}
if(done) {
success = true;
goto exit;
}
}
}
if(totalSlept > std::uint32_t(timeout)) {
break;
}
Sleep(10);
totalSlept += 10;
}
exit:
return success ? WAIT_OBJECT_0 : WAIT_TIMEOUT;
}
/*
* @brief Scan for a given byte pattern on a module
*
* @param module Base of the module to search
* @param signature IDA-style byte array pattern
*
* @returns Address of the first occurence
*/
std::uint8_t* PatternScan(void* module, const char* signature)
{
static auto pattern_to_byte = [](const char* pattern) {
auto bytes = std::vector<int>{};
auto start = const_cast<char*>(pattern);
auto end = const_cast<char*>(pattern) + strlen(pattern);
for(auto current = start; current < end; ++current) {
if(*current == '?') {
++current;
if(*current == '?')
++current;
bytes.push_back(-1);
} else {
bytes.push_back(strtoul(current, ¤t, 16));
}
}
return bytes;
};
auto dosHeader = (PIMAGE_DOS_HEADER)module;
auto ntHeaders = (PIMAGE_NT_HEADERS)((std::uint8_t*)module + dosHeader->e_lfanew);
auto sizeOfImage = ntHeaders->OptionalHeader.SizeOfImage;
auto patternBytes = pattern_to_byte(signature);
auto scanBytes = reinterpret_cast<std::uint8_t*>(module);
auto s = patternBytes.size();
auto d = patternBytes.data();
for(auto i = 0ul; i < sizeOfImage - s; ++i) {
bool found = true;
for(auto j = 0ul; j < s; ++j) {
if(scanBytes[i + j] != d[j] && d[j] != -1) {
found = false;
break;
}
}
if(found) {
return &scanBytes[i];
}
}
return nullptr;
}
/*
* @brief Set player clantag
*
* @param tag New clantag
*/
void SetClantag(const char* tag)
{
static auto fnClantagChanged = (int(__fastcall*)(const char*, const char*))PatternScan(GetModuleHandleW(L"engine.dll"), "53 56 57 8B DA 8B F9 FF 15");
fnClantagChanged(tag, tag);
}
/*
* @brief Set player name
*
* @param name New name
*/
void SetName(const char* name)
{
static auto nameConvar = g_CVar->FindVar("name");
nameConvar->m_fnChangeCallbacks.m_Size = 0;
// Fix so we can change names how many times we want
// This code will only run once because of `static`
static auto do_once = (nameConvar->SetValue("\n���"), true);
nameConvar->SetValue(name);
}
}
| 27.47 | 158 | 0.522752 | Tyler-Admin |
8b3983bd411a0009e438efb1d049f0c0a0ed2050 | 6,873 | cpp | C++ | cpp/src/test/recommender_data/TestShuffleIterator.cpp | rpalovics/Alpenglow | 63472ce667d517d6c7f47c9d0559861392fca3f9 | [
"Apache-2.0"
] | 28 | 2017-07-23T22:47:44.000Z | 2022-03-12T15:11:13.000Z | cpp/src/test/recommender_data/TestShuffleIterator.cpp | proto-n/Alpenglow | 7a15d5c57b511787379f095e7310e67423159fa0 | [
"Apache-2.0"
] | 4 | 2017-05-10T10:23:17.000Z | 2019-05-23T14:07:09.000Z | cpp/src/test/recommender_data/TestShuffleIterator.cpp | proto-n/Alpenglow | 7a15d5c57b511787379f095e7310e67423159fa0 | [
"Apache-2.0"
] | 9 | 2017-05-04T09:20:58.000Z | 2021-12-14T08:19:01.000Z | #include <vector>
#include <gtest/gtest.h>
#include "../../main/recommender_data/ShuffleIterator.h"
namespace {
class TestShuffleIterator : public ::testing::Test {
public:
RecommenderData rd;
TestShuffleIterator() {
EXPECT_TRUE(rd.initialize());
}
virtual ~TestShuffleIterator() {
// You can do clean-up work that doesn't throw exceptions here.
}
void SetUp() override {
}
void TearDown() override {
}
RecDat createRecDat(int user, int item, double time, double score){
RecDat recDat;
recDat.user=user;
recDat.item=item;
recDat.time=time;
recDat.score=score;
return recDat;
}
bool in(int element, vector<int> list){
//element is in list
for(uint i=0; i<list.size(); i++){
if(list[i]==element) return true;
}
return false;
}
};
}
TEST_F(TestShuffleIterator, size) {
RecDats recData;
recData.push_back(createRecDat(2,3,10.0,1.0));
recData.push_back(createRecDat(1,6,10.0,1.0));
recData.push_back(createRecDat(2,8,10.0,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 123124);
ASSERT_TRUE(it.initialize());
EXPECT_EQ(3,it.size());
}
TEST_F(TestShuffleIterator, hasNext) {
RecDats recData;
recData.push_back(createRecDat(2,3,10.1,1.0));
recData.push_back(createRecDat(1,6,10.2,1.0));
recData.push_back(createRecDat(2,8,10.3,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 1231212);
ASSERT_TRUE(it.initialize());
EXPECT_EQ(3,it.size());
ASSERT_TRUE(it.has_next());
it.next();
ASSERT_TRUE(it.has_next());
it.next();
ASSERT_TRUE(it.has_next());
it.next();
EXPECT_FALSE(it.has_next());
}
TEST_F(TestShuffleIterator, noshuffle_it) {
RecDats recData;
recData.push_back(createRecDat(2,3,10.1,1.0));
recData.push_back(createRecDat(1,6,10.2,1.0));
recData.push_back(createRecDat(2,8,10.3,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 1231212);
ASSERT_TRUE(it.initialize());
EXPECT_EQ(3,it.size());
ASSERT_TRUE(it.has_next());
RecDat* recDat = it.next();
EXPECT_EQ(3, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(6, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(8, recDat->item);
EXPECT_FALSE(it.has_next());
}
TEST_F(TestShuffleIterator, shuffle_it) {
RecDats recData;
recData.push_back(createRecDat(2,1,10.0,1.0));
recData.push_back(createRecDat(1,2,10.0,1.0));
recData.push_back(createRecDat(2,3,10.0,1.0));
recData.push_back(createRecDat(4,4,10.1,1.0));
recData.push_back(createRecDat(2,5,10.2,1.0));
recData.push_back(createRecDat(3,6,10.5,1.0));
recData.push_back(createRecDat(1,7,10.5,1.0));
recData.push_back(createRecDat(2,8,10.5,1.0));
recData.push_back(createRecDat(3,9,10.5,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 1239);
ASSERT_TRUE(it.initialize());
EXPECT_EQ(9,it.size());
vector<int> items; items.push_back(1); items.push_back(2); items.push_back(3);
ASSERT_TRUE(it.has_next());
RecDat* recDat = it.next();
EXPECT_EQ(10.0, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.0, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(2, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.0, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(3, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(4, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(5, recDat->item);
items.clear();
items.push_back(6);items.push_back(7);items.push_back(8);items.push_back(9);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.5, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(6, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.5, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(7, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.5, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(8, recDat->item);
ASSERT_TRUE(it.has_next());
recDat = it.next();
EXPECT_EQ(10.5, recDat->time);
EXPECT_TRUE(in(recDat->item, items));
EXPECT_NE(9, recDat->item);
}
TEST_F(TestShuffleIterator, noshuffle_get) {
RecDats recData;
recData.push_back(createRecDat(2,3,10.1,1.0));
recData.push_back(createRecDat(1,6,10.2,1.0));
recData.push_back(createRecDat(2,8,10.3,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 12361887);
ASSERT_TRUE(it.initialize());
EXPECT_EQ(3,it.size());
EXPECT_EQ(3, (it.get_future(0))->item);
EXPECT_EQ(6, (it.get_future(1))->item);
EXPECT_EQ(8, (it.get_future(2))->item);
EXPECT_EQ(6, (it.get_future(1))->item);
EXPECT_EQ(3, (it.get_future(0))->item);
EXPECT_EQ(8, (it.get_future(2))->item);
}
TEST_F(TestShuffleIterator, reproducable) {
RecDats recData;
recData.push_back(createRecDat(2,1,10.0,1.0));
recData.push_back(createRecDat(1,2,10.0,1.0));
recData.push_back(createRecDat(2,3,10.0,1.0));
recData.push_back(createRecDat(4,4,10.0,1.0));
recData.push_back(createRecDat(2,5,10.0,1.0));
recData.push_back(createRecDat(3,6,10.0,1.0));
recData.push_back(createRecDat(1,7,10.5,1.0));
recData.push_back(createRecDat(2,8,10.5,1.0));
recData.push_back(createRecDat(3,9,10.5,1.0));
rd.set_rec_data(recData);
ShuffleIterator it(&rd, 123124);
ASSERT_TRUE(it.initialize());
ShuffleIterator it2(&rd, 123124);
ASSERT_TRUE(it2.initialize());
EXPECT_EQ(it.get_future(0)->item,it2.get_future(0)->item);
EXPECT_EQ(it.get_future(1)->item,it2.get_future(1)->item);
EXPECT_EQ(it.get_future(2)->item,it2.get_future(2)->item);
EXPECT_EQ(it.get_future(3)->item,it2.get_future(3)->item);
EXPECT_EQ(it.get_future(4)->item,it2.get_future(4)->item);
EXPECT_EQ(it.get_future(5)->item,it2.get_future(5)->item);
EXPECT_EQ(it.get_future(6)->item,it2.get_future(6)->item);
EXPECT_EQ(it.get_future(7)->item,it2.get_future(7)->item);
EXPECT_EQ(it.get_future(8)->item,it2.get_future(8)->item);
}
//matrix function disabled, online recommender should not use it
//TEST_F(TestShuffleIterator, matrix) {
// RecDats recData;
// recData.push_back(createRecDat(2,3,10.0,1.0));
// recData.push_back(createRecDat(1,6,10.0,1.0));
// recData.push_back(createRecDat(2,8,10.0,1.0));
// rd.set_rec_data(recData);
// ShuffleIterator it(&rd, 1283761287);
// EXPECT_EQ(rd.matrix(),it.matrix());
//}
int main (int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 32.885167 | 82 | 0.66332 | rpalovics |
8b3a96e837d481a05a97ecc4d1b5fe5bdebb373e | 4,301 | cpp | C++ | compiler/tfldump/src/Read.cpp | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 1 | 2021-01-23T06:05:14.000Z | 2021-01-23T06:05:14.000Z | compiler/tfldump/src/Read.cpp | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | null | null | null | compiler/tfldump/src/Read.cpp | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "Read.h"
#include <sstream>
#include <string>
namespace tflread
{
// This will provide v3/v3a format neutral BuiltinOperator
tflite::BuiltinOperator builtin_code_neutral(const tflite::OperatorCode *opcode)
{
assert(opcode != nullptr);
int8_t dp_code = opcode->deprecated_builtin_code();
if (dp_code < 127 && dp_code >= 0)
return tflite::BuiltinOperator(dp_code);
return opcode->builtin_code();
}
bool is_valid(const tflite::OperatorCode *opcode)
{
tflite::BuiltinOperator code = builtin_code_neutral(opcode);
return (tflite::BuiltinOperator_MIN <= code && code <= tflite::BuiltinOperator_MAX);
}
bool is_custom(const tflite::OperatorCode *opcode)
{
tflite::BuiltinOperator code = builtin_code_neutral(opcode);
return (code == tflite::BuiltinOperator_CUSTOM);
}
std::string opcode_name(const tflite::OperatorCode *opcode)
{
assert(opcode);
if (!is_valid(opcode))
{
std::ostringstream oss;
oss << "(invalid)";
return oss.str();
}
if (is_custom(opcode))
{
if (!opcode->custom_code())
return "(invalid custom)";
std::string custom_op = "CUSTOM(";
custom_op += opcode->custom_code()->c_str();
custom_op += ")";
return custom_op;
}
tflite::BuiltinOperator code = builtin_code_neutral(opcode);
return tflite::EnumNameBuiltinOperator(code);
}
const char *tensor_type(const tflite::Tensor *tensor)
{
return tflite::EnumNameTensorType(tensor->type());
}
const char *tensor_name(const tflite::Tensor *tensor)
{
static const char *kEmptyTensorName = "(noname)";
auto name = tensor->name();
if (name)
return name->c_str();
return kEmptyTensorName;
}
Reader::Reader(const tflite::Model *model)
{
_version = model->version();
_subgraphs = model->subgraphs();
_buffers = model->buffers();
_metadata = model->metadata();
_signaturedefs = model->signature_defs();
auto opcodes = model->operator_codes();
for (const ::tflite::OperatorCode *opcode : *opcodes)
{
_op_codes.push_back(opcode);
}
}
size_t Reader::buffer_info(uint32_t buf_idx, const uint8_t **buff_data)
{
*buff_data = nullptr;
if (buf_idx == 0)
return 0;
if (auto *buffer = (*_buffers)[buf_idx])
{
if (auto *array = buffer->data())
{
if (size_t size = array->size())
{
*buff_data = reinterpret_cast<const uint8_t *>(array->data());
return size;
}
}
}
return 0;
}
tflite::BuiltinOperator Reader::builtin_code(const tflite::Operator *op) const
{
uint32_t index = op->opcode_index();
assert(index < _op_codes.size());
const tflite::OperatorCode *opcode = _op_codes.at(index);
return tflread::builtin_code_neutral(opcode);
}
std::string Reader::opcode_name(const tflite::Operator *op) const
{
uint32_t index = op->opcode_index();
assert(index < _op_codes.size());
const tflite::OperatorCode *opcode = _op_codes.at(index);
if (!is_valid(opcode))
{
std::ostringstream oss;
oss << "(invalid: " << index << ")";
return oss.str();
}
return tflread::opcode_name(opcode);
}
bool Reader::select_subgraph(uint32_t sgindex)
{
_subgraph_index = sgindex;
_tensors = nullptr;
_operators = nullptr;
_inputs.clear();
_outputs.clear();
if (_subgraphs->Length() <= sgindex)
{
assert(false);
return false;
}
const tflite::SubGraph *subgraph = (*_subgraphs)[sgindex];
auto name = subgraph->name();
_subgraph_name = name ? name->c_str() : "(noname)";
_tensors = subgraph->tensors();
_operators = subgraph->operators();
_inputs = as_index_vector(subgraph->inputs());
_outputs = as_index_vector(subgraph->outputs());
return true;
}
} // namespace tflread
| 23.762431 | 86 | 0.687515 | juitem |
8b3caed5e086b375e3f851f8eb858ac79e2db7df | 9,916 | cpp | C++ | examples/example-ftxui-extension.cpp | perfkitpp/perfkit | 19b691c8337b47594ed6be28051b3a5ee31af389 | [
"MIT"
] | null | null | null | examples/example-ftxui-extension.cpp | perfkitpp/perfkit | 19b691c8337b47594ed6be28051b3a5ee31af389 | [
"MIT"
] | 6 | 2021-10-14T15:38:06.000Z | 2022-01-08T12:55:04.000Z | examples/example-ftxui-extension.cpp | perfkitpp/perfkit | 19b691c8337b47594ed6be28051b3a5ee31af389 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2021-2022. Seungwoo Kang
//
// 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.
//
// project home: https://github.com/perfkitpp
#include "ftxui/component/captured_mouse.hpp" // for ftxui
#include "ftxui/component/component.hpp" // for Checkbox, Vertical
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
#include "perfkit/configs.h"
#include "perfkit/ftxui-extension.hpp"
#include "perfkit/traces.h"
#include "spdlog/fmt/fmt.h"
using namespace std::literals;
std::map<std::string, std::map<std::string, std::string>> ved{
{"asd", {{"asd", "weqw"}, {"vafe, ewqew", "dwrew"}}},
{"vadsfew", {{"dav ,ea w", "Ewqsad"}, {"scxz ss", "dwqewqew"}}}};
PERFKIT_CATEGORY(cfg)
{
PERFKIT_CONFIGURE(active, true).confirm();
PERFKIT_CONFIGURE(active_async, true).confirm();
PERFKIT_SUBCATEGORY(labels)
{
PERFKIT_CONFIGURE(foo, 1).confirm();
PERFKIT_CONFIGURE(bar, false).confirm();
PERFKIT_CONFIGURE(ce, "ola ollalala").confirm();
PERFKIT_CONFIGURE(ced, std::vector({1, 2, 3, 4, 5, 6})).confirm();
PERFKIT_CONFIGURE(cedr, (std::map<std::string, int>{
{"fdf", 2},
{"erwe", 4}}))
.confirm();
PERFKIT_CONFIGURE(bb, (std::map<std::string, bool>{
{"fdf", false},
{"erwe", true}}))
.confirm();
PERFKIT_CONFIGURE(cedrs, 3.141592).confirm();
PERFKIT_CONFIGURE(cedrstt, std::move(ved)).confirm();
}
PERFKIT_SUBCATEGORY(lomo)
{
PERFKIT_SUBCATEGORY(movdo)
{
PERFKIT_CONFIGURE(ce, 1).confirm();
PERFKIT_CONFIGURE(ced, 1).confirm();
PERFKIT_CONFIGURE(cedr, 1).confirm();
PERFKIT_SUBCATEGORY(cef)
{
}
PERFKIT_SUBCATEGORY(ccra)
{
PERFKIT_CONFIGURE(foo, 1).confirm();
PERFKIT_CONFIGURE(bar, 1).confirm();
PERFKIT_CONFIGURE(ce, 1).confirm();
PERFKIT_CONFIGURE(ced, 1).confirm();
PERFKIT_CONFIGURE(cedr, 1).confirm();
PERFKIT_CONFIGURE(cedrs, 1).confirm();
PERFKIT_CONFIGURE(a_foo, 1).confirm();
PERFKIT_CONFIGURE(a_bar, 1).confirm();
PERFKIT_CONFIGURE(a_ce, 1).confirm();
PERFKIT_CONFIGURE(a_ced, 1).confirm();
PERFKIT_CONFIGURE(a_cedr, 1).confirm();
PERFKIT_CONFIGURE(a_cedrs, 1).confirm();
PERFKIT_CONFIGURE(b_foo, 1).confirm();
PERFKIT_CONFIGURE(b_bar, 1).confirm();
PERFKIT_CONFIGURE(b_ce, 1).confirm();
PERFKIT_CONFIGURE(b_ced, 1).confirm();
PERFKIT_CONFIGURE(b_cedr, 1).confirm();
PERFKIT_CONFIGURE(b_cedrs, 1).confirm();
PERFKIT_CONFIGURE(c_foo, 1).confirm();
PERFKIT_CONFIGURE(c_bar, 1).confirm();
PERFKIT_CONFIGURE(c_ce, 1).confirm();
PERFKIT_CONFIGURE(c_ced, 1).confirm();
PERFKIT_CONFIGURE(c_cedr, 1).confirm();
PERFKIT_CONFIGURE(c_cedrs, 1).confirm();
PERFKIT_CONFIGURE(d_foo, 1).confirm();
PERFKIT_CONFIGURE(d_bar, 1).confirm();
PERFKIT_CONFIGURE(d_ce, 1).confirm();
PERFKIT_CONFIGURE(d_ced, 1).confirm();
PERFKIT_CONFIGURE(d_cedr, 1).confirm();
PERFKIT_CONFIGURE(d_cedrs, 1).confirm();
}
}
}
PERFKIT_CONFIGURE(foo, 1).confirm();
PERFKIT_CONFIGURE(bar, 1).confirm();
PERFKIT_CONFIGURE(ce, 1).confirm();
PERFKIT_CONFIGURE(ced, 1).confirm();
PERFKIT_CONFIGURE(cedr, 1).confirm();
PERFKIT_CONFIGURE(cedrs, 1).confirm();
PERFKIT_CONFIGURE(a_foo, 1).confirm();
PERFKIT_CONFIGURE(a_bar, 1).confirm();
PERFKIT_CONFIGURE(a_ce, 1).confirm();
PERFKIT_CONFIGURE(a_ced, 1).confirm();
PERFKIT_CONFIGURE(a_cedr, 1).confirm();
PERFKIT_CONFIGURE(a_cedrs, 1).confirm();
PERFKIT_CONFIGURE(b_foo, 1).confirm();
PERFKIT_CONFIGURE(b_bar, 1).confirm();
PERFKIT_CONFIGURE(b_ce, 1).confirm();
PERFKIT_CONFIGURE(b_ced, 1).confirm();
PERFKIT_CONFIGURE(b_cedr, 1).confirm();
PERFKIT_CONFIGURE(b_cedrs, 1).confirm();
PERFKIT_CONFIGURE(c_foo, 1).confirm();
PERFKIT_CONFIGURE(c_bar, 1).confirm();
PERFKIT_CONFIGURE(c_ce, 1).confirm();
PERFKIT_CONFIGURE(c_ced, 1).confirm();
PERFKIT_CONFIGURE(c_cedr, 1).confirm();
PERFKIT_CONFIGURE(c_cedrs, 1).confirm();
PERFKIT_CONFIGURE(d_foo, 1).confirm();
PERFKIT_CONFIGURE(d_bar, 1).confirm();
PERFKIT_CONFIGURE(d_ce, 1).confirm();
PERFKIT_CONFIGURE(d_ced, 1).confirm();
PERFKIT_CONFIGURE(d_cedr, 1).confirm();
PERFKIT_CONFIGURE(d_cedrs, 1).confirm();
PERFKIT_CONFIGURE(e_foo, 1).confirm();
PERFKIT_CONFIGURE(e_bar, 1).confirm();
PERFKIT_CONFIGURE(e_ce, 1).confirm();
PERFKIT_CONFIGURE(e_ced, 1).confirm();
PERFKIT_CONFIGURE(e_cedr, 1).confirm();
PERFKIT_CONFIGURE(e_cedrs, 1).confirm();
}
PERFKIT_CATEGORY(vlao)
{
PERFKIT_CONFIGURE(e_cedrs, 1).confirm();
PERFKIT_CONFIGURE(e_cedrsd, "").confirm();
}
PERFKIT_CATEGORY(vlao1) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao2) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao3) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao4) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao5) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao6) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao7) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao8) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao9) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao22) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao33) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao44) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
PERFKIT_CATEGORY(vlao55) { PERFKIT_CONFIGURE(e_cedrs, 1).confirm(); }
using namespace ftxui;
perfkit::tracer traces[] = {
{0, "root (1)"},
{1, "A (2)"},
{31, "B (4)"},
{-51, "C (0)"},
{14, "D (3)"},
};
class my_subscriber : public perfkit_ftxui::if_subscriber
{
public:
bool on_update(update_param_type const& param_type, perfkit::trace_variant_type const& value) override
{
traces[1].fork("Value update A")["NAME"] = param_type.name;
return true;
}
void on_end(update_param_type const& param_type) override
{
vlao::e_cedrs.async_modify(vlao::e_cedrs.get() + 1);
vlao::e_cedrsd.async_modify(std::string(param_type.name));
vlao::registry().apply_update_and_check_if_dirty();
}
};
int main(int argc, char const* argv[])
{
auto screen = ScreenInteractive::Fullscreen();
std::shared_ptr<perfkit_ftxui::string_queue> commands;
auto preset = perfkit_ftxui::PRESET(&commands, {}, std::make_shared<my_subscriber>());
auto kill_switch = perfkit_ftxui::launch_async_loop(&screen, preset);
for (int ic = 0; perfkit_ftxui::is_alive(kill_switch.get()); ++ic) {
std::this_thread::sleep_for(10ms);
cfg::registry().apply_update_and_check_if_dirty();
auto trc_root = traces[0].fork("Root Trace");
auto timer = trc_root.timer("Some Timer");
trc_root["Value 0"] = 3;
trc_root["Value 1"] = *cfg::labels::foo;
trc_root["Value 2"] = fmt::format("Hell, world! {}", *cfg::labels::foo);
trc_root["Value 3"] = false;
trc_root["Value 3"]["Subvalue 0"] = ic;
trc_root["Value 3"]["Subvalue GR"] = std::vector<int>{3, 4, 5};
trc_root["Value 3"]["Subvalue 1"] = double(ic);
trc_root["Value 3"]["Subvalue 2"] = !!(ic & 1);
trc_root["Value 4"]["Subvalue 3"] = fmt::format("Hell, world! {}", ic);
auto r = trc_root["Value 5"];
trc_root["Value 5"]["Subvalue 0"] = ic;
if (r) { trc_root["Value 5"]["Subvalue 1 Cond"] = double(ic); }
trc_root["Value 5"]["Subvalue 2"] = !!(ic & 1);
std::string to_get;
if (commands->try_getline(to_get)) {
trc_root["TEXT"] = to_get;
}
cfg::labels::foo.async_modify(cfg::labels::foo.get() + 1);
if (cfg::active_async.get() == false) {
kill_switch.reset();
break;
}
}
return 0;
}
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file. | 40.145749 | 130 | 0.619907 | perfkitpp |
8b3d56d6f717976bb780f72b942c32c9839a2262 | 945 | cc | C++ | node/binding/webgl/WebGLTexture.cc | jwxbond/GCanvas | f4bbb207d3b47abab3103da43371f47a86b0a3bd | [
"Apache-2.0"
] | 4 | 2017-08-04T04:31:33.000Z | 2019-11-01T06:32:23.000Z | node/binding/webgl/WebGLTexture.cc | jwxbond/GCanvas | f4bbb207d3b47abab3103da43371f47a86b0a3bd | [
"Apache-2.0"
] | 2 | 2017-10-31T11:55:16.000Z | 2018-02-01T10:33:39.000Z | node/binding/webgl/WebGLTexture.cc | jwxbond/GCanvas | f4bbb207d3b47abab3103da43371f47a86b0a3bd | [
"Apache-2.0"
] | null | null | null | /**
* Created by G-Canvas Open Source Team.
* Copyright (c) 2017, Alibaba, Inc. All rights reserved.
*
* This source code is licensed under the Apache Licence 2.0.
* For the full copyright and license information, please view
* the LICENSE file in the root directory of this source tree.
*/
#include "WebGLTexture.h"
namespace NodeBinding
{
Napi::FunctionReference WebGLTexture::constructor;
WebGLTexture::WebGLTexture(const Napi::CallbackInfo &info) : Napi::ObjectWrap<WebGLTexture>(info)
{
mId = info[0].As<Napi::Number>().Uint32Value();
}
void WebGLTexture::Init(Napi::Env env)
{
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(env, "WebGLTexture", {});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
}
Napi::Object WebGLTexture::NewInstance(Napi::Env env, const Napi::Value arg)
{
Napi::Object obj = constructor.New({arg});
return obj;
}
} // namespace NodeBinding | 29.53125 | 97 | 0.719577 | jwxbond |
8b3e21556e4ec325a557384cae395eda73b602c2 | 3,819 | cpp | C++ | test/unit/module/math/cosd.cpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 340 | 2020-09-16T21:12:48.000Z | 2022-03-28T15:40:33.000Z | test/unit/module/math/cosd.cpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 383 | 2020-09-17T06:56:35.000Z | 2022-03-13T15:58:53.000Z | test/unit/module/math/cosd.cpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 28 | 2021-02-27T23:11:23.000Z | 2022-03-25T12:31:29.000Z | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/concept/value.hpp>
#include <eve/constant/valmin.hpp>
#include <eve/constant/valmax.hpp>
#include <eve/constant/invpi.hpp>
#include <eve/function/cosd.hpp>
#include <eve/function/diff/cosd.hpp>
#include <eve/function/deginrad.hpp>
#include <cmath>
#include <eve/module/math/detail/constant/rempio2_limits.hpp>
#include <eve/detail/function/tmp/boost_math_cospi.hpp>
#include <eve/detail/function/tmp/boost_math_sinpi.hpp>
//==================================================================================================
// Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of cosd"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using v_t = eve::element_type_t<T>;
TTS_EXPR_IS( eve::cosd(T()) , T);
TTS_EXPR_IS( eve::cosd(v_t()), v_t);
};
//==================================================================================================
// cosd tests
//==================================================================================================
auto mquarter_c = []<typename T>(eve::as<T> const & ){ return T(-45); };
auto quarter_c = []<typename T>(eve::as<T> const & ){ return T( 45); };
auto mhalf_c = []<typename T>(eve::as<T> const & ){ return T(-90 ); };
auto half_c = []<typename T>(eve::as<T> const & ){ return T( 90 ); };
auto mmed = []<typename T>(eve::as<T> const & ){ return -5000; };
auto med = []<typename T>(eve::as<T> const & ){ return 5000; };
EVE_TEST( "Check behavior of cosd on wide"
, eve::test::simd::ieee_reals
, eve::test::generate( eve::test::randoms(mquarter_c, quarter_c)
, eve::test::randoms(mhalf_c, half_c)
, eve::test::randoms(mmed, med))
)
<typename T>(T const& a0, T const& a1, T const& a2)
{
using eve::detail::map;
using eve::cosd;
using eve::diff;
using eve::deginrad;
using v_t = eve::element_type_t<T>;
auto ref = [](auto e) -> v_t { return boost::math::cos_pi(e/180.0l); };
TTS_ULP_EQUAL(eve::quarter_circle(cosd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cosd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cosd)(a1) , map(ref, a1), 30);
TTS_ULP_EQUAL(cosd(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(cosd(a1) , map(ref, a1), 30);
TTS_ULP_EQUAL(cosd(a2) , map(ref, a2), 420);
auto dinr = 1.7453292519943295769236907684886127134428718885417e-2l;
TTS_ULP_EQUAL(diff(cosd)(a0), map([dinr](auto e) -> v_t { return -dinr*boost::math::sin_pi(e/180.0l); }, a0), 2);
};
EVE_TEST_TYPES( "Check return types of cosd"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
TTS_ULP_EQUAL(eve::cosd(T(1)) , T(0.9998476951563912391570115588139148516927403105832) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(-1)) , T(0.9998476951563912391570115588139148516927403105832) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(45.0)) , T(0.70710678118654752440084436210484903928483593768847) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(-T(45.0)) , T(0.70710678118654752440084436210484903928483593768847) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(-500.0)) , T(-0.7660444431189780352023926505554166739358324570804) , 3.5 );
TTS_ULP_EQUAL(eve::cosd(T(500.0)) , T(-0.7660444431189780352023926505554166739358324570804) , 3.5 );
};
| 46.012048 | 116 | 0.532338 | the-moisrex |
8b3e4f0a9886e7b1a98fc35c7f3e579114ba0685 | 12,285 | hpp | C++ | include/Zenject/SubContainerCreatorByNewGameObjectMethod_1.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Zenject/SubContainerCreatorByNewGameObjectMethod_1.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Zenject/SubContainerCreatorByNewGameObjectMethod_1.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Zenject.SubContainerCreatorByNewGameObjectDynamicContext
#include "Zenject/SubContainerCreatorByNewGameObjectDynamicContext.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Skipping declaration: <>c__DisplayClass2_0 because it is already included!
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: GameObjectCreationParameters
class GameObjectCreationParameters;
// Forward declaring type: GameObjectContext
class GameObjectContext;
// Forward declaring type: InjectTypeInfo
class InjectTypeInfo;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Forward declaring type: SubContainerCreatorByNewGameObjectMethod`1<TParam1>
template<typename TParam1>
class SubContainerCreatorByNewGameObjectMethod_1;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::Zenject::SubContainerCreatorByNewGameObjectMethod_1, "Zenject", "SubContainerCreatorByNewGameObjectMethod`1");
// Type namespace: Zenject
namespace Zenject {
// WARNING Size may be invalid!
// Autogenerated type: Zenject.SubContainerCreatorByNewGameObjectMethod`1
// [TokenAttribute] Offset: FFFFFFFF
// [NoReflectionBakingAttribute] Offset: FFFFFFFF
template<typename TParam1>
class SubContainerCreatorByNewGameObjectMethod_1 : public ::Zenject::SubContainerCreatorByNewGameObjectDynamicContext {
public:
// Nested type: ::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0<TParam1>
class $$c__DisplayClass2_0;
// WARNING Size may be invalid!
// Autogenerated type: Zenject.SubContainerCreatorByNewGameObjectMethod`1/Zenject.<>c__DisplayClass2_0
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class $$c__DisplayClass2_0 : public ::il2cpp_utils::il2cpp_type_check::NestedType, public ::Il2CppObject {
public:
using declaring_type = SubContainerCreatorByNewGameObjectMethod_1<TParam1>*;
static constexpr std::string_view NESTED_NAME = "<>c__DisplayClass2_0";
static constexpr bool IS_VALUE_TYPE = false;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public Zenject.SubContainerCreatorByNewGameObjectMethod`1<TParam1> <>4__this
// Size: 0x8
// Offset: 0x0
::Zenject::SubContainerCreatorByNewGameObjectMethod_1<TParam1>* $$4__this;
// Field size check
static_assert(sizeof(::Zenject::SubContainerCreatorByNewGameObjectMethod_1<TParam1>*) == 0x8);
// public System.Collections.Generic.List`1<Zenject.TypeValuePair> args
// Size: 0x8
// Offset: 0x0
::System::Collections::Generic::List_1<::Zenject::TypeValuePair>* args;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::Zenject::TypeValuePair>*) == 0x8);
public:
// Autogenerated instance field getter
// Get instance field: public Zenject.SubContainerCreatorByNewGameObjectMethod`1<TParam1> <>4__this
::Zenject::SubContainerCreatorByNewGameObjectMethod_1<TParam1>*& dyn_$$4__this() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::dyn_$$4__this");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>4__this"))->offset;
return *reinterpret_cast<::Zenject::SubContainerCreatorByNewGameObjectMethod_1<TParam1>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Collections.Generic.List`1<Zenject.TypeValuePair> args
::System::Collections::Generic::List_1<::Zenject::TypeValuePair>*& dyn_args() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::dyn_args");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "args"))->offset;
return *reinterpret_cast<::System::Collections::Generic::List_1<::Zenject::TypeValuePair>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// System.Void <AddInstallers>b__0(Zenject.DiContainer subContainer)
// Offset: 0xFFFFFFFFFFFFFFFF
void $AddInstallers$b__0(::Zenject::DiContainer* subContainer) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::<AddInstallers>b__0");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<AddInstallers>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(subContainer)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, subContainer);
}
// static private System.Object __zenCreate(System.Object[] P_0)
// Offset: 0xFFFFFFFFFFFFFFFF
static ::Il2CppObject* __zenCreate(::ArrayW<::Il2CppObject*> P_0) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::__zenCreate");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<typename SubContainerCreatorByNewGameObjectMethod_1<TParam1>::$$c__DisplayClass2_0*>::get(), "__zenCreate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(P_0)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, P_0);
}
// static private Zenject.InjectTypeInfo __zenCreateInjectTypeInfo()
// Offset: 0xFFFFFFFFFFFFFFFF
static ::Zenject::InjectTypeInfo* __zenCreateInjectTypeInfo() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::__zenCreateInjectTypeInfo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<typename SubContainerCreatorByNewGameObjectMethod_1<TParam1>::$$c__DisplayClass2_0*>::get(), "__zenCreateInjectTypeInfo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Zenject::InjectTypeInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// public System.Void .ctor()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static typename SubContainerCreatorByNewGameObjectMethod_1<TParam1>::$$c__DisplayClass2_0* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::$$c__DisplayClass2_0::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<typename SubContainerCreatorByNewGameObjectMethod_1<TParam1>::$$c__DisplayClass2_0*, creationType>()));
}
}; // Zenject.SubContainerCreatorByNewGameObjectMethod`1/Zenject.<>c__DisplayClass2_0
// Could not write size check! Type: Zenject.SubContainerCreatorByNewGameObjectMethod`1/Zenject.<>c__DisplayClass2_0 is generic, or has no fields that are valid for size checks!
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private readonly System.Action`2<Zenject.DiContainer,TParam1> _installerMethod
// Size: 0x8
// Offset: 0x0
::System::Action_2<::Zenject::DiContainer*, TParam1>* installerMethod;
// Field size check
static_assert(sizeof(::System::Action_2<::Zenject::DiContainer*, TParam1>*) == 0x8);
public:
// Autogenerated instance field getter
// Get instance field: private readonly System.Action`2<Zenject.DiContainer,TParam1> _installerMethod
::System::Action_2<::Zenject::DiContainer*, TParam1>*& dyn__installerMethod() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::dyn__installerMethod");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_installerMethod"))->offset;
return *reinterpret_cast<::System::Action_2<::Zenject::DiContainer*, TParam1>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// public System.Void .ctor(Zenject.DiContainer container, Zenject.GameObjectCreationParameters gameObjectBindInfo, System.Action`2<Zenject.DiContainer,TParam1> installerMethod)
// Offset: 0xFFFFFFFFFFFFFFFF
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SubContainerCreatorByNewGameObjectMethod_1<TParam1>* New_ctor(::Zenject::DiContainer* container, ::Zenject::GameObjectCreationParameters* gameObjectBindInfo, ::System::Action_2<::Zenject::DiContainer*, TParam1>* installerMethod) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SubContainerCreatorByNewGameObjectMethod_1<TParam1>*, creationType>(container, gameObjectBindInfo, installerMethod)));
}
// protected override System.Void AddInstallers(System.Collections.Generic.List`1<Zenject.TypeValuePair> args, Zenject.GameObjectContext context)
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: Zenject.SubContainerCreatorDynamicContext
// Base method: System.Void SubContainerCreatorDynamicContext::AddInstallers(System.Collections.Generic.List`1<Zenject.TypeValuePair> args, Zenject.GameObjectContext context)
void AddInstallers(::System::Collections::Generic::List_1<::Zenject::TypeValuePair>* args, ::Zenject::GameObjectContext* context) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::SubContainerCreatorByNewGameObjectMethod_1::AddInstallers");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddInstallers", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(args), ::il2cpp_utils::ExtractType(context)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, args, context);
}
}; // Zenject.SubContainerCreatorByNewGameObjectMethod`1
// Could not write size check! Type: Zenject.SubContainerCreatorByNewGameObjectMethod`1 is generic, or has no fields that are valid for size checks!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 67.131148 | 347 | 0.745136 | RedBrumbler |
8b3f1722dddf3cac01b47221a64d5617d9507d60 | 40,349 | cpp | C++ | libs/hwui/BakedOpDispatcher.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | libs/hwui/BakedOpDispatcher.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | libs/hwui/BakedOpDispatcher.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BakedOpDispatcher.h"
#include "BakedOpRenderer.h"
#include "Caches.h"
#include "Glop.h"
#include "GlopBuilder.h"
#include "Patch.h"
#include "PathTessellator.h"
#include "renderstate/OffscreenBufferPool.h"
#include "renderstate/RenderState.h"
#include "utils/GLUtils.h"
#include "VertexBuffer.h"
#include <algorithm>
#include <math.h>
#include <SkPaintDefaults.h>
#include <SkPathOps.h>
namespace android {
namespace uirenderer {
static void storeTexturedRect(TextureVertex* vertices, const Rect& bounds, const Rect& texCoord) {
vertices[0] = { bounds.left, bounds.top, texCoord.left, texCoord.top };
vertices[1] = { bounds.right, bounds.top, texCoord.right, texCoord.top };
vertices[2] = { bounds.left, bounds.bottom, texCoord.left, texCoord.bottom };
vertices[3] = { bounds.right, bounds.bottom, texCoord.right, texCoord.bottom };
}
void BakedOpDispatcher::onMergedBitmapOps(BakedOpRenderer& renderer,
const MergedBakedOpList& opList) {
const BakedOpState& firstState = *(opList.states[0]);
const SkBitmap* bitmap = (static_cast<const BitmapOp*>(opList.states[0]->op))->bitmap;
AssetAtlas::Entry* entry = renderer.renderState().assetAtlas().getEntry(bitmap->pixelRef());
Texture* texture = entry ? entry->texture : renderer.caches().textureCache.get(bitmap);
if (!texture) return;
const AutoTexture autoCleanup(texture);
TextureVertex vertices[opList.count * 4];
Rect texCoords(0, 0, 1, 1);
if (entry) {
entry->uvMapper.map(texCoords);
}
for (size_t i = 0; i < opList.count; i++) {
const BakedOpState& state = *(opList.states[i]);
TextureVertex* rectVerts = &vertices[i * 4];
// calculate unclipped bounds, since they'll determine texture coordinates
Rect opBounds = state.op->unmappedBounds;
state.computedState.transform.mapRect(opBounds);
if (CC_LIKELY(state.computedState.transform.isPureTranslate())) {
// pure translate, so snap (same behavior as onBitmapOp)
opBounds.snapToPixelBoundaries();
}
storeTexturedRect(rectVerts, opBounds, texCoords);
renderer.dirtyRenderTarget(opBounds);
}
const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(firstState.roundRectClipState)
.setMeshTexturedIndexedQuads(vertices, opList.count * 6)
.setFillTexturePaint(*texture, textureFillFlags, firstState.op->paint, firstState.alpha)
.setTransform(Matrix4::identity(), TransformFlags::None)
.setModelViewIdentityEmptyBounds()
.build();
ClipRect renderTargetClip(opList.clip);
const ClipBase* clip = opList.clipSideFlags ? &renderTargetClip : nullptr;
renderer.renderGlop(nullptr, clip, glop);
}
void BakedOpDispatcher::onMergedPatchOps(BakedOpRenderer& renderer,
const MergedBakedOpList& opList) {
const PatchOp& firstOp = *(static_cast<const PatchOp*>(opList.states[0]->op));
const BakedOpState& firstState = *(opList.states[0]);
AssetAtlas::Entry* entry = renderer.renderState().assetAtlas().getEntry(
firstOp.bitmap->pixelRef());
// Batches will usually contain a small number of items so it's
// worth performing a first iteration to count the exact number
// of vertices we need in the new mesh
uint32_t totalVertices = 0;
for (size_t i = 0; i < opList.count; i++) {
const PatchOp& op = *(static_cast<const PatchOp*>(opList.states[i]->op));
// TODO: cache mesh lookups
const Patch* opMesh = renderer.caches().patchCache.get(
entry, op.bitmap->width(), op.bitmap->height(),
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.patch);
totalVertices += opMesh->verticesCount;
}
const bool dirtyRenderTarget = renderer.offscreenRenderTarget();
uint32_t indexCount = 0;
TextureVertex vertices[totalVertices];
TextureVertex* vertex = &vertices[0];
// Create a mesh that contains the transformed vertices for all the
// 9-patch objects that are part of the batch. Note that onDefer()
// enforces ops drawn by this function to have a pure translate or
// identity matrix
for (size_t i = 0; i < opList.count; i++) {
const PatchOp& op = *(static_cast<const PatchOp*>(opList.states[i]->op));
const BakedOpState& state = *opList.states[i];
// TODO: cache mesh lookups
const Patch* opMesh = renderer.caches().patchCache.get(
entry, op.bitmap->width(), op.bitmap->height(),
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.patch);
uint32_t vertexCount = opMesh->verticesCount;
if (vertexCount == 0) continue;
// We use the bounds to know where to translate our vertices
// Using patchOp->state.mBounds wouldn't work because these
// bounds are clipped
const float tx = floorf(state.computedState.transform.getTranslateX()
+ op.unmappedBounds.left + 0.5f);
const float ty = floorf(state.computedState.transform.getTranslateY()
+ op.unmappedBounds.top + 0.5f);
// Copy & transform all the vertices for the current operation
TextureVertex* opVertices = opMesh->vertices.get();
for (uint32_t j = 0; j < vertexCount; j++, opVertices++) {
TextureVertex::set(vertex++,
opVertices->x + tx, opVertices->y + ty,
opVertices->u, opVertices->v);
}
// Dirty the current layer if possible. When the 9-patch does not
// contain empty quads we can take a shortcut and simply set the
// dirty rect to the object's bounds.
if (dirtyRenderTarget) {
if (!opMesh->hasEmptyQuads) {
renderer.dirtyRenderTarget(Rect(tx, ty,
tx + op.unmappedBounds.getWidth(), ty + op.unmappedBounds.getHeight()));
} else {
const size_t count = opMesh->quads.size();
for (size_t i = 0; i < count; i++) {
const Rect& quadBounds = opMesh->quads[i];
const float x = tx + quadBounds.left;
const float y = ty + quadBounds.top;
renderer.dirtyRenderTarget(Rect(x, y,
x + quadBounds.getWidth(), y + quadBounds.getHeight()));
}
}
}
indexCount += opMesh->indexCount;
}
Texture* texture = entry ? entry->texture : renderer.caches().textureCache.get(firstOp.bitmap);
if (!texture) return;
const AutoTexture autoCleanup(texture);
// 9 patches are built for stretching - always filter
int textureFillFlags = TextureFillFlags::ForceFilter;
if (firstOp.bitmap->colorType() == kAlpha_8_SkColorType) {
textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
}
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(firstState.roundRectClipState)
.setMeshTexturedIndexedQuads(vertices, indexCount)
.setFillTexturePaint(*texture, textureFillFlags, firstOp.paint, firstState.alpha)
.setTransform(Matrix4::identity(), TransformFlags::None)
.setModelViewIdentityEmptyBounds()
.build();
ClipRect renderTargetClip(opList.clip);
const ClipBase* clip = opList.clipSideFlags ? &renderTargetClip : nullptr;
renderer.renderGlop(nullptr, clip, glop);
}
static void renderTextShadow(BakedOpRenderer& renderer,
const TextOp& op, const BakedOpState& textOpState) {
if (CC_LIKELY(!PaintUtils::hasTextShadow(op.paint))) return;
FontRenderer& fontRenderer = renderer.caches().fontRenderer.getFontRenderer();
fontRenderer.setFont(op.paint, SkMatrix::I());
renderer.caches().textureState().activateTexture(0);
PaintUtils::TextShadow textShadow;
if (!PaintUtils::getTextShadow(op.paint, &textShadow)) {
LOG_ALWAYS_FATAL("failed to query shadow attributes");
}
renderer.caches().dropShadowCache.setFontRenderer(fontRenderer);
ShadowTexture* texture = renderer.caches().dropShadowCache.get(
op.paint, op.glyphs, op.glyphCount, textShadow.radius, op.positions);
// If the drop shadow exceeds the max texture size or couldn't be
// allocated, skip drawing
if (!texture) return;
const AutoTexture autoCleanup(texture);
const float sx = op.x - texture->left + textShadow.dx;
const float sy = op.y - texture->top + textShadow.dy;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(textOpState.roundRectClipState)
.setMeshTexturedUnitQuad(nullptr)
.setFillShadowTexturePaint(*texture, textShadow.color, *op.paint, textOpState.alpha)
.setTransform(textOpState.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width(), sy + texture->height()))
.build();
// Compute damage bounds and clip (since may differ from those in textOpState).
// Bounds should be same as text op, but with dx/dy offset and radius outset
// applied in local space.
auto& transform = textOpState.computedState.transform;
Rect shadowBounds = op.unmappedBounds; // STROKE
const bool expandForStroke = op.paint->getStyle() != SkPaint::kFill_Style;
if (expandForStroke) {
shadowBounds.outset(op.paint->getStrokeWidth() * 0.5f);
}
shadowBounds.translate(textShadow.dx, textShadow.dy);
shadowBounds.outset(textShadow.radius, textShadow.radius);
transform.mapRect(shadowBounds);
if (CC_UNLIKELY(expandForStroke &&
(!transform.isPureTranslate() || op.paint->getStrokeWidth() < 1.0f))) {
shadowBounds.outset(0.5f);
}
auto clipState = textOpState.computedState.clipState;
if (clipState->mode != ClipMode::Rectangle
|| !clipState->rect.contains(shadowBounds)) {
// need clip, so pass it and clip bounds
shadowBounds.doIntersect(clipState->rect);
} else {
// don't need clip, ignore
clipState = nullptr;
}
renderer.renderGlop(&shadowBounds, clipState, glop);
}
enum class TextRenderType {
Defer,
Flush
};
static void renderText(BakedOpRenderer& renderer, const TextOp& op, const BakedOpState& state,
const ClipBase* renderClip, TextRenderType renderType) {
FontRenderer& fontRenderer = renderer.caches().fontRenderer.getFontRenderer();
float x = op.x;
float y = op.y;
const Matrix4& transform = state.computedState.transform;
const bool pureTranslate = transform.isPureTranslate();
if (CC_LIKELY(pureTranslate)) {
x = floorf(x + transform.getTranslateX() + 0.5f);
y = floorf(y + transform.getTranslateY() + 0.5f);
fontRenderer.setFont(op.paint, SkMatrix::I());
fontRenderer.setTextureFiltering(false);
} else if (CC_UNLIKELY(transform.isPerspective())) {
fontRenderer.setFont(op.paint, SkMatrix::I());
fontRenderer.setTextureFiltering(true);
} else {
// We only pass a partial transform to the font renderer. That partial
// matrix defines how glyphs are rasterized. Typically we want glyphs
// to be rasterized at their final size on screen, which means the partial
// matrix needs to take the scale factor into account.
// When a partial matrix is used to transform glyphs during rasterization,
// the mesh is generated with the inverse transform (in the case of scale,
// the mesh is generated at 1.0 / scale for instance.) This allows us to
// apply the full transform matrix at draw time in the vertex shader.
// Applying the full matrix in the shader is the easiest way to handle
// rotation and perspective and allows us to always generated quads in the
// font renderer which greatly simplifies the code, clipping in particular.
float sx, sy;
transform.decomposeScale(sx, sy);
fontRenderer.setFont(op.paint, SkMatrix::MakeScale(
roundf(std::max(1.0f, sx)),
roundf(std::max(1.0f, sy))));
fontRenderer.setTextureFiltering(true);
}
Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
int alpha = PaintUtils::getAlphaDirect(op.paint) * state.alpha;
SkXfermode::Mode mode = PaintUtils::getXfermodeDirect(op.paint);
TextDrawFunctor functor(&renderer, &state, renderClip,
x, y, pureTranslate, alpha, mode, op.paint);
bool forceFinish = (renderType == TextRenderType::Flush);
bool mustDirtyRenderTarget = renderer.offscreenRenderTarget();
const Rect* localOpClip = pureTranslate ? &state.computedState.clipRect() : nullptr;
fontRenderer.renderPosText(op.paint, localOpClip, op.glyphs, op.glyphCount, x, y,
op.positions, mustDirtyRenderTarget ? &layerBounds : nullptr, &functor, forceFinish);
if (mustDirtyRenderTarget) {
if (!pureTranslate) {
transform.mapRect(layerBounds);
}
renderer.dirtyRenderTarget(layerBounds);
}
}
void BakedOpDispatcher::onMergedTextOps(BakedOpRenderer& renderer,
const MergedBakedOpList& opList) {
for (size_t i = 0; i < opList.count; i++) {
const BakedOpState& state = *(opList.states[i]);
const TextOp& op = *(static_cast<const TextOp*>(state.op));
renderTextShadow(renderer, op, state);
}
ClipRect renderTargetClip(opList.clip);
const ClipBase* clip = opList.clipSideFlags ? &renderTargetClip : nullptr;
for (size_t i = 0; i < opList.count; i++) {
const BakedOpState& state = *(opList.states[i]);
const TextOp& op = *(static_cast<const TextOp*>(state.op));
TextRenderType renderType = (i + 1 == opList.count)
? TextRenderType::Flush : TextRenderType::Defer;
renderText(renderer, op, state, clip, renderType);
}
}
namespace VertexBufferRenderFlags {
enum {
Offset = 0x1,
ShadowInterp = 0x2,
};
}
static void renderVertexBuffer(BakedOpRenderer& renderer, const BakedOpState& state,
const VertexBuffer& vertexBuffer, float translateX, float translateY,
const SkPaint& paint, int vertexBufferRenderFlags) {
if (CC_LIKELY(vertexBuffer.getVertexCount())) {
bool shadowInterp = vertexBufferRenderFlags & VertexBufferRenderFlags::ShadowInterp;
const int transformFlags = vertexBufferRenderFlags & VertexBufferRenderFlags::Offset
? TransformFlags::OffsetByFudgeFactor : 0;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshVertexBuffer(vertexBuffer)
.setFillPaint(paint, state.alpha, shadowInterp)
.setTransform(state.computedState.transform, transformFlags)
.setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
.build();
renderer.renderGlop(state, glop);
}
}
static void renderConvexPath(BakedOpRenderer& renderer, const BakedOpState& state,
const SkPath& path, const SkPaint& paint) {
VertexBuffer vertexBuffer;
// TODO: try clipping large paths to viewport
PathTessellator::tessellatePath(path, &paint, state.computedState.transform, vertexBuffer);
renderVertexBuffer(renderer, state, vertexBuffer, 0.0f, 0.0f, paint, 0);
}
static void renderPathTexture(BakedOpRenderer& renderer, const BakedOpState& state,
float xOffset, float yOffset, PathTexture& texture, const SkPaint& paint) {
Rect dest(texture.width(), texture.height());
dest.translate(xOffset + texture.left - texture.offset,
yOffset + texture.top - texture.offset);
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedUnitQuad(nullptr)
.setFillPathTexturePaint(texture, paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRect(dest)
.build();
renderer.renderGlop(state, glop);
}
SkRect getBoundsOfFill(const RecordedOp& op) {
SkRect bounds = op.unmappedBounds.toSkRect();
if (op.paint->getStyle() == SkPaint::kStrokeAndFill_Style) {
float outsetDistance = op.paint->getStrokeWidth() / 2;
bounds.outset(outsetDistance, outsetDistance);
}
return bounds;
}
void BakedOpDispatcher::onArcOp(BakedOpRenderer& renderer, const ArcOp& op, const BakedOpState& state) {
// TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
if (op.paint->getStyle() != SkPaint::kStroke_Style
|| op.paint->getPathEffect() != nullptr
|| op.useCenter) {
PathTexture* texture = renderer.caches().pathCache.getArc(
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(),
op.startAngle, op.sweepAngle, op.useCenter, op.paint);
const AutoTexture holder(texture);
if (CC_LIKELY(holder.texture)) {
renderPathTexture(renderer, state, op.unmappedBounds.left, op.unmappedBounds.top,
*texture, *(op.paint));
}
} else {
SkRect rect = getBoundsOfFill(op);
SkPath path;
if (op.useCenter) {
path.moveTo(rect.centerX(), rect.centerY());
}
path.arcTo(rect, op.startAngle, op.sweepAngle, !op.useCenter);
if (op.useCenter) {
path.close();
}
renderConvexPath(renderer, state, path, *(op.paint));
}
}
void BakedOpDispatcher::onBitmapOp(BakedOpRenderer& renderer, const BitmapOp& op, const BakedOpState& state) {
Texture* texture = renderer.getTexture(op.bitmap);
if (!texture) return;
const AutoTexture autoCleanup(texture);
const int textureFillFlags = (op.bitmap->colorType() == kAlpha_8_SkColorType)
? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedUnitQuad(texture->uvMapper)
.setFillTexturePaint(*texture, textureFillFlags, op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRectSnap(Rect(texture->width(), texture->height()))
.build();
renderer.renderGlop(state, glop);
}
void BakedOpDispatcher::onBitmapMeshOp(BakedOpRenderer& renderer, const BitmapMeshOp& op, const BakedOpState& state) {
const static UvMapper defaultUvMapper;
const uint32_t elementCount = op.meshWidth * op.meshHeight * 6;
std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]);
ColorTextureVertex* vertex = &mesh[0];
const int* colors = op.colors;
std::unique_ptr<int[]> tempColors;
if (!colors) {
uint32_t colorsCount = (op.meshWidth + 1) * (op.meshHeight + 1);
tempColors.reset(new int[colorsCount]);
memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
colors = tempColors.get();
}
Texture* texture = renderer.renderState().assetAtlas().getEntryTexture(op.bitmap->pixelRef());
const UvMapper& mapper(texture && texture->uvMapper ? *texture->uvMapper : defaultUvMapper);
for (int32_t y = 0; y < op.meshHeight; y++) {
for (int32_t x = 0; x < op.meshWidth; x++) {
uint32_t i = (y * (op.meshWidth + 1) + x) * 2;
float u1 = float(x) / op.meshWidth;
float u2 = float(x + 1) / op.meshWidth;
float v1 = float(y) / op.meshHeight;
float v2 = float(y + 1) / op.meshHeight;
mapper.map(u1, v1, u2, v2);
int ax = i + (op.meshWidth + 1) * 2;
int ay = ax + 1;
int bx = i;
int by = bx + 1;
int cx = i + 2;
int cy = cx + 1;
int dx = i + (op.meshWidth + 1) * 2 + 2;
int dy = dx + 1;
const float* vertices = op.vertices;
ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
}
}
if (!texture) {
texture = renderer.caches().textureCache.get(op.bitmap);
if (!texture) {
return;
}
}
const AutoTexture autoCleanup(texture);
/*
* TODO: handle alpha_8 textures correctly by applying paint color, but *not*
* shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh.
*/
const int textureFillFlags = TextureFillFlags::None;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshColoredTexturedMesh(mesh.get(), elementCount)
.setFillTexturePaint(*texture, textureFillFlags, op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewOffsetRect(0, 0, op.unmappedBounds)
.build();
renderer.renderGlop(state, glop);
}
void BakedOpDispatcher::onBitmapRectOp(BakedOpRenderer& renderer, const BitmapRectOp& op, const BakedOpState& state) {
Texture* texture = renderer.getTexture(op.bitmap);
if (!texture) return;
const AutoTexture autoCleanup(texture);
Rect uv(std::max(0.0f, op.src.left / texture->width()),
std::max(0.0f, op.src.top / texture->height()),
std::min(1.0f, op.src.right / texture->width()),
std::min(1.0f, op.src.bottom / texture->height()));
const int textureFillFlags = (op.bitmap->colorType() == kAlpha_8_SkColorType)
? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
const bool tryToSnap = MathUtils::areEqual(op.src.getWidth(), op.unmappedBounds.getWidth())
&& MathUtils::areEqual(op.src.getHeight(), op.unmappedBounds.getHeight());
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedUvQuad(texture->uvMapper, uv)
.setFillTexturePaint(*texture, textureFillFlags, op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRectOptionalSnap(tryToSnap, op.unmappedBounds)
.build();
renderer.renderGlop(state, glop);
}
void BakedOpDispatcher::onColorOp(BakedOpRenderer& renderer, const ColorOp& op, const BakedOpState& state) {
SkPaint paint;
paint.setColor(op.color);
paint.setXfermodeMode(op.mode);
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshUnitQuad()
.setFillPaint(paint, state.alpha)
.setTransform(Matrix4::identity(), TransformFlags::None)
.setModelViewMapUnitToRect(state.computedState.clipState->rect)
.build();
renderer.renderGlop(state, glop);
}
void BakedOpDispatcher::onFunctorOp(BakedOpRenderer& renderer, const FunctorOp& op, const BakedOpState& state) {
renderer.renderFunctor(op, state);
}
void BakedOpDispatcher::onLinesOp(BakedOpRenderer& renderer, const LinesOp& op, const BakedOpState& state) {
VertexBuffer buffer;
PathTessellator::tessellateLines(op.points, op.floatCount, op.paint,
state.computedState.transform, buffer);
int displayFlags = op.paint->isAntiAlias() ? 0 : VertexBufferRenderFlags::Offset;
renderVertexBuffer(renderer, state, buffer, 0, 0, *(op.paint), displayFlags);
}
void BakedOpDispatcher::onOvalOp(BakedOpRenderer& renderer, const OvalOp& op, const BakedOpState& state) {
if (op.paint->getPathEffect() != nullptr) {
PathTexture* texture = renderer.caches().pathCache.getOval(
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.paint);
const AutoTexture holder(texture);
if (CC_LIKELY(holder.texture)) {
renderPathTexture(renderer, state, op.unmappedBounds.left, op.unmappedBounds.top,
*texture, *(op.paint));
}
} else {
SkPath path;
SkRect rect = getBoundsOfFill(op);
path.addOval(rect);
if (state.computedState.localProjectionPathMask != nullptr) {
// Mask the ripple path by the local space projection mask in local space.
// Note that this can create CCW paths.
Op(path, *state.computedState.localProjectionPathMask, kIntersect_SkPathOp, &path);
}
renderConvexPath(renderer, state, path, *(op.paint));
}
}
void BakedOpDispatcher::onPatchOp(BakedOpRenderer& renderer, const PatchOp& op, const BakedOpState& state) {
// 9 patches are built for stretching - always filter
int textureFillFlags = TextureFillFlags::ForceFilter;
if (op.bitmap->colorType() == kAlpha_8_SkColorType) {
textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
}
// TODO: avoid redoing the below work each frame:
AssetAtlas::Entry* entry = renderer.renderState().assetAtlas().getEntry(op.bitmap->pixelRef());
const Patch* mesh = renderer.caches().patchCache.get(
entry, op.bitmap->width(), op.bitmap->height(),
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.patch);
Texture* texture = entry ? entry->texture : renderer.caches().textureCache.get(op.bitmap);
if (CC_LIKELY(texture)) {
const AutoTexture autoCleanup(texture);
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshPatchQuads(*mesh)
.setFillTexturePaint(*texture, textureFillFlags, op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewOffsetRectSnap(op.unmappedBounds.left, op.unmappedBounds.top,
Rect(op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight()))
.build();
renderer.renderGlop(state, glop);
}
}
void BakedOpDispatcher::onPathOp(BakedOpRenderer& renderer, const PathOp& op, const BakedOpState& state) {
PathTexture* texture = renderer.caches().pathCache.get(op.path, op.paint);
const AutoTexture holder(texture);
if (CC_LIKELY(holder.texture)) {
// Unlike other callers to renderPathTexture, no offsets are used because PathOp doesn't
// have any translate built in, other than what's in the SkPath itself
renderPathTexture(renderer, state, 0, 0, *texture, *(op.paint));
}
}
void BakedOpDispatcher::onPointsOp(BakedOpRenderer& renderer, const PointsOp& op, const BakedOpState& state) {
VertexBuffer buffer;
PathTessellator::tessellatePoints(op.points, op.floatCount, op.paint,
state.computedState.transform, buffer);
int displayFlags = op.paint->isAntiAlias() ? 0 : VertexBufferRenderFlags::Offset;
renderVertexBuffer(renderer, state, buffer, 0, 0, *(op.paint), displayFlags);
}
// See SkPaintDefaults.h
#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
void BakedOpDispatcher::onRectOp(BakedOpRenderer& renderer, const RectOp& op, const BakedOpState& state) {
if (op.paint->getStyle() != SkPaint::kFill_Style) {
// only fill + default miter is supported by drawConvexPath, since others must handle joins
static_assert(SkPaintDefaults_MiterLimit == 4.0f, "Miter limit has changed");
if (CC_UNLIKELY(op.paint->getPathEffect() != nullptr
|| op.paint->getStrokeJoin() != SkPaint::kMiter_Join
|| op.paint->getStrokeMiter() != SkPaintDefaults_MiterLimit)) {
PathTexture* texture = renderer.caches().pathCache.getRect(
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.paint);
const AutoTexture holder(texture);
if (CC_LIKELY(holder.texture)) {
renderPathTexture(renderer, state, op.unmappedBounds.left, op.unmappedBounds.top,
*texture, *(op.paint));
}
} else {
SkPath path;
path.addRect(getBoundsOfFill(op));
renderConvexPath(renderer, state, path, *(op.paint));
}
} else {
if (op.paint->isAntiAlias() && !state.computedState.transform.isSimple()) {
SkPath path;
path.addRect(op.unmappedBounds.toSkRect());
renderConvexPath(renderer, state, path, *(op.paint));
} else {
// render simple unit quad, no tessellation required
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshUnitQuad()
.setFillPaint(*op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRect(op.unmappedBounds)
.build();
renderer.renderGlop(state, glop);
}
}
}
void BakedOpDispatcher::onRoundRectOp(BakedOpRenderer& renderer, const RoundRectOp& op, const BakedOpState& state) {
if (op.paint->getPathEffect() != nullptr) {
PathTexture* texture = renderer.caches().pathCache.getRoundRect(
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(),
op.rx, op.ry, op.paint);
const AutoTexture holder(texture);
if (CC_LIKELY(holder.texture)) {
renderPathTexture(renderer, state, op.unmappedBounds.left, op.unmappedBounds.top,
*texture, *(op.paint));
}
} else {
const VertexBuffer* buffer = renderer.caches().tessellationCache.getRoundRect(
state.computedState.transform, *(op.paint),
op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.rx, op.ry);
renderVertexBuffer(renderer, state, *buffer,
op.unmappedBounds.left, op.unmappedBounds.top, *(op.paint), 0);
}
}
static void renderShadow(BakedOpRenderer& renderer, const BakedOpState& state, float casterAlpha,
const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
SkPaint paint;
paint.setAntiAlias(true); // want to use AlphaVertex
// The caller has made sure casterAlpha > 0.
uint8_t ambientShadowAlpha = renderer.getLightInfo().ambientShadowAlpha;
if (CC_UNLIKELY(Properties::overrideAmbientShadowStrength >= 0)) {
ambientShadowAlpha = Properties::overrideAmbientShadowStrength;
}
if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
paint.setAlpha((uint8_t)(casterAlpha * ambientShadowAlpha));
renderVertexBuffer(renderer, state, *ambientShadowVertexBuffer, 0, 0,
paint, VertexBufferRenderFlags::ShadowInterp);
}
uint8_t spotShadowAlpha = renderer.getLightInfo().spotShadowAlpha;
if (CC_UNLIKELY(Properties::overrideSpotShadowStrength >= 0)) {
spotShadowAlpha = Properties::overrideSpotShadowStrength;
}
if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
paint.setAlpha((uint8_t)(casterAlpha * spotShadowAlpha));
renderVertexBuffer(renderer, state, *spotShadowVertexBuffer, 0, 0,
paint, VertexBufferRenderFlags::ShadowInterp);
}
}
void BakedOpDispatcher::onShadowOp(BakedOpRenderer& renderer, const ShadowOp& op, const BakedOpState& state) {
TessellationCache::vertexBuffer_pair_t buffers = op.shadowTask->getResult();
renderShadow(renderer, state, op.casterAlpha, buffers.first, buffers.second);
}
void BakedOpDispatcher::onSimpleRectsOp(BakedOpRenderer& renderer, const SimpleRectsOp& op, const BakedOpState& state) {
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshIndexedQuads(&op.vertices[0], op.vertexCount / 4)
.setFillPaint(*op.paint, state.alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewOffsetRect(0, 0, op.unmappedBounds)
.build();
renderer.renderGlop(state, glop);
}
void BakedOpDispatcher::onTextOp(BakedOpRenderer& renderer, const TextOp& op, const BakedOpState& state) {
renderTextShadow(renderer, op, state);
renderText(renderer, op, state, state.computedState.getClipIfNeeded(), TextRenderType::Flush);
}
void BakedOpDispatcher::onTextOnPathOp(BakedOpRenderer& renderer, const TextOnPathOp& op, const BakedOpState& state) {
// Note: can't trust clipSideFlags since we record with unmappedBounds == clip.
// TODO: respect clipSideFlags, once we record with bounds
auto renderTargetClip = state.computedState.clipState;
FontRenderer& fontRenderer = renderer.caches().fontRenderer.getFontRenderer();
fontRenderer.setFont(op.paint, SkMatrix::I());
fontRenderer.setTextureFiltering(true);
Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
int alpha = PaintUtils::getAlphaDirect(op.paint) * state.alpha;
SkXfermode::Mode mode = PaintUtils::getXfermodeDirect(op.paint);
TextDrawFunctor functor(&renderer, &state, renderTargetClip,
0.0f, 0.0f, false, alpha, mode, op.paint);
bool mustDirtyRenderTarget = renderer.offscreenRenderTarget();
const Rect localSpaceClip = state.computedState.computeLocalSpaceClip();
if (fontRenderer.renderTextOnPath(op.paint, &localSpaceClip, op.glyphs, op.glyphCount,
op.path, op.hOffset, op.vOffset,
mustDirtyRenderTarget ? &layerBounds : nullptr, &functor)) {
if (mustDirtyRenderTarget) {
// manually dirty render target, since TextDrawFunctor won't
state.computedState.transform.mapRect(layerBounds);
renderer.dirtyRenderTarget(layerBounds);
}
}
}
void BakedOpDispatcher::onTextureLayerOp(BakedOpRenderer& renderer, const TextureLayerOp& op, const BakedOpState& state) {
const bool tryToSnap = !op.layer->getForceFilter();
float alpha = (op.layer->getAlpha() / 255.0f) * state.alpha;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO
.setFillTextureLayer(*(op.layer), alpha)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRectOptionalSnap(tryToSnap, Rect(op.layer->getWidth(), op.layer->getHeight()))
.build();
renderer.renderGlop(state, glop);
}
void renderRectForLayer(BakedOpRenderer& renderer, const LayerOp& op, const BakedOpState& state,
int color, SkXfermode::Mode mode, SkColorFilter* colorFilter) {
SkPaint paint;
paint.setColor(color);
paint.setXfermodeMode(mode);
paint.setColorFilter(colorFilter);
RectOp rectOp(op.unmappedBounds, op.localMatrix, op.localClip, &paint);
BakedOpDispatcher::onRectOp(renderer, rectOp, state);
}
void BakedOpDispatcher::onLayerOp(BakedOpRenderer& renderer, const LayerOp& op, const BakedOpState& state) {
// Note that we don't use op->paint in this function - it's never set on a LayerOp
OffscreenBuffer* buffer = *op.layerHandle;
if (CC_UNLIKELY(!buffer)) return;
float layerAlpha = op.alpha * state.alpha;
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedIndexedVbo(buffer->vbo, buffer->elementCount)
.setFillLayer(buffer->texture, op.colorFilter, layerAlpha, op.mode, Blend::ModeOrderSwap::NoSwap)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewOffsetRectSnap(op.unmappedBounds.left, op.unmappedBounds.top,
Rect(op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight()))
.build();
renderer.renderGlop(state, glop);
if (!buffer->hasRenderedSinceRepaint) {
buffer->hasRenderedSinceRepaint = true;
if (CC_UNLIKELY(Properties::debugLayersUpdates)) {
// render debug layer highlight
renderRectForLayer(renderer, op, state,
0x7f00ff00, SkXfermode::Mode::kSrcOver_Mode, nullptr);
} else if (CC_UNLIKELY(Properties::debugOverdraw)) {
// render transparent to increment overdraw for repaint area
renderRectForLayer(renderer, op, state,
SK_ColorTRANSPARENT, SkXfermode::Mode::kSrcOver_Mode, nullptr);
}
}
}
void BakedOpDispatcher::onCopyToLayerOp(BakedOpRenderer& renderer, const CopyToLayerOp& op, const BakedOpState& state) {
LOG_ALWAYS_FATAL_IF(*(op.layerHandle) != nullptr, "layer already exists!");
*(op.layerHandle) = renderer.copyToLayer(state.computedState.clippedBounds);
LOG_ALWAYS_FATAL_IF(*op.layerHandle == nullptr, "layer copy failed");
}
void BakedOpDispatcher::onCopyFromLayerOp(BakedOpRenderer& renderer, const CopyFromLayerOp& op, const BakedOpState& state) {
LOG_ALWAYS_FATAL_IF(*op.layerHandle == nullptr, "no layer to draw underneath!");
if (!state.computedState.clippedBounds.isEmpty()) {
if (op.paint && op.paint->getAlpha() < 255) {
SkPaint layerPaint;
layerPaint.setAlpha(op.paint->getAlpha());
layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
layerPaint.setColorFilter(op.paint->getColorFilter());
RectOp rectOp(state.computedState.clippedBounds, Matrix4::identity(), nullptr, &layerPaint);
BakedOpDispatcher::onRectOp(renderer, rectOp, state);
}
OffscreenBuffer& layer = **(op.layerHandle);
auto mode = PaintUtils::getXfermodeDirect(op.paint);
Glop glop;
GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
.setRoundRectClipState(state.roundRectClipState)
.setMeshTexturedUvQuad(nullptr, layer.getTextureCoordinates())
.setFillLayer(layer.texture, nullptr, 1.0f, mode, Blend::ModeOrderSwap::Swap)
.setTransform(state.computedState.transform, TransformFlags::None)
.setModelViewMapUnitToRect(state.computedState.clippedBounds)
.build();
renderer.renderGlop(state, glop);
}
renderer.renderState().layerPool().putOrDelete(*op.layerHandle);
}
} // namespace uirenderer
} // namespace android
| 46.324914 | 124 | 0.667997 | Keneral |
8b3f702a6b81cfdd8959c5c94baef649a2f9fa82 | 18,192 | cc | C++ | test/extensions/filters/network/ratelimit/ratelimit_test.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 17,703 | 2017-09-14T18:23:43.000Z | 2022-03-31T22:04:17.000Z | test/extensions/filters/network/ratelimit/ratelimit_test.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 15,957 | 2017-09-14T16:38:22.000Z | 2022-03-31T23:56:30.000Z | test/extensions/filters/network/ratelimit/ratelimit_test.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 3,780 | 2017-09-14T18:58:47.000Z | 2022-03-31T17:10:47.000Z | #include <memory>
#include <string>
#include <vector>
#include "envoy/extensions/filters/network/ratelimit/v3/rate_limit.pb.h"
#include "envoy/extensions/filters/network/tcp_proxy/v3/tcp_proxy.pb.h"
#include "envoy/stats/stats.h"
#include "source/common/buffer/buffer_impl.h"
#include "source/common/network/filter_manager_impl.h"
#include "source/common/tcp_proxy/tcp_proxy.h"
#include "source/extensions/filters/network/ratelimit/ratelimit.h"
#include "source/extensions/filters/network/well_known_names.h"
#include "test/extensions/filters/common/ratelimit/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/ratelimit/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/factory_context.h"
#include "test/mocks/stream_info/mocks.h"
#include "test/mocks/tracing/mocks.h"
#include "test/test_common/printers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::InSequence;
using testing::Invoke;
using testing::NiceMock;
using testing::Return;
using testing::WithArgs;
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace RateLimitFilter {
class RateLimitFilterTest : public testing::Test {
public:
void SetUpTest(const std::string& yaml) {
ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enabled", 100))
.WillByDefault(Return(true));
ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enforcing", 100))
.WillByDefault(Return(true));
envoy::extensions::filters::network::ratelimit::v3::RateLimit proto_config{};
TestUtility::loadFromYaml(yaml, proto_config);
config_ = std::make_shared<Config>(proto_config, stats_store_, runtime_);
client_ = new Filters::Common::RateLimit::MockClient();
filter_ = std::make_unique<Filter>(config_, Filters::Common::RateLimit::ClientPtr{client_});
filter_->initializeReadFilterCallbacks(filter_callbacks_);
// NOP currently.
filter_->onAboveWriteBufferHighWatermark();
filter_->onBelowWriteBufferLowWatermark();
}
~RateLimitFilterTest() override {
for (const Stats::GaugeSharedPtr& gauge : stats_store_.gauges()) {
EXPECT_EQ(0U, gauge->value());
}
}
const std::string filter_config_ = R"EOF(
domain: foo
descriptors:
- entries:
- key: hello
value: world
- key: foo
value: bar
- entries:
- key: foo2
value: bar2
stat_prefix: name
)EOF";
const std::string fail_close_config_ = R"EOF(
domain: foo
descriptors:
- entries:
- key: hello
value: world
- key: foo
value: bar
- entries:
- key: foo2
value: bar2
stat_prefix: name
failure_mode_deny: true
)EOF";
Stats::TestUtil::TestStore stats_store_;
NiceMock<Runtime::MockLoader> runtime_;
ConfigSharedPtr config_;
Filters::Common::RateLimit::MockClient* client_;
std::unique_ptr<Filter> filter_;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks_;
Filters::Common::RateLimit::RequestCallbacks* request_callbacks_{};
};
TEST_F(RateLimitFilterTest, OK) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo",
testing::ContainerEq(std::vector<RateLimit::Descriptor>{
{{{"hello", "world"}, {"foo", "bar"}}}, {{{"foo2", "bar2"}}}}),
testing::A<Tracing::Span&>(), _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_CALL(filter_callbacks_, continueReading());
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::OK, nullptr, nullptr,
nullptr, "", nullptr);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel()).Times(0);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::LocalClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.ok").value());
}
TEST_F(RateLimitFilterTest, OverLimit) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_CALL(filter_callbacks_.connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(*client_, cancel()).Times(0);
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::OverLimit, nullptr, nullptr,
nullptr, "", nullptr);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.over_limit").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.cx_closed").value());
}
TEST_F(RateLimitFilterTest, OverLimitWithDynamicMetadata) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
Filters::Common::RateLimit::DynamicMetadataPtr dynamic_metadata =
std::make_unique<ProtobufWkt::Struct>();
auto* fields = dynamic_metadata->mutable_fields();
(*fields)["name"] = ValueUtil::stringValue("my-limit");
(*fields)["x"] = ValueUtil::numberValue(3);
NiceMock<StreamInfo::MockStreamInfo> stream_info;
EXPECT_CALL(filter_callbacks_.connection_, streamInfo()).WillOnce(ReturnRef(stream_info));
EXPECT_CALL(stream_info, setDynamicMetadata(_, _))
.WillOnce(Invoke([&dynamic_metadata](const std::string& ns,
const ProtobufWkt::Struct& returned_dynamic_metadata) {
EXPECT_EQ(ns, NetworkFilterNames::get().RateLimit);
EXPECT_TRUE(TestUtility::protoEqual(returned_dynamic_metadata, *dynamic_metadata));
}));
EXPECT_CALL(filter_callbacks_.connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(*client_, cancel()).Times(0);
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::OverLimit, nullptr, nullptr,
nullptr, "", std::move(dynamic_metadata));
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.over_limit").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.cx_closed").value());
}
TEST_F(RateLimitFilterTest, OverLimitNotEnforcing) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enforcing", 100))
.WillOnce(Return(false));
EXPECT_CALL(filter_callbacks_.connection_, close(_)).Times(0);
EXPECT_CALL(*client_, cancel()).Times(0);
EXPECT_CALL(filter_callbacks_, continueReading());
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::OverLimit, nullptr, nullptr,
nullptr, "", nullptr);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.over_limit").value());
EXPECT_EQ(0U, stats_store_.counter("ratelimit.name.cx_closed").value());
}
TEST_F(RateLimitFilterTest, Error) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_CALL(filter_callbacks_, continueReading());
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::Error, nullptr, nullptr,
nullptr, "", nullptr);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel()).Times(0);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.error").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.failure_mode_allowed").value());
}
TEST_F(RateLimitFilterTest, Disconnect) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel());
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
}
TEST_F(RateLimitFilterTest, ImmediateOK) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(filter_callbacks_, continueReading()).Times(0);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
callbacks.complete(Filters::Common::RateLimit::LimitStatus::OK, nullptr, nullptr,
nullptr, "", nullptr);
})));
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel()).Times(0);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.ok").value());
}
TEST_F(RateLimitFilterTest, ImmediateError) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(filter_callbacks_, continueReading()).Times(0);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
callbacks.complete(Filters::Common::RateLimit::LimitStatus::Error, nullptr, nullptr,
nullptr, "", nullptr);
})));
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel()).Times(0);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.error").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.failure_mode_allowed").value());
}
TEST_F(RateLimitFilterTest, RuntimeDisable) {
InSequence s;
SetUpTest(filter_config_);
EXPECT_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enabled", 100))
.WillOnce(Return(false));
EXPECT_CALL(*client_, limit(_, _, _, _, _)).Times(0);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
}
TEST_F(RateLimitFilterTest, ErrorResponseWithFailureModeAllowOff) {
InSequence s;
SetUpTest(fail_close_config_);
EXPECT_CALL(*client_, limit(_, "foo", _, _, _))
.WillOnce(
WithArgs<0>(Invoke([&](Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks_ = &callbacks;
})));
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection());
Buffer::OwnedImpl data("hello");
EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onData(data, false));
request_callbacks_->complete(Filters::Common::RateLimit::LimitStatus::Error, nullptr, nullptr,
nullptr, "", nullptr);
EXPECT_EQ(Network::FilterStatus::Continue, filter_->onData(data, false));
EXPECT_CALL(*client_, cancel()).Times(0);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.total").value());
EXPECT_EQ(1U, stats_store_.counter("ratelimit.name.error").value());
EXPECT_EQ(0U, stats_store_.counter("ratelimit.name.failure_mode_allowed").value());
}
class NetworkFilterManagerRateLimitTest : public testing::Test {
public:
void SetUp() override {
EXPECT_CALL(connection_, getReadBuffer).WillRepeatedly(Invoke([this]() {
return Network::StreamBuffer{read_buffer_, read_end_stream_};
}));
EXPECT_CALL(connection_, getWriteBuffer).WillRepeatedly(Invoke([this]() {
return Network::StreamBuffer{write_buffer_, write_end_stream_};
}));
}
NiceMock<Network::MockFilterManagerConnection> connection_;
NiceMock<Network::MockListenSocket> socket_;
Buffer::OwnedImpl read_buffer_;
Buffer::OwnedImpl write_buffer_;
bool read_end_stream_{};
bool write_end_stream_{};
};
// This is a very important flow so make sure it works correctly in aggregate.
TEST_F(NetworkFilterManagerRateLimitTest, RateLimitAndTcpProxy) {
InSequence s;
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
NiceMock<Network::MockClientConnection> upstream_connection;
NiceMock<Tcp::ConnectionPool::MockInstance> conn_pool;
Network::FilterManagerImpl manager(connection_, socket_);
std::string rl_yaml = R"EOF(
domain: foo
descriptors:
- entries:
- key: hello
value: world
stat_prefix: name
)EOF";
ON_CALL(factory_context.runtime_loader_.snapshot_,
featureEnabled("ratelimit.tcp_filter_enabled", 100))
.WillByDefault(Return(true));
ON_CALL(factory_context.runtime_loader_.snapshot_,
featureEnabled("ratelimit.tcp_filter_enforcing", 100))
.WillByDefault(Return(true));
envoy::extensions::filters::network::ratelimit::v3::RateLimit proto_config{};
TestUtility::loadFromYaml(rl_yaml, proto_config);
Extensions::NetworkFilters::RateLimitFilter::ConfigSharedPtr rl_config(
new Extensions::NetworkFilters::RateLimitFilter::Config(proto_config, factory_context.scope_,
factory_context.runtime_loader_));
Extensions::Filters::Common::RateLimit::MockClient* rl_client =
new Extensions::Filters::Common::RateLimit::MockClient();
manager.addReadFilter(std::make_shared<Extensions::NetworkFilters::RateLimitFilter::Filter>(
rl_config, Extensions::Filters::Common::RateLimit::ClientPtr{rl_client}));
factory_context.cluster_manager_.initializeThreadLocalClusters({"fake_cluster"});
envoy::extensions::filters::network::tcp_proxy::v3::TcpProxy tcp_proxy;
tcp_proxy.set_stat_prefix("name");
tcp_proxy.set_cluster("fake_cluster");
TcpProxy::ConfigSharedPtr tcp_proxy_config(new TcpProxy::Config(tcp_proxy, factory_context));
manager.addReadFilter(
std::make_shared<TcpProxy::Filter>(tcp_proxy_config, factory_context.cluster_manager_));
Extensions::Filters::Common::RateLimit::RequestCallbacks* request_callbacks{};
EXPECT_CALL(*rl_client, limit(_, "foo",
testing::ContainerEq(
std::vector<RateLimit::Descriptor>{{{{"hello", "world"}}}}),
testing::A<Tracing::Span&>(), _))
.WillOnce(WithArgs<0>(
Invoke([&](Extensions::Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks = &callbacks;
})));
EXPECT_EQ(manager.initializeReadFilters(), true);
EXPECT_CALL(factory_context.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _))
.WillOnce(Return(Upstream::TcpPoolData([]() {}, &conn_pool)));
request_callbacks->complete(Extensions::Filters::Common::RateLimit::LimitStatus::OK, nullptr,
nullptr, nullptr, "", nullptr);
conn_pool.poolReady(upstream_connection);
Buffer::OwnedImpl buffer("hello");
EXPECT_CALL(upstream_connection, write(BufferEqual(&buffer), _));
read_buffer_.add("hello");
manager.onRead();
connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
}
} // namespace RateLimitFilter
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| 39.633987 | 100 | 0.711906 | dcillera |
8b4044dfc93820f57b4efeb09353d3bd75fb4479 | 11,553 | cpp | C++ | celix/dfi/private/test/json_rpc_tests.cpp | marcojansen/android-inaetics | c9b938c6a1323a96e8d7094f3a74300f67872bc4 | [
"Apache-2.0"
] | null | null | null | celix/dfi/private/test/json_rpc_tests.cpp | marcojansen/android-inaetics | c9b938c6a1323a96e8d7094f3a74300f67872bc4 | [
"Apache-2.0"
] | null | null | null | celix/dfi/private/test/json_rpc_tests.cpp | marcojansen/android-inaetics | c9b938c6a1323a96e8d7094f3a74300f67872bc4 | [
"Apache-2.0"
] | null | null | null | /**
*Licensed to the Apache Software Foundation (ASF) under one
*or more contributor license agreements. See the NOTICE file
*distributed with this work for additional information
*regarding copyright ownership. The ASF licenses this file
*to you under the Apache License, Version 2.0 (the
*"License"); you may not use this file except in compliance
*with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
#include <CppUTest/TestHarness.h>
#include <float.h>
#include <assert.h>
#include "CppUTest/CommandLineTestRunner.h"
extern "C" {
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <ffi.h>
#include "dyn_common.h"
#include "dyn_type.h"
#include "json_serializer.h"
#include "json_rpc.h"
static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) {
va_list ap;
const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"};
fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line);
va_start(ap, msg);
vfprintf(stderr, msg, ap);
fprintf(stderr, "\n");
}
void prepareTest(void) {
dyn_function_type *dynFunc = NULL;
int rc = dynFunction_parseWithStr("add(#am=handle;PDD#am=pre;*D)N", NULL, &dynFunc);
CHECK_EQUAL(0, rc);
char *result = NULL;
void *handle = NULL;
double arg1 = 1.0;
double arg2 = 2.0;
void *args[4];
args[0] = &handle;
args[1] = &arg1;
args[2] = &arg2;
rc = jsonRpc_prepareInvokeRequest(dynFunc, "add", args, &result);
CHECK_EQUAL(0, rc);
//printf("result is %s\n", result);
STRCMP_CONTAINS("\"add\"", result);
STRCMP_CONTAINS("1.0", result);
STRCMP_CONTAINS("2.0", result);
free(result);
dynFunction_destroy(dynFunc);
}
void handleTestPre(void) {
dyn_function_type *dynFunc = NULL;
int rc = dynFunction_parseWithStr("add(#am=handle;PDD#am=pre;*D)N", NULL, &dynFunc);
CHECK_EQUAL(0, rc);
const char *reply = "{\"r\":2.2}";
double result = -1.0;
double *out = &result;
void *args[4];
args[3] = &out;
rc = jsonRpc_handleReply(dynFunc, reply, args);
CHECK_EQUAL(0, rc);
//CHECK_EQUAL(2.2, result);
dynFunction_destroy(dynFunc);
}
int add(void *handle, double a, double b, double *result) {
*result = a + b;
return 0;
}
int getName_example4(void *handle, char** result) {
*result = strdup("allocatedInFunction");
return 0;
}
struct tst_seq {
uint32_t cap;
uint32_t len;
double *buf;
};
//StatsResult={DDD[D average min max input}
struct tst_StatsResult {
double average;
double min;
double max;
struct tst_seq input;
};
int stats(void *handle, struct tst_seq input, struct tst_StatsResult **out) {
assert(out != NULL);
assert(*out == NULL);
double total = 0.0;
unsigned int count = 0;
double max = DBL_MIN;
double min = DBL_MAX;
unsigned int i;
for (i = 0; i<input.len; i += 1) {
total += input.buf[i];
count += 1;
if (input.buf[i] > max) {
max = input.buf[i];
}
if (input.buf[i] < min) {
min = input.buf[i];
}
}
struct tst_StatsResult *result = (struct tst_StatsResult *) calloc(1, sizeof(*result));
result->average = total / count;
result->min = min;
result->max = max;
double *buf = (double *)calloc(input.len, sizeof(double));
memcpy(buf, input.buf, input.len * sizeof(double));
result->input.len = input.len;
result->input.cap = input.len;
result->input.buf = buf;
*out = result;
return 0;
}
struct item {
double a;
double b;
};
struct item_seq {
uint32_t cap;
uint32_t len;
struct item **buf;
};
struct tst_serv {
void *handle;
int (*add)(void *, double, double, double *);
int (*sub)(void *, double, double, double *);
int (*sqrt)(void *, double, double *);
int (*stats)(void *, struct tst_seq, struct tst_StatsResult **);
};
struct tst_serv_example4 {
void *handle;
int (*getName_example4)(void *, char** name);
};
void callTestPreAllocated(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example1.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
char *result = NULL;
struct tst_serv serv;
serv.handle = NULL;
serv.add = add;
rc = jsonRpc_call(intf, &serv, "{\"m\":\"add(DD)D\", \"a\": [1.0,2.0]}", &result);
CHECK_EQUAL(0, rc);
STRCMP_CONTAINS("3.0", result);
free(result);
dynInterface_destroy(intf);
}
void callTestOutput(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example1.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
char *result = NULL;
struct tst_serv serv;
serv.handle = NULL;
serv.stats = stats;
rc = jsonRpc_call(intf, &serv, "{\"m\":\"stats([D)LStatsResult;\", \"a\": [[1.0,2.0]]}", &result);
CHECK_EQUAL(0, rc);
STRCMP_CONTAINS("1.5", result); //avg
free(result);
dynInterface_destroy(intf);
}
void handleTestOut(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example1.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
struct methods_head *head;
dynInterface_methods(intf, &head);
dyn_function_type *func = NULL;
struct method_entry *entry = NULL;
TAILQ_FOREACH(entry, head, entries) {
if (strcmp(entry->name, "stats") == 0) {
func = entry->dynFunc;
break;
}
}
CHECK(func != NULL);
const char *reply = "{\"r\":{\"input\":[1.0,2.0],\"max\":2.0,\"average\":1.5,\"min\":1.0}}";
void *args[3];
args[0] = NULL;
args[1] = NULL;
args[2] = NULL;
struct tst_StatsResult *result = NULL;
void *out = &result;
args[2] = &out;
rc = jsonRpc_handleReply(func, reply, args);
CHECK_EQUAL(0, rc);
CHECK_EQUAL(1.5, result->average);
free(result->input.buf);
free(result);
dynInterface_destroy(intf);
}
static void handleTestOutputSequence(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example2.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
struct methods_head *head;
dynInterface_methods(intf, &head);
dyn_function_type *func = NULL;
struct method_entry *entry = NULL;
TAILQ_FOREACH(entry, head, entries) {
if (strcmp(entry->name, "example1") == 0) {
func = entry->dynFunc;
break;
}
}
CHECK(func != NULL);
//dyn_type *arg = dynFunction_argumentTypeForIndex(func, 1);
//dynType_print(arg, stdout);
const char *reply = "{\"r\":[{\"a\":1.0,\"b\":1.5},{\"a\":2.0,\"b\":2.5}]}";
void *args[2];
args[0] = NULL;
args[1] = NULL;
struct item_seq *result = NULL;
void *out = &result;
args[1] = &out;
rc = jsonRpc_handleReply(func, reply, args);
CHECK_EQUAL(0, rc);
CHECK_EQUAL(2, result->len);
CHECK_EQUAL(1.0, result->buf[0]->a);
CHECK_EQUAL(1.5, result->buf[0]->b);
CHECK_EQUAL(2.0, result->buf[1]->a);
CHECK_EQUAL(2.5, result->buf[1]->b);
unsigned int i;
for (i = 0; i < result->len; i +=1 ) {
free(result->buf[i]);
}
free(result->buf);
free(result);
dynInterface_destroy(intf);
}
void callTestOutChar(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example4.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
char *result = NULL;
struct tst_serv_example4 serv;
serv.handle = NULL;
serv.getName_example4 = getName_example4;
rc = jsonRpc_call(intf, &serv, "{\"m\":\"getName(V)t\", \"a\": []}", &result);
CHECK_EQUAL(0, rc);
STRCMP_CONTAINS("allocatedInFunction", result);
free(result);
dynInterface_destroy(intf);
}
void handleTestOutChar(void) {
dyn_interface_type *intf = NULL;
FILE *desc = fopen("descriptors/example4.descriptor", "r");
CHECK(desc != NULL);
int rc = dynInterface_parse(desc, &intf);
CHECK_EQUAL(0, rc);
fclose(desc);
struct methods_head *head;
dynInterface_methods(intf, &head);
dyn_function_type *func = NULL;
struct method_entry *entry = NULL;
TAILQ_FOREACH(entry, head, entries) {
if (strcmp(entry->name, "getName") == 0) {
func = entry->dynFunc;
break;
}
}
CHECK(func != NULL);
const char *reply = "{\"r\": \"this is a test string\" }";
char *result = NULL;
void *out = &result;
void *args[2];
args[0] = NULL;
args[1] = &out;
rc = jsonRpc_handleReply(func, reply, args);
STRCMP_EQUAL("this is a test string", result);
free(result);
dynInterface_destroy(intf);
}
}
TEST_GROUP(JsonRpcTests) {
void setup() {
int lvl = 1;
dynCommon_logSetup(stdLog, NULL, lvl);
dynType_logSetup(stdLog, NULL,lvl);
dynFunction_logSetup(stdLog, NULL,lvl);
dynInterface_logSetup(stdLog, NULL,lvl);
jsonSerializer_logSetup(stdLog, NULL, lvl);
jsonRpc_logSetup(stdLog, NULL, lvl);
}
};
TEST(JsonRpcTests, prepareTest) {
prepareTest();
}
TEST(JsonRpcTests, handleTestPre) {
handleTestPre();
}
TEST(JsonRpcTests, handleTestOut) {
handleTestOut();
}
TEST(JsonRpcTests, callPre) {
callTestPreAllocated();
}
TEST(JsonRpcTests, callOut) {
callTestOutput();
}
TEST(JsonRpcTests, handleOutSeq) {
handleTestOutputSequence();
}
TEST(JsonRpcTests, callTestOutChar) {
callTestOutChar();
}
TEST(JsonRpcTests, handleOutChar) {
handleTestOutChar();
}
| 26.93007 | 211 | 0.553882 | marcojansen |
8b4747e4710b7cca1bd4bea6ef6bc8b09e003976 | 5,173 | cc | C++ | chromium/mojo/shell/public/cpp/lib/application_test_base.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mojo/shell/public/cpp/lib/application_test_base.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mojo/shell/public/cpp/lib/application_test_base.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <utility>
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/environment/environment.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/shell/public/cpp/application_impl.h"
#include "mojo/shell/public/cpp/application_test_base.h"
#include "mojo/shell/public/interfaces/application.mojom.h"
namespace mojo {
namespace test {
namespace {
// Share the application URL with multiple application tests.
String g_url;
// Application request handle passed from the shell in MojoMain, stored in
// between SetUp()/TearDown() so we can (re-)intialize new ApplicationImpls.
InterfaceRequest<Application> g_application_request;
// Shell pointer passed in the initial mojo.Application.Initialize() call,
// stored in between initial setup and the first test and between SetUp/TearDown
// calls so we can (re-)initialize new ApplicationImpls.
ShellPtr g_shell;
class ShellGrabber : public Application {
public:
explicit ShellGrabber(InterfaceRequest<Application> application_request)
: binding_(this, std::move(application_request)) {}
void WaitForInitialize() {
// Initialize is always the first call made on Application.
MOJO_CHECK(binding_.WaitForIncomingMethodCall());
}
private:
// Application implementation.
void Initialize(ShellPtr shell, const mojo::String& url) override {
g_url = url;
g_application_request = binding_.Unbind();
g_shell = std::move(shell);
}
void AcceptConnection(const String& requestor_url,
InterfaceRequest<ServiceProvider> services,
ServiceProviderPtr exposed_services,
Array<String> allowed_interfaces,
const String& url) override {
MOJO_CHECK(false);
}
void OnQuitRequested(const Callback<void(bool)>& callback) override {
MOJO_CHECK(false);
}
Binding<Application> binding_;
};
} // namespace
MojoResult RunAllTests(MojoHandle application_request_handle) {
{
// This loop is used for init, and then destroyed before running tests.
Environment::InstantiateDefaultRunLoop();
// Grab the shell handle.
ShellGrabber grabber(
MakeRequest<Application>(MakeScopedHandle(
MessagePipeHandle(application_request_handle))));
grabber.WaitForInitialize();
MOJO_CHECK(g_shell);
MOJO_CHECK(g_application_request.is_pending());
int argc = 0;
base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
const char** argv = new const char* [cmd_line->argv().size() + 1];
#if defined(OS_WIN)
std::vector<std::string> local_strings;
#endif
for (auto& arg : cmd_line->argv()) {
#if defined(OS_WIN)
local_strings.push_back(base::WideToUTF8(arg));
argv[argc++] = local_strings.back().c_str();
#else
argv[argc++] = arg.c_str();
#endif
}
argv[argc] = nullptr;
testing::InitGoogleTest(&argc, const_cast<char**>(&(argv[0])));
Environment::DestroyDefaultRunLoop();
}
int result = RUN_ALL_TESTS();
// Shut down our message pipes before exiting.
(void)g_application_request.PassMessagePipe();
g_shell.reset();
return (result == 0) ? MOJO_RESULT_OK : MOJO_RESULT_UNKNOWN;
}
TestHelper::TestHelper(ApplicationDelegate* delegate)
: application_impl_(new ApplicationImpl(
delegate == nullptr ? &default_application_delegate_ : delegate,
std::move(g_application_request))) {
// Fake application initialization.
Application* application = application_impl_.get();
application->Initialize(std::move(g_shell), g_url);
}
TestHelper::~TestHelper() {
// TODO: commented out until http://crbug.com/533107 is solved.
// {
// ApplicationImpl::TestApi test_api(application_impl_);
// test_api.UnbindConnections(&g_application_request, &g_shell);
// }
// We may have supplied a member as the delegate. Delete |application_impl_|
// while still valid.
application_impl_.reset();
}
ApplicationTestBase::ApplicationTestBase() : test_helper_(nullptr) {}
ApplicationTestBase::~ApplicationTestBase() {
}
ApplicationDelegate* ApplicationTestBase::GetApplicationDelegate() {
return nullptr;
}
void ApplicationTestBase::SetUp() {
// A run loop is recommended for ApplicationImpl initialization and
// communication.
if (ShouldCreateDefaultRunLoop())
Environment::InstantiateDefaultRunLoop();
MOJO_CHECK(g_application_request.is_pending());
MOJO_CHECK(g_shell);
// New applications are constructed for each test to avoid persisting state.
test_helper_.reset(new TestHelper(GetApplicationDelegate()));
}
void ApplicationTestBase::TearDown() {
MOJO_CHECK(!g_application_request.is_pending());
MOJO_CHECK(!g_shell);
test_helper_.reset();
if (ShouldCreateDefaultRunLoop())
Environment::DestroyDefaultRunLoop();
}
bool ApplicationTestBase::ShouldCreateDefaultRunLoop() {
return true;
}
} // namespace test
} // namespace mojo
| 30.791667 | 80 | 0.727818 | wedataintelligence |
8b47a768f57943a5439417a4d261faa7a68a47b4 | 3,115 | cpp | C++ | third_party/p7zip/CPP/7zip/UI/FileManager/ListViewDialog.cpp | VirtualLib/juice | 3d5912059f3a80ec1fef5c5031a395578904fe9c | [
"MIT"
] | 4 | 2017-03-02T10:19:03.000Z | 2020-03-05T03:29:28.000Z | third_party/p7zip/CPP/7zip/UI/FileManager/ListViewDialog.cpp | VirtualLib/juice | 3d5912059f3a80ec1fef5c5031a395578904fe9c | [
"MIT"
] | null | null | null | third_party/p7zip/CPP/7zip/UI/FileManager/ListViewDialog.cpp | VirtualLib/juice | 3d5912059f3a80ec1fef5c5031a395578904fe9c | [
"MIT"
] | 2 | 2021-12-04T06:44:33.000Z | 2021-12-08T15:14:42.000Z | // ListViewDialog.cpp
#include "StdAfx.h"
#include "ListViewDialog.h"
#include "RegistryUtils.h"
#ifdef LANG
#include "LangUtils.h"
#endif
using namespace NWindows;
bool CListViewDialog::OnInit()
{
#ifdef LANG
LangSetDlgItems(*this, NULL, 0);
#endif
_listView.Attach(GetItem(IDL_LISTVIEW));
// FIXME if (ReadSingleClick())
// FIXME _listView.SetExtendedListViewStyle(LVS_EX_ONECLICKACTIVATE | LVS_EX_TRACKSELECT);
SetText(Title);
LVCOLUMN columnInfo;
columnInfo.mask = LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM;
columnInfo.fmt = LVCFMT_LEFT;
columnInfo.iSubItem = 0;
columnInfo.cx = 200;
_listView.InsertColumn(0, &columnInfo);
FOR_VECTOR (i, Strings)
_listView.InsertItem(i, Strings[i]);
if (Strings.Size() > 0)
_listView.SetItemState_FocusedSelected(0);
_listView.SetColumnWidthAuto(0);
StringsWereChanged = false;
NormalizeSize();
return CModalDialog::OnInit();
}
bool CListViewDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
{
#ifdef _WIN32
int mx, my;
GetMargins(8, mx, my);
int bx1, bx2, by;
GetItemSizes(IDCANCEL, bx1, by);
GetItemSizes(IDOK, bx2, by);
int y = ySize - my - by;
int x = xSize - mx - bx1;
/*
RECT rect;
GetClientRect(&rect);
rect.top = y - my;
InvalidateRect(&rect);
*/
InvalidateRect(NULL);
MoveItem(IDCANCEL, x, y, bx1, by);
MoveItem(IDOK, x - mx - bx2, y, bx2, by);
/*
if (wParam == SIZE_MAXSHOW || wParam == SIZE_MAXIMIZED || wParam == SIZE_MAXHIDE)
mx = 0;
*/
_listView.Move(mx, my, xSize - mx * 2, y - my * 2);
#endif
return false;
}
extern bool g_LVN_ITEMACTIVATE_Support;
bool CListViewDialog::OnNotify(UINT /* controlID */, LPNMHDR header)
{
#ifdef _WIN32
if (header->hwndFrom != _listView)
return false;
switch (header->code)
{
case LVN_ITEMACTIVATE:
if (g_LVN_ITEMACTIVATE_Support)
{
OnOK();
return true;
}
break;
case NM_DBLCLK:
case NM_RETURN: // probabably it's unused
if (!g_LVN_ITEMACTIVATE_Support)
{
OnOK();
return true;
}
break;
case LVN_KEYDOWN:
{
LPNMLVKEYDOWN keyDownInfo = LPNMLVKEYDOWN(header);
switch (keyDownInfo->wVKey)
{
case VK_DELETE:
{
if (!DeleteIsAllowed)
return false;
for (;;)
{
int index = _listView.GetNextSelectedItem(-1);
if (index < 0)
break;
StringsWereChanged = true;
_listView.DeleteItem(index);
Strings.Delete(index);
}
int focusedIndex = _listView.GetFocusedItem();
if (focusedIndex >= 0)
_listView.SetItemState_FocusedSelected(focusedIndex);
_listView.SetColumnWidthAuto(0);
return true;
}
case 'A':
{
if (IsKeyDown(VK_CONTROL))
{
_listView.SelectAll();
return true;
}
}
}
}
}
#endif
return false;
}
void CListViewDialog::OnOK()
{
FocusedItemIndex = _listView.GetFocusedItem();
CModalDialog::OnOK();
}
| 21.335616 | 94 | 0.611878 | VirtualLib |
8b493c1079d1ebbc4ee13a035bfc4be94fca4e05 | 2,724 | cc | C++ | components/services/app_service/public/cpp/icon_loader.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/services/app_service/public/cpp/icon_loader.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/services/app_service/public/cpp/icon_loader.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/services/app_service/public/cpp/icon_loader.h"
#include <utility>
#include "base/callback.h"
namespace apps {
IconLoader::Releaser::Releaser(std::unique_ptr<IconLoader::Releaser> next,
base::OnceClosure closure)
: next_(std::move(next)), closure_(std::move(closure)) {}
IconLoader::Releaser::~Releaser() {
std::move(closure_).Run();
}
IconLoader::Key::Key(apps::mojom::AppType app_type,
const std::string& app_id,
const apps::mojom::IconKeyPtr& icon_key,
apps::mojom::IconType icon_type,
int32_t size_hint_in_dip,
bool allow_placeholder_icon)
: app_type_(app_type),
app_id_(app_id),
timeline_(icon_key ? icon_key->timeline : 0),
resource_id_(icon_key ? icon_key->resource_id : 0),
icon_effects_(icon_key ? icon_key->icon_effects : 0),
icon_type_(icon_type),
size_hint_in_dip_(size_hint_in_dip),
allow_placeholder_icon_(allow_placeholder_icon) {}
IconLoader::Key::Key(const Key& other) = default;
bool IconLoader::Key::operator<(const Key& that) const {
if (this->app_type_ != that.app_type_) {
return this->app_type_ < that.app_type_;
}
if (this->timeline_ != that.timeline_) {
return this->timeline_ < that.timeline_;
}
if (this->resource_id_ != that.resource_id_) {
return this->resource_id_ < that.resource_id_;
}
if (this->icon_effects_ != that.icon_effects_) {
return this->icon_effects_ < that.icon_effects_;
}
if (this->icon_type_ != that.icon_type_) {
return this->icon_type_ < that.icon_type_;
}
if (this->size_hint_in_dip_ != that.size_hint_in_dip_) {
return this->size_hint_in_dip_ < that.size_hint_in_dip_;
}
if (this->allow_placeholder_icon_ != that.allow_placeholder_icon_) {
return this->allow_placeholder_icon_ < that.allow_placeholder_icon_;
}
return this->app_id_ < that.app_id_;
}
IconLoader::IconLoader() = default;
IconLoader::~IconLoader() = default;
std::unique_ptr<IconLoader::Releaser> IconLoader::LoadIcon(
apps::mojom::AppType app_type,
const std::string& app_id,
apps::mojom::IconType icon_type,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
apps::mojom::Publisher::LoadIconCallback callback) {
return LoadIconFromIconKey(app_type, app_id, GetIconKey(app_id), icon_type,
size_hint_in_dip, allow_placeholder_icon,
std::move(callback));
}
} // namespace apps
| 34.05 | 77 | 0.676946 | mghgroup |
8b497b3621445471c08ac0031a630a4c1e176df9 | 188 | cpp | C++ | c++/ld/include/slice.cpp | nkysg/Asenal | 12444c7e50fae2be82d3c4737715a52e3693a3cd | [
"Apache-2.0"
] | 5 | 2017-04-10T03:35:40.000Z | 2020-11-26T10:00:57.000Z | c++/ld/include/slice.cpp | nkysg/Asenal | 12444c7e50fae2be82d3c4737715a52e3693a3cd | [
"Apache-2.0"
] | 1 | 2015-04-09T13:45:25.000Z | 2015-04-09T13:45:25.000Z | c++/ld/include/slice.cpp | baotiao/Asenal | 102170aa92ae72b1d589dd74e8bbbc9ae27a8d97 | [
"Apache-2.0"
] | 15 | 2015-03-10T04:15:10.000Z | 2021-03-19T13:00:48.000Z | #include <slice.h>
namespace ld {
bool Slice::starts_with(const Slice& rhs) const
{
return (size_ >= rhs.size_) && (memcmp(data_, rhs.data(), rhs.size_) == 0);
}
}
| 15.666667 | 83 | 0.574468 | nkysg |
8b4f1b0fee4fbc0a88e890a4008cce88d17c4842 | 1,519 | cpp | C++ | event_loop_base_kqueue.cpp | looyao/mevent | fa268e93b33264c71d086ba9387b5ab2fabd0257 | [
"MIT"
] | 42 | 2017-03-07T02:45:22.000Z | 2019-02-26T15:26:25.000Z | event_loop_base_kqueue.cpp | looyao/mevent | fa268e93b33264c71d086ba9387b5ab2fabd0257 | [
"MIT"
] | null | null | null | event_loop_base_kqueue.cpp | looyao/mevent | fa268e93b33264c71d086ba9387b5ab2fabd0257 | [
"MIT"
] | 11 | 2017-03-07T06:42:30.000Z | 2019-03-06T03:15:46.000Z | #include "event_loop_base.h"
#include <sys/event.h>
#include <stdlib.h>
namespace mevent {
int EventLoopBase::Create() {
return kqueue();
}
int EventLoopBase::Add(int evfd, int fd, int mask, void *data) {
struct kevent ev;
if (mask & MEVENT_IN) {
EV_SET(&ev, fd, EVFILT_READ, EV_ADD, 0, 0, data);
kevent(evfd, &ev, 1, NULL, 0, NULL);
}
if (mask & MEVENT_OUT) {
EV_SET(&ev, fd, EVFILT_WRITE, EV_ADD, 0, 0, data);
kevent(evfd, &ev, 1, NULL, 0, NULL);
}
return 0;
}
int EventLoopBase::Modify(int evfd, int fd, int mask, void *data) {
return Add(evfd, fd, mask, data);
}
int EventLoopBase::Poll(int evfd, EventLoopBase::Event *events, int size, struct timeval *tv) {
struct kevent evs[size];
int nfds;
if (tv) {
struct timespec timeout;
timeout.tv_sec = tv->tv_sec;
timeout.tv_nsec = tv->tv_usec * 1000;
nfds = kevent(evfd, NULL, 0, evs, size, &timeout);
} else {
nfds = kevent(evfd, NULL, 0, evs, size, NULL);
}
if (nfds > 0) {
for (int i = 0; i < nfds; i++) {
events[i].data.ptr = evs[i].udata;
events[i].mask = 0;
if (evs[i].filter == EVFILT_READ) {
events[i].mask |= MEVENT_IN;
}
if (evs[i].filter == EVFILT_WRITE) {
events[i].mask |= MEVENT_OUT;
}
}
}
return nfds;
}
}//namespace mevent | 23.734375 | 95 | 0.520737 | looyao |
8b4f9229f18863d94803761c7014227131f0b0ec | 7,863 | hxx | C++ | opencascade/AIS_InteractiveObject.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 37 | 2020-01-20T21:50:21.000Z | 2022-02-09T13:01:09.000Z | opencascade/AIS_InteractiveObject.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/AIS_InteractiveObject.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 22 | 2020-04-03T21:59:52.000Z | 2022-03-06T18:43:35.000Z | // Created on: 1996-12-11
// Created by: Robert COUBLANC
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AIS_InteractiveObject_HeaderFile
#define _AIS_InteractiveObject_HeaderFile
#include <AIS_KindOfInteractive.hxx>
#include <AIS_DragAction.hxx>
#include <SelectMgr_SelectableObject.hxx>
class AIS_InteractiveContext;
class Graphic3d_MaterialAspect;
class Prs3d_BasicAspect;
class Bnd_Box;
class V3d_View;
//! Defines a class of objects with display and selection services.
//! Entities which are visualized and selected are Interactive Objects.
//! Specific attributes of entities such as arrow aspect for dimensions must be loaded in a Prs3d_Drawer.
//!
//! You can make use of classes of standard Interactive Objects for which all necessary methods have already been programmed,
//! or you can implement your own classes of Interactive Objects.
//! Key interface methods to be implemented by every Interactive Object:
//! * Presentable Object (PrsMgr_PresentableObject)
//! Consider defining an enumeration of supported Display Mode indexes for particular Interactive Object or class of Interactive Objects.
//! - AcceptDisplayMode() accepting display modes implemented by this object;
//! - Compute() computing presentation for the given display mode index;
//! * Selectable Object (SelectMgr_SelectableObject)
//! Consider defining an enumeration of supported Selection Mode indexes for particular Interactive Object or class of Interactive Objects.
//! - ComputeSelection() computing selectable entities for the given selection mode index.
class AIS_InteractiveObject : public SelectMgr_SelectableObject
{
friend class AIS_InteractiveContext;
DEFINE_STANDARD_RTTIEXT(AIS_InteractiveObject, SelectMgr_SelectableObject)
public:
//! Returns the kind of Interactive Object; AIS_KOI_None by default.
virtual AIS_KindOfInteractive Type() const { return AIS_KOI_None; }
//! Specifies additional characteristics of Interactive Object of Type(); -1 by default.
//! Among the datums, this signature is attributed to the shape.
//! The remaining datums have the following default signatures:
//! - Point signature 1
//! - Axis signature 2
//! - Trihedron signature 3
//! - PlaneTrihedron signature 4
//! - Line signature 5
//! - Circle signature 6
//! - Plane signature 7.
virtual Standard_Integer Signature() const { return -1; }
//! Updates the active presentation; if <AllModes> = Standard_True
//! all the presentations inside are recomputed.
//! IMPORTANT: It is preferable to call Redisplay method of
//! corresponding AIS_InteractiveContext instance for cases when it
//! is accessible. This method just redirects call to myCTXPtr,
//! so this class field must be up to date for proper result.
Standard_EXPORT void Redisplay (const Standard_Boolean AllModes = Standard_False);
//! Indicates whether the Interactive Object has a pointer to an interactive context.
Standard_Boolean HasInteractiveContext() const { return myCTXPtr != NULL; }
//! Returns the context pointer to the interactive context.
AIS_InteractiveContext* InteractiveContext() const { return myCTXPtr; }
//! Sets the interactive context aCtx and provides a link
//! to the default drawing tool or "Drawer" if there is none.
Standard_EXPORT virtual void SetContext (const Handle(AIS_InteractiveContext)& aCtx);
//! Returns true if the object has an owner attributed to it.
//! The owner can be a shape for a set of sub-shapes or a sub-shape for sub-shapes which it is composed of, and takes the form of a transient.
Standard_Boolean HasOwner() const { return !myOwner.IsNull(); }
//! Returns the owner of the Interactive Object.
//! The owner can be a shape for a set of sub-shapes or
//! a sub-shape for sub-shapes which it is composed of,
//! and takes the form of a transient.
//! There are two types of owners:
//! - Direct owners, decomposition shapes such as
//! edges, wires, and faces.
//! - Users, presentable objects connecting to sensitive
//! primitives, or a shape which has been decomposed.
const Handle(Standard_Transient)& GetOwner() const { return myOwner; }
//! Allows you to attribute the owner theApplicativeEntity to
//! an Interactive Object. This can be a shape for a set of
//! sub-shapes or a sub-shape for sub-shapes which it
//! is composed of. The owner takes the form of a transient.
void SetOwner (const Handle(Standard_Transient)& theApplicativeEntity) { myOwner = theApplicativeEntity; }
//! Each Interactive Object has methods which allow us to attribute an Owner to it in the form of a Transient.
//! This method removes the owner from the graphic entity.
void ClearOwner() { myOwner.Nullify(); }
//! Drag object in the viewer.
//! @param theCtx [in] interactive context
//! @param theView [in] active View
//! @param theOwner [in] the owner of detected entity
//! @param theDragFrom [in] drag start point
//! @param theDragTo [in] drag end point
//! @param theAction [in] drag action
//! @return FALSE if object rejects dragging action (e.g. AIS_DragAction_Start)
Standard_EXPORT virtual Standard_Boolean ProcessDragging (const Handle(AIS_InteractiveContext)& theCtx,
const Handle(V3d_View)& theView,
const Handle(SelectMgr_EntityOwner)& theOwner,
const Graphic3d_Vec2i& theDragFrom,
const Graphic3d_Vec2i& theDragTo,
const AIS_DragAction theAction);
public:
//! Returns the context pointer to the interactive context.
Standard_EXPORT Handle(AIS_InteractiveContext) GetContext() const;
//! Returns TRUE when this object has a presentation in the current DisplayMode()
Standard_EXPORT Standard_Boolean HasPresentation() const;
//! Returns the current presentation of this object according to the current DisplayMode()
Standard_EXPORT Handle(Prs3d_Presentation) Presentation() const;
//! Sets the graphic basic aspect to the current presentation.
Standard_DEPRECATED("Deprecated method, results might be undefined")
Standard_EXPORT void SetAspect (const Handle(Prs3d_BasicAspect)& anAspect);
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
//! The TypeOfPresention3d means that the interactive object
//! may have a presentation dependant of the view of Display.
Standard_EXPORT AIS_InteractiveObject(const PrsMgr_TypeOfPresentation3d aTypeOfPresentation3d = PrsMgr_TOP_AllView);
protected:
AIS_InteractiveContext* myCTXPtr; //!< pointer to Interactive Context, where object is currently displayed; @sa SetContext()
Handle(Standard_Transient) myOwner; //!< application-specific owner object
};
DEFINE_STANDARD_HANDLE(AIS_InteractiveObject, SelectMgr_SelectableObject)
#endif // _AIS_InteractiveObject_HeaderFile
| 50.403846 | 144 | 0.732926 | valgur |
332b529cc50e39e2da681bfc7adf5fbcaff7d7b6 | 352 | cpp | C++ | test/error/reduction_bounds.cpp | OAID/Halide | 769b8554ec36b70ea53c73605ad021cf431476fc | [
"Apache-2.0"
] | 4,303 | 2015-01-02T12:04:37.000Z | 2022-03-31T11:35:06.000Z | test/error/reduction_bounds.cpp | OAID/Halide | 769b8554ec36b70ea53c73605ad021cf431476fc | [
"Apache-2.0"
] | 4,323 | 2015-01-01T13:31:25.000Z | 2022-03-31T22:43:57.000Z | test/error/reduction_bounds.cpp | OAID/Halide | 769b8554ec36b70ea53c73605ad021cf431476fc | [
"Apache-2.0"
] | 1,032 | 2015-01-12T12:50:16.000Z | 2022-03-28T01:55:11.000Z | #include "Halide.h"
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f("f"), g("g");
Var x("x");
RDom r(0, 100, "r");
f(x) = x;
g(x) = 0;
g(x) = f(g(x - 1)) + r;
f.compute_at(g, r.x);
// Use of f is unbounded in g.
g.realize({100});
printf("Success!\n");
return 0;
}
| 14.08 | 34 | 0.485795 | OAID |
332d77eb71a4311cc316f682b76f34991f99d338 | 2,324 | cpp | C++ | automated-tests/src/dali/dali-test-suite-utils/test-render-surface.cpp | nui-dali/dali-core | bc9255ec35bec7223cd6a18fb2b3a6fcc273936b | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | automated-tests/src/dali/dali-test-suite-utils/test-render-surface.cpp | nui-dali/dali-core | bc9255ec35bec7223cd6a18fb2b3a6fcc273936b | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-03-22T10:19:17.000Z | 2020-03-22T10:19:17.000Z | automated-tests/src/dali/dali-test-suite-utils/test-render-surface.cpp | fayhot/dali-core | a69ea317f30961164520664a645ac36c387055ef | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "test-render-surface.h"
namespace Dali
{
TestRenderSurface::TestRenderSurface( Dali::PositionSize positionSize )
: mPositionSize( positionSize ),
mBackgroundColor()
{
}
TestRenderSurface::~TestRenderSurface()
{
}
Dali::PositionSize TestRenderSurface::GetPositionSize() const
{
return mPositionSize;
};
void TestRenderSurface::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical )
{
dpiHorizontal = dpiVertical = 96;
};
void TestRenderSurface::InitializeGraphics()
{
}
void TestRenderSurface::CreateSurface()
{
}
void TestRenderSurface::DestroySurface()
{
}
bool TestRenderSurface::ReplaceGraphicsSurface()
{
return false;
}
void TestRenderSurface::MoveResize( Dali::PositionSize positionSize )
{
mPositionSize = positionSize;
}
void TestRenderSurface::StartRender()
{
}
bool TestRenderSurface::PreRender( bool resizingSurface )
{
return true;
}
void TestRenderSurface::PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface )
{
}
void TestRenderSurface::StopRender()
{
}
void TestRenderSurface::ReleaseLock()
{
}
Dali::Integration::RenderSurface::Type TestRenderSurface::GetSurfaceType()
{
return WINDOW_RENDER_SURFACE;
}
void TestRenderSurface::MakeContextCurrent()
{
}
Integration::DepthBufferAvailable TestRenderSurface::GetDepthBufferRequired()
{
return Integration::DepthBufferAvailable::TRUE;
}
Integration::StencilBufferAvailable TestRenderSurface::GetStencilBufferRequired()
{
return Integration::StencilBufferAvailable::TRUE;
}
void TestRenderSurface::SetBackgroundColor( Vector4 color )
{
mBackgroundColor = color;
}
Vector4 TestRenderSurface::GetBackgroundColor()
{
return mBackgroundColor;
}
} // Namespace dali
| 20.034483 | 99 | 0.770224 | nui-dali |
332ef21318659e715f1f6001ab794cc66f16270b | 94,272 | cpp | C++ | src/test/app/AccountTxPaging_test.cpp | sneh19337/rippled | 442205bdf270d26f0936f7ece5f03bcc952a6a8b | [
"BSL-1.0"
] | 3,804 | 2015-01-02T01:50:44.000Z | 2022-03-31T23:28:19.000Z | src/test/app/AccountTxPaging_test.cpp | sneh19337/rippled | 442205bdf270d26f0936f7ece5f03bcc952a6a8b | [
"BSL-1.0"
] | 3,131 | 2015-01-01T04:00:06.000Z | 2022-03-31T19:41:33.000Z | src/test/app/AccountTxPaging_test.cpp | sneh19337/rippled | 442205bdf270d26f0936f7ece5f03bcc952a6a8b | [
"BSL-1.0"
] | 1,349 | 2015-01-04T04:36:22.000Z | 2022-03-31T08:56:50.000Z | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2016 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/beast/unit_test.h>
#include <ripple/protocol/SField.h>
#include <ripple/protocol/jss.h>
#include <cstdlib>
#include <test/jtx.h>
#include <ripple/rpc/GRPCHandlers.h>
#include <ripple/rpc/impl/RPCHelpers.h>
#include <test/rpc/GRPCTestClientBase.h>
namespace ripple {
class AccountTxPaging_test : public beast::unit_test::suite
{
bool
checkTransaction(Json::Value const& tx, int sequence, int ledger)
{
return (
tx[jss::tx][jss::Sequence].asInt() == sequence &&
tx[jss::tx][jss::ledger_index].asInt() == ledger);
}
auto
next(
test::jtx::Env& env,
test::jtx::Account const& account,
int ledger_min,
int ledger_max,
int limit,
bool forward,
Json::Value const& marker = Json::nullValue)
{
Json::Value jvc;
jvc[jss::account] = account.human();
jvc[jss::ledger_index_min] = ledger_min;
jvc[jss::ledger_index_max] = ledger_max;
jvc[jss::forward] = forward;
jvc[jss::limit] = limit;
if (marker)
jvc[jss::marker] = marker;
return env.rpc("json", "account_tx", to_string(jvc))[jss::result];
}
void
testAccountTxPaging()
{
testcase("Paging for Single Account");
using namespace test::jtx;
Env env(*this);
Account A1{"A1"};
Account A2{"A2"};
Account A3{"A3"};
env.fund(XRP(10000), A1, A2, A3);
env.close();
env.trust(A3["USD"](1000), A1);
env.trust(A2["USD"](1000), A1);
env.trust(A3["USD"](1000), A2);
env.close();
for (auto i = 0; i < 5; ++i)
{
env(pay(A2, A1, A2["USD"](2)));
env(pay(A3, A1, A3["USD"](2)));
env(offer(A1, XRP(11), A1["USD"](1)));
env(offer(A2, XRP(10), A2["USD"](1)));
env(offer(A3, XRP(9), A3["USD"](1)));
env.close();
}
/* The sequence/ledger for A3 are as follows:
* seq ledger_index
* 3 ----> 3
* 1 ----> 3
* 2 ----> 4
* 2 ----> 4
* 2 ----> 5
* 3 ----> 5
* 4 ----> 6
* 5 ----> 6
* 6 ----> 7
* 7 ----> 7
* 8 ----> 8
* 9 ----> 8
* 10 ----> 9
* 11 ----> 9
*/
// page through the results in several ways.
{
// limit = 2, 3 batches giving the first 6 txs
auto jrr = next(env, A3, 2, 5, 2, true);
auto txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
BEAST_EXPECT(checkTransaction(txs[1u], 3, 3));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 2, 5, 2, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 4));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 2, 5, 2, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 5));
BEAST_EXPECT(checkTransaction(txs[1u], 5, 5));
BEAST_EXPECT(!jrr[jss::marker]);
}
{
// limit 1, 3 requests giving the first 3 txs
auto jrr = next(env, A3, 3, 9, 1, true);
auto txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 1, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 1, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
// continue with limit 3, to end of all txs
jrr = next(env, A3, 3, 9, 3, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 5));
BEAST_EXPECT(checkTransaction(txs[2u], 5, 5));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 6, 6));
BEAST_EXPECT(checkTransaction(txs[1u], 7, 6));
BEAST_EXPECT(checkTransaction(txs[2u], 8, 7));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 9, 7));
BEAST_EXPECT(checkTransaction(txs[1u], 10, 8));
BEAST_EXPECT(checkTransaction(txs[2u], 11, 8));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, true, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 12, 9));
BEAST_EXPECT(checkTransaction(txs[1u], 13, 9));
BEAST_EXPECT(!jrr[jss::marker]);
}
{
// limit 2, descending, 2 batches giving last 4 txs
auto jrr = next(env, A3, 3, 9, 2, false);
auto txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 13, 9));
BEAST_EXPECT(checkTransaction(txs[1u], 12, 9));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 2, false, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 11, 8));
BEAST_EXPECT(checkTransaction(txs[1u], 10, 8));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
// continue with limit 3 until all txs have been seen
jrr = next(env, A3, 3, 9, 3, false, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 9, 7));
BEAST_EXPECT(checkTransaction(txs[1u], 8, 7));
BEAST_EXPECT(checkTransaction(txs[2u], 7, 6));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, false, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 6, 6));
BEAST_EXPECT(checkTransaction(txs[1u], 5, 5));
BEAST_EXPECT(checkTransaction(txs[2u], 4, 5));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, false, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[2u], 3, 3));
if (!BEAST_EXPECT(jrr[jss::marker]))
return;
jrr = next(env, A3, 3, 9, 3, false, jrr[jss::marker]);
txs = jrr[jss::transactions];
if (!BEAST_EXPECT(txs.isArray() && txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
BEAST_EXPECT(!jrr[jss::marker]);
}
}
class GrpcAccountTxClient : public test::GRPCTestClientBase
{
public:
org::xrpl::rpc::v1::GetAccountTransactionHistoryRequest request;
org::xrpl::rpc::v1::GetAccountTransactionHistoryResponse reply;
explicit GrpcAccountTxClient(std::string const& port)
: GRPCTestClientBase(port)
{
}
void
AccountTx()
{
status =
stub_->GetAccountTransactionHistory(&context, request, &reply);
}
};
bool
checkTransaction(
org::xrpl::rpc::v1::GetTransactionResponse const& tx,
int sequence,
int ledger)
{
return (
tx.transaction().sequence().value() == sequence &&
tx.ledger_index() == ledger);
}
std::pair<
org::xrpl::rpc::v1::GetAccountTransactionHistoryResponse,
grpc::Status>
nextBinary(
std::string grpcPort,
test::jtx::Env& env,
std::string const& account = "",
int ledger_min = -1,
int ledger_max = -1,
int limit = -1,
bool forward = false,
org::xrpl::rpc::v1::Marker* marker = nullptr)
{
GrpcAccountTxClient client{grpcPort};
auto& request = client.request;
if (account != "")
request.mutable_account()->set_address(account);
if (ledger_min != -1)
request.mutable_ledger_range()->set_ledger_index_min(ledger_min);
if (ledger_max != -1)
request.mutable_ledger_range()->set_ledger_index_max(ledger_max);
request.set_forward(forward);
request.set_binary(true);
if (limit != -1)
request.set_limit(limit);
if (marker)
{
*request.mutable_marker() = *marker;
}
client.AccountTx();
return {client.reply, client.status};
}
std::pair<
org::xrpl::rpc::v1::GetAccountTransactionHistoryResponse,
grpc::Status>
next(
std::string grpcPort,
test::jtx::Env& env,
std::string const& account = "",
int ledger_min = -1,
int ledger_max = -1,
int limit = -1,
bool forward = false,
org::xrpl::rpc::v1::Marker* marker = nullptr)
{
GrpcAccountTxClient client{grpcPort};
auto& request = client.request;
if (account != "")
request.mutable_account()->set_address(account);
if (ledger_min != -1)
request.mutable_ledger_range()->set_ledger_index_min(ledger_min);
if (ledger_max != -1)
request.mutable_ledger_range()->set_ledger_index_max(ledger_max);
request.set_forward(forward);
if (limit != -1)
request.set_limit(limit);
if (marker)
{
*request.mutable_marker() = *marker;
}
client.AccountTx();
return {client.reply, client.status};
}
std::pair<
org::xrpl::rpc::v1::GetAccountTransactionHistoryResponse,
grpc::Status>
nextWithSeq(
std::string grpcPort,
test::jtx::Env& env,
std::string const& account = "",
int ledger_seq = -1,
int limit = -1,
bool forward = false,
org::xrpl::rpc::v1::Marker* marker = nullptr)
{
GrpcAccountTxClient client{grpcPort};
auto& request = client.request;
if (account != "")
request.mutable_account()->set_address(account);
if (ledger_seq != -1)
request.mutable_ledger_specifier()->set_sequence(ledger_seq);
request.set_forward(forward);
if (limit != -1)
request.set_limit(limit);
if (marker)
{
*request.mutable_marker() = *marker;
}
client.AccountTx();
return {client.reply, client.status};
}
std::pair<
org::xrpl::rpc::v1::GetAccountTransactionHistoryResponse,
grpc::Status>
nextWithHash(
std::string grpcPort,
test::jtx::Env& env,
std::string const& account = "",
uint256 const& hash = beast::zero,
int limit = -1,
bool forward = false,
org::xrpl::rpc::v1::Marker* marker = nullptr)
{
GrpcAccountTxClient client{grpcPort};
auto& request = client.request;
if (account != "")
request.mutable_account()->set_address(account);
if (hash != beast::zero)
request.mutable_ledger_specifier()->set_hash(
hash.data(), hash.size());
request.set_forward(forward);
if (limit != -1)
request.set_limit(limit);
if (marker)
{
*request.mutable_marker() = *marker;
}
client.AccountTx();
return {client.reply, client.status};
}
void
testAccountTxParametersGrpc()
{
testcase("Test Account_tx Grpc");
using namespace test::jtx;
std::unique_ptr<Config> config = envconfig(addGrpcConfig);
std::string grpcPort = *(*config)["port_grpc"].get<std::string>("port");
Env env(*this, std::move(config));
Account A1{"A1"};
env.fund(XRP(10000), A1);
env.close();
// Ledger 3 has the two txs associated with funding the account
// All other ledgers have no txs
auto hasTxs = [](auto res) {
return res.second.error_code() == 0 &&
(res.first.transactions().size() == 2) &&
//(res.transactions()[0u].transaction().has_account_set()) &&
(res.first.transactions()[1u].transaction().has_payment());
};
auto noTxs = [](auto res) {
return res.second.error_code() == 0 &&
(res.first.transactions().size() == 0);
};
auto isErr = [](auto res, auto expect) {
return res.second.error_code() == expect;
};
BEAST_EXPECT(
isErr(next(grpcPort, env, ""), grpc::StatusCode::INVALID_ARGUMENT));
BEAST_EXPECT(isErr(
next(grpcPort, env, "0xDEADBEEF"),
grpc::StatusCode::INVALID_ARGUMENT));
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human())));
// Ledger min/max index
{
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human())));
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human(), 0, 100)));
BEAST_EXPECT(noTxs(next(grpcPort, env, A1.human(), 1, 2)));
BEAST_EXPECT(isErr(
next(grpcPort, env, A1.human(), 2, 1),
grpc::StatusCode::INVALID_ARGUMENT));
}
// Ledger index min only
{
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human(), -1)));
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human(), 1)));
BEAST_EXPECT(isErr(
next(grpcPort, env, A1.human(), env.current()->info().seq),
grpc::StatusCode::INVALID_ARGUMENT));
}
// Ledger index max only
{
BEAST_EXPECT(hasTxs(next(grpcPort, env, A1.human(), -1, -1)));
BEAST_EXPECT(hasTxs(next(
grpcPort, env, A1.human(), -1, env.current()->info().seq)));
BEAST_EXPECT(hasTxs(
next(grpcPort, env, A1.human(), -1, env.closed()->info().seq)));
BEAST_EXPECT(noTxs(next(
grpcPort, env, A1.human(), -1, env.closed()->info().seq - 1)));
}
// Ledger Sequence
{
BEAST_EXPECT(hasTxs(nextWithSeq(
grpcPort, env, A1.human(), env.closed()->info().seq)));
BEAST_EXPECT(noTxs(nextWithSeq(
grpcPort, env, A1.human(), env.closed()->info().seq - 1)));
BEAST_EXPECT(isErr(
nextWithSeq(
grpcPort, env, A1.human(), env.current()->info().seq),
grpc::StatusCode::INVALID_ARGUMENT));
BEAST_EXPECT(isErr(
nextWithSeq(
grpcPort, env, A1.human(), env.current()->info().seq + 1),
grpc::StatusCode::NOT_FOUND));
}
// Ledger Hash
{
BEAST_EXPECT(hasTxs(nextWithHash(
grpcPort, env, A1.human(), env.closed()->info().hash)));
BEAST_EXPECT(noTxs(nextWithHash(
grpcPort, env, A1.human(), env.closed()->info().parentHash)));
}
}
struct TxCheck
{
uint32_t sequence;
uint32_t ledgerIndex;
std::string hash;
std::function<bool(org::xrpl::rpc::v1::Transaction const& res)>
checkTxn;
};
void
testAccountTxContentsGrpc()
{
testcase("Test AccountTx context grpc");
// Get results for all transaction types that can be associated
// with an account. Start by generating all transaction types.
using namespace test::jtx;
using namespace std::chrono_literals;
std::unique_ptr<Config> config = envconfig(addGrpcConfig);
std::string grpcPort = *(*config)["port_grpc"].get<std::string>("port");
Env env(*this, std::move(config));
// Set time to this value (or greater) to get delivered_amount in meta
env.timeKeeper().set(NetClock::time_point{446000001s});
Account const alice{"alice"};
Account const alie{"alie"};
Account const gw{"gw"};
auto const USD{gw["USD"]};
std::vector<std::shared_ptr<STTx const>> txns;
env.fund(XRP(1000000), alice, gw);
env.close();
// AccountSet
env(noop(alice));
txns.emplace_back(env.tx());
// Payment
env(pay(alice, gw, XRP(100)), stag(42), dtag(24), last_ledger_seq(20));
txns.emplace_back(env.tx());
// Regular key set
env(regkey(alice, alie));
env.close();
txns.emplace_back(env.tx());
// Trust and Offers
env(trust(alice, USD(200)), sig(alie));
txns.emplace_back(env.tx());
std::uint32_t const offerSeq{env.seq(alice)};
env(offer(alice, USD(50), XRP(150)), sig(alie));
txns.emplace_back(env.tx());
env.close();
env(offer_cancel(alice, offerSeq), sig(alie));
env.close();
txns.emplace_back(env.tx());
// SignerListSet
env(signers(alice, 1, {{"bogie", 1}, {"demon", 1}, {gw, 1}}),
sig(alie));
txns.emplace_back(env.tx());
// Escrow
{
// Create an escrow. Requires either a CancelAfter or FinishAfter.
auto escrow = [](Account const& account,
Account const& to,
STAmount const& amount) {
Json::Value escro;
escro[jss::TransactionType] = jss::EscrowCreate;
escro[jss::Flags] = tfUniversal;
escro[jss::Account] = account.human();
escro[jss::Destination] = to.human();
escro[jss::Amount] = amount.getJson(JsonOptions::none);
return escro;
};
NetClock::time_point const nextTime{env.now() + 2s};
Json::Value escrowWithFinish{escrow(alice, alice, XRP(500))};
escrowWithFinish[sfFinishAfter.jsonName] =
nextTime.time_since_epoch().count();
std::uint32_t const escrowFinishSeq{env.seq(alice)};
env(escrowWithFinish, sig(alie));
txns.emplace_back(env.tx());
Json::Value escrowWithCancel{escrow(alice, alice, XRP(500))};
escrowWithCancel[sfFinishAfter.jsonName] =
nextTime.time_since_epoch().count();
escrowWithCancel[sfCancelAfter.jsonName] =
nextTime.time_since_epoch().count() + 1;
std::uint32_t const escrowCancelSeq{env.seq(alice)};
env(escrowWithCancel, sig(alie));
env.close();
txns.emplace_back(env.tx());
{
Json::Value escrowFinish;
escrowFinish[jss::TransactionType] = jss::EscrowFinish;
escrowFinish[jss::Flags] = tfUniversal;
escrowFinish[jss::Account] = alice.human();
escrowFinish[sfOwner.jsonName] = alice.human();
escrowFinish[sfOfferSequence.jsonName] = escrowFinishSeq;
env(escrowFinish, sig(alie));
txns.emplace_back(env.tx());
}
{
Json::Value escrowCancel;
escrowCancel[jss::TransactionType] = jss::EscrowCancel;
escrowCancel[jss::Flags] = tfUniversal;
escrowCancel[jss::Account] = alice.human();
escrowCancel[sfOwner.jsonName] = alice.human();
escrowCancel[sfOfferSequence.jsonName] = escrowCancelSeq;
env(escrowCancel, sig(alie));
txns.emplace_back(env.tx());
}
env.close();
}
// PayChan
{
std::uint32_t payChanSeq{env.seq(alice)};
Json::Value payChanCreate;
payChanCreate[jss::TransactionType] = jss::PaymentChannelCreate;
payChanCreate[jss::Flags] = tfUniversal;
payChanCreate[jss::Account] = alice.human();
payChanCreate[jss::Destination] = gw.human();
payChanCreate[jss::Amount] =
XRP(500).value().getJson(JsonOptions::none);
payChanCreate[sfSettleDelay.jsonName] =
NetClock::duration{100s}.count();
payChanCreate[sfPublicKey.jsonName] = strHex(alice.pk().slice());
env(payChanCreate, sig(alie));
env.close();
txns.emplace_back(env.tx());
std::string const payChanIndex{
strHex(keylet::payChan(alice, gw, payChanSeq).key)};
{
Json::Value payChanFund;
payChanFund[jss::TransactionType] = jss::PaymentChannelFund;
payChanFund[jss::Flags] = tfUniversal;
payChanFund[jss::Account] = alice.human();
payChanFund[sfChannel.jsonName] = payChanIndex;
payChanFund[jss::Amount] =
XRP(200).value().getJson(JsonOptions::none);
env(payChanFund, sig(alie));
env.close();
txns.emplace_back(env.tx());
}
{
Json::Value payChanClaim;
payChanClaim[jss::TransactionType] = jss::PaymentChannelClaim;
payChanClaim[jss::Flags] = tfClose;
payChanClaim[jss::Account] = gw.human();
payChanClaim[sfChannel.jsonName] = payChanIndex;
payChanClaim[sfPublicKey.jsonName] = strHex(alice.pk().slice());
env(payChanClaim);
env.close();
txns.emplace_back(env.tx());
}
}
// Check
{
auto const aliceCheckId = keylet::check(alice, env.seq(alice)).key;
env(check::create(alice, gw, XRP(300)), sig(alie));
auto txn = env.tx();
auto const gwCheckId = keylet::check(gw, env.seq(gw)).key;
env(check::create(gw, alice, XRP(200)));
env.close();
// need to switch the order of the previous 2 txns, since they are
// in the same ledger and account_tx returns them in a different
// order
txns.emplace_back(env.tx());
txns.emplace_back(txn);
env(check::cash(alice, gwCheckId, XRP(200)), sig(alie));
txns.emplace_back(env.tx());
env(check::cancel(alice, aliceCheckId), sig(alie));
txns.emplace_back(env.tx());
env.close();
}
// Deposit preauthorization.
env(deposit::auth(alice, gw), sig(alie));
env.close();
txns.emplace_back(env.tx());
// Multi Sig with memo
auto const baseFee = env.current()->fees().base;
env(noop(alice),
msig(gw),
fee(2 * baseFee),
memo("data", "format", "type"));
env.close();
txns.emplace_back(env.tx());
if (!BEAST_EXPECT(txns.size() == 20))
return;
// Setup is done. Look at the transactions returned by account_tx.
static const TxCheck txCheck[]{
{21,
15,
strHex(txns[txns.size() - 1]->getTransactionID()),
[this, &txns](auto res) {
auto txnJson =
txns[txns.size() - 1]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_account_set()) &&
BEAST_EXPECT(res.has_fee()) &&
BEAST_EXPECT(res.fee().drops() == 20) &&
BEAST_EXPECT(res.memos_size() == 1) &&
BEAST_EXPECT(res.memos(0).has_memo_data()) &&
BEAST_EXPECT(res.memos(0).memo_data().value() == "data") &&
BEAST_EXPECT(res.memos(0).has_memo_format()) &&
BEAST_EXPECT(
res.memos(0).memo_format().value() == "format") &&
BEAST_EXPECT(res.memos(0).has_memo_type()) &&
BEAST_EXPECT(res.memos(0).memo_type().value() == "type") &&
BEAST_EXPECT(res.has_signing_public_key()) &&
BEAST_EXPECT(res.signing_public_key().value() == "") &&
BEAST_EXPECT(res.signers_size() == 1) &&
BEAST_EXPECT(res.signers(0).has_account()) &&
BEAST_EXPECT(
res.signers(0).account().value().address() ==
txnJson["Signers"][0u]["Signer"]["Account"]) &&
BEAST_EXPECT(res.signers(0).has_transaction_signature()) &&
BEAST_EXPECT(
strHex(res.signers(0)
.transaction_signature()
.value()) ==
txnJson["Signers"][0u]["Signer"]["TxnSignature"]) &&
BEAST_EXPECT(res.signers(0).has_signing_public_key()) &&
BEAST_EXPECT(
strHex(
res.signers(0).signing_public_key().value()) ==
txnJson["Signers"][0u]["Signer"]["SigningPubKey"]);
}},
{20,
14,
strHex(txns[txns.size() - 2]->getTransactionID()),
[&txns, this](auto res) {
return BEAST_EXPECT(res.has_deposit_preauth()) &&
BEAST_EXPECT(
res.deposit_preauth()
.authorize()
.value()
.address() ==
// TODO do them all like this
txns[txns.size() - 2]->getJson(
JsonOptions::none)["Authorize"]);
}},
{19,
13,
strHex(txns[txns.size() - 3]->getTransactionID()),
[&txns, this](auto res) {
return BEAST_EXPECT(res.has_check_cancel()) &&
BEAST_EXPECT(
strHex(res.check_cancel().check_id().value()) ==
txns[txns.size() - 3]->getJson(
JsonOptions::none)["CheckID"]);
}},
{18,
13,
strHex(txns[txns.size() - 4]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 4]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_check_cash()) &&
BEAST_EXPECT(
strHex(res.check_cash().check_id().value()) ==
txnJson["CheckID"]) &&
BEAST_EXPECT(res.check_cash()
.amount()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.check_cash()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt());
}},
{17,
12,
strHex(txns[txns.size() - 5]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 5]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_check_create()) &&
BEAST_EXPECT(
res.check_create()
.destination()
.value()
.address() == txnJson["Destination"]) &&
BEAST_EXPECT(res.check_create()
.send_max()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.check_create()
.send_max()
.value()
.xrp_amount()
.drops() == txnJson["SendMax"].asUInt());
}},
{5,
12,
strHex(txns[txns.size() - 6]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 6]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_check_create()) &&
BEAST_EXPECT(
res.check_create()
.destination()
.value()
.address() == txnJson["Destination"]) &&
BEAST_EXPECT(res.check_create()
.send_max()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.check_create()
.send_max()
.value()
.xrp_amount()
.drops() ==
txnJson["SendMax"].asUInt());
}},
{4,
11,
strHex(txns[txns.size() - 7]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 7]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_payment_channel_claim()) &&
BEAST_EXPECT(
strHex(res.payment_channel_claim()
.channel()
.value()) == txnJson["Channel"]) &&
BEAST_EXPECT(
strHex(res.payment_channel_claim()
.public_key()
.value()) == txnJson["PublicKey"]);
}},
{16,
10,
strHex(txns[txns.size() - 8]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 8]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_payment_channel_fund()) &&
BEAST_EXPECT(
strHex(
res.payment_channel_fund().channel().value()) ==
txnJson["Channel"]) &&
BEAST_EXPECT(res.payment_channel_fund()
.amount()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.payment_channel_fund()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt());
}},
{15,
9,
strHex(txns[txns.size() - 9]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 9]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_payment_channel_create()) &&
BEAST_EXPECT(res.payment_channel_create()
.amount()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.payment_channel_create()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt()) &&
BEAST_EXPECT(
res.payment_channel_create()
.destination()
.value()
.address() == txnJson["Destination"]) &&
BEAST_EXPECT(
res.payment_channel_create()
.settle_delay()
.value() == txnJson["SettleDelay"].asUInt()) &&
BEAST_EXPECT(
strHex(res.payment_channel_create()
.public_key()
.value()) == txnJson["PublicKey"]);
}},
{14,
8,
strHex(txns[txns.size() - 10]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 10]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_escrow_cancel()) &&
BEAST_EXPECT(
res.escrow_cancel().owner().value().address() ==
txnJson["Owner"]) &&
BEAST_EXPECT(
res.escrow_cancel().offer_sequence().value() ==
txnJson["OfferSequence"].asUInt()
);
}},
{13,
8,
strHex(txns[txns.size() - 11]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 11]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_escrow_finish()) &&
BEAST_EXPECT(
res.escrow_finish().owner().value().address() ==
txnJson["Owner"]) &&
BEAST_EXPECT(
res.escrow_finish().offer_sequence().value() ==
txnJson["OfferSequence"].asUInt()
);
}},
{12,
7,
strHex(txns[txns.size() - 12]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 12]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_escrow_create()) &&
BEAST_EXPECT(res.escrow_create()
.amount()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.escrow_create()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt()) &&
BEAST_EXPECT(
res.escrow_create()
.destination()
.value()
.address() == txnJson["Destination"]) &&
BEAST_EXPECT(
res.escrow_create().cancel_after().value() ==
txnJson["CancelAfter"].asUInt()) &&
BEAST_EXPECT(
res.escrow_create().finish_after().value() ==
txnJson["FinishAfter"].asUInt());
}},
{11,
7,
strHex(txns[txns.size() - 13]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 13]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_escrow_create()) &&
BEAST_EXPECT(res.escrow_create()
.amount()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.escrow_create()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt()) &&
BEAST_EXPECT(
res.escrow_create()
.destination()
.value()
.address() == txnJson["Destination"]) &&
BEAST_EXPECT(
res.escrow_create().finish_after().value() ==
txnJson["FinishAfter"].asUInt());
}},
{10,
7,
strHex(txns[txns.size() - 14]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 14]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_signer_list_set()) &&
BEAST_EXPECT(
res.signer_list_set().signer_quorum().value() ==
txnJson["SignerQuorum"].asUInt()) &&
BEAST_EXPECT(
res.signer_list_set().signer_entries().size() ==
3) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[0]
.account()
.value()
.address() ==
txnJson["SignerEntries"][0u]["SignerEntry"]
["Account"]) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[0]
.signer_weight()
.value() ==
txnJson["SignerEntries"][0u]["SignerEntry"]
["SignerWeight"]
.asUInt()) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[1]
.account()
.value()
.address() ==
txnJson["SignerEntries"][1u]["SignerEntry"]
["Account"]) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[1]
.signer_weight()
.value() ==
txnJson["SignerEntries"][1u]["SignerEntry"]
["SignerWeight"]
.asUInt()) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[2]
.account()
.value()
.address() ==
txnJson["SignerEntries"][2u]["SignerEntry"]
["Account"]) &&
BEAST_EXPECT(
res.signer_list_set()
.signer_entries()[2]
.signer_weight()
.value() ==
txnJson["SignerEntries"][2u]["SignerEntry"]
["SignerWeight"]
.asUInt());
}},
{9,
6,
strHex(txns[txns.size() - 15]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 15]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_offer_cancel()) &&
BEAST_EXPECT(
res.offer_cancel().offer_sequence().value() ==
txnJson["OfferSequence"].asUInt());
}},
{8,
5,
strHex(txns[txns.size() - 16]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 16]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_offer_create()) &&
BEAST_EXPECT(res.offer_create()
.taker_gets()
.value()
.has_xrp_amount()) &&
BEAST_EXPECT(
res.offer_create()
.taker_gets()
.value()
.xrp_amount()
.drops() == txnJson["TakerGets"].asUInt()) &&
BEAST_EXPECT(res.offer_create()
.taker_pays()
.value()
.has_issued_currency_amount()) &&
BEAST_EXPECT(
res.offer_create()
.taker_pays()
.value()
.issued_currency_amount()
.currency()
.name() == txnJson["TakerPays"]["currency"]) &&
BEAST_EXPECT(
res.offer_create()
.taker_pays()
.value()
.issued_currency_amount()
.value() == txnJson["TakerPays"]["value"]) &&
BEAST_EXPECT(
res.offer_create()
.taker_pays()
.value()
.issued_currency_amount()
.issuer()
.address() == txnJson["TakerPays"]["issuer"]);
}},
{7,
5,
strHex(txns[txns.size() - 17]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 17]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_trust_set()) &&
BEAST_EXPECT(res.trust_set()
.limit_amount()
.value()
.has_issued_currency_amount()) &&
BEAST_EXPECT(
res.trust_set()
.limit_amount()
.value()
.issued_currency_amount()
.currency()
.name() ==
txnJson["LimitAmount"]["currency"]) &&
BEAST_EXPECT(
res.trust_set()
.limit_amount()
.value()
.issued_currency_amount()
.value() == txnJson["LimitAmount"]["value"]) &&
BEAST_EXPECT(
res.trust_set()
.limit_amount()
.value()
.issued_currency_amount()
.issuer()
.address() == txnJson["LimitAmount"]["issuer"]);
}},
{6,
4,
strHex(txns[txns.size() - 18]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 18]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_set_regular_key()) &&
BEAST_EXPECT(
res.set_regular_key()
.regular_key()
.value()
.address() == txnJson["RegularKey"]);
}},
{5,
4,
strHex(txns[txns.size() - 19]->getTransactionID()),
[&txns, this](auto res) {
auto txnJson =
txns[txns.size() - 19]->getJson(JsonOptions::none);
return BEAST_EXPECT(res.has_payment()) &&
BEAST_EXPECT(
res.payment().amount().value().has_xrp_amount()) &&
BEAST_EXPECT(
res.payment()
.amount()
.value()
.xrp_amount()
.drops() == txnJson["Amount"].asUInt()) &&
BEAST_EXPECT(
res.payment().destination().value().address() ==
txnJson["Destination"]) &&
BEAST_EXPECT(res.has_source_tag()) &&
BEAST_EXPECT(
res.source_tag().value() ==
txnJson["SourceTag"].asUInt()) &&
BEAST_EXPECT(res.payment().has_destination_tag()) &&
BEAST_EXPECT(
res.payment().destination_tag().value() ==
txnJson["DestinationTag"].asUInt()) &&
BEAST_EXPECT(res.has_last_ledger_sequence()) &&
BEAST_EXPECT(
res.last_ledger_sequence().value() ==
txnJson["LastLedgerSequence"].asUInt()) &&
BEAST_EXPECT(res.has_transaction_signature()) &&
BEAST_EXPECT(res.has_account()) &&
BEAST_EXPECT(
res.account().value().address() ==
txnJson["Account"]) &&
BEAST_EXPECT(res.has_flags()) &&
BEAST_EXPECT(
res.flags().value() == txnJson["Flags"].asUInt());
}},
{4,
4,
strHex(txns[txns.size() - 20]->getTransactionID()),
[this](auto res) { return BEAST_EXPECT(res.has_account_set()); }},
{3,
3,
"9CE54C3B934E473A995B477E92EC229F99CED5B62BF4D2ACE4DC42719103AE2F",
[this](auto res) {
return BEAST_EXPECT(res.has_account_set()) &&
BEAST_EXPECT(res.account_set().set_flag().value() == 8);
}},
{1,
3,
"2B5054734FA43C6C7B54F61944FAD6178ACD5D0272B39BA7FCD32A5D3932FBFF",
[&alice, this](auto res) {
return BEAST_EXPECT(res.has_payment()) &&
BEAST_EXPECT(
res.payment().amount().value().has_xrp_amount()) &&
BEAST_EXPECT(
res.payment()
.amount()
.value()
.xrp_amount()
.drops() == 1000000000010) &&
BEAST_EXPECT(
res.payment().destination().value().address() ==
alice.human());
}}};
using MetaCheck =
std::function<bool(org::xrpl::rpc::v1::Meta const& res)>;
static const MetaCheck txMetaCheck[]{
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](org::xrpl::rpc::v1::AffectedNode const&
entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DEPOSIT_PREAUTH;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_CHECK;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_CHECK;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_CHECK;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_CHECK;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_PAY_CHANNEL;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_PAY_CHANNEL;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_PAY_CHANNEL;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ESCROW;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ESCROW;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 2) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ESCROW;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ESCROW;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 3) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_SIGNER_LIST;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 4) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_OFFER;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 4) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_OFFER;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 5) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_DIRECTORY_NODE;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_RIPPLE_STATE;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 2) &&
BEAST_EXPECT(meta.affected_nodes_size() == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 1) &&
BEAST_EXPECT(meta.affected_nodes_size() == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 2) &&
BEAST_EXPECT(meta.affected_nodes_size() == 1) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 1);
}},
{[this](auto meta) {
return BEAST_EXPECT(meta.transaction_index() == 0) &&
BEAST_EXPECT(meta.affected_nodes_size() == 2) &&
BEAST_EXPECT(
std::count_if(
meta.affected_nodes().begin(),
meta.affected_nodes().end(),
[](auto entry) {
return entry.ledger_entry_type() ==
org::xrpl::rpc::v1::LedgerEntryType::
LEDGER_ENTRY_TYPE_ACCOUNT_ROOT;
}) == 2);
}}};
auto doCheck = [this](auto txn, auto txCheck) {
return BEAST_EXPECT(txn.has_transaction()) &&
BEAST_EXPECT(txn.validated()) &&
BEAST_EXPECT(strHex(txn.hash()) == txCheck.hash) &&
BEAST_EXPECT(txn.ledger_index() == txCheck.ledgerIndex) &&
BEAST_EXPECT(
txn.transaction().sequence().value() ==
txCheck.sequence) &&
txCheck.checkTxn(txn.transaction());
};
auto doMetaCheck = [this](auto txn, auto txMetaCheck) {
return BEAST_EXPECT(txn.has_meta()) &&
BEAST_EXPECT(txn.meta().has_transaction_result()) &&
BEAST_EXPECT(
txn.meta().transaction_result().result_type() ==
org::xrpl::rpc::v1::TransactionResult::
RESULT_TYPE_TES) &&
BEAST_EXPECT(
txn.meta().transaction_result().result() ==
"tesSUCCESS") &&
txMetaCheck(txn.meta());
};
auto [res, status] = next(grpcPort, env, alice.human());
if (!BEAST_EXPECT(status.error_code() == 0))
return;
if (!BEAST_EXPECT(res.transactions().size() == std::size(txCheck)))
return;
for (int i = 0; i < res.transactions().size(); ++i)
{
BEAST_EXPECT(doCheck(res.transactions()[i], txCheck[i]));
BEAST_EXPECT(doMetaCheck(res.transactions()[i], txMetaCheck[i]));
}
// test binary representation
std::tie(res, status) = nextBinary(grpcPort, env, alice.human());
// txns vector does not contain the first two transactions returned by
// account_tx
if (!BEAST_EXPECT(res.transactions().size() == txns.size() + 2))
return;
std::reverse(txns.begin(), txns.end());
for (int i = 0; i < txns.size(); ++i)
{
auto toByteString = [](auto data) {
const char* bytes = reinterpret_cast<const char*>(data.data());
return std::string(bytes, data.size());
};
auto tx = txns[i];
Serializer s = tx->getSerializer();
std::string bin = toByteString(s);
BEAST_EXPECT(res.transactions(i).transaction_binary() == bin);
}
}
void
testAccountTxPagingGrpc()
{
testcase("Test Account_tx Grpc");
using namespace test::jtx;
std::unique_ptr<Config> config = envconfig(addGrpcConfig);
std::string grpcPort = *(*config)["port_grpc"].get<std::string>("port");
Env env(*this, std::move(config));
Account A1{"A1"};
Account A2{"A2"};
Account A3{"A3"};
env.fund(XRP(10000), A1, A2, A3);
env.close();
env.trust(A3["USD"](1000), A1);
env.trust(A2["USD"](1000), A1);
env.trust(A3["USD"](1000), A2);
env.close();
for (auto i = 0; i < 5; ++i)
{
env(pay(A2, A1, A2["USD"](2)));
env(pay(A3, A1, A3["USD"](2)));
env(offer(A1, XRP(11), A1["USD"](1)));
env(offer(A2, XRP(10), A2["USD"](1)));
env(offer(A3, XRP(9), A3["USD"](1)));
env.close();
}
/* The sequence/ledger for A3 are as follows:
* seq ledger_index
* 3 ----> 3
* 1 ----> 3
* 2 ----> 4
* 2 ----> 4
* 2 ----> 5
* 3 ----> 5
* 4 ----> 6
* 5 ----> 6
* 6 ----> 7
* 7 ----> 7
* 8 ----> 8
* 9 ----> 8
* 10 ----> 9
* 11 ----> 9
*/
// page through the results in several ways.
{
// limit = 2, 3 batches giving the first 6 txs
auto [res, status] = next(grpcPort, env, A3.human(), 2, 5, 2, true);
auto txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
BEAST_EXPECT(checkTransaction(txs[1u], 3, 3));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 2, 5, 2, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 4));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 2, 5, 2, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 5));
BEAST_EXPECT(checkTransaction(txs[1u], 5, 5));
BEAST_EXPECT(!res.has_marker());
return;
}
{
// limit 1, 3 requests giving the first 3 txs
auto [res, status] = next(grpcPort, env, A3.human(), 3, 9, 1, true);
auto txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 1, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 1, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
if (!BEAST_EXPECT(res.has_marker()))
return;
// continue with limit 3, to end of all txs
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 3, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 5));
BEAST_EXPECT(checkTransaction(txs[2u], 5, 5));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 3, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 6, 6));
BEAST_EXPECT(checkTransaction(txs[1u], 7, 6));
BEAST_EXPECT(checkTransaction(txs[2u], 8, 7));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 3, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 9, 7));
BEAST_EXPECT(checkTransaction(txs[1u], 10, 8));
BEAST_EXPECT(checkTransaction(txs[2u], 11, 8));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort, env, A3.human(), 3, 9, 3, true, res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 12, 9));
BEAST_EXPECT(checkTransaction(txs[1u], 13, 9));
BEAST_EXPECT(!res.has_marker());
}
{
// limit 2, descending, 2 batches giving last 4 txs
auto [res, status] =
next(grpcPort, env, A3.human(), 3, 9, 2, false);
auto txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 13, 9));
BEAST_EXPECT(checkTransaction(txs[1u], 12, 9));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort,
env,
A3.human(),
3,
9,
2,
false,
res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 2))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 11, 8));
BEAST_EXPECT(checkTransaction(txs[1u], 10, 8));
if (!BEAST_EXPECT(res.has_marker()))
return;
// continue with limit 3 until all txs have been seen
std::tie(res, status) = next(
grpcPort,
env,
A3.human(),
3,
9,
3,
false,
res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 9, 7));
BEAST_EXPECT(checkTransaction(txs[1u], 8, 7));
BEAST_EXPECT(checkTransaction(txs[2u], 7, 6));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort,
env,
A3.human(),
3,
9,
3,
false,
res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 6, 6));
BEAST_EXPECT(checkTransaction(txs[1u], 5, 5));
BEAST_EXPECT(checkTransaction(txs[2u], 4, 5));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort,
env,
A3.human(),
3,
9,
3,
false,
res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 3))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[1u], 4, 4));
BEAST_EXPECT(checkTransaction(txs[2u], 3, 3));
if (!BEAST_EXPECT(res.has_marker()))
return;
std::tie(res, status) = next(
grpcPort,
env,
A3.human(),
3,
9,
3,
false,
res.mutable_marker());
txs = res.transactions();
if (!BEAST_EXPECT(txs.size() == 1))
return;
BEAST_EXPECT(checkTransaction(txs[0u], 3, 3));
BEAST_EXPECT(!res.has_marker());
}
}
public:
void
run() override
{
testAccountTxPaging();
testAccountTxPagingGrpc();
testAccountTxParametersGrpc();
testAccountTxContentsGrpc();
}
};
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, ripple);
} // namespace ripple
| 43.403315 | 80 | 0.409761 | sneh19337 |
332f0f13acb05d384ddc9992f6123529f29d7dcc | 1,791 | hpp | C++ | plugins/account_plugin/include/eosio/account_plugin/account_manager.hpp | jayden211/eos3 | 974e98739f3ce5cbcf8c8bc4a241a9e29c7e1d22 | [
"MIT"
] | null | null | null | plugins/account_plugin/include/eosio/account_plugin/account_manager.hpp | jayden211/eos3 | 974e98739f3ce5cbcf8c8bc4a241a9e29c7e1d22 | [
"MIT"
] | null | null | null | plugins/account_plugin/include/eosio/account_plugin/account_manager.hpp | jayden211/eos3 | 974e98739f3ce5cbcf8c8bc4a241a9e29c7e1d22 | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/transaction.hpp>
#include "model.hpp"
namespace fc { class variant; }
namespace eosio {
namespace account {
/// Provides associate of wallet name to wallet and manages the interaction with each wallet.
///
/// The name of the wallet is also used as part of the file name by wallet_api. See account_manager::create.
/// No const methods because timeout may cause lock_all() to be called.
class account_manager {
public:
account_manager() = default;
account_manager(const account_manager&) = delete;
account_manager(account_manager&&) = delete;
account_manager& operator=(const account_manager&) = delete;
account_manager& operator=(account_manager&&) = delete;
~account_manager() = default;
/// Create a new wallet.
/// A new wallet is created in file dir/{name}.wallet see set_dir.
/// The new wallet is unlocked after creation.
/// @param name of the wallet and name of the file without ext .wallet.
/// @return Plaintext password that is needed to unlock wallet. Caller is responsible for saving password otherwise
/// they will not be able to unlock their wallet. Note user supplied passwords are not supported.
/// @throws fc::exception if wallet with name already exists (or filename already exists)
fc::variant create(const eosio::account::account_create& args);
fc::mutable_variant_object createkey(const int& num);
// get account balance
fc::variant get_account_balance(const currency_balance& args);
// transfer
fc::variant transfer(const transfer_info& args);
private:
std::string eosio_key = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3";
};
} // namespace wallet
} // namespace eosio
| 30.355932 | 118 | 0.726968 | jayden211 |
332fabc654220811b7f2a3fa3e8e4b966530a521 | 2,602 | cpp | C++ | test/protobuf-pbop-plugin-unittest/TestBufferedConnection.cpp | themucha/protobuf-pbop-plugin | 824b9db7d64d699f9c00fc79ea50b460345994d8 | [
"MIT"
] | 4 | 2020-09-10T08:38:40.000Z | 2022-02-28T23:39:32.000Z | test/protobuf-pbop-plugin-unittest/TestBufferedConnection.cpp | themucha/protobuf-pbop-plugin | 824b9db7d64d699f9c00fc79ea50b460345994d8 | [
"MIT"
] | 15 | 2020-06-24T20:31:56.000Z | 2020-07-25T16:30:56.000Z | test/protobuf-pbop-plugin-unittest/TestBufferedConnection.cpp | end2endzone/protobuf-pipe-plugin | 40dd2ba245fe0713f6b1f68622bc765711d3c7b8 | [
"MIT-0",
"MIT"
] | 3 | 2021-07-16T21:22:38.000Z | 2022-02-28T23:39:34.000Z | /**********************************************************************************
* MIT License
*
* Copyright (c) 2018 Antoine Beauchamp
*
* 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 "TestBufferedConnection.h"
#include "pbop/BufferedConnection.h"
using namespace pbop;
void TestBufferedConnection::SetUp()
{
}
void TestBufferedConnection::TearDown()
{
}
TEST_F(TestBufferedConnection, testReadWrite)
{
std::string bufferA;
std::string bufferB;
BufferedConnection conn1(&bufferA, &bufferB);
BufferedConnection conn2(&bufferB, &bufferA);
Status s;
//write data to connection 1
const std::string write_data = "hello!";
s = conn1.Write(write_data);
ASSERT_TRUE( s.Success() ) << s.GetDescription();
//read data from connection 2
std::string read_data;
s = conn2.Read(read_data);
ASSERT_TRUE( s.Success() ) << s.GetDescription();
//expect readed and written data to be identical.
ASSERT_EQ(write_data, read_data);
}
TEST_F(TestBufferedConnection, testInvalidWrite)
{
std::string buffer;
BufferedConnection conn(&buffer, NULL);
//write data to connection
const std::string data = "hello!";
Status s = conn.Write(data);
ASSERT_FALSE( s.Success() ) << s.GetDescription();
}
TEST_F(TestBufferedConnection, testInvalidRead)
{
std::string buffer;
BufferedConnection conn(NULL, &buffer);
//read data to connection
std::string data;
Status s = conn.Read(data);
ASSERT_FALSE( s.Success() ) << s.GetDescription();
}
| 30.611765 | 83 | 0.690623 | themucha |
332fd4ce8d394e1084a66c35b4bbbbef0b6c7d66 | 12,318 | cpp | C++ | amt/Selection.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 8 | 2016-08-29T13:34:18.000Z | 2020-12-04T15:20:36.000Z | amt/Selection.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 221 | 2016-06-20T19:51:48.000Z | 2022-03-29T20:46:46.000Z | amt/Selection.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 13 | 2016-06-24T15:59:31.000Z | 2022-01-01T11:48:20.000Z | #include "StdAfx.h"
#include "Selection.h"
// ===========================================================================
class NoCaseCompare
{
public:
bool operator ()(const std::_tstring & l, const std::_tstring & r) const
{
return _tcsicmp(l.c_str(), r.c_str()) < 0;
}
};
// ===========================================================================
CSelection::CSelection(WTL::CTreeViewCtrlEx * tree)
{
m_tree = tree;
}
CSelection::~CSelection(void)
{
}
void CSelection::Clear()
{
CWaitCursor wait;
m_attrs.clear();
WTL::CTreeItem item = m_tree->GetRootItem();
while (item)
{
InitState((CTreeNode*)item.GetData(), THREESTATE_UNCHECKED);
item = item.GetNextVisible();
}
}
THREESTATE CSelection::CalcWorkspaceState(IWorkspace * workspace) const
{
bool unchecked = false;
bool checked = false;
IWorkspaceVector workspaces;
workspace->GetChildWorkspaces(workspaces);
for(IWorkspaceVector::const_iterator itr = workspaces.begin(); itr != workspaces.end(); ++itr)
{
switch(CalcWorkspaceState(itr->get()))
{
case THREESTATE_CHECKED:
checked = true;
break;
case THREESTATE_UNCHECKED:
unchecked = true;
break;
case THREESTATE_PARTIALCHECKED:
return THREESTATE_PARTIALCHECKED;
}
}
IWorkspaceItemVector workspaceItems;
workspace->GetWindows(workspaceItems);
for(IWorkspaceItemVector::const_iterator itr = workspaceItems.begin();itr != workspaceItems.end(); ++itr)
{
if (itr->get()->GetType() == WORKSPACE_ITEM_ATTRIBUTE)
{
AttributeStateMap::const_iterator found = m_attrs.find(itr->get()->GetAttribute());
if (found != m_attrs.end() && found->second.m_checked == true)
checked = true;
else
unchecked = true;
}
if (checked && unchecked)
return THREESTATE_PARTIALCHECKED;
}
if (checked)
return THREESTATE_CHECKED;
return THREESTATE_UNCHECKED;
}
THREESTATE CSelection::CalcModuleState(IModule * module) const
{
bool unchecked = false;
bool checked = false;
IModuleVector modules;
module->GetModules(modules);
for(IModuleVector::iterator itr = modules.begin(); itr != modules.end(); ++itr)
{
switch (CalcModuleState(itr->get()))
{
case THREESTATE_CHECKED:
checked = true;
break;
case THREESTATE_UNCHECKED:
unchecked = true;
break;
default:
return THREESTATE_PARTIALCHECKED;
}
if (checked && unchecked)
return THREESTATE_PARTIALCHECKED;
}
unsigned int attrCount = 0;
for(AttributeStateMap::const_iterator itr = m_attrs.begin(); itr != m_attrs.end(); ++itr)
{
if (boost::algorithm::iequals(module->GetQualifiedLabel(), itr->first->GetModule()->GetQualifiedLabel()))
{
attrCount++;
if (itr->second.m_checked == true)
checked = true;
else
unchecked = true;
}
if (checked && unchecked)
return THREESTATE_PARTIALCHECKED;
}
if (checked)
{
IAttributeVector attributes;
return module->GetAttributes(attributes, true) - attrCount == 0 ? THREESTATE_CHECKED : THREESTATE_PARTIALCHECKED; //(Module could contain more attrs than the ones we know about in m_attrs)
}
return THREESTATE_UNCHECKED;
}
THREESTATE CSelection::CalcAttributeState(IAttribute * attribute) const
{
if (!attribute->Exists())
return THREESTATE_BLANK;
AttributeStateMap::const_iterator itr = m_attrs.find(attribute);
if (itr != m_attrs.end())
{
return itr->second.m_checked ? THREESTATE_CHECKED : THREESTATE_UNCHECKED;
}
return THREESTATE_UNCHECKED;
}
THREESTATE CSelection::CalcAttributeHistoryState(IAttribute * attribute, int version) const
{
AttributeStateMap::const_iterator itr = m_attrs.find(attribute);
if (itr != m_attrs.end() && itr->second.m_version == version && itr->second.m_checked)
{
return THREESTATE_RADIO_CHECKED;
}
return THREESTATE_RADIO_UNCHECKED;
}
void CSelection::InitState(CTreeNode * item, THREESTATE knownState)
{
if (CComQIPtr<CWorkspacePairNode> node = item)
{
SetCheckThreeState(*item, knownState != THREESTATE_UNKNOWN ? knownState : CalcWorkspaceState(node->m_lhs));
}
else if (CComQIPtr<CModulePairNode> node = item)
{
SetCheckThreeState(*item, knownState != THREESTATE_UNKNOWN ? knownState : CalcModuleState(node->m_lhs));
}
else if (CComQIPtr<CAttributePairNode> node = item)
{
THREESTATE state = knownState != THREESTATE_UNKNOWN ? knownState : CalcAttributeState(node->m_lhs);
SetState(node->m_lhs, state == THREESTATE_CHECKED);
SetCheckThreeState(*item, state);
}
else if (CComQIPtr<CAttributeHistoryPairNode> node = item)
{
CComQIPtr<CAttributePairNode> parent = item->GetParentNode();
IAttribute * attr = parent->m_lhs;
if (m_attrs[attr].m_version == 0 && *parent->GetChildNode() == *item && !attr->IsSandboxed() && m_attrs[attr].m_checked)
SetCheckThreeState(*item, THREESTATE_RADIO_CHECKED);
else
SetCheckThreeState(*item, CalcAttributeHistoryState(parent->m_lhs, node->m_lhs->GetVersion()));
}
}
void CSelection::SetState(IAttribute * attribute, bool checked)
{
ATLASSERT(attribute);
if (!attribute->Exists())
return;
AttributeStateMap::const_iterator itr = m_attrs.find(attribute);
if (itr == m_attrs.end()) //Does not exist...
{
m_attrs[attribute].m_version = 0;
m_attrs[attribute].m_history = NULL;
m_attrs[attribute].m_checked = false;
}
if (m_attrs[attribute].m_checked != checked)
{
m_attrs[attribute].m_version = 0;
m_attrs[attribute].m_history = NULL;
m_attrs[attribute].m_checked = checked;
}
}
void CSelection::ItemClicked(CTreeNode * item, IAttributeVector * attrs, IAttributeVector * dependants)
{
THREESTATE curState = GetCheckThreeState(*item);
THREESTATE newState = curState == THREESTATE_BUSY_CHECKED ? THREESTATE_UNCHECKED : THREESTATE_CHECKED;
if (CComQIPtr<CWorkspacePairNode> node = item)
{
IWorkspace * ws = node->m_lhs;
SetSelection(item, *attrs, newState == THREESTATE_CHECKED);
}
else if (CComQIPtr<CModulePairNode> node = item)
{
IModule * mod = node->m_lhs;
SetSelection(item, *attrs, newState == THREESTATE_CHECKED);
}
else if (CComQIPtr<CAttributePairNode> node = item)
{
attrs->push_back(node->m_lhs.p);
SetSelection(item, *attrs, newState == THREESTATE_CHECKED);
}
else if (CComQIPtr<CAttributeHistoryPairNode> node = item)
{
CComQIPtr<CAttributePairNode> parent = node->GetParentNode();
CComQIPtr<CModulePairNode> gparent = parent->GetParentNode();
IAttribute * attr = parent->m_lhs;
m_attrs[attr].m_version = node->m_lhs->GetVersion();
m_attrs[attr].m_history = node->m_lhs;
m_attrs[attr].m_checked = true;
// TODO: GJS - This doesn't refresh to the top of nested modules...
Refresh(parent);
}
// Dependents could be anywhere...
if (!dependants->empty())
SetSelection(*dependants, newState == THREESTATE_CHECKED);
}
void CSelection::Refresh(CAttributePairNode * node)
{
SetCheckThreeState(*node, CalcAttributeState(node->m_lhs));
// Recalc Parents.
if (CComQIPtr<CWorkspacePairNode> parent = node->GetParentNode())
SetCheckThreeState(*parent, CalcWorkspaceState(parent->m_lhs));
else if (CComQIPtr<CModulePairNode> parent = node->GetParentNode())
SetCheckThreeState(*parent, CalcModuleState(parent->m_lhs));
// Recalc Children.
for(CComQIPtr<CAttributeHistoryPairNode> child = node->GetChildNode(); child; child = child->GetNextSiblingItem())
{
InitState(child);
}
}
bool CSelection::HasSelection() const
{
for(AttributeStateMap::const_iterator itr = m_attrs.begin(); itr != m_attrs.end(); ++itr)
{
if (itr->second.m_checked)
return true;
}
return false;
}
//class IAttributeSelectionCompare
//{
//public:
// bool operator ()(IAttributeSelection & l, IAttributeSelection & r)
// {
// CString lhsModule = l.m_moduleLabel.c_str();
// int compare = lhsModule.CompareNoCase(r.m_moduleLabel.c_str());
// if (compare == 0)
// {
// CString lhs = l.m_attrLabel.c_str();
// return lhs.CompareNoCase(r.m_attrLabel.c_str()) > 0 ? false : true;
// }
// else
// return compare > 0 ? false : true;
// }
//};
int CSelection::GetSelection(IRepository * rep, IWorkspaceVector & workspaces, IAttributeHistoryVector & attrs) const
{
WTL::CTreeItem item = m_tree->GetRootItem();
while(item)
{
CComPtr<CTreeNode> node = (CTreeNode *)item.GetData();
if (CComQIPtr<CWorkspacePairNode> ws_node = node)
{
switch (GetCheckThreeState(item))
{
case THREESTATE_CHECKED:
case THREESTATE_PARTIALCHECKED:
workspaces.push_back(ws_node->m_lhs.p);
break;
}
}
item = item.GetNextVisible();
}
for(AttributeStateMap::const_iterator itr = m_attrs.begin(); itr != m_attrs.end(); ++itr)
{
if (itr->second.m_checked)
{
if (itr->second.m_version == 0)
attrs.push_back(itr->first->GetAsHistory());
else
attrs.push_back(itr->second.m_history.p);
}
}
IAttributeHistoryCompare compare;
std::sort(attrs.begin(), attrs.end(), compare);
return attrs.size();
}
void CSelection::SetSelection(IAttributeVector & attrs, bool checked)
{
if (attrs.empty())
return;
CWaitCursor wait;
for(IAttributeVector::const_iterator itr = attrs.begin(); itr != attrs.end(); ++itr)
{
SetState(*itr, checked);
}
WTL::CTreeItem item = m_tree->GetRootItem();
while(item)
{
InitState((CTreeNode *)item.GetData());
item = item.GetNextVisible();
}
}
void RecursiveRefreshChildren(CSelection * self, WTL::CTreeItem * _item, THREESTATE knownState)
{
WTL::CTreeItem childItem = _item->GetChild();
while(childItem)
{
self->InitState((CTreeNode *)childItem.GetData(), knownState);
RecursiveRefreshChildren(self, &childItem, knownState);
childItem = childItem.GetNextSibling();
}
}
void CSelection::SetSelection(CTreeNode * _item, IAttributeVector & attrs, bool checked)
{
for(IAttributeVector::const_iterator itr = attrs.begin(); itr != attrs.end(); ++itr)
{
SetState(*itr, checked); //GJS this does not work for dependent attrs!!!!
}
SetCheckThreeState(*_item, checked ? THREESTATE_CHECKED : THREESTATE_UNCHECKED);
// Refresh Ancestors
WTL::CTreeItem item = _item->GetParent();
while(item)
{
InitState((CTreeNode *)item.GetData());
item = item.GetParent();
}
// Refresh Children
if (_item->IsExpanded())
RecursiveRefreshChildren(this, _item, checked ? THREESTATE_CHECKED : THREESTATE_UNCHECKED);
SetSelection(attrs, checked);
}
int CSelection::GetSelection(std::_tstring & attrs) const
{
for(AttributeStateMap::const_iterator itr = m_attrs.begin(); itr != m_attrs.end(); ++itr)
{
if (itr->second.m_checked)
{
if (attrs.length())
attrs += _T("\r\n");
attrs += itr->first->GetQualifiedLabel();
}
}
return attrs.size();
}
THREESTATE CSelection::GetCheckThreeState(HTREEITEM hItem) const
{
ATLASSERT(m_tree && m_tree->IsWindow());
UINT uRet = m_tree->GetItemState(hItem, TVIS_STATEIMAGEMASK);
return (THREESTATE)((uRet >> 12) - 1);
}
BOOL CSelection::SetCheckThreeState(HTREEITEM hItem, THREESTATE state)
{
ATLASSERT(m_tree && m_tree->IsWindow());
int nCheck = (int)state;
ATLASSERT(nCheck > THREESTATE_UNKNOWN && nCheck < THREESTATE_LAST);
return m_tree->SetItemState(hItem, INDEXTOSTATEIMAGEMASK(nCheck+1), TVIS_STATEIMAGEMASK);
}
| 31.911917 | 196 | 0.632408 | dehilsterlexis |
332feca63b89116619245c718a218cf790008234 | 3,347 | hpp | C++ | includes/utils/opengl/Shader.hpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 6 | 2020-03-13T16:45:13.000Z | 2022-03-30T18:20:48.000Z | includes/utils/opengl/Shader.hpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 191 | 2020-03-02T14:47:19.000Z | 2020-06-03T08:13:00.000Z | includes/utils/opengl/Shader.hpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | null | null | null | #ifndef SHADER_HPP_
#define SHADER_HPP_
#include <string>
#include <fstream>
#include <sstream>
#include "includesOpengl.hpp"
/**
* @brief Shader class used to manage shader compilation
*
* It also adds some tools to set uniform and activate shader easier
* Warning! before instantiating a Shader object you need to create the opengl contex with glfwCreateWindow
*/
class Shader {
public:
Shader(std::string const vsPath, std::string const fsPath, std::string const gsPath = "");
Shader(Shader const &src);
virtual ~Shader();
Shader &operator=(Shader const &rhs);
void use();
void unuse();
void setBool(const std::string &name, bool value) const;
void setInt(const std::string &name, int value) const;
void setFloat(const std::string &name, float value) const;
void setDouble(const std::string &name, double value) const;
void setVec2(const std::string &name, float x, float y) const;
void setVec2(const std::string &name, const glm::vec2 &vec) const;
void setVec2Double(const std::string &name, double x, double y) const;
void setVec2Double(const std::string &name, const glm::tvec2<double> &vec) const;
void setVec3(const std::string &name, float x, float y, float z) const;
void setVec3(const std::string &name, const glm::vec3 &vec) const;
void setVec3Double(const std::string &name, double x, double y, double z) const;
void setVec3Double(const std::string &name, const glm::tvec3<double> &vec) const;
void setVec4(const std::string &name, float x, float y, float z, float w) const;
void setVec4(const std::string &name, const glm::vec4 &vec) const;
void setVec4Double(const std::string &name, double x, double y, double z, double w) const;
void setVec4Double(const std::string &name, const glm::tvec4<double> &vec) const;
void setMat2(const std::string &name, const glm::mat2 &mat) const;
void setMat2Double(const std::string &name, const glm::dmat2 &mat) const;
void setMat3(const std::string &name, const glm::mat3 &mat) const;
void setMat3Double(const std::string &name, const glm::dmat3 &mat) const;
void setMat4(const std::string &name, const glm::mat4 &mat) const;
void setMat4Double(const std::string &name, const glm::dmat4 &mat) const;
/**
* @brief Shader exception
*/
class ShaderError : public std::exception {
public:
/**
* @brief Function auto called on errors
*
* @return const char* Error message
*/
virtual const char* what() const throw() = 0;
};
/**
* @brief Shader compilation exception
*/
class ShaderCompileException : public ShaderError {
public:
/**
* @brief Function auto called on errors
*
* @return const char* Error message
*/
virtual const char* what() const throw() {
return ("Shader failed to compile!");
}
};
/**
* @brief Shader linking exception
*/
class ShaderLinkingException : public ShaderError {
public:
/**
* @brief Function auto called on errors
*
* @return const char* Error message
*/
virtual const char* what() const throw() {
return ("Shader program failed to link!");
}
};
uint32_t id; /**< shader ID */
private:
void checkCompileErrors(uint32_t shader, std::string type);
std::string _vsPath;
std::string _gsPath;
std::string _fsPath;
};
#endif // SHADER_HPP_
| 31.87619 | 107 | 0.683896 | tnicolas42 |
3331757475cabab8b155d46b723b7294567871bc | 1,570 | hpp | C++ | Source/AliveLibAE/FootSwitch.hpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | Source/AliveLibAE/FootSwitch.hpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | Source/AliveLibAE/FootSwitch.hpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | #pragma once
#include "BaseAnimatedWithPhysicsGameObject.hpp"
#include "Path.hpp"
#include "FunctionFwd.hpp"
enum class SwitchOp : s16;
enum class FootSwitchTriggerBy : s16
{
eOnlyAbe_0 = 0,
eAnyone_1 = 1,
};
struct Path_FootSwitch final : public Path_TLV
{
s16 field_10_id;
Scale_short field_12_scale;
SwitchOp field_14_action;
FootSwitchTriggerBy field_16_trigger_by;
};
ALIVE_ASSERT_SIZEOF_ALWAYS(Path_FootSwitch, 0x18);
struct FootSwitch_Data final
{
s32 field_0_frameTableOffset;
s32 field_4_frameTableOffset;
s16 field_8_maxH;
s16 field_A_frameTableOffset;
};
ALIVE_ASSERT_SIZEOF_ALWAYS(FootSwitch_Data, 0xC);
class FootSwitch final : public ::BaseAnimatedWithPhysicsGameObject
{
public:
EXPORT FootSwitch* ctor_4DE090(Path_FootSwitch* pTlv, s32 tlvInfo);
virtual BaseGameObject* VDestructor(s32 flags) override;
virtual void VUpdate() override;
virtual void VScreenChanged() override;
private:
EXPORT FootSwitch* vdtor_4DE240(s32 flags);
EXPORT void dtor_4DE670();
EXPORT void vScreenChanged_4DE650();
EXPORT void vUpdate_4DE270();
EXPORT BaseAliveGameObject* WhoIsStoodOnMe_4DE700();
private:
s32 field_F4_tlvInfo;
enum class States : s16
{
eWaitForStepOnMe_0 = 0,
eWaitForGetOffMe_1 = 1,
};
States field_F8_state;
s16 field_FA_id;
SwitchOp field_FC_action;
FootSwitchTriggerBy field_FE_trigger_by;
s32 field_100_obj_id;
s16 field_104_bUnknown;
s16 field_106_bFindStander;
};
ALIVE_ASSERT_SIZEOF(FootSwitch, 0x108);
| 23.787879 | 71 | 0.751592 | Leonard2 |
3332cd4f747431afa12ee581f73f6c5d4515a574 | 18,366 | cc | C++ | src/tint/reader/spirv/parser_type.cc | encounter/dawn-cmake | 64a23ce0ede5f232cc209b69d64164ede6810b65 | [
"Apache-2.0"
] | null | null | null | src/tint/reader/spirv/parser_type.cc | encounter/dawn-cmake | 64a23ce0ede5f232cc209b69d64164ede6810b65 | [
"Apache-2.0"
] | null | null | null | src/tint/reader/spirv/parser_type.cc | encounter/dawn-cmake | 64a23ce0ede5f232cc209b69d64164ede6810b65 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or stateied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/tint/reader/spirv/parser_type.h"
#include <string>
#include <unordered_map>
#include <utility>
#include "src/tint/program_builder.h"
#include "src/tint/utils/hash.h"
#include "src/tint/utils/map.h"
#include "src/tint/utils/unique_allocator.h"
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Type);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Void);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Bool);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::U32);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::F32);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::I32);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Pointer);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Reference);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Vector);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Matrix);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Array);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Sampler);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Texture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::DepthTexture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::DepthMultisampledTexture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::MultisampledTexture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::SampledTexture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::StorageTexture);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Named);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Alias);
TINT_INSTANTIATE_TYPEINFO(tint::reader::spirv::Struct);
namespace tint::reader::spirv {
namespace {
struct PointerHasher {
size_t operator()(const Pointer& t) const { return utils::Hash(t.type, t.storage_class); }
};
struct ReferenceHasher {
size_t operator()(const Reference& t) const { return utils::Hash(t.type, t.storage_class); }
};
struct VectorHasher {
size_t operator()(const Vector& t) const { return utils::Hash(t.type, t.size); }
};
struct MatrixHasher {
size_t operator()(const Matrix& t) const { return utils::Hash(t.type, t.columns, t.rows); }
};
struct ArrayHasher {
size_t operator()(const Array& t) const { return utils::Hash(t.type, t.size, t.stride); }
};
struct AliasHasher {
size_t operator()(const Alias& t) const { return utils::Hash(t.name); }
};
struct StructHasher {
size_t operator()(const Struct& t) const { return utils::Hash(t.name); }
};
struct SamplerHasher {
size_t operator()(const Sampler& s) const { return utils::Hash(s.kind); }
};
struct DepthTextureHasher {
size_t operator()(const DepthTexture& t) const { return utils::Hash(t.dims); }
};
struct DepthMultisampledTextureHasher {
size_t operator()(const DepthMultisampledTexture& t) const { return utils::Hash(t.dims); }
};
struct MultisampledTextureHasher {
size_t operator()(const MultisampledTexture& t) const { return utils::Hash(t.dims, t.type); }
};
struct SampledTextureHasher {
size_t operator()(const SampledTexture& t) const { return utils::Hash(t.dims, t.type); }
};
struct StorageTextureHasher {
size_t operator()(const StorageTexture& t) const {
return utils::Hash(t.dims, t.format, t.access);
}
};
} // namespace
// Equality operators
//! @cond Doxygen_Suppress
static bool operator==(const Pointer& a, const Pointer& b) {
return a.type == b.type && a.storage_class == b.storage_class;
}
static bool operator==(const Reference& a, const Reference& b) {
return a.type == b.type && a.storage_class == b.storage_class;
}
static bool operator==(const Vector& a, const Vector& b) {
return a.type == b.type && a.size == b.size;
}
static bool operator==(const Matrix& a, const Matrix& b) {
return a.type == b.type && a.columns == b.columns && a.rows == b.rows;
}
static bool operator==(const Array& a, const Array& b) {
return a.type == b.type && a.size == b.size && a.stride == b.stride;
}
static bool operator==(const Named& a, const Named& b) {
return a.name == b.name;
}
static bool operator==(const Sampler& a, const Sampler& b) {
return a.kind == b.kind;
}
static bool operator==(const DepthTexture& a, const DepthTexture& b) {
return a.dims == b.dims;
}
static bool operator==(const DepthMultisampledTexture& a, const DepthMultisampledTexture& b) {
return a.dims == b.dims;
}
static bool operator==(const MultisampledTexture& a, const MultisampledTexture& b) {
return a.dims == b.dims && a.type == b.type;
}
static bool operator==(const SampledTexture& a, const SampledTexture& b) {
return a.dims == b.dims && a.type == b.type;
}
static bool operator==(const StorageTexture& a, const StorageTexture& b) {
return a.dims == b.dims && a.format == b.format;
}
//! @endcond
const ast::Type* Void::Build(ProgramBuilder& b) const {
return b.ty.void_();
}
const ast::Type* Bool::Build(ProgramBuilder& b) const {
return b.ty.bool_();
}
const ast::Type* U32::Build(ProgramBuilder& b) const {
return b.ty.u32();
}
const ast::Type* F32::Build(ProgramBuilder& b) const {
return b.ty.f32();
}
const ast::Type* I32::Build(ProgramBuilder& b) const {
return b.ty.i32();
}
Pointer::Pointer(const Type* t, ast::StorageClass s) : type(t), storage_class(s) {}
Pointer::Pointer(const Pointer&) = default;
const ast::Type* Pointer::Build(ProgramBuilder& b) const {
return b.ty.pointer(type->Build(b), storage_class);
}
Reference::Reference(const Type* t, ast::StorageClass s) : type(t), storage_class(s) {}
Reference::Reference(const Reference&) = default;
const ast::Type* Reference::Build(ProgramBuilder& b) const {
return type->Build(b);
}
Vector::Vector(const Type* t, uint32_t s) : type(t), size(s) {}
Vector::Vector(const Vector&) = default;
const ast::Type* Vector::Build(ProgramBuilder& b) const {
return b.ty.vec(type->Build(b), size);
}
Matrix::Matrix(const Type* t, uint32_t c, uint32_t r) : type(t), columns(c), rows(r) {}
Matrix::Matrix(const Matrix&) = default;
const ast::Type* Matrix::Build(ProgramBuilder& b) const {
return b.ty.mat(type->Build(b), columns, rows);
}
Array::Array(const Type* t, uint32_t sz, uint32_t st) : type(t), size(sz), stride(st) {}
Array::Array(const Array&) = default;
const ast::Type* Array::Build(ProgramBuilder& b) const {
if (size > 0) {
return b.ty.array(type->Build(b), u32(size), stride);
} else {
return b.ty.array(type->Build(b), nullptr, stride);
}
}
Sampler::Sampler(ast::SamplerKind k) : kind(k) {}
Sampler::Sampler(const Sampler&) = default;
const ast::Type* Sampler::Build(ProgramBuilder& b) const {
return b.ty.sampler(kind);
}
Texture::Texture(ast::TextureDimension d) : dims(d) {}
Texture::Texture(const Texture&) = default;
DepthTexture::DepthTexture(ast::TextureDimension d) : Base(d) {}
DepthTexture::DepthTexture(const DepthTexture&) = default;
const ast::Type* DepthTexture::Build(ProgramBuilder& b) const {
return b.ty.depth_texture(dims);
}
DepthMultisampledTexture::DepthMultisampledTexture(ast::TextureDimension d) : Base(d) {}
DepthMultisampledTexture::DepthMultisampledTexture(const DepthMultisampledTexture&) = default;
const ast::Type* DepthMultisampledTexture::Build(ProgramBuilder& b) const {
return b.ty.depth_multisampled_texture(dims);
}
MultisampledTexture::MultisampledTexture(ast::TextureDimension d, const Type* t)
: Base(d), type(t) {}
MultisampledTexture::MultisampledTexture(const MultisampledTexture&) = default;
const ast::Type* MultisampledTexture::Build(ProgramBuilder& b) const {
return b.ty.multisampled_texture(dims, type->Build(b));
}
SampledTexture::SampledTexture(ast::TextureDimension d, const Type* t) : Base(d), type(t) {}
SampledTexture::SampledTexture(const SampledTexture&) = default;
const ast::Type* SampledTexture::Build(ProgramBuilder& b) const {
return b.ty.sampled_texture(dims, type->Build(b));
}
StorageTexture::StorageTexture(ast::TextureDimension d, ast::TexelFormat f, ast::Access a)
: Base(d), format(f), access(a) {}
StorageTexture::StorageTexture(const StorageTexture&) = default;
const ast::Type* StorageTexture::Build(ProgramBuilder& b) const {
return b.ty.storage_texture(dims, format, access);
}
Named::Named(Symbol n) : name(n) {}
Named::Named(const Named&) = default;
Named::~Named() = default;
Alias::Alias(Symbol n, const Type* ty) : Base(n), type(ty) {}
Alias::Alias(const Alias&) = default;
const ast::Type* Alias::Build(ProgramBuilder& b) const {
return b.ty.type_name(name);
}
Struct::Struct(Symbol n, TypeList m) : Base(n), members(std::move(m)) {}
Struct::Struct(const Struct&) = default;
Struct::~Struct() = default;
const ast::Type* Struct::Build(ProgramBuilder& b) const {
return b.ty.type_name(name);
}
/// The PIMPL state of the Types object.
struct TypeManager::State {
/// The allocator of primitive types
utils::BlockAllocator<Type> allocator_;
/// The lazily-created Void type
spirv::Void const* void_ = nullptr;
/// The lazily-created Bool type
spirv::Bool const* bool_ = nullptr;
/// The lazily-created U32 type
spirv::U32 const* u32_ = nullptr;
/// The lazily-created F32 type
spirv::F32 const* f32_ = nullptr;
/// The lazily-created I32 type
spirv::I32 const* i32_ = nullptr;
/// Unique Pointer instances
utils::UniqueAllocator<spirv::Pointer, PointerHasher> pointers_;
/// Unique Reference instances
utils::UniqueAllocator<spirv::Reference, ReferenceHasher> references_;
/// Unique Vector instances
utils::UniqueAllocator<spirv::Vector, VectorHasher> vectors_;
/// Unique Matrix instances
utils::UniqueAllocator<spirv::Matrix, MatrixHasher> matrices_;
/// Unique Array instances
utils::UniqueAllocator<spirv::Array, ArrayHasher> arrays_;
/// Unique Alias instances
utils::UniqueAllocator<spirv::Alias, AliasHasher> aliases_;
/// Unique Struct instances
utils::UniqueAllocator<spirv::Struct, StructHasher> structs_;
/// Unique Sampler instances
utils::UniqueAllocator<spirv::Sampler, SamplerHasher> samplers_;
/// Unique DepthTexture instances
utils::UniqueAllocator<spirv::DepthTexture, DepthTextureHasher> depth_textures_;
/// Unique DepthMultisampledTexture instances
utils::UniqueAllocator<spirv::DepthMultisampledTexture, DepthMultisampledTextureHasher>
depth_multisampled_textures_;
/// Unique MultisampledTexture instances
utils::UniqueAllocator<spirv::MultisampledTexture, MultisampledTextureHasher>
multisampled_textures_;
/// Unique SampledTexture instances
utils::UniqueAllocator<spirv::SampledTexture, SampledTextureHasher> sampled_textures_;
/// Unique StorageTexture instances
utils::UniqueAllocator<spirv::StorageTexture, StorageTextureHasher> storage_textures_;
};
const Type* Type::UnwrapPtr() const {
const Type* type = this;
while (auto* ptr = type->As<Pointer>()) {
type = ptr->type;
}
return type;
}
const Type* Type::UnwrapRef() const {
const Type* type = this;
while (auto* ptr = type->As<Reference>()) {
type = ptr->type;
}
return type;
}
const Type* Type::UnwrapAlias() const {
const Type* type = this;
while (auto* alias = type->As<Alias>()) {
type = alias->type;
}
return type;
}
const Type* Type::UnwrapAll() const {
auto* type = this;
while (true) {
if (auto* alias = type->As<Alias>()) {
type = alias->type;
} else if (auto* ptr = type->As<Pointer>()) {
type = ptr->type;
} else {
break;
}
}
return type;
}
bool Type::IsFloatScalar() const {
return Is<F32>();
}
bool Type::IsFloatScalarOrVector() const {
return IsFloatScalar() || IsFloatVector();
}
bool Type::IsFloatVector() const {
return Is([](const Vector* v) { return v->type->IsFloatScalar(); });
}
bool Type::IsIntegerScalar() const {
return IsAnyOf<U32, I32>();
}
bool Type::IsIntegerScalarOrVector() const {
return IsUnsignedScalarOrVector() || IsSignedScalarOrVector();
}
bool Type::IsScalar() const {
return IsAnyOf<F32, U32, I32, Bool>();
}
bool Type::IsSignedIntegerVector() const {
return Is([](const Vector* v) { return v->type->Is<I32>(); });
}
bool Type::IsSignedScalarOrVector() const {
return Is<I32>() || IsSignedIntegerVector();
}
bool Type::IsUnsignedIntegerVector() const {
return Is([](const Vector* v) { return v->type->Is<U32>(); });
}
bool Type::IsUnsignedScalarOrVector() const {
return Is<U32>() || IsUnsignedIntegerVector();
}
TypeManager::TypeManager() {
state = std::make_unique<State>();
}
TypeManager::~TypeManager() = default;
const spirv::Void* TypeManager::Void() {
if (!state->void_) {
state->void_ = state->allocator_.Create<spirv::Void>();
}
return state->void_;
}
const spirv::Bool* TypeManager::Bool() {
if (!state->bool_) {
state->bool_ = state->allocator_.Create<spirv::Bool>();
}
return state->bool_;
}
const spirv::U32* TypeManager::U32() {
if (!state->u32_) {
state->u32_ = state->allocator_.Create<spirv::U32>();
}
return state->u32_;
}
const spirv::F32* TypeManager::F32() {
if (!state->f32_) {
state->f32_ = state->allocator_.Create<spirv::F32>();
}
return state->f32_;
}
const spirv::I32* TypeManager::I32() {
if (!state->i32_) {
state->i32_ = state->allocator_.Create<spirv::I32>();
}
return state->i32_;
}
const spirv::Pointer* TypeManager::Pointer(const Type* el, ast::StorageClass sc) {
return state->pointers_.Get(el, sc);
}
const spirv::Reference* TypeManager::Reference(const Type* el, ast::StorageClass sc) {
return state->references_.Get(el, sc);
}
const spirv::Vector* TypeManager::Vector(const Type* el, uint32_t size) {
return state->vectors_.Get(el, size);
}
const spirv::Matrix* TypeManager::Matrix(const Type* el, uint32_t columns, uint32_t rows) {
return state->matrices_.Get(el, columns, rows);
}
const spirv::Array* TypeManager::Array(const Type* el, uint32_t size, uint32_t stride) {
return state->arrays_.Get(el, size, stride);
}
const spirv::Alias* TypeManager::Alias(Symbol name, const Type* ty) {
return state->aliases_.Get(name, ty);
}
const spirv::Struct* TypeManager::Struct(Symbol name, TypeList members) {
return state->structs_.Get(name, std::move(members));
}
const spirv::Sampler* TypeManager::Sampler(ast::SamplerKind kind) {
return state->samplers_.Get(kind);
}
const spirv::DepthTexture* TypeManager::DepthTexture(ast::TextureDimension dims) {
return state->depth_textures_.Get(dims);
}
const spirv::DepthMultisampledTexture* TypeManager::DepthMultisampledTexture(
ast::TextureDimension dims) {
return state->depth_multisampled_textures_.Get(dims);
}
const spirv::MultisampledTexture* TypeManager::MultisampledTexture(ast::TextureDimension dims,
const Type* ty) {
return state->multisampled_textures_.Get(dims, ty);
}
const spirv::SampledTexture* TypeManager::SampledTexture(ast::TextureDimension dims,
const Type* ty) {
return state->sampled_textures_.Get(dims, ty);
}
const spirv::StorageTexture* TypeManager::StorageTexture(ast::TextureDimension dims,
ast::TexelFormat fmt,
ast::Access access) {
return state->storage_textures_.Get(dims, fmt, access);
}
// Debug String() methods for Type classes. Only enabled in debug builds.
#ifndef NDEBUG
std::string Void::String() const {
return "void";
}
std::string Bool::String() const {
return "bool";
}
std::string U32::String() const {
return "u32";
}
std::string F32::String() const {
return "f32";
}
std::string I32::String() const {
return "i32";
}
std::string Pointer::String() const {
std::stringstream ss;
ss << "ptr<" << std::string(ast::ToString(storage_class)) << ", " << type->String() + ">";
return ss.str();
}
std::string Reference::String() const {
std::stringstream ss;
ss << "ref<" + std::string(ast::ToString(storage_class)) << ", " << type->String() << ">";
return ss.str();
}
std::string Vector::String() const {
std::stringstream ss;
ss << "vec" << size << "<" << type->String() << ">";
return ss.str();
}
std::string Matrix::String() const {
std::stringstream ss;
ss << "mat" << columns << "x" << rows << "<" << type->String() << ">";
return ss.str();
}
std::string Array::String() const {
std::stringstream ss;
ss << "array<" << type->String() << ", " << size << ", " << stride << ">";
return ss.str();
}
std::string Sampler::String() const {
switch (kind) {
case ast::SamplerKind::kSampler:
return "sampler";
case ast::SamplerKind::kComparisonSampler:
return "sampler_comparison";
}
return "<unknown sampler>";
}
std::string DepthTexture::String() const {
std::stringstream ss;
ss << "depth_" << dims;
return ss.str();
}
std::string DepthMultisampledTexture::String() const {
std::stringstream ss;
ss << "depth_multisampled_" << dims;
return ss.str();
}
std::string MultisampledTexture::String() const {
std::stringstream ss;
ss << "texture_multisampled_" << dims << "<" << type << ">";
return ss.str();
}
std::string SampledTexture::String() const {
std::stringstream ss;
ss << "texture_" << dims << "<" << type << ">";
return ss.str();
}
std::string StorageTexture::String() const {
std::stringstream ss;
ss << "texture_storage_" << dims << "<" << format << ", " << access << ">";
return ss.str();
}
std::string Named::String() const {
return name.to_str();
}
#endif // NDEBUG
} // namespace tint::reader::spirv
| 31.181664 | 97 | 0.67674 | encounter |
3334a81c2583860a639ea5e929b629572b6d3297 | 3,958 | cpp | C++ | sensing/preprocessor/pointcloud/pointcloud_preprocessor/src/outlier_filter/voxel_grid_outlier_filter_nodelet.cpp | kmiya/AutowareArchitectureProposal.iv | 386b52c9cc90f4535ad833014f2f9500f0e64ccf | [
"Apache-2.0"
] | null | null | null | sensing/preprocessor/pointcloud/pointcloud_preprocessor/src/outlier_filter/voxel_grid_outlier_filter_nodelet.cpp | kmiya/AutowareArchitectureProposal.iv | 386b52c9cc90f4535ad833014f2f9500f0e64ccf | [
"Apache-2.0"
] | null | null | null | sensing/preprocessor/pointcloud/pointcloud_preprocessor/src/outlier_filter/voxel_grid_outlier_filter_nodelet.cpp | kmiya/AutowareArchitectureProposal.iv | 386b52c9cc90f4535ad833014f2f9500f0e64ccf | [
"Apache-2.0"
] | 1 | 2021-07-20T09:38:30.000Z | 2021-07-20T09:38:30.000Z | // Copyright 2020 Tier IV, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "pointcloud_preprocessor/outlier_filter/voxel_grid_outlier_filter_nodelet.hpp"
#include "pcl/kdtree/kdtree_flann.h"
#include "pcl/search/kdtree.h"
#include "pcl/segmentation/segment_differences.h"
namespace pointcloud_preprocessor
{
VoxelGridOutlierFilterComponent::VoxelGridOutlierFilterComponent(
const rclcpp::NodeOptions & options)
: Filter("VoxelGridOutlierFilter", options)
{
// set initial parameters
{
voxel_size_x_ = static_cast<double>(declare_parameter("voxel_size_x", 0.3));
voxel_size_y_ = static_cast<double>(declare_parameter("voxel_size_y", 0.3));
voxel_size_z_ = static_cast<double>(declare_parameter("voxel_size_z", 0.1));
voxel_points_threshold_ = static_cast<int>(declare_parameter("voxel_points_threshold", 2));
}
using std::placeholders::_1;
set_param_res_ = this->add_on_set_parameters_callback(
std::bind(&VoxelGridOutlierFilterComponent::paramCallback, this, _1));
}
void VoxelGridOutlierFilterComponent::filter(
const PointCloud2ConstPtr & input, const IndicesPtr & indices, PointCloud2 & output)
{
boost::mutex::scoped_lock lock(mutex_);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_input(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_voxelized_input(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_output(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*input, *pcl_input);
pcl_voxelized_input->points.reserve(pcl_input->points.size());
voxel_filter.setInputCloud(pcl_input);
voxel_filter.setSaveLeafLayout(true);
voxel_filter.setLeafSize(voxel_size_x_, voxel_size_y_, voxel_size_z_);
voxel_filter.setMinimumPointsNumberPerVoxel(voxel_points_threshold_);
voxel_filter.filter(*pcl_voxelized_input);
pcl_output->points.reserve(pcl_input->points.size());
for (size_t i = 0; i < pcl_input->points.size(); ++i) {
const int index = voxel_filter.getCentroidIndexAt(
voxel_filter.getGridCoordinates(
pcl_input->points.at(i).x, pcl_input->points.at(i).y, pcl_input->points.at(i).z));
if (index != -1) { // not empty voxel
pcl_output->points.push_back(pcl_input->points.at(i));
}
}
pcl::toROSMsg(*pcl_output, output);
output.header = input->header;
}
rcl_interfaces::msg::SetParametersResult VoxelGridOutlierFilterComponent::paramCallback(
const std::vector<rclcpp::Parameter> & p)
{
boost::mutex::scoped_lock lock(mutex_);
if (get_param(p, "voxel_size_x", voxel_size_x_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_x_);
}
if (get_param(p, "voxel_size_y", voxel_size_y_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_y_);
}
if (get_param(p, "voxel_size_z", voxel_size_z_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_z_);
}
if (get_param(p, "voxel_points_threshold", voxel_points_threshold_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %d.", voxel_points_threshold_);
}
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
return result;
}
} // namespace pointcloud_preprocessor
#include "rclcpp_components/register_node_macro.hpp"
RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::VoxelGridOutlierFilterComponent)
| 40.387755 | 98 | 0.755937 | kmiya |
333598e821152bec2c7cb5871a80786fb60c2dd7 | 28,411 | cpp | C++ | tests/unit/test_timer.cpp | TanJay/openthread | ffd28ebd4d874fbc71f556ced86efc306e6a2d4b | [
"BSD-3-Clause"
] | null | null | null | tests/unit/test_timer.cpp | TanJay/openthread | ffd28ebd4d874fbc71f556ced86efc306e6a2d4b | [
"BSD-3-Clause"
] | null | null | null | tests/unit/test_timer.cpp | TanJay/openthread | ffd28ebd4d874fbc71f556ced86efc306e6a2d4b | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "test_platform.h"
#include "openthread-instance.h"
#include "common/debug.hpp"
#include "common/timer.hpp"
enum
{
kCallCountIndexAlarmStop = 0,
kCallCountIndexAlarmStart,
kCallCountIndexTimerHandler,
kCallCountIndexMax
};
uint32_t sNow;
uint32_t sPlatT0;
uint32_t sPlatDt;
bool sTimerOn;
uint32_t sCallCount[kCallCountIndexMax];
void testTimerAlarmStop(otInstance *)
{
sTimerOn = false;
sCallCount[kCallCountIndexAlarmStop]++;
}
void testTimerAlarmStartAt(otInstance *, uint32_t aT0, uint32_t aDt)
{
sTimerOn = true;
sCallCount[kCallCountIndexAlarmStart]++;
sPlatT0 = aT0;
sPlatDt = aDt;
}
uint32_t testTimerAlarmGetNow(void)
{
return sNow;
}
void InitTestTimer(void)
{
g_testPlatAlarmStop = testTimerAlarmStop;
g_testPlatAlarmStartAt = testTimerAlarmStartAt;
g_testPlatAlarmGetNow = testTimerAlarmGetNow;
}
void InitCounters(void)
{
memset(sCallCount, 0, sizeof(sCallCount));
}
/**
* `TestTimer` sub-classes `ot::TimerMilli` and provides a handler and a counter to keep track of number of times timer gets
* fired.
*/
class TestTimer: public ot::TimerMilli
{
public:
TestTimer(otInstance *aInstance):
ot::TimerMilli(aInstance, TestTimer::HandleTimerFired, NULL),
mFiredCounter(0)
{ }
static void HandleTimerFired(ot::Timer &aTimer) {
static_cast<TestTimer &>(aTimer).HandleTimerFired();
}
void HandleTimerFired(void) {
sCallCount[kCallCountIndexTimerHandler]++;
mFiredCounter++;
}
uint32_t GetFiredCounter(void) { return mFiredCounter; }
void ResetFiredCounter(void) { mFiredCounter = 0; }
private:
uint32_t mFiredCounter; //< Number of times timer has been fired so far
};
/**
* Test the TimerScheduler's behavior of one timer started and fired.
*/
int TestOneTimer(void)
{
const uint32_t kTimeT0 = 1000;
const uint32_t kTimerInterval = 10;
otInstance *instance = testInitInstance();
TestTimer timer(instance);
// Test one Timer basic operation.
InitTestTimer();
InitCounters();
printf("TestOneTimer() ");
sNow = kTimeT0;
timer.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n");
VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n");
sNow += kTimerInterval;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n");
// Test one Timer that spans the 32-bit wrap.
InitCounters();
sNow = 0 - (kTimerInterval - 2);
timer.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == 0 - (kTimerInterval - 2) && sPlatDt == 10, "TestOneTimer: Start params Failed.\n");
VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n");
sNow += kTimerInterval;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n");
// Test one Timer that is late by several msec
InitCounters();
sNow = kTimeT0;
timer.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n");
VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n");
sNow += kTimerInterval + 5;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n");
// Test one Timer that is early by several msec
InitCounters();
sNow = kTimeT0;
timer.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == 1000 && sPlatDt == 10, "TestOneTimer: Start params Failed.\n");
VerifyOrQuit(timer.IsRunning(), "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestOneTimer: Platform Timer State Failed.\n");
sNow += kTimerInterval - 2;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(timer.IsRunning() == true, "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == true, "TestOneTimer: Platform Timer State Failed.\n");
sNow += kTimerInterval;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestOneTimer: Handler CallCount Failed.\n");
VerifyOrQuit(timer.IsRunning() == false, "TestOneTimer: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestOneTimer: Platform Timer State Failed.\n");
printf(" --> PASSED\n");
testFreeInstance(instance);
return 0;
}
/**
* Test the TimerScheduler's behavior of two timers started and fired.
*/
int TestTwoTimers(void)
{
const uint32_t kTimeT0 = 1000;
const uint32_t kTimerInterval = 10;
otInstance *instance = testInitInstance();
TestTimer timer1(instance);
TestTimer timer2(instance);
InitTestTimer();
printf("TestTwoTimers() ");
// Test when second timer stars at the fire time of first timer (before alarm callback).
InitCounters();
sNow = kTimeT0;
timer1.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
sNow += kTimerInterval;
timer2.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(sPlatT0 == sNow && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n");
sNow += kTimerInterval;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n");
// Test when second timer starts at the fire time of first timer (before otPlatAlarmMilliFired()) and its fire time
// is before the first timer. Ensure that the second timer handler is invoked before the first one.
InitCounters();
timer1.ResetFiredCounter();
timer2.ResetFiredCounter();
sNow = kTimeT0;
timer1.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
sNow += kTimerInterval;
timer2.StartAt(kTimeT0, kTimerInterval - 2); // Timer 2 is even before timer 1
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(sPlatT0 == sNow && sPlatDt == 0, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n");
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n");
// Timer 1 fire callback is late by some ticks/ms, and second timer is scheduled (before call to otPlatAlarmMilliFired)
// with a maximum interval. This is to test (corner-case) scenario where the fire time of two timers spanning over
// the maximum interval.
InitCounters();
timer1.ResetFiredCounter();
timer2.ResetFiredCounter();
sNow = kTimeT0;
timer1.Start(kTimerInterval);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == kTimeT0 && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning(), "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
sNow += kTimerInterval + 5;
timer2.Start(ot::Timer::kMaxDt);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n");
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(sPlatT0 == sNow, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(sPlatDt == ot::Timer::kMaxDt, "TestTwoTimers: Start params Failed.\n");
VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n");
sNow += ot::Timer::kMaxDt;
otPlatAlarmMilliFired(instance);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n");
VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n");
VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n");
VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n");
printf(" --> PASSED\n");
testFreeInstance(instance);
return 0;
}
/**
* Test the TimerScheduler's behavior of ten timers started and fired.
*
* `aTimeShift` is added to the t0 and trigger times for all timers. It can be used to check the ten timer behavior
* at different start time (e.g., around a 32-bit wrap).
*/
static void TenTimers(uint32_t aTimeShift)
{
const uint32_t kNumTimers = 10;
const uint32_t kNumTriggers = 7;
const uint32_t kTimeT0[kNumTimers] =
{
1000,
1000,
1001,
1002,
1003,
1004,
1005,
1006,
1007,
1008
};
const uint32_t kTimerInterval[kNumTimers] =
{
20,
100,
(ot::Timer::kMaxDt - kTimeT0[2]),
100000,
1000000,
10,
ot::Timer::kMaxDt,
200,
200,
200
};
// Expected timer fire order
// timer # Trigger time
// 5 1014
// 0 1020
// 1 1100
// 7 1206
// 8 1207
// 9 1208
// 3 101002
// 4 1001003
// 2 kMaxDt
// 6 kMaxDt + 1005
const uint32_t kTriggerTimes[kNumTriggers] =
{
1014,
1020,
1100,
1207,
101004,
ot::Timer::kMaxDt,
ot::Timer::kMaxDt + kTimeT0[6]
};
// Expected timers fired by each kTriggerTimes[] value
// Trigger # Timers Fired
// 0 5
// 1 0
// 2 1
// 3 7, 8
// 4 9, 3
// 5 4, 2
// 6 6
const bool kTimerStateAfterTrigger [kNumTriggers][kNumTimers] =
{
{ true, true, true, true, true, false, true, true, true, true}, // 5
{ false, true, true, true, true, false, true, true, true, true}, // 0
{ false, false, true, true, true, false, true, true, true, true}, // 1
{ false, false, true, true, true, false, true, false, false, true}, // 7, 8
{ false, false, true, false, true, false, true, false, false, false}, // 9, 3
{ false, false, false, false, false, false, true, false, false, false}, // 4, 2
{ false, false, false, false, false, false, false, false, false, false} // 6
};
const bool kSchedulerStateAfterTrigger[kNumTriggers] =
{
true,
true,
true,
true,
true,
true,
false
};
const uint32_t kTimerHandlerCountAfterTrigger[kNumTriggers] =
{
1,
2,
3,
5,
7,
9,
10
};
const uint32_t kTimerStopCountAfterTrigger[kNumTriggers] =
{
0,
0,
0,
0,
0,
0,
1
};
const uint32_t kTimerStartCountAfterTrigger[kNumTriggers] =
{
3,
4,
5,
7,
9,
11,
11
};
otInstance *instance = testInitInstance();
TestTimer timer0(instance);
TestTimer timer1(instance);
TestTimer timer2(instance);
TestTimer timer3(instance);
TestTimer timer4(instance);
TestTimer timer5(instance);
TestTimer timer6(instance);
TestTimer timer7(instance);
TestTimer timer8(instance);
TestTimer timer9(instance);
TestTimer *timers[kNumTimers] =
{
&timer0,
&timer1,
&timer2,
&timer3,
&timer4,
&timer5,
&timer6,
&timer7,
&timer8,
&timer9
};
size_t i;
printf("TestTenTimer() with aTimeShift=%-10u ", aTimeShift);
// Start the Ten timers.
InitTestTimer();
InitCounters();
for (i = 0; i < kNumTimers ; i++)
{
sNow = kTimeT0[i] + aTimeShift;
timers[i]->Start(kTimerInterval[i]);
}
// given the order in which timers are started, the TimerScheduler should call otPlatAlarmMilliStartAt 2 times.
// one for timer[0] and one for timer[5] which will supercede timer[0].
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTenTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTenTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 0, "TestTenTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sPlatT0 == kTimeT0[5] + aTimeShift, "TestTenTimer: Start params Failed.\n");
VerifyOrQuit(sPlatDt == kTimerInterval[5], "TestTenTimer: Start params Failed.\n");
VerifyOrQuit(sTimerOn, "TestTenTimer: Platform Timer State Failed.\n");
for (i = 0 ; i < kNumTimers ; i++)
{
VerifyOrQuit(timers[i]->IsRunning(), "TestTenTimer: Timer running Failed.\n");
}
// Issue the triggers and test the State after each trigger.
for (size_t trigger = 0 ; trigger < kNumTriggers ; trigger++)
{
sNow = kTriggerTimes[trigger] + aTimeShift;
do
{
// By design, each call to otPlatAlarmMilliFired() can result in 0 or 1 calls to a timer handler.
// For some combinations of sNow and Timers queued, it is necessary to call otPlatAlarmMilliFired()
// multiple times in order to handle all the expired timers. It can be determined that another
// timer is ready to be triggered by examining the aDt arg passed into otPlatAlarmMilliStartAt(). If
// that value is 0, then otPlatAlarmMilliFired should be fired immediately. This loop calls otPlatAlarmMilliFired()
// the requisite number of times based on the aDt argument.
otPlatAlarmMilliFired(instance);
}
while (sPlatDt == 0);
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == kTimerStartCountAfterTrigger[trigger],
"TestTenTimer: Start CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == kTimerStopCountAfterTrigger[trigger],
"TestTenTimer: Stop CallCount Failed.\n");
VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == kTimerHandlerCountAfterTrigger[trigger],
"TestTenTimer: Handler CallCount Failed.\n");
VerifyOrQuit(sTimerOn == kSchedulerStateAfterTrigger[trigger],
"TestTenTimer: Platform Timer State Failed.\n");
for (i = 0 ; i < kNumTimers ; i++)
{
VerifyOrQuit(
timers[i]->IsRunning() == kTimerStateAfterTrigger[trigger][i],
"TestTenTimer: Timer running Failed.\n"
);
}
}
for (i = 0 ; i < kNumTimers ; i++)
{
VerifyOrQuit(timers[i]->GetFiredCounter() == 1, "TestTenTimer: Timer fired counter Failed.\n");
}
printf("--> PASSED\n");
testFreeInstance(instance);
}
int TestTenTimers(void)
{
// Time shift to change the start/fire time of ten timers.
const uint32_t kTimeShift[] =
{
0,
100000U,
0U - 1U,
0U - 1100U,
ot::Timer::kMaxDt,
ot::Timer::kMaxDt + 1020U,
};
size_t i;
for (i = 0; i < sizeof(kTimeShift) / sizeof(kTimeShift[0]); i++)
{
TenTimers(kTimeShift[i]);
}
return 0;
}
void RunTimerTests(void)
{
TestOneTimer();
TestTwoTimers();
TestTenTimers();
}
#ifdef ENABLE_TEST_MAIN
int main(void)
{
RunTimerTests();
printf("All tests passed\n");
return 0;
}
#endif
| 42.723308 | 127 | 0.639189 | TanJay |
333a7c80909dbe0c80e2f55ad224219311a575aa | 2,983 | cpp | C++ | lib/ai/strategy.cpp | TaimoorRana/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 3 | 2016-05-23T09:39:08.000Z | 2016-10-08T03:28:24.000Z | lib/ai/strategy.cpp | TaimoorRana/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 3 | 2017-09-11T00:51:55.000Z | 2017-09-11T00:52:05.000Z | lib/ai/strategy.cpp | Taimoorrana1/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 1 | 2017-02-12T19:35:39.000Z | 2017-02-12T19:35:39.000Z | #include "strategy.h"
#include "librisk.h"
Strategy::Strategy() {
this->driver = GameDriver::getInstance();
}
/**
* @brief A signal sent to the Strategy class from the game driver to indicate
* that a computer-controlled player should made their move.
*
* The AI strategy implementations override each of the fooPhase() methods
* which return the name(s) of the country or countries to act upon.
*
* Empty string indicates the AI wishes to make no move, or there are none
* possible.
*/
void Strategy::takeAction(Mode mode) {
RiskMap* map = this->driver->getRiskMap();
if (mode == REINFORCEMENT) {
std::string countryName = this->reinforcePhase();
if (countryName == "") {
return;
}
Country* country = map->getCountry(countryName);
Player* player = map->getPlayer(country->getPlayer());
this->driver->reinforceCountry(player, country, player->getReinforcements());
}
else if (mode == ATTACK) {
std::pair<std::string, std::string> countryNames = this->attackPhase();
if (countryNames.first == "" || countryNames.second == "") {
return;
}
driver->attackCountry(map->getCountry(countryNames.first), map->getCountry(countryNames.second));
}
else if (mode == FORTIFICATION) {
std::pair<std::string, std::string> countryNames = this->fortifyPhase();
if (countryNames.first == "" || countryNames.second == "") {
return;
}
// Given the two countries, fortify so that the armies are as equal as possible.
Country* origin = map->getCountry(countryNames.first);
Country* destination = map->getCountry(countryNames.second);
int splitDifference = std::abs(origin->getArmies() - destination->getArmies()) / 2;
this->driver->fortifyCountry(origin, destination, splitDifference);
}
}
/**
* @brief Reinforcement phase decision making. Places all reinforcements on the
* country with the fewest armies.
*/
std::string Strategy::reinforcePhase() {
RiskMap* map = this->driver->getRiskMap();
std::string playerName = this->driver->getCurrentPlayerName();
int minArmies = 10000;
Country* minArmiesCountry = nullptr;
// add the reinforcements to the player
int numCardsSelected = map->getPlayer(playerName)->getCards();
int armiesEarned = convertCardsToReinforcements(numCardsSelected);
if (armiesEarned > 0) {
this->driver->addCardsTradeReinforcements(armiesEarned);
this->driver->updatePlayerCards(-numCardsSelected);
}
// Reinforce the weakest country
for (const std::string countryName : map->getCountriesOwnedByPlayer(playerName)) {
Country* country = map->getCountry(countryName);
int armies = country->getArmies();
if (armies < minArmies) {
minArmies = armies;
minArmiesCountry = country;
}
}
if (minArmiesCountry == nullptr) {
return "";
}
return minArmiesCountry->getName();
}
/**
* @brief Fortification phase decision making
*/
std::pair<std::string, std::string> Strategy::fortifyPhase() {
// Not implemented in the current AI.
return std::pair<std::string, std::string>("", "");
}
| 32.78022 | 99 | 0.712035 | TaimoorRana |
333be30b4764b335302c25d2b6dc8ac79f8e55f5 | 1,137 | cpp | C++ | TwitchXX/PeriodType.cpp | burannah/TwitchXX | d1845c615d106bfb223e20cdab0c88923f2588ad | [
"BSD-3-Clause"
] | 8 | 2016-10-22T11:36:48.000Z | 2021-02-03T07:09:54.000Z | TwitchXX/PeriodType.cpp | burannah/TwitchXX | d1845c615d106bfb223e20cdab0c88923f2588ad | [
"BSD-3-Clause"
] | 3 | 2018-10-01T20:48:03.000Z | 2018-10-25T12:11:25.000Z | TwitchXX/PeriodType.cpp | burannah/TwitchXX | d1845c615d106bfb223e20cdab0c88923f2588ad | [
"BSD-3-Clause"
] | 3 | 2017-12-09T11:29:31.000Z | 2020-11-09T15:19:25.000Z | //
// Created by buran on 14/03/18.
//
#include <PeriodType.h>
#include <TwitchException.h>
std::string TwitchXX::PeriodType::toString(TwitchXX::PeriodType::Value v)
{
static const std::map<Value, std::string> strs{{Value::ALL, "all"}, {Value::DAY, "day"}, {Value::WEEK, "week"}, {Value::MONTH, "month"}};
try
{
return strs.at(v);
}
catch(const std::out_of_range& e)
{
throw TwitchException("Value type is not supported");
}
}
TwitchXX::PeriodType::Value TwitchXX::PeriodType::fromString(const std::string &s)
{
static const std::map<std::string,Value> strs{{"all", Value::ALL}, {"day", Value::DAY}, {"week", Value::WEEK}, {"month", Value::MONTH}};
try
{
return strs.at(s);
}
catch(const std::out_of_range& e)
{
throw TwitchException("Can not convert string to period type");
}
}
TwitchXX::PeriodType::Value TwitchXX::PeriodType::fromInt(int i)
{
if(static_cast<int>(Value::ALL) > i || static_cast<int>(Value::MONTH) < i)
{
throw TwitchException("Value is not within PeriodType range");
}
return static_cast<Value>(i);
}
| 27.071429 | 141 | 0.626209 | burannah |
333c389d97af347535bf2571053a19641ff8cb80 | 1,307 | cpp | C++ | libs/network/example/http/hello_world_client.cpp | antoinelefloch/cpp-netlib | 5eb9b5550a10d06f064ee9883c7d942d3426f31b | [
"BSL-1.0"
] | 1 | 2018-01-28T14:30:42.000Z | 2018-01-28T14:30:42.000Z | libs/network/example/http/hello_world_client.cpp | antoinelefloch/cpp-netlib | 5eb9b5550a10d06f064ee9883c7d942d3426f31b | [
"BSL-1.0"
] | 1 | 2018-08-10T04:47:12.000Z | 2018-08-10T13:54:57.000Z | libs/network/example/http/hello_world_client.cpp | antoinelefloch/cpp-netlib | 5eb9b5550a10d06f064ee9883c7d942d3426f31b | [
"BSL-1.0"
] | 5 | 2017-12-28T12:42:25.000Z | 2021-07-01T07:41:53.000Z | // Copyright (c) Glyn Matthews 2010.
// 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)
//[ hello_world_client_main
/*`
This is a part of the 'Hello World' example. We create a client
object and make a single HTTP request. If we use make this request
to the `hello_world_server`, then the output is simply "Hello,
World!".
*/
#include <boost/network/protocol/http/client.hpp>
#include <iostream>
namespace http = boost::network::http;
int
main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " url" << std::endl;
return 1;
}
try {
/*<< Creates the client. >>*/
http::client client;
/*<< Creates a request using a URI supplied on the command
line. >>*/
http::client::request request(argv[1]);
/*<< Gets a response from the HTTP server. >>*/
http::client::response response = client.get(request);
/*<< Prints the response body to the console. >>*/
std::cout << body(response) << std::endl;
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
//]
| 27.229167 | 69 | 0.58378 | antoinelefloch |
33402a2eec18bba9e74289088e47168089f2333e | 464 | cpp | C++ | libfree/inet_pton_ipv4.cpp | xmac1/udpserver | d392eaf716f7762ec40bc01710a108364e0b2ca2 | [
"Apache-2.0"
] | null | null | null | libfree/inet_pton_ipv4.cpp | xmac1/udpserver | d392eaf716f7762ec40bc01710a108364e0b2ca2 | [
"Apache-2.0"
] | null | null | null | libfree/inet_pton_ipv4.cpp | xmac1/udpserver | d392eaf716f7762ec40bc01710a108364e0b2ca2 | [
"Apache-2.0"
] | null | null | null | //
// Created by xmac on 18-10-17.
//
#include <bits/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
int inet_pton(int family, const char* strptr, void* addrptr) {
if (family == AF_INET) {
struct in_addr in_val;
if (inet_aton(strptr, &in_val)) {
memcpy(addrptr, &in_val, sizeof(struct in_addr));
return (1);
}
return 0;
}
errno = EAFNOSUPPORT;
}
| 19.333333 | 62 | 0.586207 | xmac1 |
33406a33053a64a4375a14b8d09d72fab0ccf2d6 | 387 | cpp | C++ | assets/code_box/bk_2748_slow.cpp | happyOBO/happyOBO.github.io | 96e60a67b9b84c26f01312f8ca5ade35803c521f | [
"MIT"
] | 2 | 2020-10-24T03:25:30.000Z | 2021-08-01T05:18:18.000Z | assets/code_box/bk_2748_slow.cpp | happyOBO/happyOBO.github.io | 96e60a67b9b84c26f01312f8ca5ade35803c521f | [
"MIT"
] | 2 | 2020-12-05T14:31:19.000Z | 2020-12-06T05:09:43.000Z | assets/code_box/bk_2748_slow.cpp | happyOBO/happyOBO.github.io | 96e60a67b9b84c26f01312f8ca5ade35803c521f | [
"MIT"
] | 4 | 2020-08-26T10:02:11.000Z | 2020-10-22T05:55:18.000Z | #include <iostream>
#include <vector>
#include <utility> // pair
using namespace std;
// 동적 계획법
int pibonacci(int n)
{
if(n <= 1)
{
return n;
}
else
{
return pibonacci(n-1) + pibonacci(n-2);
}
}
int main(void)
{
// int n;
// cin>>n;
for(int i = 0; i< 90;i++)
{
cout<<pibonacci(i)<<endl;
}
return 0;
} | 11.727273 | 47 | 0.472868 | happyOBO |
334518e6b1c62b6b6f2af9bd1a633e2cb1498c13 | 35,923 | cxx | C++ | main/sc/source/ui/dbgui/pvlaydlg.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/ui/dbgui/pvlaydlg.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/ui/dbgui/pvlaydlg.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "pvlaydlg.hxx"
#include <com/sun/star/sheet/DataPilotFieldOrientation.hpp>
#include <com/sun/star/sheet/DataPilotFieldSortMode.hpp>
#include <sfx2/dispatch.hxx>
#include <vcl/mnemonic.hxx>
#include <vcl/msgbox.hxx>
#include "dbdocfun.hxx"
#include "uiitems.hxx"
#include "rangeutl.hxx"
#include "document.hxx"
#include "viewdata.hxx"
#include "tabvwsh.hxx"
#include "reffact.hxx"
#include "scresid.hxx"
#include "globstr.hrc"
#include "pivot.hrc"
#include "dpobject.hxx"
#include "dpsave.hxx"
#include "dpshttab.hxx"
#include "scmod.hxx"
#include "sc.hrc" //CHINA001
#include "scabstdlg.hxx" //CHINA001
// ============================================================================
using namespace ::com::sun::star;
using ::rtl::OUString;
// ============================================================================
namespace {
const sal_uInt16 STD_FORMAT = sal_uInt16( SCA_VALID | SCA_TAB_3D | SCA_COL_ABSOLUTE | SCA_ROW_ABSOLUTE | SCA_TAB_ABSOLUTE );
OUString lclGetNameWithoutMnemonic( const FixedText& rFixedText )
{
return MnemonicGenerator::EraseAllMnemonicChars( rFixedText.GetText() );
}
} // namespace
// ============================================================================
ScPivotLayoutDlg::ScPivotLayoutDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, const ScDPObject& rDPObject ) :
ScAnyRefDlg( pB, pCW, pParent, RID_SCDLG_PIVOT_LAYOUT ),
maFlLayout( this, ScResId( FL_LAYOUT ) ),
maScrPage( this, ScResId( SCROLL_PAGE ) ),
maFtPage( this, ScResId( FT_PAGE ) ),
maWndPage( this, ScResId( WND_PAGE ), maScrPage, &maFtPage, lclGetNameWithoutMnemonic( maFtPage ), PIVOTFIELDTYPE_PAGE, HID_SC_DPLAY_PAGE, POINTER_PIVOT_FIELD, 5, 2, 1, 0 ),
maScrCol( this, ScResId( SCROLL_COL ) ),
maFtCol( this, ScResId( FT_COL ) ),
maWndCol( this, ScResId( WND_COL ), maScrCol, &maFtCol, lclGetNameWithoutMnemonic( maFtCol ), PIVOTFIELDTYPE_COL, HID_SC_DPLAY_COLUMN, POINTER_PIVOT_COL, 4, 2, 1, 0 ),
maScrRow( this, ScResId( SCROLL_ROW ) ),
maFtRow( this, ScResId( FT_ROW ) ),
maWndRow( this, ScResId( WND_ROW ), maScrRow, &maFtRow, lclGetNameWithoutMnemonic( maFtRow ), PIVOTFIELDTYPE_ROW, HID_SC_DPLAY_ROW, POINTER_PIVOT_ROW, 1, 8, 1, 0 ),
maScrData( this, ScResId( SCROLL_DATA ) ),
maFtData( this, ScResId( FT_DATA ) ),
maWndData( this, ScResId( WND_DATA ), maScrData, &maFtData, lclGetNameWithoutMnemonic( maFtData ), PIVOTFIELDTYPE_DATA, HID_SC_DPLAY_DATA, POINTER_PIVOT_FIELD, 1, 8, 4, 0 ),
maFlSelect( this, ScResId( FL_SELECT ) ),
maScrSelect( this, ScResId( WND_HSCROLL ) ),
maWndSelect( this, ScResId( WND_SELECT ), maScrSelect, 0, String( ScResId( STR_SELECT ) ), PIVOTFIELDTYPE_SELECT, HID_SC_DPLAY_SELECT, POINTER_PIVOT_FIELD, 2, 10, 1, 2 ),
maFtInfo( this, ScResId( FT_INFO ) ),
maFlAreas( this, ScResId( FL_OUTPUT ) ),
maFtInArea( this, ScResId( FT_INAREA) ),
maEdInPos( this, this, ScResId( ED_INAREA) ),
maRbInPos( this, ScResId( RB_INAREA ), &maEdInPos, this ),
maLbOutPos( this, ScResId( LB_OUTAREA ) ),
maFtOutArea( this, ScResId( FT_OUTAREA ) ),
maEdOutPos( this, this, ScResId( ED_OUTAREA ) ),
maRbOutPos( this, ScResId( RB_OUTAREA ), &maEdOutPos, this ),
maBtnIgnEmptyRows( this, ScResId( BTN_IGNEMPTYROWS ) ),
maBtnDetectCat( this, ScResId( BTN_DETECTCAT ) ),
maBtnTotalCol( this, ScResId( BTN_TOTALCOL ) ),
maBtnTotalRow( this, ScResId( BTN_TOTALROW ) ),
maBtnFilter( this, ScResId( BTN_FILTER ) ),
maBtnDrillDown( this, ScResId( BTN_DRILLDOWN ) ),
maBtnOk( this, ScResId( BTN_OK ) ),
maBtnCancel( this, ScResId( BTN_CANCEL ) ),
maBtnHelp( this, ScResId( BTN_HELP ) ),
maBtnRemove( this, ScResId( BTN_REMOVE ) ),
maBtnOptions( this, ScResId( BTN_OPTIONS ) ),
maBtnMore( this, ScResId( BTN_MORE ) ),
mxDlgDPObject( new ScDPObject( rDPObject ) ),
mpViewData( ((ScTabViewShell*)SfxViewShell::Current())->GetViewData() ),
mpDoc( ((ScTabViewShell*)SfxViewShell::Current())->GetViewData()->GetDocument() ),
mpFocusWindow( 0 ),
mpTrackingWindow( 0 ),
mpDropWindow( 0 ),
mpActiveEdit( 0 ),
mbRefInputMode( false )
{
DBG_ASSERT( mpViewData && mpDoc, "ScPivotLayoutDlg::ScPivotLayoutDlg - missing document or view data" );
mxDlgDPObject->SetAlive( true ); // needed to get structure information
mxDlgDPObject->FillOldParam( maPivotData );
mxDlgDPObject->FillLabelData( maPivotData );
maBtnRemove.SetClickHdl( LINK( this, ScPivotLayoutDlg, ClickHdl ) );
maBtnOptions.SetClickHdl( LINK( this, ScPivotLayoutDlg, ClickHdl ) );
// PIVOT_MAXFUNC defined in sc/inc/dpglobal.hxx
maFuncNames.reserve( PIVOT_MAXFUNC );
for( sal_uInt16 i = 1; i <= PIVOT_MAXFUNC; ++i )
maFuncNames.push_back( String( ScResId( i ) ) );
maBtnMore.AddWindow( &maFlAreas );
maBtnMore.AddWindow( &maFtInArea );
maBtnMore.AddWindow( &maEdInPos );
maBtnMore.AddWindow( &maRbInPos );
maBtnMore.AddWindow( &maFtOutArea );
maBtnMore.AddWindow( &maLbOutPos );
maBtnMore.AddWindow( &maEdOutPos );
maBtnMore.AddWindow( &maRbOutPos );
maBtnMore.AddWindow( &maBtnIgnEmptyRows );
maBtnMore.AddWindow( &maBtnDetectCat );
maBtnMore.AddWindow( &maBtnTotalCol );
maBtnMore.AddWindow( &maBtnTotalRow );
maBtnMore.AddWindow( &maBtnFilter );
maBtnMore.AddWindow( &maBtnDrillDown );
maBtnMore.SetClickHdl( LINK( this, ScPivotLayoutDlg, MoreClickHdl ) );
if( mxDlgDPObject->GetSheetDesc() )
{
maEdInPos.Enable();
maRbInPos.Enable();
ScRange aRange = mxDlgDPObject->GetSheetDesc()->aSourceRange;
String aString;
aRange.Format( aString, SCR_ABS_3D, mpDoc, mpDoc->GetAddressConvention() );
maEdInPos.SetText( aString );
}
else
{
// data is not reachable, so could be a remote database
maEdInPos.Disable();
maRbInPos.Disable();
}
// #i29203# align right border of page window with data window
long nPagePosX = maWndData.GetPosPixel().X() + maWndData.GetSizePixel().Width() - maWndPage.GetSizePixel().Width();
maWndPage.SetPosPixel( Point( nPagePosX, maWndPage.GetPosPixel().Y() ) );
maScrPage.SetPosPixel( Point( maScrData.GetPosPixel().X(), maScrPage.GetPosPixel().Y() ) );
InitFieldWindows();
maLbOutPos.SetSelectHdl( LINK( this, ScPivotLayoutDlg, SelAreaHdl ) );
maEdOutPos.SetModifyHdl( LINK( this, ScPivotLayoutDlg, EdOutModifyHdl ) );
maEdInPos.SetModifyHdl( LINK( this, ScPivotLayoutDlg, EdInModifyHdl ) );
maBtnOk.SetClickHdl( LINK( this, ScPivotLayoutDlg, OkHdl ) );
maBtnCancel.SetClickHdl( LINK( this, ScPivotLayoutDlg, CancelHdl ) );
if( mpViewData && mpDoc )
{
/*
* Aus den RangeNames des Dokumentes werden nun die
* in einem Zeiger-Array gemerkt, bei denen es sich
* um sinnvolle Bereiche handelt
*/
maLbOutPos.Clear();
maLbOutPos.InsertEntry( String( ScResId( SCSTR_UNDEFINED ) ), 0 );
maLbOutPos.InsertEntry( String( ScResId( SCSTR_NEWTABLE ) ), 1 );
ScAreaNameIterator aIter( mpDoc );
String aName;
ScRange aRange;
String aRefStr;
while ( aIter.Next( aName, aRange ) )
{
if ( !aIter.WasDBName() ) // hier keine DB-Bereiche !
{
sal_uInt16 nInsert = maLbOutPos.InsertEntry( aName );
aRange.aStart.Format( aRefStr, SCA_ABS_3D, mpDoc, mpDoc->GetAddressConvention() );
maLbOutPos.SetEntryData( nInsert, new String( aRefStr ) );
}
}
}
if ( maPivotData.nTab != MAXTAB+1 )
{
String aStr;
ScAddress( maPivotData.nCol,
maPivotData.nRow,
maPivotData.nTab ).Format( aStr, STD_FORMAT, mpDoc, mpDoc->GetAddressConvention() );
maEdOutPos.SetText( aStr );
EdOutModifyHdl( 0 );
}
else
{
maLbOutPos.SelectEntryPos( maLbOutPos.GetEntryCount()-1 );
SelAreaHdl(NULL);
}
maBtnIgnEmptyRows.Check( maPivotData.bIgnoreEmptyRows );
maBtnDetectCat.Check( maPivotData.bDetectCategories );
maBtnTotalCol.Check( maPivotData.bMakeTotalCol );
maBtnTotalRow.Check( maPivotData.bMakeTotalRow );
const ScDPSaveData* pSaveData = mxDlgDPObject->GetSaveData();
maBtnFilter.Check( !pSaveData || pSaveData->GetFilterButton() );
maBtnDrillDown.Check( !pSaveData || pSaveData->GetDrillDown() );
// child event listener handles field movement when keyboard shortcut is pressed
AddChildEventListener( LINK( this, ScPivotLayoutDlg, ChildEventListener ) );
GrabFieldFocus( maWndSelect );
FreeResource();
}
ScPivotLayoutDlg::~ScPivotLayoutDlg()
{
RemoveChildEventListener( LINK( this, ScPivotLayoutDlg, ChildEventListener ) );
for( sal_uInt16 i = 2, nEntries = maLbOutPos.GetEntryCount(); i < nEntries; ++i )
delete (String*)maLbOutPos.GetEntryData( i );
}
ScDPLabelData* ScPivotLayoutDlg::GetLabelData( SCCOL nCol, size_t* pnIndex )
{
ScDPLabelData* pLabelData = 0;
for( ScDPLabelDataVector::iterator aIt = maLabelData.begin(), aEnd = maLabelData.end(); !pLabelData && (aIt != aEnd); ++aIt )
{
if( aIt->mnCol == nCol )
{
pLabelData = &*aIt;
if( pnIndex )
*pnIndex = aIt - maLabelData.begin();
}
}
return pLabelData;
}
String ScPivotLayoutDlg::GetFuncString( sal_uInt16& rnFuncMask, bool bIsValue )
{
String aStr;
if( (rnFuncMask == PIVOT_FUNC_NONE) || (rnFuncMask == PIVOT_FUNC_AUTO) )
{
if( bIsValue )
{
aStr = GetFuncName( PIVOTSTR_SUM );
rnFuncMask = PIVOT_FUNC_SUM;
}
else
{
aStr = GetFuncName( PIVOTSTR_COUNT );
rnFuncMask = PIVOT_FUNC_COUNT;
}
}
else if( rnFuncMask == PIVOT_FUNC_SUM ) aStr = GetFuncName( PIVOTSTR_SUM );
else if( rnFuncMask == PIVOT_FUNC_COUNT ) aStr = GetFuncName( PIVOTSTR_COUNT );
else if( rnFuncMask == PIVOT_FUNC_AVERAGE ) aStr = GetFuncName( PIVOTSTR_AVG );
else if( rnFuncMask == PIVOT_FUNC_MAX ) aStr = GetFuncName( PIVOTSTR_MAX );
else if( rnFuncMask == PIVOT_FUNC_MIN ) aStr = GetFuncName( PIVOTSTR_MIN );
else if( rnFuncMask == PIVOT_FUNC_PRODUCT ) aStr = GetFuncName( PIVOTSTR_PROD );
else if( rnFuncMask == PIVOT_FUNC_COUNT_NUM ) aStr = GetFuncName( PIVOTSTR_COUNT2 );
else if( rnFuncMask == PIVOT_FUNC_STD_DEV ) aStr = GetFuncName( PIVOTSTR_DEV );
else if( rnFuncMask == PIVOT_FUNC_STD_DEVP ) aStr = GetFuncName( PIVOTSTR_DEV2 );
else if( rnFuncMask == PIVOT_FUNC_STD_VAR ) aStr = GetFuncName( PIVOTSTR_VAR );
else if( rnFuncMask == PIVOT_FUNC_STD_VARP ) aStr = GetFuncName( PIVOTSTR_VAR2 );
else
{
aStr = ScGlobal::GetRscString( STR_TABLE_ERGEBNIS );
aStr.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " - " ) );
}
return aStr;
}
void ScPivotLayoutDlg::NotifyStartTracking( ScPivotFieldWindow& rSourceWindow )
{
mpTrackingWindow = &rSourceWindow;
mpDropWindow = 0;
rSourceWindow.NotifyStartTracking();
StartTracking( STARTTRACK_BUTTONREPEAT );
SetPointer( Pointer( rSourceWindow.GetDropPointerStyle() ) );
}
void ScPivotLayoutDlg::NotifyDoubleClick( ScPivotFieldWindow& rSourceWindow )
{
// nothing to do on double-click in selection window
if( rSourceWindow.GetType() == PIVOTFIELDTYPE_SELECT )
return;
const ScPivotFuncData* pFuncData = rSourceWindow.GetSelectedFuncData();
DBG_ASSERT( pFuncData, "ScPivotLayoutDlg::NotifyDoubleClick - invalid selection" );
if( !pFuncData )
return;
ScDPLabelData* pLabelData = GetLabelData( pFuncData->mnCol );
DBG_ASSERT( pLabelData, "ScPivotLayoutDlg::NotifyDoubleClick - missing label data" );
if( !pLabelData )
return;
ScAbstractDialogFactory* pFactory = ScAbstractDialogFactory::Create();
DBG_ASSERT( pFactory, "ScPivotLayoutDlg::NotifyDoubleClick - ScAbstractDialogFactory creation failed" );
if( !pFactory )
return;
if( rSourceWindow.GetType() == PIVOTFIELDTYPE_DATA )
{
::std::auto_ptr< AbstractScDPFunctionDlg > xDlg( pFactory->CreateScDPFunctionDlg(
this, RID_SCDLG_DPDATAFIELD, maLabelData, *pLabelData, *pFuncData ) );
if( xDlg->Execute() == RET_OK )
{
ScPivotFuncData aFuncData( *pFuncData );
aFuncData.mnFuncMask = pLabelData->mnFuncMask = xDlg->GetFuncMask();
aFuncData.maFieldRef = xDlg->GetFieldRef();
rSourceWindow.ModifySelectedField( aFuncData );
}
}
else
{
// list of plain names of all data fields
ScDPNameVec aDataFieldNames;
maWndData.WriteFieldNames( aDataFieldNames );
// allow to modify layout options for row fields, if multiple data fields exist, or if it is not the last row field
bool bLayout = (rSourceWindow.GetType() == PIVOTFIELDTYPE_ROW) && ((aDataFieldNames.size() > 1) || (rSourceWindow.GetSelectedIndex() + 1 < rSourceWindow.GetFieldCount()));
::std::auto_ptr< AbstractScDPSubtotalDlg > xDlg( pFactory->CreateScDPSubtotalDlg(
this, RID_SCDLG_PIVOTSUBT, *mxDlgDPObject, *pLabelData, *pFuncData, aDataFieldNames, bLayout ) );
if( xDlg->Execute() == RET_OK )
{
xDlg->FillLabelData( *pLabelData );
ScPivotFuncData aFuncData( *pFuncData );
aFuncData.mnFuncMask = pLabelData->mnFuncMask;
rSourceWindow.ModifySelectedField( aFuncData );
}
}
}
void ScPivotLayoutDlg::NotifyFieldRemoved( ScPivotFieldWindow& rSourceWindow )
{
// update focus: move to selection window, if source window is empty now
GrabFieldFocus( rSourceWindow );
}
// protected ------------------------------------------------------------------
void ScPivotLayoutDlg::Tracking( const TrackingEvent& rTEvt )
{
DBG_ASSERT( mpTrackingWindow, "ScPivotLayoutDlg::Tracking - missing tracking source window" );
if( !mpTrackingWindow )
return;
// find target window
const Point& rDialogPos = rTEvt.GetMouseEvent().GetPosPixel();
ScPivotFieldWindow* pTargetWindow = dynamic_cast< ScPivotFieldWindow* >( FindWindow( rDialogPos ) );
// check if the target orientation is allowed for this field
if( pTargetWindow && (mpTrackingWindow != pTargetWindow) && !IsInsertAllowed( *mpTrackingWindow, *pTargetWindow ) )
pTargetWindow = 0;
// tracking from selection window: do not show "delete" mouse pointer
PointerStyle eTargetPointer = pTargetWindow ? pTargetWindow->GetDropPointerStyle() :
((mpTrackingWindow->GetType() == PIVOTFIELDTYPE_SELECT) ? POINTER_NOTALLOWED : POINTER_PIVOT_DELETE);
// after calculating pointer style, check if target is selection window
if( pTargetWindow && (pTargetWindow->GetType() == PIVOTFIELDTYPE_SELECT) )
pTargetWindow = 0;
// notify windows about tracking
if( mpDropWindow != pTargetWindow )
{
// tracking window changed
if( mpDropWindow )
mpDropWindow->NotifyEndTracking( ENDTRACKING_SUSPEND );
if( pTargetWindow )
pTargetWindow->NotifyStartTracking();
mpDropWindow = pTargetWindow;
}
if( mpDropWindow )
mpDropWindow->NotifyTracking( rDialogPos - pTargetWindow->GetPosPixel() );
// end tracking: move or remove field
if( rTEvt.IsTrackingEnded() )
{
bool bCancelled = rTEvt.IsTrackingCanceled();
if( mpDropWindow )
{
mpDropWindow->NotifyEndTracking( bCancelled ? ENDTRACKING_CANCEL : ENDTRACKING_DROP );
if( !bCancelled )
{
size_t nInsertIndex = mpDropWindow->GetDropIndex( rDialogPos - mpDropWindow->GetPosPixel() );
bool bMoved = MoveField( *mpTrackingWindow, *mpDropWindow, nInsertIndex, true );
// focus drop window, if move was successful, otherwise back to source window
GrabFieldFocus( bMoved ? *mpDropWindow : *mpTrackingWindow );
}
}
else
{
// drop target invalid (outside field windows): remove tracked field
if( !bCancelled )
mpTrackingWindow->RemoveSelectedField();
// focus source window (or another window, if it is empty now)
GrabFieldFocus( *mpTrackingWindow );
}
eTargetPointer = POINTER_ARROW;
if( mpTrackingWindow != mpDropWindow )
mpTrackingWindow->NotifyEndTracking( ENDTRACKING_CANCEL );
mpTrackingWindow = mpDropWindow = 0;
}
SetPointer( eTargetPointer );
}
void ScPivotLayoutDlg::SetReference( const ScRange& rRef, ScDocument* pDocP )
{
if( !mbRefInputMode || !mpActiveEdit )
return;
if( rRef.aStart != rRef.aEnd )
RefInputStart( mpActiveEdit );
if( mpActiveEdit == &maEdInPos )
{
String aRefStr;
rRef.Format( aRefStr, SCR_ABS_3D, pDocP, pDocP->GetAddressConvention() );
mpActiveEdit->SetRefString( aRefStr );
}
else if( mpActiveEdit == &maEdOutPos )
{
String aRefStr;
rRef.aStart.Format( aRefStr, STD_FORMAT, pDocP, pDocP->GetAddressConvention() );
mpActiveEdit->SetRefString( aRefStr );
}
}
sal_Bool ScPivotLayoutDlg::IsRefInputMode() const
{
return mbRefInputMode;
}
void ScPivotLayoutDlg::SetActive()
{
if( mbRefInputMode )
{
if( mpActiveEdit )
mpActiveEdit->GrabFocus();
if( mpActiveEdit == &maEdInPos )
EdInModifyHdl( 0 );
else if( mpActiveEdit == &maEdOutPos )
EdOutModifyHdl( 0 );
}
else
{
GrabFocus();
}
RefInputDone();
}
sal_Bool ScPivotLayoutDlg::Close()
{
return DoClose( ScPivotLayoutWrapper::GetChildWindowId() );
}
// private --------------------------------------------------------------------
ScPivotFieldWindow& ScPivotLayoutDlg::GetFieldWindow( ScPivotFieldType eFieldType )
{
switch( eFieldType )
{
case PIVOTFIELDTYPE_PAGE: return maWndPage;
case PIVOTFIELDTYPE_ROW: return maWndRow;
case PIVOTFIELDTYPE_COL: return maWndCol;
case PIVOTFIELDTYPE_DATA: return maWndData;
default:;
}
return maWndSelect;
}
bool ScPivotLayoutDlg::IsInsertAllowed( const ScPivotFieldWindow& rSourceWindow, const ScPivotFieldWindow& rTargetWindow )
{
if( rTargetWindow.GetType() != PIVOTFIELDTYPE_SELECT )
{
const ScPivotFuncData* pSourceData = rSourceWindow.GetSelectedFuncData();
ScDPLabelData* pLabelData = pSourceData ? GetLabelData( pSourceData->mnCol ) : 0;
DBG_ASSERT( pLabelData, "ScPivotLayoutDlg::IsInsertAllowed - label data not found" );
if( pLabelData )
{
sheet::DataPilotFieldOrientation eOrient = sheet::DataPilotFieldOrientation_HIDDEN;
switch( rTargetWindow.GetType() )
{
case PIVOTFIELDTYPE_PAGE: eOrient = sheet::DataPilotFieldOrientation_PAGE; break;
case PIVOTFIELDTYPE_COL: eOrient = sheet::DataPilotFieldOrientation_COLUMN; break;
case PIVOTFIELDTYPE_ROW: eOrient = sheet::DataPilotFieldOrientation_ROW; break;
case PIVOTFIELDTYPE_DATA: eOrient = sheet::DataPilotFieldOrientation_DATA; break;
default: return false;
}
return ScDPObject::IsOrientationAllowed( static_cast< sal_uInt16 >( eOrient ), pLabelData->mnFlags );
}
}
return false;
}
void ScPivotLayoutDlg::InitFieldWindows()
{
maLabelData = maPivotData.maLabelArray;
maWndSelect.ReadDataLabels( maLabelData );
maWndPage.ReadPivotFields( maPivotData.maPageArr );
maWndCol.ReadPivotFields( maPivotData.maColArr );
maWndRow.ReadPivotFields( maPivotData.maRowArr );
maWndData.ReadPivotFields( maPivotData.maDataArr );
}
void ScPivotLayoutDlg::GrabFieldFocus( ScPivotFieldWindow& rFieldWindow )
{
if( rFieldWindow.IsEmpty() )
{
if( maWndSelect.IsEmpty() )
maBtnOk.GrabFocus();
else
maWndSelect.GrabFocus();
}
else
rFieldWindow.GrabFocus();
}
namespace {
void lclFindFieldWindow( ScPivotFieldWindow*& rpFieldWindow, const ScPivotFuncData*& rpFuncData, size_t& rnFieldIndex, ScPivotFieldWindow& rFieldWindow )
{
ScPivotFuncDataEntry aEntry = rFieldWindow.FindFuncDataByCol( rpFuncData->mnCol );
if( aEntry.first )
{
rpFieldWindow = &rFieldWindow;
rpFuncData = aEntry.first;
rnFieldIndex = aEntry.second;
}
}
} // namespace
bool ScPivotLayoutDlg::MoveField( ScPivotFieldWindow& rSourceWindow, ScPivotFieldWindow& rTargetWindow, size_t nInsertIndex, bool bMoveExisting )
{
// move inside the same window
if( &rSourceWindow == &rTargetWindow )
return bMoveExisting && rTargetWindow.MoveSelectedField( nInsertIndex );
// do not insert if not supported by target window
if( !IsInsertAllowed( rSourceWindow, rTargetWindow ) )
{
rSourceWindow.RemoveSelectedField();
return false;
}
// move from one window to another window
if( const ScPivotFuncData* pSourceData = rSourceWindow.GetSelectedFuncData() )
{
// move to page/col/row window: try to find existing field in another window
ScPivotFieldWindow* pSourceWindow = &rSourceWindow;
size_t nSourceIndex = rSourceWindow.GetSelectedIndex();
if( rTargetWindow.GetType() != PIVOTFIELDTYPE_DATA )
{
lclFindFieldWindow( pSourceWindow, pSourceData, nSourceIndex, maWndPage );
lclFindFieldWindow( pSourceWindow, pSourceData, nSourceIndex, maWndCol );
lclFindFieldWindow( pSourceWindow, pSourceData, nSourceIndex, maWndRow );
}
// found in target window: move to new position
if( pSourceWindow == &rTargetWindow )
return bMoveExisting && pSourceWindow->MoveField( nSourceIndex, nInsertIndex );
// insert field into target window
rTargetWindow.InsertField( nInsertIndex, *pSourceData );
// remove field from source window
pSourceWindow->RemoveField( nSourceIndex );
// remove field from data window, if it is the original source
if( (rSourceWindow.GetType() == PIVOTFIELDTYPE_DATA) && (pSourceWindow->GetType() != PIVOTFIELDTYPE_DATA) )
rSourceWindow.RemoveSelectedField();
return true;
}
return false;
}
// handlers -------------------------------------------------------------------
IMPL_LINK( ScPivotLayoutDlg, ClickHdl, PushButton *, pBtn )
{
if( mpFocusWindow )
{
/* Raising sub dialogs (from the NotifyDoubleClick function) triggers
VCL child window focus events from this sub dialog which may
invalidate the member mpFocusWindow pointing to the target field
window. This would cause a crash with the following call to the
GrabFieldFocus function, if mpFocusWindow is used directly. */
ScPivotFieldWindow& rTargetWindow = *mpFocusWindow;
if( pBtn == &maBtnRemove )
{
rTargetWindow.RemoveSelectedField();
// focus back to field window
GrabFieldFocus( rTargetWindow );
}
else if( pBtn == &maBtnOptions )
{
NotifyDoubleClick( rTargetWindow );
// focus back to field window
GrabFieldFocus( rTargetWindow );
}
}
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, OkHdl, OKButton *, EMPTYARG )
{
String aOutPosStr = maEdOutPos.GetText();
ScAddress aAdrDest;
bool bToNewTable = maLbOutPos.GetSelectEntryPos() == 1;
sal_uInt16 nResult = !bToNewTable ? aAdrDest.Parse( aOutPosStr, mpDoc, mpDoc->GetAddressConvention() ) : 0;
if( bToNewTable || ((aOutPosStr.Len() > 0) && ((nResult & SCA_VALID) == SCA_VALID)) )
{
ScPivotFieldVector aPageFields, aColFields, aRowFields, aDataFields;
maWndPage.WritePivotFields( aPageFields );
maWndCol.WritePivotFields( aColFields );
maWndRow.WritePivotFields( aRowFields );
maWndData.WritePivotFields( aDataFields );
// TODO: handle data field in dialog field windows?
aRowFields.resize( aRowFields.size() + 1 );
aRowFields.back().nCol = PIVOT_DATA_FIELD;
ScDPSaveData* pOldSaveData = mxDlgDPObject->GetSaveData();
ScRange aOutRange( aAdrDest ); // bToNewTable is passed separately
ScDPSaveData aSaveData;
aSaveData.SetIgnoreEmptyRows( maBtnIgnEmptyRows.IsChecked() );
aSaveData.SetRepeatIfEmpty( maBtnDetectCat.IsChecked() );
aSaveData.SetColumnGrand( maBtnTotalCol.IsChecked() );
aSaveData.SetRowGrand( maBtnTotalRow.IsChecked() );
aSaveData.SetFilterButton( maBtnFilter.IsChecked() );
aSaveData.SetDrillDown( maBtnDrillDown.IsChecked() );
uno::Reference< sheet::XDimensionsSupplier > xSource = mxDlgDPObject->GetSource();
ScDPObject::ConvertOrientation( aSaveData, aPageFields, sheet::DataPilotFieldOrientation_PAGE, 0, 0, 0, xSource, false );
ScDPObject::ConvertOrientation( aSaveData, aColFields, sheet::DataPilotFieldOrientation_COLUMN, 0, 0, 0, xSource, false );
ScDPObject::ConvertOrientation( aSaveData, aRowFields, sheet::DataPilotFieldOrientation_ROW, 0, 0, 0, xSource, false );
ScDPObject::ConvertOrientation( aSaveData, aDataFields, sheet::DataPilotFieldOrientation_DATA, 0, 0, 0, xSource, false, &aColFields, &aRowFields, &aPageFields );
for( ScDPLabelDataVector::const_iterator aIt = maLabelData.begin(), aEnd = maLabelData.end(); aIt != aEnd; ++aIt )
{
if( ScDPSaveDimension* pDim = aSaveData.GetExistingDimensionByName( aIt->maName ) )
{
pDim->SetUsedHierarchy( aIt->mnUsedHier );
pDim->SetShowEmpty( aIt->mbShowAll );
pDim->SetSortInfo( &aIt->maSortInfo );
pDim->SetLayoutInfo( &aIt->maLayoutInfo );
pDim->SetAutoShowInfo( &aIt->maShowInfo );
ScDPSaveDimension* pOldDim = NULL;
if (pOldSaveData)
{
// Transfer the existing layout names to new dimension instance.
pOldDim = pOldSaveData->GetExistingDimensionByName(aIt->maName);
if (pOldDim)
{
const OUString* pLayoutName = pOldDim->GetLayoutName();
if (pLayoutName)
pDim->SetLayoutName(*pLayoutName);
const OUString* pSubtotalName = pOldDim->GetSubtotalName();
if (pSubtotalName)
pDim->SetSubtotalName(*pSubtotalName);
}
}
bool bManualSort = ( aIt->maSortInfo.Mode == sheet::DataPilotFieldSortMode::MANUAL );
// visibility of members
for (::std::vector<ScDPLabelData::Member>::const_iterator itr = aIt->maMembers.begin(), itrEnd = aIt->maMembers.end();
itr != itrEnd; ++itr)
{
ScDPSaveMember* pMember = pDim->GetMemberByName(itr->maName);
// #i40054# create/access members only if flags are not default
// (or in manual sorting mode - to keep the order)
if (bManualSort || !itr->mbVisible || !itr->mbShowDetails)
{
pMember->SetIsVisible(itr->mbVisible);
pMember->SetShowDetails(itr->mbShowDetails);
}
if (pOldDim)
{
// Transfer the existing layout name.
ScDPSaveMember* pOldMember = pOldDim->GetMemberByName(itr->maName);
if (pOldMember)
{
const OUString* pLayoutName = pOldMember->GetLayoutName();
if (pLayoutName)
pMember->SetLayoutName(*pLayoutName);
}
}
}
}
}
ScDPSaveDimension* pDim = aSaveData.GetDataLayoutDimension();
if (pDim && pOldSaveData)
{
ScDPSaveDimension* pOldDim = pOldSaveData->GetDataLayoutDimension();
if (pOldDim)
{
const OUString* pLayoutName = pOldDim->GetLayoutName();
if (pLayoutName)
pDim->SetLayoutName(*pLayoutName);
}
}
// also transfer grand total name
if (pOldSaveData)
{
const OUString* pGrandTotalName = pOldSaveData->GetGrandTotalName();
if (pGrandTotalName)
aSaveData.SetGrandTotalName(*pGrandTotalName);
}
sal_uInt16 nWhichPivot = SC_MOD()->GetPool().GetWhich( SID_PIVOT_TABLE );
ScPivotItem aOutItem( nWhichPivot, &aSaveData, &aOutRange, bToNewTable );
mbRefInputMode = false; // to allow deselecting when switching sheets
SetDispatcherLock( false );
SwitchToDocument();
// #95513# don't hide the dialog before executing the slot, instead it is used as
// parent for message boxes in ScTabViewShell::GetDialogParent
const SfxPoolItem* pRet = GetBindings().GetDispatcher()->Execute(
SID_PIVOT_TABLE, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD, &aOutItem, 0L, 0L );
bool bSuccess = true;
if (pRet)
{
const SfxBoolItem* pItem = dynamic_cast<const SfxBoolItem*>(pRet);
if (pItem)
bSuccess = pItem->GetValue();
}
if (bSuccess)
// Table successfully inserted.
Close();
else
{
// Table insertion failed. Keep the dialog open.
mbRefInputMode = true;
SetDispatcherLock(true);
}
}
else
{
if( !maBtnMore.GetState() )
maBtnMore.SetState( true );
ErrorBox( this, WinBits( WB_OK | WB_DEF_OK ), ScGlobal::GetRscString( STR_INVALID_TABREF ) ).Execute();
maEdOutPos.GrabFocus();
}
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, CancelHdl, CancelButton *, EMPTYARG )
{
Close();
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, MoreClickHdl, MoreButton *, EMPTYARG )
{
if ( maBtnMore.GetState() )
{
mbRefInputMode = true;
if ( maEdInPos.IsEnabled() )
{
maEdInPos.Enable();
maEdInPos.GrabFocus();
maEdInPos.Enable();
}
else
{
maEdOutPos.Enable();
maEdOutPos.GrabFocus();
maEdOutPos.Enable();
}
}
else
{
mbRefInputMode = false;
}
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, EdOutModifyHdl, Edit *, EMPTYARG )
{
String theCurPosStr = maEdOutPos.GetText();
sal_uInt16 nResult = ScAddress().Parse( theCurPosStr, mpDoc, mpDoc->GetAddressConvention() );
if ( SCA_VALID == (nResult & SCA_VALID) )
{
String* pStr = 0;
bool bFound = false;
sal_uInt16 i = 0;
sal_uInt16 nCount = maLbOutPos.GetEntryCount();
for ( i=2; i<nCount && !bFound; i++ )
{
pStr = (String*)maLbOutPos.GetEntryData( i );
bFound = (theCurPosStr == *pStr);
}
if ( bFound )
maLbOutPos.SelectEntryPos( --i );
else
maLbOutPos.SelectEntryPos( 0 );
}
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, EdInModifyHdl, Edit *, EMPTYARG )
{
String theCurPosStr = maEdInPos.GetText();
sal_uInt16 nResult = ScRange().Parse( theCurPosStr, mpDoc, mpDoc->GetAddressConvention() );
// invalid source range
if( SCA_VALID != (nResult & SCA_VALID) )
return 0;
ScRefAddress start, end;
ConvertDoubleRef( mpDoc, theCurPosStr, 1, start, end, mpDoc->GetAddressConvention() );
ScRange aNewRange( start.GetAddress(), end.GetAddress() );
ScSheetSourceDesc inSheet = *mxDlgDPObject->GetSheetDesc();
// new range is identical to the current range
if( inSheet.aSourceRange == aNewRange )
return 0;
ScTabViewShell* pTabViewShell = mpViewData->GetViewShell();
inSheet.aSourceRange = aNewRange;
mxDlgDPObject->SetSheetDesc( inSheet );
mxDlgDPObject->FillOldParam( maPivotData );
mxDlgDPObject->FillLabelData( maPivotData );
// SetDialogDPObject does not take ownership but makes a copy internally
pTabViewShell->SetDialogDPObject( mxDlgDPObject.get() );
// re-initialize the field windows from the new data
InitFieldWindows();
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, SelAreaHdl, ListBox *, EMPTYARG )
{
String aString;
sal_uInt16 nSelPos = maLbOutPos.GetSelectEntryPos();
if( nSelPos > 1 )
{
aString = *(String*)maLbOutPos.GetEntryData( nSelPos );
}
else
{
// do not allow to specify output position, if target is "new sheet"
bool bNewSheet = nSelPos == 1;
maEdOutPos.Enable( !bNewSheet );
maRbOutPos.Enable( !bNewSheet );
}
maEdOutPos.SetText( aString );
return 0;
}
IMPL_LINK( ScPivotLayoutDlg, ChildEventListener, VclWindowEvent*, pEvent )
{
Window* pWindow = pEvent->GetWindow();
// check that this dialog is the parent of the window, to ignore focus events from sub dialogs
if( (pEvent->GetId() == VCLEVENT_WINDOW_GETFOCUS) && pWindow && (pWindow->GetParent() == this) )
{
// check if old window and/or new window are field windows
ScPivotFieldWindow* pSourceWindow = mpFocusWindow;
ScPivotFieldWindow* pTargetWindow = dynamic_cast< ScPivotFieldWindow* >( pWindow );
/* Enable or disable the Remove/Options buttons. Do nothing if the
buttons themselves get the focus.
#128113# The TestTool may set the focus into an empty window. Then
the Remove/Options buttons must be disabled. */
if( (pWindow != &maBtnRemove) && (pWindow != &maBtnOptions) )
{
bool bEnableButtons = pTargetWindow && (pTargetWindow->GetType() != PIVOTFIELDTYPE_SELECT) && !pTargetWindow->IsEmpty();
maBtnRemove.Enable( bEnableButtons );
maBtnOptions.Enable( bEnableButtons );
/* Remember the new focus window (will not be changed, if
Remove/Option buttons are getting focus, because they need to
know the field window they are working on). */
mpFocusWindow = pTargetWindow;
}
/* Move the last selected field to target window, if focus changes via
keyboard shortcut. */
if( pSourceWindow && pTargetWindow && (pSourceWindow != pTargetWindow) && ((pTargetWindow->GetGetFocusFlags() & GETFOCUS_MNEMONIC) != 0) )
{
// append field in target window
MoveField( *pSourceWindow, *pTargetWindow, pTargetWindow->GetFieldCount(), false );
// move cursor in selection window to next field
if( pSourceWindow->GetType() == PIVOTFIELDTYPE_SELECT )
pSourceWindow->SelectNextField();
// return focus to source window (if it is not empty)
GrabFieldFocus( pSourceWindow->IsEmpty() ? *pTargetWindow : *pSourceWindow );
}
mpActiveEdit = dynamic_cast< ::formula::RefEdit* >( pEvent->GetWindow() );
}
return 0;
}
// ============================================================================
| 37.694648 | 179 | 0.650725 | Grosskopf |
33459a3e4d3f4d771d7a680d4943e8f3028c6087 | 2,673 | hpp | C++ | graph_tree/HLD_lazy.hpp | hotman78/cpplib | c2f85c8741cdd0b731a5aa828b28b38c70c8d699 | [
"CC0-1.0"
] | null | null | null | graph_tree/HLD_lazy.hpp | hotman78/cpplib | c2f85c8741cdd0b731a5aa828b28b38c70c8d699 | [
"CC0-1.0"
] | null | null | null | graph_tree/HLD_lazy.hpp | hotman78/cpplib | c2f85c8741cdd0b731a5aa828b28b38c70c8d699 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include"./graph_template.hpp"
#include"../segment_tree/lazy_segment_tree.hpp"
template<typename T,typename E,typename F,typename G,typename H>
class HLD_lazy{
int child_size(const graph& v,int n,int p){
int cnt=0;
for(auto t:v[n]){
if(t!=p)cnt+=child_size(v,t,n);
}
return sz[n]=cnt+1;
}
void make(const graph& v,int root){
sz=new int[v.size()];
vertex=new int[v.size()];
par=new int[v.size()];
head=new int[v.size()];
child_size(v,root,-1);
stack<tuple<int,int>>stk;
stk.emplace(root,-1);
int idx=0;
par[root]=root;
head[root]=root;
while(!stk.empty()){
int n,p;
tie(n,p)=stk.top();
stk.pop();
vertex[n]=idx++;
int mx=0,heavy=-1;
for(auto t:v[n])if(t!=p&&mx<sz[t]){
mx=sz[t];
heavy=t;
}
for(auto t:v[n]){
if(t!=heavy&&t!=p){
par[t]=n;
head[t]=t;
stk.emplace(t,n);
}
}
if(heavy!=-1){
par[heavy]=par[n];
head[heavy]=head[n];
stk.emplace(heavy,n);
}
}
}
int* sz;
int* vertex;
int* par;
int* head;
F _f;G _g;H _h;
lazy_segment_tree<T,E,F,G,H>* seg;
public:
HLD_lazy(const graph& v,int root=0,F f=F(),G g=G(),H h=H()):_f(f),_g(g),_h(h){
make(v,root);
seg=new lazy_segment_tree<T,E,F,G,H>(v.size(),f,g,h);
}
// HLD_lazy(const graph& v,const vector<T>& a,int root=0,F f=F(),G g=G(),H h=H()):_f(f),_g(g),_h(h){
// vector<T>tmp(v.size());
// make(v,root);
// for(int i=0;i<(int)v.size();i++){
// tmp[vertex[i]]=a[i];
// }
// seg=new lazy_segment_tree(tmp,f,g,h);
// }
int lca(int l,int r){
while(1){
if(head[l]==head[r])return sz[l]>sz[r]?l:r;
else if(sz[head[l]]>sz[head[r]])r=par[r];
else l=par[l];
}
}
inline void update_vertex(int u,E x){
seg->update(vertex[u],vertex[u],x);
}
inline maybe<T> get_vertex(int u){
return seg->get(vertex[u],vertex[u]);
}
inline void update_subtree(int u,E x){
seg->update(vertex[u],vertex[u]+sz[u]-1);
}
inline maybe<T> get_subtree(int u){
return seg->get(vertex[u],vertex[u]+sz[u]-1);
}
void update_path(int u,int v,E x){
while(1){
if(head[u]==head[v]){
seg->update(vertex[u],vertex[v],x);
break;
}
else if(sz[head[u]]>sz[head[v]]){
seg->update(vertex[v],vertex[head[v]],x);
v=par[v];
}
else{
seg->update(vertex[u],vertex[head[u]],x);
u=par[u];
}
}
}
T get_path(int u,int v){
auto f=expand<T,F>(_f);
maybe<T> res;
while(1){
if(head[u]==head[v]){
return f(res,seg->get(vertex[u],vertex[v]));
}
else if(sz[head[u]]>sz[head[v]]){
res=f(res,seg->get(vertex[v],vertex[head[v]]));
v=par[v];
}
else{
res=f(res,seg->get(vertex[u],vertex[head[u]]));
u=par[u];
}
}
}
}; | 22.275 | 101 | 0.564908 | hotman78 |
3345f74f0df4da067d4ae5922f0dba006d80869e | 676 | cpp | C++ | src/sequencer_src/interface/components/field/PitchParameterField.cpp | pigatron-industries/xen_sequence | 0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1 | [
"Unlicense"
] | null | null | null | src/sequencer_src/interface/components/field/PitchParameterField.cpp | pigatron-industries/xen_sequence | 0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1 | [
"Unlicense"
] | null | null | null | src/sequencer_src/interface/components/field/PitchParameterField.cpp | pigatron-industries/xen_sequence | 0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1 | [
"Unlicense"
] | null | null | null | #include "PitchParameterField.h"
PitchParameterField::PitchParameterField(const char* _name) :
ParameterField(_name) {
}
void PitchParameterField::increment(int16_t amount) {
value += amount;
if(value > max) {
value = max;
}
dirtyValue = true;
}
void PitchParameterField::decrement(int16_t amount) {
value -= amount;
if(value < min) {
value = min;
}
dirtyValue = true;
}
void PitchParameterField::render(GraphicsContext& g) {
if(visible) {
ParameterField::render(g);
if(dirtyValue || g.full) {
Hardware::display.print(noteNames[value]);
dirtyValue = false;
}
}
}
| 21.125 | 61 | 0.613905 | pigatron-industries |
334643dd47c207e863046585a1cc5f7bdea0d79f | 1,005 | hpp | C++ | SDK/ARKSurvivalEvolved_Task_StunForestKaiju_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Task_StunForestKaiju_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Task_StunForestKaiju_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Task_StunForestKaiju_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Task_StunForestKaiju.Task_StunForestKaiju_C.ReceiveExecute
struct UTask_StunForestKaiju_C_ReceiveExecute_Params
{
class AActor** OwnerActor; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Task_StunForestKaiju.Task_StunForestKaiju_C.ExecuteUbergraph_Task_StunForestKaiju
struct UTask_StunForestKaiju_C_ExecuteUbergraph_Task_StunForestKaiju_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 29.558824 | 152 | 0.553234 | 2bite |
33465f942ba9784413f05fae279e98d3edfb5ef4 | 4,878 | cpp | C++ | HelicopterGame/Engine.cpp | MattGardiner97/HelicopterGame | 7cb14bd66e7ce69adb528a4974e5a1933b9fb057 | [
"MIT"
] | 2 | 2020-04-23T11:32:45.000Z | 2020-11-05T16:33:46.000Z | HelicopterGame/Engine.cpp | MattGardiner97/HelicopterGame | 7cb14bd66e7ce69adb528a4974e5a1933b9fb057 | [
"MIT"
] | null | null | null | HelicopterGame/Engine.cpp | MattGardiner97/HelicopterGame | 7cb14bd66e7ce69adb528a4974e5a1933b9fb057 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string>
#include "Engine.h"
using namespace std;
bool Engine::Init(string WindowTitle) {
TTF_Init();
_graphics = new Graphics;
if (_graphics->Init(WindowTitle) == false)
return false;
_textureManager = new TextureManager(_graphics->GetRenderer());
_time = new Time;
if (_time->Init() == false)
return false;
_input = new Input;
if (_input->Init() == false)
return false;
_textTextureGenerator = new TextTextureGenerator(_graphics->GetRenderer());
_mainMenu = new MainMenu(this);
if (_mainMenu->Init() == false)
return false;
_scoreGUI = new ScoreGUI(this);
if (_scoreGUI->Init() == false)
return false;
_scoreGUI->UpdateScore(0);
_easyDifficulty = new EasyDifficulty;
_mediumDifficulty = new MediumDifficulty;
_hardDifficulty = new HardDifficulty;
_currentDifficulty = _easyDifficulty;
//Load helicopter texture
SDL_Texture* helicopterTexture = _textureManager->LoadFromFile(Constants::HELICOPTER_IMAGE_NAME);
if (helicopterTexture == NULL)
return false;
//Load background texture
SDL_Texture* backgroundTexture = _textureManager->LoadFromFile(Constants::BACKGROUND_IMAGE_NAME);
if (backgroundTexture == NULL)
return false;
//Load obstacle texture
SDL_Texture* obstacleTexture = _textureManager->LoadFromFile(Constants::OBSTACLE_IMAGE_NAME);
if (obstacleTexture == NULL)
return false;
_helicopter = new Helicopter(helicopterTexture, this);
_background = new Background(backgroundTexture, this);
_background2 = new Background(backgroundTexture, this);
_background2->SetX(Constants::WINDOW_WIDTH - 1);
_obstacleManager = new ObstacleManager(obstacleTexture, this);
_obstacleManager->Init();
return true;
}
void Engine::Cleanup() {
if (_graphics != NULL)
{
_graphics->Cleanup();
delete _graphics;
_graphics = NULL;
}
if (_time != NULL) {
_time->Cleanup();
delete _time;
_time = NULL;
}
if (_input != NULL)
{
_input->Cleanup();
delete _input;
_input = NULL;
}
if (_helicopter != NULL)
{
_helicopter->Cleanup();
delete _helicopter;
_helicopter = NULL;
}
if (_background != NULL)
{
_background->Cleanup();
delete _background;
_background = NULL;
}
if (_background2 != NULL)
{
_background2->Cleanup();
delete _background2;
_background2 = NULL;
}
if (_obstacleManager != NULL)
{
_obstacleManager->Cleanup();
delete _obstacleManager;
_obstacleManager = NULL;
}
_currentDifficulty = NULL;
if (_easyDifficulty != NULL)
{
delete _easyDifficulty;
_easyDifficulty = NULL;
}
if (_mediumDifficulty != NULL)
{
delete _mediumDifficulty;
_mediumDifficulty = NULL;
}
if (_hardDifficulty != NULL)
{
delete _hardDifficulty;
_hardDifficulty = NULL;
}
if (_mainMenu != NULL)
{
_mainMenu->Cleanup();
delete _mainMenu;
_mainMenu = NULL;
}
if (_scoreGUI != NULL)
{
_scoreGUI->Cleanup();
delete _scoreGUI;
_scoreGUI = NULL;
}
if (_textTextureGenerator != NULL)
{
delete _textTextureGenerator;
_textTextureGenerator = NULL;
}
SDL_Quit();
IMG_Quit();
}
void Engine::Run() {
while (_input->IsQuitRequested() == false) {
//Update Timer
_time->Update();
//Update Input
_input->Poll();
//Update
_background->Update();
_background2->Update();
_helicopter->Update();
_obstacleManager->Update();
_mainMenu->Update();
if (GameActive == false && _mainMenu->NewGameRequested == true)
NewGame();
//Check collisions
if (_obstacleManager->CheckPlayerCollision(_helicopter->GetBoundingRectangle()))
GameOver();
//Check helicopter offscreen
if (_helicopter->IsOffScreen())
GameOver();
//Clear render target
_graphics->Clear();
//Draw helicopter
_background->Draw();
_background2->Draw();
_obstacleManager->Draw();
_helicopter->Draw();
_mainMenu->Draw();
_scoreGUI->Draw();
//Present render target
_graphics->Present();
SDL_Delay(8);
}
}
Input* Engine::GetInput() {
return _input;
}
Graphics* Engine::GetGraphics() {
return _graphics;
}
Time* Engine::GetTime() {
return _time;
}
Difficulty* Engine::GetCurrentDifficulty() {
return _currentDifficulty;
}
void Engine::GameOver() {
GameActive = false;
_mainMenu->Active = true;
_obstacleManager->Active = false;
_helicopter->Active = false;
_mainMenu->NewGameRequested = false;
}
void Engine::NewGame() {
_mainMenu->NewGameRequested = false;
switch (_mainMenu->SelectedDifficulty)
{
case 0:
_currentDifficulty = _easyDifficulty;
break;
case 1:
_currentDifficulty = _mediumDifficulty;
break;
case 2:
_currentDifficulty = _hardDifficulty;
break;
}
GameActive = true;
_mainMenu->Active = false;
_obstacleManager->Reset();
_helicopter->Reset();
_scoreGUI->UpdateScore(0);
}
TextTextureGenerator* Engine::GetTextTextureGenerator() {
return _textTextureGenerator;
}
void Engine::IncrementScore() {
_scoreGUI->UpdateScore(_scoreGUI->Score + 1);
} | 19.280632 | 98 | 0.709922 | MattGardiner97 |
334786e68bc004796b29c2ee3ed234a180ba5a9b | 1,182 | hpp | C++ | source/gameplay/EnemyProjectiles.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | null | null | null | source/gameplay/EnemyProjectiles.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | null | null | null | source/gameplay/EnemyProjectiles.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | 1 | 2020-11-20T03:12:02.000Z | 2020-11-20T03:12:02.000Z | //--------------------------------------------------------------------------------
// EnemyProjectiles.hpp
//--------------------------------------------------------------------------------
// The class that manages the projectiles fired by the enemies
//--------------------------------------------------------------------------------
#pragma once
#include <tonc.h>
#include "Projectile.hpp"
#include "graphics/ObjectTilePointer.hpp"
#include "graphics/PalettePointer.hpp"
class GameScene;
class EnemyProjectiles final
{
constexpr static u32 MaxProjectiles = 128;
GameScene& gameScene();
Projectile projectiles[MaxProjectiles];
u32 numProjectiles;
ObjectTilePointer tilePtr;
SinglePalettePointer palPtr;
public:
void init();
void update();
void pushGraphics();
void add(vec2<s16f7> pos, vec2<s16f7> vel, u16 type)
{
ASSERT(numProjectiles < MaxProjectiles);
projectiles[numProjectiles++] = { pos, vel, type };
}
void add(vec2<s16f7> pos, vec2<s16f7> vel, u16 type, u16 arg)
{
ASSERT(numProjectiles < MaxProjectiles);
projectiles[numProjectiles++] = { pos, vel, type, arg };
}
};
| 25.695652 | 82 | 0.538071 | Xett |
334a491b4cee77ecb4bcce660376daef16196376 | 2,522 | hpp | C++ | SuperReads_RNA/global-1/jellyfish/include/jellyfish/text_dumper.hpp | Kuanhao-Chao/multiStringTie | be37f9b4ae72b14e7cf645f24725b7186f66a816 | [
"MIT"
] | 255 | 2015-02-18T20:27:23.000Z | 2022-03-18T18:55:35.000Z | SuperReads_RNA/global-1/jellyfish/include/jellyfish/text_dumper.hpp | Kuanhao-Chao/multiStringTie | be37f9b4ae72b14e7cf645f24725b7186f66a816 | [
"MIT"
] | 350 | 2015-03-11T14:24:06.000Z | 2022-03-29T03:54:10.000Z | SuperReads_RNA/global-1/jellyfish/include/jellyfish/text_dumper.hpp | wrf/stringtie | 2e99dccd9a2e2ce51cfddcb3896984fa773697f7 | [
"MIT"
] | 66 | 2015-02-19T00:21:38.000Z | 2022-03-30T09:52:23.000Z | /* This file is part of Jellyfish.
Jellyfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jellyfish 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 Jellyfish. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __JELLYFISH_TEXT_DUMPER_HPP__
#define __JELLYFISH_TEXT_DUMPER_HPP__
#include <jellyfish/sorted_dumper.hpp>
namespace jellyfish {
template<typename Key, typename Val>
class text_writer {
public:
void write(std::ostream& out, const Key& key, const Val val) {
out << key << " " << val << "\n";
}
};
template<typename storage_t>
class text_dumper : public sorted_dumper<text_dumper<storage_t>, storage_t> {
typedef sorted_dumper<text_dumper<storage_t>, storage_t> super;
text_writer<typename super::key_type, uint64_t> writer;
public:
static const char* format;
text_dumper(int nb_threads, const char* file_prefix, file_header* header = 0) :
super(nb_threads, file_prefix, header)
{ }
virtual void _dump(storage_t* ary) {
if(super::header_) {
super::header_->update_from_ary(*ary);
super::header_->format(format);
}
super::_dump(ary);
}
void write_key_value_pair(std::ostream& out, typename super::heap_item item) {
writer.write(out, item->key_, item->val_);
}
};
template<typename storage_t>
const char* jellyfish::text_dumper<storage_t>::format = "text/sorted";
template<typename Key, typename Val>
class text_reader {
std::istream& is_;
char* buffer_;
Key key_;
Val val_;
const RectangularBinaryMatrix m_;
const size_t size_mask_;
public:
text_reader(std::istream& is,
file_header* header) :
is_(is),
buffer_(new char[header->key_len() / 2 + 1]),
key_(header->key_len() / 2),
m_(header->matrix()),
size_mask_(header->size() - 1)
{ }
const Key& key() const { return key_; }
const Val& val() const { return val_; }
size_t pos() const { return m_.times(key()) & size_mask_; }
bool next() {
is_ >> key_ >> val_;
return is_.good();
}
};
}
#endif /* __JELLYFISH_TEXT_DUMPER_HPP__ */
| 28.337079 | 81 | 0.693101 | Kuanhao-Chao |
334be7e3852fcf1c0eca1319c7605414027b5142 | 6,194 | cc | C++ | chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-16T13:10:29.000Z | 2021-11-16T13:10:29.000Z | chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.h"
#include <utility>
#include "ash/public/cpp/app_list/app_list_config.h"
#include "ash/public/cpp/app_list/vector_icons/vector_icons.h"
#include "base/bind.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/apps/app_service/app_icon/app_icon_factory.h"
#include "chrome/browser/ash/arc/icon_decode_request.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/app_list/arc/arc_playstore_app_context_menu.h"
#include "chrome/browser/ui/app_list/search/search_tags_util.h"
#include "components/arc/mojom/app.mojom.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/session/arc_service_manager.h"
#include "components/crx_file/id_util.h"
#include "ui/base/models/image_model.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/image/canvas_image_source.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/paint_vector_icon.h"
namespace {
// The id prefix to identify a Play Store search result.
constexpr char kPlayAppPrefix[] = "play://";
// Badge icon color.
constexpr SkColor kBadgeColor = gfx::kGoogleGrey700;
// Size of the vector icon inside the badge.
constexpr int kBadgeIconSize = 12;
// The background image source for badge.
class BadgeBackgroundImageSource : public gfx::CanvasImageSource {
public:
explicit BadgeBackgroundImageSource(int size)
: CanvasImageSource(gfx::Size(size, size)) {}
BadgeBackgroundImageSource(const BadgeBackgroundImageSource&) = delete;
BadgeBackgroundImageSource& operator=(const BadgeBackgroundImageSource&) =
delete;
~BadgeBackgroundImageSource() override = default;
private:
// gfx::CanvasImageSource overrides:
void Draw(gfx::Canvas* canvas) override {
cc::PaintFlags flags;
flags.setColor(SK_ColorWHITE);
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
const float origin = static_cast<float>(size().width()) / 2;
canvas->DrawCircle(gfx::PointF(origin, origin), origin, flags);
}
};
gfx::ImageSkia CreateBadgeIcon(const gfx::VectorIcon& vector_icon,
int badge_size,
int icon_size,
SkColor icon_color) {
gfx::ImageSkia background(
std::make_unique<BadgeBackgroundImageSource>(badge_size),
gfx::Size(badge_size, badge_size));
gfx::ImageSkia foreground(
gfx::CreateVectorIcon(vector_icon, icon_size, icon_color));
return gfx::ImageSkiaOperations::CreateSuperimposedImage(background,
foreground);
}
bool LaunchIntent(const std::string& intent_uri, int64_t display_id) {
auto* arc_service_manager = arc::ArcServiceManager::Get();
if (!arc_service_manager)
return false;
auto* arc_bridge = arc_service_manager->arc_bridge_service();
if (auto* app_instance =
ARC_GET_INSTANCE_FOR_METHOD(arc_bridge->app(), LaunchIntent)) {
app_instance->LaunchIntent(intent_uri, display_id);
return true;
}
if (auto* app_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge->app(), LaunchIntentDeprecated)) {
app_instance->LaunchIntentDeprecated(intent_uri, absl::nullopt);
return true;
}
return false;
}
} // namespace
namespace app_list {
ArcPlayStoreSearchResult::ArcPlayStoreSearchResult(
arc::mojom::AppDiscoveryResultPtr data,
Profile* profile,
AppListControllerDelegate* list_controller,
const std::u16string& query)
: data_(std::move(data)),
profile_(profile),
list_controller_(list_controller) {
const auto title = base::UTF8ToUTF16(label().value());
SetTitle(title);
SetTitleTags(CalculateTags(query, title));
set_id(kPlayAppPrefix +
crx_file::id_util::GenerateId(install_intent_uri().value()));
SetCategory(Category::kPlayStore);
SetDisplayType(ash::SearchResultDisplayType::kTile);
// TODO: The badge icon should be updated to pass through a vector icon and
// color id rather than hardcoding the colors here.
SetBadgeIcon(ui::ImageModel::FromImageSkia(CreateBadgeIcon(
is_instant_app() ? ash::kBadgeInstantIcon : ash::kBadgePlayIcon,
ash::SharedAppListConfig::instance().search_tile_badge_icon_dimension(),
kBadgeIconSize, kBadgeColor)));
SetFormattedPrice(base::UTF8ToUTF16(formatted_price().value()));
SetRating(review_score());
SetResultType(is_instant_app() ? ash::AppListSearchResultType::kInstantApp
: ash::AppListSearchResultType::kPlayStoreApp);
SetMetricsType(is_instant_app() ? ash::PLAY_STORE_INSTANT_APP
: ash::PLAY_STORE_UNINSTALLED_APP);
apps::ArcRawIconPngDataToImageSkia(
std::move(data_->icon),
ash::SharedAppListConfig::instance().search_tile_icon_dimension(),
base::BindOnce(&ArcPlayStoreSearchResult::OnIconDecoded,
weak_ptr_factory_.GetWeakPtr()));
}
ArcPlayStoreSearchResult::~ArcPlayStoreSearchResult() = default;
void ArcPlayStoreSearchResult::Open(int event_flags) {
LaunchIntent(install_intent_uri().value(),
list_controller_->GetAppListDisplayId());
}
void ArcPlayStoreSearchResult::GetContextMenuModel(
GetMenuModelCallback callback) {
context_menu_ = std::make_unique<ArcPlayStoreAppContextMenu>(
this, profile_, list_controller_);
// TODO(755701): Enable context menu once Play Store API starts returning both
// install and launch intents.
std::move(callback).Run(nullptr);
}
void ArcPlayStoreSearchResult::ExecuteLaunchCommand(int event_flags) {
Open(event_flags);
}
AppContextMenu* ArcPlayStoreSearchResult::GetAppContextMenu() {
return context_menu_.get();
}
void ArcPlayStoreSearchResult::OnIconDecoded(const gfx::ImageSkia& icon) {
SetIcon(IconInfo(icon));
}
} // namespace app_list
| 36.650888 | 80 | 0.733775 | zealoussnow |
334d01c7077b5ab8b0418cc313ebb7b6942228d6 | 265,388 | cpp | C++ | groups/bsl/bslstl/bslstl_stack.t.cpp | eddiepierce/bde | 45953ece9dd1cd8732f01a1cd24bbe838791d298 | [
"Apache-2.0"
] | 1 | 2021-01-05T00:22:16.000Z | 2021-01-05T00:22:16.000Z | groups/bsl/bslstl/bslstl_stack.t.cpp | eddiepierce/bde | 45953ece9dd1cd8732f01a1cd24bbe838791d298 | [
"Apache-2.0"
] | 2 | 2020-11-05T15:20:55.000Z | 2021-01-05T19:38:43.000Z | groups/bsl/bslstl/bslstl_stack.t.cpp | eddiepierce/bde | 45953ece9dd1cd8732f01a1cd24bbe838791d298 | [
"Apache-2.0"
] | 2 | 2020-01-16T17:58:12.000Z | 2020-08-11T20:59:30.000Z | // bslstl_stack.t.cpp -*-C++-*-
#include <bslstl_stack.h>
#include <bslstl_vector.h>
#include <bsltf_stdstatefulallocator.h>
#include <bsltf_stdtestallocator.h>
#include <bsltf_templatetestfacility.h>
#include <bsltf_testvaluesarray.h>
#include <bslma_allocator.h>
#include <bslma_default.h>
#include <bslma_defaultallocatorguard.h>
#include <bslma_mallocfreeallocator.h>
#include <bslma_testallocator.h>
#include <bslma_testallocatormonitor.h>
#include <bslalg_rangecompare.h>
#include <bslmf_issame.h>
#include <bslmf_haspointersemantics.h>
#include <bslmf_movableref.h>
#include <bsls_alignmentutil.h>
#include <bsls_asserttest.h>
#include <bsls_bsltestutil.h>
#include <bsls_compilerfeatures.h>
#include <bsls_nameof.h>
#include <bsls_platform.h>
#include <algorithm>
#include <functional>
#include <typeinfo>
#include <cstdio>
#include <cstdio>
#include <cstdlib>
#include <stdlib.h> // atoi
#include <string.h>
// ============================================================================
// ADL SWAP TEST HELPER
// ----------------------------------------------------------------------------
template <class TYPE>
void invokeAdlSwap(TYPE& a, TYPE& b)
// Exchange the values of the specified 'a' and 'b' objects using the
// 'swap' method found by ADL (Argument Dependent Lookup). The behavior
// is undefined unless 'a' and 'b' were created with the same allocator.
{
using namespace bsl;
swap(a, b);
}
// The following 'using' directives must come *after* the definition of
// 'invokeAdlSwap' (above).
using namespace BloombergLP;
using namespace bsl;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// The object under test is a container whose interface and contract is
// dictated by the C++ standard. The general concerns are compliance,
// exception safety, and proper dispatching (for member function templates such
// as assign and insert). This container is implemented in the form of a class
// template, and thus its proper instantiation for several types is a concern.
// Regarding the allocator template argument, we use mostly a 'bsl::allocator'
// together with a 'bslma::TestAllocator' mechanism, but we also verify the C++
// standard.
//
// The Primary Manipulators and Basic Accessors are decided to be:
//
// Primary Manipulators:
//: o 'push'
//: o 'pop
//
// Basic Accessors:
//: o 'empty'
//: o 'size'
//: o 'top'
//
// This test plan follows the standard approach for components implementing
// value-semantic containers. We have chosen as *primary* *manipulators* the
// 'push' and 'pop' methods to be used by the generator functions 'g' and
// 'gg'. Note that some manipulators must support aliasing, and those that
// perform memory allocation must be tested for exception neutrality via the
// 'bslma::TestAllocator' component. After the mandatory sequence of cases
// (1--10) for value-semantic types (cases 5 and 10 are not implemented, as
// there is not output or streaming below bslstl), we test each individual
// constructor, manipulator, and accessor in subsequent cases.
//
// Certain standard value-semantic-type test cases are omitted:
//: o BSLX streaming is not (yet) implemented for this class.
//
// Global Concerns:
//: o The test driver is robust w.r.t. reuse in other, similar components.
//: o ACCESSOR methods are declared 'const'.
//: o CREATOR & MANIPULATOR pointer/reference parameters are declared 'const'.
//: o No memory is ever allocated from the global allocator.
//: o Any allocated memory is always from the object allocator.
//: o An object's value is independent of the allocator used to supply memory.
//: o Injected exceptions are safely propagated during memory allocation.
//: o Precondition violations are detected in appropriate build modes.
//
// Global Assumptions:
//: o All explicit memory allocations are presumed to use the global, default,
//: or object allocator.
//: o ACCESSOR methods are 'const' thread-safe.
//: o Individual attribute types are presumed to be *alias-safe*; hence, only
//: certain methods require the testing of this property:
//: o copy-assignment
//: o swap
// ----------------------------------------------------------------------------
// CREATORS
// [ 7] copy c'tor
// [ 2] stack, stack(bslma::Allocator *bA)
// [17] stack(MovableRef container)
// [17] stack(MovableRef container, bslma::Allocator *bA)
// [17] stack(MovableRef stack)
// [17] stack(MovableRef stack, bslma::Allocator *bA)
//
// MANIPULATORS
// [ 9] operator=
// [18] operator=(MovableRef stack)
// [ 8] member swap
// [ 2] Primary Manipulators -- push and pop
// [18] push(MovableRef value)
// [18] emplace(Args&&.. args)
//
// ACCESSORS
// [15] testing empty, size
// [ 4] Primary Accessors
//
// FREE FUNCTIONS
// [12] inequality comparisons: '<', '>', '<=', '>='
// [ 6] equality comparisons: '==', '!='
// [ 5] operator<< (N/A)
// ----------------------------------------------------------------------------
// [16] Usage Example
// [14] testing simple container that does not support allocators
// [13] testing container override of specified 'VALUE'
// [11] type traits
// [10] allocator
// [ 3] Primary generator functions 'gg' and 'ggg'
// [ 1] Breathing Test
// [19] CONCERN: Methods qualifed 'noexcept' in standard are so implemented.
//
// ============================================================================
// STANDARD BDE ASSERT TEST MACROS
// ----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
namespace {
int testStatus = 0;
void aSsErT(bool b, const char *s, int i)
{
if (b) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
} // close unnamed namespace
//=============================================================================
// STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
// ============================================================================
// PRINTF FORMAT MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU
// ============================================================================
// GLOBAL TEST VALUES
// ----------------------------------------------------------------------------
static bool verbose;
static bool veryVerbose;
static bool veryVeryVerbose;
static bool veryVeryVeryVerbose;
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
// Define DEFAULT DATA used in multiple test cases.
static const size_t DEFAULT_MAX_LENGTH = 32;
struct DefaultDataRow {
int d_line; // source line number
const char *d_spec; // specification string, for input to 'gg' function
const char *d_results; // expected element values
};
static
const DefaultDataRow DEFAULT_DATA[] = {
//line spec results
//---- -------- -------
{ L_, "", "" },
{ L_, "A", "A" },
{ L_, "AA", "A" },
{ L_, "B", "B" },
{ L_, "AB", "AB" },
{ L_, "BA", "AB" },
{ L_, "AC", "AC" },
{ L_, "CD", "CD" },
{ L_, "ABC", "ABC" },
{ L_, "ACB", "ABC" },
{ L_, "BAC", "ABC" },
{ L_, "BCA", "ABC" },
{ L_, "CAB", "ABC" },
{ L_, "CBA", "ABC" },
{ L_, "BAD", "ABD" },
{ L_, "ABCA", "ABC" },
{ L_, "ABCB", "ABC" },
{ L_, "ABCC", "ABC" },
{ L_, "ABCABC", "ABC" },
{ L_, "AABBCC", "ABC" },
{ L_, "ABCD", "ABCD" },
{ L_, "ACBD", "ABCD" },
{ L_, "BDCA", "ABCD" },
{ L_, "DCBA", "ABCD" },
{ L_, "BEAD", "ABDE" },
{ L_, "BCDE", "BCDE" },
{ L_, "ABCDE", "ABCDE" },
{ L_, "ACBDE", "ABCDE" },
{ L_, "CEBDA", "ABCDE" },
{ L_, "EDCBA", "ABCDE" },
{ L_, "FEDCB", "BCDEF" },
{ L_, "FEDCBA", "ABCDEF" },
{ L_, "ABCDEFG", "ABCDEFG" },
{ L_, "ABCDEFGH", "ABCDEFGH" },
{ L_, "ABCDEFGHI", "ABCDEFGHI" },
{ L_, "ABCDEFGHIJKLMNOP", "ABCDEFGHIJKLMNOP" },
{ L_, "PONMLKJIGHFEDCBA", "ABCDEFGHIJKLMNOP" },
{ L_, "ABCDEFGHIJKLMNOPQ", "ABCDEFGHIJKLMNOPQ" },
{ L_, "DHBIMACOPELGFKNJQ", "ABCDEFGHIJKLMNOPQ" }
};
static const int DEFAULT_NUM_DATA = sizeof DEFAULT_DATA / sizeof *DEFAULT_DATA;
typedef bslmf::MovableRefUtil MoveUtil;
//=============================================================================
// GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------
#ifndef BSLS_PLATFORM_OS_WINDOWS
# define TEST_TYPES_REGULAR(containerArg) \
containerArg<signed char>, \
containerArg<size_t>, \
containerArg<bsltf::TemplateTestFacility::ObjectPtr>, \
containerArg<bsltf::TemplateTestFacility::FunctionPtr>, \
containerArg<bsltf::TemplateTestFacility::MethodPtr>, \
containerArg<bsltf::EnumeratedTestType::Enum>, \
containerArg<bsltf::UnionTestType>, \
containerArg<bsltf::SimpleTestType>, \
containerArg<bsltf::AllocTestType>, \
containerArg<bsltf::BitwiseMoveableTestType>, \
containerArg<bsltf::AllocBitwiseMoveableTestType>, \
containerArg<bsltf::NonTypicalOverloadsTestType>
#else
# define TEST_TYPES_REGULAR(containerArg) \
containerArg<signed char>, \
containerArg<size_t>, \
containerArg<bsltf::TemplateTestFacility::ObjectPtr>, \
containerArg<bsltf::TemplateTestFacility::MethodPtr>, \
containerArg<bsltf::EnumeratedTestType::Enum>, \
containerArg<bsltf::UnionTestType>, \
containerArg<bsltf::SimpleTestType>, \
containerArg<bsltf::AllocTestType>, \
containerArg<bsltf::BitwiseMoveableTestType>, \
containerArg<bsltf::AllocBitwiseMoveableTestType>, \
containerArg<bsltf::NonTypicalOverloadsTestType>
#endif
#define TEST_TYPES_INEQUAL_COMPARABLE(containerArg) \
containerArg<signed char>, \
containerArg<size_t>, \
containerArg<bsltf::TemplateTestFacility::ObjectPtr>, \
containerArg<bsltf::EnumeratedTestType::Enum>
#define TEST_TYPES_MOVABLE(containerArg) \
containerArg<bsltf::MovableTestType>, \
containerArg<bsltf::MovableAllocTestType>
namespace bsl {
// stack-specific print function.
template <class VALUE, class CONTAINER>
void debugprint(const bsl::stack<VALUE, CONTAINER>& s)
{
if (s.empty()) {
printf("<empty>");
}
else {
printf("size: %d, top: ", (int)s.size());
bsls::BslTestUtil::callDebugprint(static_cast<char>(
bsltf::TemplateTestFacility::getIdentifier(s.top())));
}
fflush(stdout);
}
} // close namespace bsl
template <class VALUE>
struct NonAllocCont {
// PUBLIC TYPES
typedef VALUE value_type;
typedef VALUE& reference;
typedef const VALUE& const_reference;
typedef std::size_t size_type;
private:
// DATA
bsl::vector<VALUE> d_vector;
public:
// CREATORS
NonAllocCont() : d_vector(&bslma::MallocFreeAllocator::singleton()) {}
~NonAllocCont() {}
// MANIPULATORS
NonAllocCont& operator=(const NonAllocCont& rhs)
{
d_vector = rhs.d_vector;
return *this;
}
reference back() { return d_vector.back(); }
void pop_back() { d_vector.pop_back(); }
void push_back(const value_type& value) { d_vector.push_back(value); }
bsl::vector<value_type>& contents() { return d_vector; }
// ACCESSORS
bool operator==(const NonAllocCont& rhs) const
{
return d_vector == rhs.d_vector;
}
bool operator!=(const NonAllocCont& rhs) const
{
return !operator==(rhs);
}
bool operator<(const NonAllocCont& rhs) const
{
return d_vector < rhs.d_vector;
}
bool operator>=(const NonAllocCont& rhs) const
{
return !operator<(rhs);
}
bool operator>(const NonAllocCont& rhs) const
{
return d_vector > rhs.d_vector;
}
bool operator<=(const NonAllocCont& rhs) const
{
return !operator>(rhs);
}
const_reference back() const { return d_vector.back(); }
size_type size() const { return d_vector.size(); }
};
namespace std {
template <class VALUE>
void swap(NonAllocCont<VALUE>& lhs, NonAllocCont<VALUE>& rhs)
{
lhs.contents().swap(rhs.contents());
}
} // close namespace std
template <class VALUE>
struct ValueName {
private:
// NOT IMPLEMENTED
static const char *name();
// Not implemented, so that an attempt to show the name of an
// unrecognized type will result in failure to link.
};
template <>
struct ValueName<signed char> {
static const char *name() { return "signed char"; }
};
template <>
struct ValueName<size_t> {
static const char *name() { return "size_t"; }
};
template <>
struct ValueName<bsltf::TemplateTestFacility::ObjectPtr> {
static const char *name() { return "TemplateTestFacility::ObjectPtr"; }
};
template <>
struct ValueName<bsltf::TemplateTestFacility::FunctionPtr> {
static const char *name() { return "TemplateTestFacility::FunctionPtr"; }
};
template <>
struct ValueName<bsltf::TemplateTestFacility::MethodPtr> {
static const char *name() { return "TemplateTestFacility::MethodPtr"; }
};
template <>
struct ValueName<bsltf::EnumeratedTestType::Enum> {
static const char *name() { return "EnumeratedTestType::Enum"; }
};
template <>
struct ValueName<bsltf::UnionTestType> {
static const char *name() { return "UnionTestType"; }
};
template <>
struct ValueName<bsltf::SimpleTestType> {
static const char *name() { return "SimpleTestType"; }
};
template <>
struct ValueName<bsltf::AllocTestType> {
static const char *name() { return "AllocTestType"; }
};
template <>
struct ValueName<bsltf::BitwiseMoveableTestType> {
static const char *name() { return "BitwiseMoveableTestType"; }
};
template <>
struct ValueName<bsltf::AllocBitwiseMoveableTestType> {
static const char *name() { return "AllocBitwiseMoveableTestType"; }
};
template <>
struct ValueName<bsltf::NonTypicalOverloadsTestType> {
static const char *name() { return "NonTypicalOverloadsTestType"; }
};
template <class CONTAINER>
struct ContainerName {
static const char *name();
};
template <class VALUE>
struct ContainerName<deque<VALUE> > {
static const char *name()
{
static char buf[1000];
strcpy(buf, "deque<");
strcat(buf, ValueName<VALUE>::name());
strcat(buf, ">");
return buf;
}
};
template <class VALUE>
struct ContainerName<vector<VALUE> > {
static const char *name()
{
static char buf[1000];
strcpy(buf, "vector<");
strcat(buf, ValueName<VALUE>::name());
strcat(buf, ">");
return buf;
}
};
bool expectToAllocate(int n)
// Return 'true' if the container is expected to allocate memory on the
// specified 'n'th element, and 'false' otherwise.
{
if (n > 32) {
return (0 == n % 32); // RETURN
}
return (((n - 1) & n) == 0); // Allocate when 'n' is a power of 2
}
template<class CONTAINER, class VALUES>
void emptyNVerifyStack(stack<typename CONTAINER::value_type,
CONTAINER> *pmX,
const VALUES& expectedValues,
size_t expectedSize,
const int LINE)
// Verify the specified 'container' has the specified 'expectedSize' and
// contains the same values as the array in the specified 'expectedValues'.
// Return 0 if 'container' has the expected values, and a non-zero value
// otherwise.
{
const char *cont = ContainerName<CONTAINER>::name();
const char *val = ValueName<typename CONTAINER::value_type>::name();
ASSERTV(cont, val, LINE, expectedSize, pmX->size(),
expectedSize == pmX->size());
if (expectedSize != pmX->size()) {
return; // RETURN
}
for (int i = static_cast<int>(expectedSize) - 1; i >= 0; --i) {
if (expectedValues[i] != pmX->top()) P_(cont);
ASSERTV(val, i, LINE, expectedValues[i], pmX->top(),
expectedValues[i] == pmX->top());
pmX->pop();
}
}
template<class CONTAINER, class VALUES>
void verifyStack(const stack<typename CONTAINER::value_type,
CONTAINER>& X,
const VALUES& expectedValues,
size_t expectedSize,
const int LINE,
bslma::Allocator *allocator = 0)
{
stack<typename CONTAINER::value_type, CONTAINER>
copyX(X, bslma::Default::allocator(allocator));
emptyNVerifyStack(©X, expectedValues, expectedSize, LINE);
}
// ----------------------------------------------------------------------------
// HELPERS: "Called Method" Classes: 'NonMovableVector' and 'MovableVector'
// ----------------------------------------------------------------------------
enum CalledMethod
// Enumerations used to indicate if appropriate special container's method
// has been invoked.
{
e_NONE = 0
, e_CTOR_DFT_SANS_ALLOC = 1 << 0
, e_CTOR_DFT_AVEC_ALLOC = 1 << 1
, e_CTOR_CPY_SANS_ALLOC = 1 << 3
, e_CTOR_CPY_AVEC_ALLOC = 1 << 4
, e_CTOR_MOV_SANS_ALLOC = 1 << 5
, e_CTOR_MOV_AVEC_ALLOC = 1 << 6
, e_ASSIGN_CREF = 1 << 7
, e_ASSIGN_MOVE = 1 << 8
, e_PUSH_BACK_CREF = 1 << 9
, e_PUSH_BACK_MOVE = 1 << 10
, e_EMPLACE_0 = 1 << 11
, e_EMPLACE_1 = 1 << 12
, e_EMPLACE_2 = 1 << 13
, e_EMPLACE_3 = 1 << 14
, e_EMPLACE_4 = 1 << 15
, e_EMPLACE_5 = 1 << 16
, e_EMPLACE_6 = 1 << 17
, e_EMPLACE_7 = 1 << 18
, e_EMPLACE_8 = 1 << 19
, e_EMPLACE_9 = 1 << 20
, e_EMPLACE_A = 1 << 21
};
void debugprint(enum CalledMethod calledMethod)
{
const char *ascii;
#define CASE(X) case(e_ ## X): ascii = #X; break;
switch (calledMethod) {
CASE(NONE)
CASE(CTOR_DFT_SANS_ALLOC)
CASE(CTOR_DFT_AVEC_ALLOC)
CASE(CTOR_CPY_SANS_ALLOC)
CASE(CTOR_CPY_AVEC_ALLOC)
CASE(CTOR_MOV_SANS_ALLOC)
CASE(CTOR_MOV_AVEC_ALLOC)
CASE(ASSIGN_CREF)
CASE(ASSIGN_MOVE)
CASE(PUSH_BACK_CREF)
CASE(PUSH_BACK_MOVE)
CASE(EMPLACE_0)
CASE(EMPLACE_1)
CASE(EMPLACE_2)
CASE(EMPLACE_3)
CASE(EMPLACE_4)
CASE(EMPLACE_5)
CASE(EMPLACE_6)
CASE(EMPLACE_7)
CASE(EMPLACE_8)
CASE(EMPLACE_9)
CASE(EMPLACE_A)
default: ascii = "(* UNKNOWN *)";
}
#undef CASE
printf("%s", ascii);
}
inline CalledMethod operator|=(CalledMethod& lhs, CalledMethod rhs)
// Bitwise OR the values of the specified 'lhs' and 'rhs' flags, and return
// the resulting value.
{
lhs = static_cast<CalledMethod>(
static_cast<int>(lhs) | static_cast<int>(rhs));
return lhs;
}
CalledMethod g_calledMethodFlag; // global variable, that stores information
// about called methods for special
// containers 'NonMovableVector' and
// 'MovableVector'.
void setupCalledMethodCheck()
// Reset 'g_calledMethodFlag' global variable's value.
{
g_calledMethodFlag = e_NONE;
}
enum CalledMethod getCalledMethod()
{
return g_calledMethodFlag;
}
// ======================
// class NonMovableVector
// ======================
template <class VALUE, class ALLOCATOR>
class NonMovableVector;
template<class VALUE, class ALLOCATOR>
bool operator==(const NonMovableVector<VALUE, ALLOCATOR>& lhs,
const NonMovableVector<VALUE, ALLOCATOR>& rhs);
template <class VALUE, class ALLOCATOR = bsl::allocator<VALUE> >
class NonMovableVector {
// This class is a value-semantic class template, acting as a transparent
// proxy for the underlying 'bsl::vector' container, that holds elements of
// the (template parameter) 'VALUE', and recording in the global variable
// 'g_calledMethodFlag' methods being invoked. The information recorded is
// used to verify that 'stack' invokes expected container methods.
// DATA
bsl::vector<VALUE> d_vector; // container for it's behaviour simulation
// FRIENDS
friend bool operator==<VALUE, ALLOCATOR>(const NonMovableVector& lhs,
const NonMovableVector& rhs);
public:
// CLASS METHODS
static int GGG(NonMovableVector *object,
const char *spec,
int verbose = 1);
static NonMovableVector GG(NonMovableVector *object,
const char *spec);
// PUBLIC TYPES
typedef ALLOCATOR allocator_type;
typedef VALUE value_type;
typedef VALUE& reference;
typedef const VALUE& const_reference;
typedef std::size_t size_type;
typedef VALUE *iterator;
typedef const VALUE *const_iterator;
// CREATORS
NonMovableVector()
: d_vector()
// Create an empty vector. Method invocation is recorded.
{
g_calledMethodFlag |= e_CTOR_DFT_SANS_ALLOC;
}
NonMovableVector(const ALLOCATOR& basicAllocator)
: d_vector(basicAllocator)
// Create an empty vector, using the specified 'basicAllocator' to
// supply memory. Method invocation is recorded.
{
g_calledMethodFlag |= e_CTOR_DFT_AVEC_ALLOC;
}
NonMovableVector(const NonMovableVector& original)
// Create a vector that has the same value as the specified 'original'
// vector. Method invocation is recorded.
: d_vector(original.d_vector)
{
g_calledMethodFlag |= e_CTOR_CPY_SANS_ALLOC;
}
NonMovableVector(const NonMovableVector& original,
const ALLOCATOR& basicAllocator)
// Create a vector that has the same value as the specified 'original'
// vector, using the specified 'basicAllocator' to supply memory.
// Method invocation is recorded.
: d_vector(original.d_vector, basicAllocator)
{
g_calledMethodFlag |= e_CTOR_CPY_AVEC_ALLOC;
}
// MANIPULATORS
NonMovableVector& operator=(const NonMovableVector& rhs)
// Assign to this vector the value of the specified 'other' vector and
// return a reference to this modifiable vector. Method invocation is
// recorded.
{
d_vector = rhs.d_vector;
g_calledMethodFlag |= e_ASSIGN_CREF;
return *this;
}
void pop_back()
// Erase the last element from this vector.
{
d_vector.pop_back();
}
void push_back(const value_type& value)
// Append a copy of the specified 'value' at the end of this vector.
// Method invocation is recorded.
{
g_calledMethodFlag |= e_PUSH_BACK_CREF;
d_vector.push_back(value);
}
template <class INPUT_ITER>
iterator insert(const_iterator position,
INPUT_ITER first,
INPUT_ITER last)
// Insert at the specified 'position' in this vector the values in
// the range starting at the specified 'first' and ending
// immediately before the specified 'last' iterators of the
// (template parameter) type 'INPUT_ITER', and return an iterator
// to the first newly inserted element.
{
return d_vector.insert(position, first, last);
}
iterator begin()
// Return an iterator pointing the first element in this modifiable
// vector (or the past-the-end iterator if this vector is empty).
{
return d_vector.begin();
}
iterator end()
// Return the past-the-end iterator for this modifiable vector.
{
return d_vector.end();
}
reference front()
// Return a reference to the modifiable element at the first position
// in this vector. The behavior is undefined if this vector is empty.
{
return d_vector.front();
}
reference back()
// Return a reference to the modifiable element at the last position in
// this vector. The behavior is undefined if this vector is empty.
{
return d_vector.back();
}
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class... Args> void emplace_back(Args&&... arguments)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the specified 'arguments'. Note that this method is written only
// for testing purposes, it DOESN'T simulate standard vector behavior
// and requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
int argumentsNumber = sizeof...(arguments);
g_calledMethodFlag |= static_cast<CalledMethod>(
static_cast<int>(e_EMPLACE_0) << argumentsNumber);
d_vector.push_back(value_type(1));
}
#elif BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
inline
void emplace_back()
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter. Note that
// this method is written only for testing purposes, it DOESN'T
// simulate standard vector behavior and requires that the (template
// parameter) type 'VALUE_TYPE' has constructor, accepting integer
// value as a parameter. Method invocation is recorded.
{
g_calledMethodFlag |= e_EMPLACE_0;
d_vector.push_back(value_type(1));
}
template <class Args_01>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed argument. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
g_calledMethodFlag |= e_EMPLACE_1;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
g_calledMethodFlag |= e_EMPLACE_2;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
g_calledMethodFlag |= e_EMPLACE_3;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
g_calledMethodFlag |= e_EMPLACE_4;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
g_calledMethodFlag |= e_EMPLACE_5;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
g_calledMethodFlag |= e_EMPLACE_6;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
g_calledMethodFlag |= e_EMPLACE_7;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
g_calledMethodFlag |= e_EMPLACE_8;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
(void)args_09;
g_calledMethodFlag |= e_EMPLACE_9;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) args_10)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
(void)args_09;
(void)args_10;
g_calledMethodFlag |= e_EMPLACE_A;
d_vector.push_back(value_type(1));
}
#else
template <class... Args> void emplace_back(
BSLS_COMPILERFEATURES_FORWARD_REF(Args)... arguments)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the specified 'arguments'. Note that this method is written only
// for testing purposes, it DOESN'T simulate standard vector behavior
// and requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
int argumentsNumber = sizeof...(arguments);
g_calledMethodFlag |= static_cast<CalledMethod>(
static_cast<int>(e_EMPLACE_0) << argumentsNumber);
d_vector.push_back(value_type(1));
}
#endif
// ACCESSORS
const_iterator begin() const
// Return an iterator pointing the first element in this non-modifiable
// vector (or the past-the-end iterator if this vector is empty).
{
return d_vector.begin();
}
const_iterator end() const
// Return the past-the-end iterator for this non-modifiable vector.
{
return d_vector.end();
}
const_reference front() const
// Return a reference to the non-modifiable element at the first
// position in this vector. The behavior is undefined if this vector
// is empty.
{
return d_vector.front();
}
const_reference back() const
// Return a reference to the non-modifiable element at the last
// position in this vector. The behavior is undefined if this vector
// is empty.
{
return d_vector.back();
}
size_type size() const
// Return the number of elements in this vector.
{
return d_vector.size();
}
bool empty() const
// Return 'true' if this vector has size 0, and 'false' otherwise.
{
return d_vector.empty();
}
};
// ----------------------
// class NonMovableVector
// ----------------------
// CLASS METHODS
template <class CONTAINER>
class TestDriver;
template <class VALUE, class ALLOCATOR>
int NonMovableVector<VALUE, ALLOCATOR>::
GGG(NonMovableVector *object,
const char *spec,
int verbose)
{
bslma::DefaultAllocatorGuard guard(
&bslma::NewDeleteAllocator::singleton());
typename TestDriver<NonMovableVector>::TestValues VALUES;
enum { SUCCESS = -1 };
for (int i = 0; spec[i]; ++i) {
if ('A' <= spec[i] && spec[i] <= 'Z') {
object->push_back(VALUES[spec[i] - 'A']);
}
else {
if (verbose) {
printf("Error, bad character ('%c') "
"in spec \"%s\" at position %d.\n", spec[i], spec, i);
}
// Discontinue processing this spec.
return i; // RETURN
}
}
return SUCCESS;
}
template <class VALUE, class ALLOCATOR>
NonMovableVector<VALUE, ALLOCATOR>
NonMovableVector<VALUE, ALLOCATOR>::
GG(NonMovableVector *object, const char *spec)
{
ASSERTV(GGG(object, spec) < 0);
return *object;
}
// FREE OPERATORS
template<class VALUE, class ALLOCATOR>
bool operator==(const NonMovableVector<VALUE, ALLOCATOR>& lhs,
const NonMovableVector<VALUE, ALLOCATOR>& rhs)
{
return lhs.d_vector == rhs.d_vector;
}
// ===================
// class MovableVector
// ===================
template <class VALUE, class ALLOCATOR>
class MovableVector;
template<class VALUE, class ALLOCATOR>
bool operator==(const MovableVector<VALUE, ALLOCATOR>& lhs,
const MovableVector<VALUE, ALLOCATOR>& rhs);
template <class VALUE, class ALLOCATOR = bsl::allocator<VALUE> >
class MovableVector
{
// TBD
//
// This class is a value-semantic class template, acting as a transparent
// proxy for the underlying 'bsl::vector' container, that holds elements of
// the (template parameter) 'VALUE', and recording in the global variable
// 'g_calledMethodFlag' methods being invoked. The information recorded is
// used to verify that 'stack' invokes expected container methods.
private:
// DATA
bsl::vector<VALUE> d_vector; // provides required behavior
// FRIENDS
friend bool operator==<VALUE, ALLOCATOR>(
const MovableVector<VALUE, ALLOCATOR>& lhs,
const MovableVector<VALUE, ALLOCATOR>& rhs);
public:
// CLASS METHODS
static int GGG(MovableVector *object,
const char *spec,
int verbose = 1);
static MovableVector GG(MovableVector *object,
const char *spec);
// PUBLIC TYPES
typedef ALLOCATOR allocator_type;
typedef VALUE value_type;
typedef VALUE& reference;
typedef const VALUE& const_reference;
typedef std::size_t size_type;
typedef VALUE* iterator;
typedef const VALUE* const_iterator;
// CREATORS
MovableVector()
: d_vector()
// Create an empty vector. Method invocation is recorded.
{
g_calledMethodFlag |= e_CTOR_DFT_SANS_ALLOC;
}
MovableVector(const ALLOCATOR& basicAllocator)
: d_vector( basicAllocator)
// Create an empty vector, using the specified 'basicAllocator' to
// supply memory. Method invocation is recorded.
{
g_calledMethodFlag |= e_CTOR_DFT_AVEC_ALLOC;
}
MovableVector(const MovableVector& original)
// Create a vector that has the same value as the specified 'original'
// vector. Method invocation is recorded.
: d_vector(original.d_vector)
{
g_calledMethodFlag |= e_CTOR_CPY_SANS_ALLOC;
}
MovableVector(bslmf::MovableRef<MovableVector> original)
// Create a vector that has the same value as the specified 'original'
// vector. Method invocation is recorded.
: d_vector(MoveUtil::move(MoveUtil::access(original).d_vector))
{
g_calledMethodFlag |= e_CTOR_MOV_SANS_ALLOC;
}
MovableVector(const MovableVector& original,
const ALLOCATOR& basicAllocator)
// Create a vector that has the same value as the specified 'original'
// vector, using the specified 'basicAllocator' to supply memory.
// Method invocation is recorded.
: d_vector(original.d_vector, basicAllocator)
{
g_calledMethodFlag |= e_CTOR_CPY_AVEC_ALLOC;
}
MovableVector(bslmf::MovableRef<MovableVector> original,
const ALLOCATOR& basicAllocator)
// Create a vector that has the same value as the specified 'original'
// vector, using the specified 'basicAllocator' to supply memory.
// Method invocation is recorded.
: d_vector(MoveUtil::move(MoveUtil::access(original).d_vector),
basicAllocator)
{
g_calledMethodFlag |= e_CTOR_MOV_AVEC_ALLOC;
}
// MANIPULATORS
MovableVector& operator=(const MovableVector& rhs)
// Assign to this vector the value of the specified 'other' vector and
// return a reference to this modifiable vector. Method invocation is
// recorded.
{
g_calledMethodFlag |= e_ASSIGN_CREF;
d_vector = rhs.d_vector;
return *this;
}
MovableVector& operator=(bslmf::MovableRef<MovableVector> rhs)
// Assign to this vector the value of the specified 'other' vector and
// return a reference to this modifiable vector. Method invocation is
// recorded.
{
g_calledMethodFlag |= e_ASSIGN_MOVE;
d_vector = MoveUtil::move(MoveUtil::access(rhs).d_vector);
return *this;
}
void pop_back()
// Erase the last element from this vector.
{
d_vector.pop_back();
}
void push_back(const value_type& value)
// Append a copy of the specified 'value' at the end of this vector.
// Method invocation is recorded.
{
g_calledMethodFlag |= e_PUSH_BACK_CREF;
d_vector.push_back(value);
}
void push_back(bslmf::MovableRef<value_type> value)
// Append a copy of the specified 'value' at the end of this vector.
// Method invocation is recorded.
{
g_calledMethodFlag |= e_PUSH_BACK_MOVE;
d_vector.push_back(MoveUtil::move(value));
}
template <class INPUT_ITER>
iterator insert(const_iterator position,
INPUT_ITER first,
INPUT_ITER last)
// Insert at the specified 'position' in this vector the values in
// the range starting at the specified 'first' and ending
// immediately before the specified 'last' iterators of the
// (template parameter) type 'INPUT_ITER', and return an iterator
// to the first newly inserted element.
{
return d_vector.insert(position, first, last);
}
iterator begin()
// Return an iterator pointing the first element in this modifiable
// vector (or the past-the-end iterator if this vector is empty).
{
return d_vector.begin(); }
iterator end()
// Return the past-the-end iterator for this modifiable vector.
{
return d_vector.end();
}
reference front()
// Return a reference to the modifiable element at the first position
// in this vector. The behavior is undefined if this vector is empty.
{
return d_vector.front();
}
reference back()
// Return a reference to the modifiable element at the last position in
// this vector. The behavior is undefined if this vector is empty.
{
return d_vector.back();
}
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class... Args> void emplace_back(Args&&... arguments)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the specified 'arguments'. Note that this method is written only
// for testing purposes, it DOESN'T simulate standard vector behavior
// and requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
int argumentsNumber = sizeof...(arguments);
g_calledMethodFlag |= static_cast<CalledMethod>(
static_cast<int>(e_EMPLACE_0) << argumentsNumber);
d_vector.push_back(value_type(1));
}
#elif BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
inline
void emplace_back()
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter. Note that
// this method is written only for testing purposes, it DOESN'T
// simulate standard vector behavior and requires that the (template
// parameter) type 'VALUE_TYPE' has constructor, accepting integer
// value as a parameter. Method invocation is recorded.
{
g_calledMethodFlag |= e_EMPLACE_0;
d_vector.push_back(value_type(1));
}
template <class Args_01>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed argument. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
g_calledMethodFlag |= e_EMPLACE_1;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
g_calledMethodFlag |= e_EMPLACE_2;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
g_calledMethodFlag |= e_EMPLACE_3;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
g_calledMethodFlag |= e_EMPLACE_4;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
g_calledMethodFlag |= e_EMPLACE_5;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
g_calledMethodFlag |= e_EMPLACE_6;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
g_calledMethodFlag |= e_EMPLACE_7;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
g_calledMethodFlag |= e_EMPLACE_8;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
(void)args_09;
g_calledMethodFlag |= e_EMPLACE_9;
d_vector.push_back(value_type(1));
}
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
inline
void emplace_back(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) args_10)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the passed arguments. Note that this method is written only for
// testing purposes, it DOESN'T simulate standard vector behavior and
// requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
// Compiler warnings suppression.
(void)args_01;
(void)args_02;
(void)args_03;
(void)args_04;
(void)args_05;
(void)args_06;
(void)args_07;
(void)args_08;
(void)args_09;
(void)args_10;
g_calledMethodFlag |= e_EMPLACE_A;
d_vector.push_back(value_type(1));
}
#else
template <class... Args> void emplace_back(
BSLS_COMPILERFEATURES_FORWARD_REF(Args)... arguments)
// Append to the end of this vector a newly created 'value_type'
// object, constructed with integer literal as a parameter, despite of
// the specified 'arguments'. Note that this method is written only
// for testing purposes, it DOESN'T simulate standard vector behavior
// and requires that the (template parameter) type 'VALUE_TYPE' has
// constructor, accepting integer value as a parameter. Method
// invocation is recorded.
{
int argumentsNumber = sizeof...(arguments);
g_calledMethodFlag |= static_cast<CalledMethod>(
static_cast<int>(e_EMPLACE_0) << argumentsNumber);
d_vector.push_back(value_type(1));
}
#endif
// ACCESSORS
const_iterator begin() const
// Return an iterator pointing the first element in this non-modifiable
// vector (or the past-the-end iterator if this vector is empty).
{
return d_vector.begin();
}
const_iterator end() const
// Return the past-the-end iterator for this non-modifiable vector.
{
return d_vector.end();
}
const_reference front() const
// Return a reference to the non-modifiable element at the first
// position in this vector. The behavior is undefined if this vector
// is empty.
{
return d_vector.front();
}
const_reference back() const
// Return a reference to the non-modifiable element at the last
// position in this vector. The behavior is undefined if this vector
// is empty.
{
return d_vector.back();
}
size_type size() const
// Return the number of elements in this vector.
{
return d_vector.size();
}
bool empty() const
// Return 'true' if this vector has size 0, and 'false' otherwise.
{
return d_vector.empty();
}
};
// -------------------
// class MovableVector
// -------------------
// CLASS METHODS
template <class CONTAINER>
class TestDriver;
template <class VALUE, class ALLOCATOR>
int MovableVector<VALUE, ALLOCATOR>::
GGG(MovableVector *object,
const char *spec,
int verbose)
{
bslma::DefaultAllocatorGuard guard(
&bslma::NewDeleteAllocator::singleton());
typename TestDriver<MovableVector>::TestValues VALUES;
enum { SUCCESS = -1 };
for (int i = 0; spec[i]; ++i) {
if ('A' <= spec[i] && spec[i] <= 'Z') {
object->push_back(VALUES[spec[i] - 'A']);
}
else {
if (verbose) {
printf("Error, bad character ('%c') "
"in spec \"%s\" at position %d.\n", spec[i], spec, i);
}
// Discontinue processing this spec.
return i; // RETURN
}
}
return SUCCESS;
}
template <class VALUE, class ALLOCATOR>
MovableVector<VALUE, ALLOCATOR>
MovableVector<VALUE, ALLOCATOR>::
GG(MovableVector *object, const char *spec)
{
ASSERTV(GGG(object, spec) < 0);
return *object;
}
// FREE OPERATORS
template<class VALUE, class ALLOCATOR>
bool operator==(const MovableVector<VALUE, ALLOCATOR>& lhs,
const MovableVector<VALUE, ALLOCATOR>& rhs)
{
return lhs.d_vector == rhs.d_vector;
}
// ==========================
// class StatefulStlAllocator
// ==========================
template <class VALUE>
class StatefulStlAllocator : public bsltf::StdTestAllocator<VALUE>
// This class implements a standard compliant allocator that has an
// attribute, 'id'.
{
// DATA
int d_id; // identifier
private:
// TYPES
typedef bsltf::StdTestAllocator<VALUE> StlAlloc;
// Alias for the base class.
public:
template <class OTHER_TYPE>
struct rebind {
// This nested 'struct' template, parameterized by some 'OTHER_TYPE',
// provides a namespace for an 'other' type alias, which is an
// allocator type following the same template as this one but that
// allocates elements of 'OTHER_TYPE'. Note that this allocator type
// is convertible to and from 'other' for any 'OTHER_TYPE' including
// 'void'.
typedef StatefulStlAllocator<OTHER_TYPE> other;
};
// CREATORS
StatefulStlAllocator()
// Create a 'StatefulStlAllocator' object.
: StlAlloc()
{
}
//! StatefulStlAllocator(const StatefulStlAllocator& original) = default;
// Create a 'StatefulStlAllocator' object having the same id as the
// specified 'original'.
template <class OTHER_TYPE>
StatefulStlAllocator(const StatefulStlAllocator<OTHER_TYPE>& original)
// Create a 'StatefulStlAllocator' object having the same id as the
// specified 'original' with a different template type.
: StlAlloc(original)
, d_id(original.id())
{
}
// MANIPULATORS
void setId(int value)
// Set the 'id' attribute of this object to the specified 'value'.
{
d_id = value;
}
// ACCESSORS
int id() const
// Return the value of the 'id' attribute of this object.
{
return d_id;
}
};
template <class T>
struct SpecialContainerTrait
// A class should declare this trait if it registers it's methods
// invocation in 'g_calledMethodFlag' global variable.
{
static const bool is_special_container = false;
};
template <class T>
struct SpecialContainerTrait<NonMovableVector<T> >
{
static const bool is_special_container = true;
};
template <class T>
struct SpecialContainerTrait<MovableVector<T> >
{
static const bool is_special_container = true;
};
template <class CONTAINER>
bool isCalledMethodCheckPassed(CalledMethod flag)
// Return 'true' if global variable 'g_calledMethodFlag' has the same value
// as the specified 'flag', and 'false' otherwise. Note that this check is
// performed only for special containers, defined above. Function always
// returns 'true' for all other classes.
{
if (SpecialContainerTrait<CONTAINER>::is_special_container) {
return flag == g_calledMethodFlag;
}
return true;
}
//=============================================================================
// USAGE EXAMPLE
//=============================================================================
// Suppose a husband wants to keep track of chores his wife has asked him to
// do. Over the years of being married, he has noticed that his wife generally
// wants the most recently requested task done first. If she has a new task in
// mind that is low-priority, she will avoid asking for it until higher
// priority tasks are finished. When he has finished all tasks, he is to
// report to his wife that he is ready for more.
// First, we define the class implementing the 'to-do' list.
class ToDoList {
// DATA
bsl::stack<const char *> d_stack;
public:
// MANIPULATORS
void enqueueTask(const char *task);
// Add the specified 'task', a string describing a task, to the
// list. Note the lifetime of the string referred to by 'task' must
// exceed the lifetime of the task in this list.
bool finishTask();
// Remove the current task from the list. Return 'true' if a task was
// removed and it was the last task on the list, and return 'false'
// otherwise.
// ACCESSORS
const char *currentTask() const;
// Return the string representing the current task. If there
// is no current task, return the string "<EMPTY>", which is
// not a valid task.
};
// MANIPULATORS
void ToDoList::enqueueTask(const char *task)
{
d_stack.push(task);
}
bool ToDoList::finishTask()
{
if (!d_stack.empty()) {
d_stack.pop();
return d_stack.empty(); // RETURN
}
return false;
};
// ACCESSORS
const char *ToDoList::currentTask() const
{
if (d_stack.empty()) {
return "<EMPTY>"; // RETURN
}
return d_stack.top();
}
//=============================================================================
// ====================
// class ExceptionGuard
// ====================
template <class OBJECT>
struct ExceptionGuard {
// This class provide a mechanism to verify the strong exception guarantee
// in exception-throwing code. On construction, this class stores the
// a copy of an object of the parameterized type 'OBJECT' and the address
// of that object. On destruction, if 'release' was not invoked, it will
// verify the value of the object is the same as the value of the copy
// create on construction. This class requires the copy constructor and
// 'operator ==' to be tested before use.
// DATA
int d_line; // the line number at construction
OBJECT d_copy; // copy of the object being tested
const OBJECT *d_object_p; // address of the original object
public:
// CREATORS
ExceptionGuard(const OBJECT *object,
int line,
bslma::Allocator *basicAllocator = 0)
: d_line(line)
, d_copy(*object, basicAllocator)
, d_object_p(object)
// Create the exception guard for the specified 'object' at the
// specified 'line' number. Optionally, specify 'basicAllocator' used
// to supply memory.
{}
~ExceptionGuard()
// Destroy the exception guard. If the guard was not released, verify
// that the state of the object supplied at construction has not
// change.
{
if (d_object_p) {
const int LINE = d_line;
ASSERTV(LINE, d_copy == *d_object_p);
}
}
// MANIPULATORS
void release()
// Release the guard from verifying the state of the object.
{
d_object_p = 0;
}
};
// ============================================================================
// GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------
//
// ================
// class TestDriver
// ================
template <class CONTAINER>
class TestDriver {
// TBD
//
// This templatized struct provide a namespace for testing the 'set'
// container. The parameterized 'KEY', 'COMP' and 'ALLOC' specifies the
// value type, comparator type and allocator type respectively. Each
// "testCase*" method test a specific aspect of 'stack<VALUE, CONTAINER>'.
// Every test cases should be invoked with various parameterized type to
// fully test the container.
public:
// PUBLIC TYPES
typedef bsl::stack<typename CONTAINER::value_type, CONTAINER> Obj;
// Type under test.
private:
// TYPES
typedef typename Obj::value_type value_type;
typedef typename Obj::reference reference;
typedef typename Obj::const_reference const_reference;
typedef typename Obj::size_type size_type;
typedef CONTAINER container_type;
// Shorthands
public:
typedef bsltf::TestValuesArray<value_type> TestValues;
private:
// TEST APPARATUS
//-------------------------------------------------------------------------
// The generating functions interpret the given 'spec' in order from left
// to right to configure the object according to a custom language.
// Uppercase letters [A..Z] correspond to arbitrary (but unique) char
// values to be appended to the 'stack<VALUE, CONTAINER>' object.
//..
// LANGUAGE SPECIFICATION:
// -----------------------
//
// <SPEC> ::= <EMPTY> | <LIST>
//
// <EMPTY> ::=
//
// <LIST> ::= <ITEM> | <ITEM><LIST>
//
// <ITEM> ::= <ELEMENT> | <CLEAR>
//
// <ELEMENT> ::= 'A' | 'B' | 'C' | 'D' | 'E' | ... | 'Z'
// // unique but otherwise arbitrary
// Spec String Description
// ----------- -----------------------------------------------------------
// "" Has no effect; leaves the object empty.
// "A" Insert the value corresponding to A.
// "AA" Insert two values both corresponding to A.
// "ABC" Insert three values corresponding to A, B and C.
//..
//-------------------------------------------------------------------------
static int ggg(Obj *object, const char *spec, int verbose = 1);
// Configure the specified 'object' according to the specified 'spec',
// using only the primary manipulator function 'insert' and white-box
// manipulator 'clear'. Optionally specify a zero 'verbose' to
// suppress 'spec' syntax error messages. Return the index of the
// first invalid character, and a negative value otherwise. Note that
// this function is used to implement 'gg' as well as allow for
// verification of syntax error detection.
static Obj& gg(Obj *object, const char *spec);
// Return, by reference, the specified object with its value adjusted
// according to the specified 'spec'.
static Obj g(const char *spec);
// Return, by value, a new object corresponding to the specified
// 'spec'.
static void emptyAndVerify(Obj *obj,
const TestValues& testValues,
size_t numTestValues,
const int LINE);
// Pop the elements out of 'obj', verifying that they exactly match
// the first 'numTestValues' elements in 'testValues'.
static bool typeAlloc()
{
return bslma::UsesBslmaAllocator<value_type>::value;
}
static bool emptyWillAlloc()
{
// Creating an empty 'deque' allocates memory, creating an empty
// 'vector' does not.
return bsl::is_same<CONTAINER, deque<value_type> >::value;
}
static bool use_same_allocator(Obj& object,
int TYPE_ALLOC,
bslma::TestAllocator *ta);
// Return 'true' if the specified 'object' uses the specified 'ta'
// allocator for supplying memory. The specified 'TYPE_ALLOC'
// identifies, if 'object' uses allocator at all. Return 'false' if
// object doesn't use 'ta'.
public:
// TEST CASES
static void testCase19();
// Test 'noexcept' specifications
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
static void testCase18MoveOnlyType();
// Test move manipulators on move-only types
static void testCase17MoveOnlyType();
// Test move manipulators on move-only types
#endif // !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <bool PROPAGATE_ON_CONTAINER_MOVE_ASSIGNMENT_FLAG,
bool OTHER_FLAGS>
static void testCase18_propagate_on_container_move_assignment_dispatch();
static void testCase18_propagate_on_container_move_assignment();
// Test 'propagate_on_container_move_assignment'.
static void testCase18(bool isMovableContainer);
// Test move manipulators
static void testCase17(bool isMovableContainer);
// Test move constructors
static void testCase12();
// Test inequality operators
static void testCase11();
// Test type traits.
static void testCase10();
// Test bslma::Allocator.
template <bool PROPAGATE_ON_CONTAINER_COPY_ASSIGNMENT_FLAG,
bool OTHER_FLAGS>
static void testCase9_propagate_on_container_copy_assignment_dispatch();
static void testCase9_propagate_on_container_copy_assignment();
// Test 'propagate_on_container_copy_assignment'.
static void testCase9();
// Test assignment operator ('operator=').
template <bool PROPAGATE_ON_CONTAINER_SWAP_FLAG,
bool OTHER_FLAGS>
static void testCase8_propagate_on_container_swap_dispatch();
static void testCase8_propagate_on_container_swap();
// Test 'propagate_on_container_swap'.
static void testCase8();
// Test 'swap' member.
template <bool SELECT_ON_CONTAINER_COPY_CONSTRUCTION_FLAG,
bool OTHER_FLAGS>
static void testCase7_select_on_container_copy_construction_dispatch();
static void testCase7_select_on_container_copy_construction();
// Test 'select_on_container_copy_construction'.
static void testCase7();
// Test copy constructor.
static void testCase6();
// Test equality operator ('operator==').
static void testCase5();
// Reserved for (<<) operator.
static void testCase4();
// Test basic accessors ('size' and 'top').
static void testCase3();
// Test generator functions 'ggg', and 'gg'.
static void testCase2();
// Test primary manipulators ('push' and 'pop').
static void testCase1(int *testKeys,
size_t numValues);
// Breathing test. This test *exercises* basic functionality but
// *test* nothing.
static void testCase1_NoAlloc(int *testValues,
size_t numValues);
// Breathing test, except on a non-allocator container. This test
// *exercises* basic functionality but *test* nothing.
};
// ----------------
// class TestDriver
// ----------------
template <class CONTAINER>
bool TestDriver<CONTAINER>::use_same_allocator(Obj& object,
int TYPE_ALLOC,
bslma::TestAllocator *ta)
{
bslma::DefaultAllocatorGuard guard(
&bslma::NewDeleteAllocator::singleton());
const TestValues VALUES;
if (0 == TYPE_ALLOC) { // If 'VALUE' does not use allocator, return true.
return true; // RETURN
}
const bsls::Types::Int64 BB = ta->numBlocksTotal();
const bsls::Types::Int64 B = ta->numBlocksInUse();
object.push(VALUES[0]);
const bsls::Types::Int64 AA = ta->numBlocksTotal();
const bsls::Types::Int64 A = ta->numBlocksInUse();
if (BB + TYPE_ALLOC <= AA && B + TYPE_ALLOC <= A) {
return true; // RETURN
}
if (veryVerbose) {
Q(Did find expected allocator)
P(ta->name())
}
return false;
}
template <class CONTAINER>
int TestDriver<CONTAINER>::ggg(Obj *object,
const char *spec,
int verbose)
{
bslma::DefaultAllocatorGuard guard(
&bslma::NewDeleteAllocator::singleton());
const TestValues VALUES;
enum { SUCCESS = -1 };
for (int i = 0; spec[i]; ++i) {
if ('A' <= spec[i] && spec[i] <= 'Z') {
object->push(VALUES[spec[i] - 'A']);
}
else {
if (verbose) {
printf("Error, bad character ('%c') "
"in spec \"%s\" at position %d.\n", spec[i], spec, i);
}
// Discontinue processing this spec.
return i; // RETURN
}
}
return SUCCESS;
}
template <class CONTAINER>
bsl::stack<typename CONTAINER::value_type, CONTAINER>&
TestDriver<CONTAINER>::gg(Obj *object,
const char *spec)
{
ASSERTV(ggg(object, spec) < 0);
return *object;
}
template <class CONTAINER>
bsl::stack<typename CONTAINER::value_type, CONTAINER>
TestDriver<CONTAINER>::g(const char *spec)
{
Obj object((bslma::Allocator *)0);
return gg(&object, spec);
}
template <class CONTAINER>
void TestDriver<CONTAINER>::emptyAndVerify(Obj *obj,
const TestValues& testValues,
size_t numTestValues,
const int LINE)
{
ASSERTV(LINE, numTestValues, obj->size(), numTestValues == obj->size());
for (int ti = static_cast<int>(numTestValues) - 1; ti >= 0; --ti) {
ASSERTV(LINE, testValues[ti], obj->top(),
testValues[ti] == obj->top());
obj->pop();
}
ASSERTV(LINE, obj->size(), obj->empty());
ASSERTV(LINE, obj->size(), 0 == obj->size());
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase19()
{
// ------------------------------------------------------------------------
// 'noexcept' SPECIFICATION
//
// Concerns:
//: 1 The 'noexcept' specification has been applied to all class interfaces
//: required by the standard.
//
// Plan:
//: 1 Apply the uniary 'noexcept' operator to expressions that mimic those
//: appearing in the standard and confirm that calculated boolean value
//: matches the expected value.
//:
//: 2 Since the 'noexcept' specification does not vary with the 'TYPE'
//: of the container, we need test for just one general type and any
//: 'TYPE' specializations.
//
// Testing:
// CONCERN: Methods qualifed 'noexcept' in standard are so implemented.
// ------------------------------------------------------------------------
if (verbose) {
P(bsls::NameOf<CONTAINER>())
}
// N4594: 23.6.6.1 'stack' definition
// page 905:
//..
// void swap(stack& s) noexcept(is_nothrow_swappable_v<Container>)
// { using std::swap; swap(c, s.c); }
//..
{
Obj c;
Obj s;
ASSERT(false == BSLS_KEYWORD_NOEXCEPT_OPERATOR(c.swap(s)));
}
// page 905
//..
// template <class T, class Container>
// void swap(stack<T, Container>& x, stack<T, Container>& y)
// noexcept(noexcept(x.swap(y)));
//..
{
Obj x;
Obj y;
ASSERT(false == BSLS_KEYWORD_NOEXCEPT_OPERATOR(swap(x, y)));
}
}
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase18MoveOnlyType()
{
// ------------------------------------------------------------------------
// MOVE MANIPULATORS FOR MOVE ONLY TYPES
//
// Concerns:
//: 1 The implementation of the move manipulator methods do not rely on
//: the (non-existent) copy construction or copy assignment methods of
//: the contained type.
//
// Plan:
//: 1 Instantiate this test method for the instrumented helper container
//: class, 'MovableVector', using 'bsltf::MoveOnlyAllocTestType' for the
//: contained value type.
//:
//: 2 Recast the tests of 'testCase18' so there is no reliance on copy
//: construction or copy assignment.
//
// Testing:
// operator=(MovableRef queue)
// emplace(Args&&.. args)
// push(MovableRef value)
// ------------------------------------------------------------------------
enum { k_MAX_NUM_PARAMS = 10 };
typedef typename CONTAINER::value_type VALUE;
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
const bool is_special_container =
SpecialContainerTrait<CONTAINER>::is_special_container;
const bool is_copy_constructible = bsl::is_copy_constructible<VALUE>::value;
if (verbose) {
P_(bsls::NameOf<CONTAINER>())
P_(bsls::NameOf<VALUE>())
P_(is_special_container)
P_(is_copy_constructible)
P (TYPE_ALLOC)
}
ASSERT( is_special_container);
ASSERT(!is_copy_constructible);
if (verbose) { printf("Movable 'push'"); }
{
const CalledMethod expectedPushMethod = e_PUSH_BACK_MOVE;
const int count = 3;
Obj mX; const Obj& X = mX; // test object for 'push'
for (int i = 0; i < count; ++i) {
if (veryVerbose) { P(i) }
static VALUE value0(VALUE(0));
setupCalledMethodCheck();
mX.push(MoveUtil::move(VALUE(i)));
ASSERT(isCalledMethodCheckPassed<CONTAINER>(expectedPushMethod));
ASSERT(value0 == X.front());
ASSERT(VALUE(i) == X.back());
}
}
if (verbose) { printf("Movable 'operator='"); }
{
const CalledMethod expectedAssignMethod = e_ASSIGN_MOVE;
const int count = 3;
for (int i = 0; i < count; ++i) {
if (veryVerbose) { P(i) }
Obj mX; const Obj& X = mX;
Obj mY; const Obj& Y = mY;
for (int j = 0; j < i; ++j) {
mX.push(VALUE(j));
mY.push(VALUE(j));
}
Obj mZ; const Obj& Z = mZ;
setupCalledMethodCheck();
mZ = MoveUtil::move(mX);
ASSERTV(
i,
bsls::NameOf<CONTAINER>(),
expectedAssignMethod,
getCalledMethod(),
isCalledMethodCheckPassed<CONTAINER>(expectedAssignMethod));
ASSERT(Y == Z);
}
}
if (verbose) { printf("'emplace'"); }
{
Obj mA; const Obj& A = mA; // test object for 'emplace'
Obj mB; const Obj& B = mB; // control object for 'emplace'
(void) A; // Compiler warnings suppression.
(void) B; // Compiler warnings suppression.
for (int numArgs = 0; numArgs < k_MAX_NUM_PARAMS; ++numArgs) {
if (veryVerbose) { P(numArgs) }
VALUE *addressOfResult = 0;
CalledMethod expectedEmplacePush =
static_cast<CalledMethod>(static_cast<int>(e_EMPLACE_0)
<< numArgs);
setupCalledMethodCheck();
switch (numArgs) {
case 0: {
VALUE& result = mA.emplace();
addressOfResult = bsls::Util::addressOf(result);
} break;
case 1: {
VALUE& result = mA.emplace(0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 2: {
VALUE& result = mA.emplace(0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 3: {
VALUE& result = mA.emplace(0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 4: {
VALUE& result = mA.emplace(0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 5: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 6: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 7: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 8: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 9: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 10: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
default:
ASSERT(!"'value' not in range '[0, k_MAX_NUM_PARAMS]'");
}
ASSERTV(
numArgs,
bsls::NameOf<CONTAINER>(),
expectedEmplacePush,
getCalledMethod(),
isCalledMethodCheckPassed<CONTAINER>(expectedEmplacePush));
const VALUE *ADDRESS_OF_TOP_VALUE = bsls::Util::addressOf(A.top());
ASSERTV(numArgs, bsls::NameOf<CONTAINER>(),
ADDRESS_OF_TOP_VALUE == addressOfResult);
// Track expected value of 'A'. Note that the 'emplace' methods of
// '(Non)?MovableVector' append 'VALUE(1)' regardless the number
// and value of their arguments.
mB.push(VALUE(1));
ASSERTV(A.size(), B.size(), B == A);
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase17MoveOnlyType()
{
// ------------------------------------------------------------------------
// MOVE CONSTRUCTORS FOR MOVE ONLY TYPES
//
// Concerns:
//: 1 The implementation of the move constructors do not rely on the
//: (non-existent) copy construction and copy assignment methods of the
//: contained type.
//
// Plan:
//: 1 Instantiate this test method for the instrumented helper container
//: class, 'MovableVector', using 'bsltf::MoveOnlyAllocTestType' for the
//: contained value type.
//:
//: 2 Recast the tests of 'testCase18' so there is no reliance on copy
//: construction or copy assignment.
//
// Testing:
// queue(MovableRef container);
// queue(MovableRef original);
// queue(MovableRef container, const ALLOCATOR& allocator);
// queue(MovableRef original, const ALLOCATOR& allocator);
// ------------------------------------------------------------------------
typedef typename CONTAINER::value_type VALUE;
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
const bool is_special_container =
SpecialContainerTrait<CONTAINER>::is_special_container;
const bool is_copy_constructible = bsl::is_copy_constructible<VALUE>
::value;
if (verbose) {
P_(bsls::NameOf<CONTAINER>())
P_(bsls::NameOf<VALUE>())
P_(is_special_container)
P_(is_copy_constructible)
P (TYPE_ALLOC)
}
ASSERT( is_special_container);
ASSERT(!is_copy_constructible);
{
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
const TestValues VALUES;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line; // source line number
const char *const SPEC = DATA[ti].d_spec;
if (veryVerbose) {
T_ P_(LINE) P(SPEC);
}
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator sa("source" , veryVeryVeryVerbose);
for (char cfg = 'a'; cfg <= 'e'; ++cfg) {
const char CONFIG = cfg; // how we call the constructor
if (veryVerbose) {
T_ T_ P(CONFIG);
}
// Create source object
Obj *pX = new Obj(&sa);
Obj& mX = *pX; const Obj& X = mX;
// Create control object
Obj mZ; const Obj& Z = mZ;
// Create value ('CONTAINER') object
CONTAINER mC(&sa); const CONTAINER& C = mC;
// Install default allocator.
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocator ta("target", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr; (void)objAllocatorPtr;
setupCalledMethodCheck();
CalledMethod expectedCtor;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(MoveUtil::move(mX));
objAllocatorPtr = &sa;
expectedCtor = e_CTOR_MOV_SANS_ALLOC;
} break;
case 'b': {
objPtr = new (fa) Obj(MoveUtil::move(mX),
(bslma::Allocator *)0);
objAllocatorPtr = &da;
expectedCtor = e_CTOR_MOV_AVEC_ALLOC;
} break;
case 'c': {
objPtr = new (fa) Obj(MoveUtil::move(mX), &ta);
objAllocatorPtr = &ta;
expectedCtor = e_CTOR_MOV_AVEC_ALLOC;
} break;
case 'd': {
objPtr = new (fa) Obj(MoveUtil::move(mC));
objAllocatorPtr = &sa;
expectedCtor = e_CTOR_MOV_SANS_ALLOC;
} break;
case 'e': {
objPtr = new (fa) Obj(MoveUtil::move(mC),
(bslma::Allocator *)0);
objAllocatorPtr = &da;
expectedCtor = e_CTOR_MOV_AVEC_ALLOC;
} break;
case 'f': {
objPtr = new (fa) Obj(MoveUtil::move(mC), &ta);
objAllocatorPtr = &ta;
expectedCtor = e_CTOR_MOV_AVEC_ALLOC;
} break;
default: {
ASSERTV(LINE, SPEC, CONFIG, !"Bad constructor config.");
return; // RETURN
} break;
}
Obj& mY = *objPtr; const Obj& Y = mY; // test object
ASSERTV(
bsls::NameOf<CONTAINER>(),
LINE,
SPEC,
expectedCtor,
getCalledMethod(),
true == isCalledMethodCheckPassed<CONTAINER>(expectedCtor));
ASSERTV(LINE, SPEC, CONFIG, sizeof(Obj) == fa.numBytesInUse());
// Reclaim dynamically allocated source object.
delete pX;
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
ASSERTV(LINE, SPEC, CONFIG, fa.numBlocksInUse(),
0 == fa.numBlocksInUse());
ASSERTV(LINE, SPEC, CONFIG, ta.numBlocksInUse(),
0 == ta.numBlocksInUse());
}
ASSERTV(LINE, SPEC, da.numBlocksInUse(), 0 == da.numBlocksInUse());
ASSERTV(LINE, SPEC, sa.numBlocksInUse(), 0 == sa.numBlocksInUse());
}
}
}
#endif // !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class CONTAINER>
template <bool PROPAGATE_ON_CONTAINER_MOVE_ASSIGNMENT_FLAG,
bool OTHER_FLAGS>
void TestDriver<CONTAINER>::
testCase18_propagate_on_container_move_assignment_dispatch()
{
typedef typename CONTAINER::value_type VALUE;
// Set the three properties of 'bsltf::StdStatefulAllocator' that are not
// under test in this test case to 'false'.
typedef bsltf::StdStatefulAllocator<
VALUE,
OTHER_FLAGS,
OTHER_FLAGS,
OTHER_FLAGS,
PROPAGATE_ON_CONTAINER_MOVE_ASSIGNMENT_FLAG>
StdAlloc;
typedef bsl::deque<VALUE, StdAlloc> CObj;
typedef bsl::stack<VALUE, CObj> Obj;
const bool PROPAGATE = PROPAGATE_ON_CONTAINER_MOVE_ASSIGNMENT_FLAG;
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
};
const int NUM_SPECS = static_cast<const int>(sizeof SPECS / sizeof *SPECS);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
// Create control and source objects.
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const ISPEC = SPECS[ti];
const size_t ILENGTH = strlen(ISPEC);
TestValues IVALUES(ISPEC);
bslma::TestAllocator oas("source", veryVeryVeryVerbose);
bslma::TestAllocator oat("target", veryVeryVeryVerbose);
StdAlloc mas(&oas);
StdAlloc mat(&oat);
StdAlloc scratch(&da);
const CObj CI(IVALUES.begin(), IVALUES.end(), scratch);
const Obj W(CI, scratch); // control
// Create target object.
for (int tj = 0; tj < NUM_SPECS; ++tj) {
const char *const JSPEC = SPECS[tj];
const size_t JLENGTH = strlen(JSPEC);
TestValues JVALUES(JSPEC);
{
Obj mY(CI, mas); const Obj& Y = mY;
if (veryVerbose) { T_ P_(ISPEC) P_(Y) P(W) }
const CObj CJ(JVALUES.begin(), JVALUES.end(), scratch);
Obj mX(CJ, mat); const Obj& X = mX;
bslma::TestAllocatorMonitor oasm(&oas);
bslma::TestAllocatorMonitor oatm(&oat);
Obj *mR = &(mX = MoveUtil::move(mY));
ASSERTV(ISPEC, JSPEC, W, X, W == X);
ASSERTV(ISPEC, JSPEC, mR, &mX, mR == &mX);
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(ISPEC, JSPEC, PROPAGATE,
!PROPAGATE == (mat == X.get_allocator()));
ASSERTV(ISPEC, JSPEC, PROPAGATE,
PROPAGATE == (mas == X.get_allocator()));
ASSERTV(ISPEC, JSPEC, mas == Y.get_allocator());
#endif
if (PROPAGATE) {
ASSERTV(ISPEC, JSPEC, 0 == oat.numBlocksInUse());
}
else {
ASSERTV(ISPEC, JSPEC, oasm.isInUseSame());
}
}
ASSERTV(ISPEC, 0 == oas.numBlocksInUse());
ASSERTV(ISPEC, 0 == oat.numBlocksInUse());
}
}
ASSERTV(0 == da.numBlocksInUse());
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase18_propagate_on_container_move_assignment()
{
// ------------------------------------------------------------------------
// MOVE-ASSIGNMENT OPERATOR: ALLOCATOR PROPAGATION
//
// Concerns:
//: 1 If the 'propagate_on_container_move_assignment' trait is 'false', the
//: allocator used by the target object remains unchanged (i.e., the
//: source object's allocator is *not* propagated).
//:
//: 2 If the 'propagate_on_container_move_assignment' trait is 'true', the
//: allocator used by the target object is updated to be a copy of that
//: used by the source object (i.e., the source object's allocator *is*
//: propagated).
//:
//: 3 The allocator used by the source object remains unchanged whether or
//; not it is propagated to the target object.
//:
//: 4 If the allocator is propagated from the source object to the target
//: object, all memory allocated from the target object's original
//: allocator is released.
//:
//: 5 The effect of the 'propagate_on_container_move_assignment' trait is
//: independent of the other three allocator propagation traits.
//
// Plan:
//: 1 Specify a set S of object values with varied differences, ordered by
//: increasing length, to be used in the following tests.
//:
//: 2 Create two 'bsltf::StdStatefulAllocator' objects with their
//: 'propagate_on_container_move_assignment' property configured to
//: 'false'. In two successive iterations of P-3, first configure the
//: three properties not under test to be 'false', then configure them
//: all to be 'true'.
//:
//: 3 For each value '(x, y)' in the cross product S x S: (C-1)
//:
//: 1 Initialize an object 'X' from 'x' using one of the allocators from
//: P-2.
//:
//: 2 Initialize two objects from 'y', a control object 'W' using a
//: scratch allocator and an object 'Y' using the other allocator from
//: P-2.
//:
//: 3 Move-assign 'Y' to 'X' and use 'operator==' to verify that 'X'
//: subsequently has the same value as 'W'.
//:
//: 4 Use the 'get_allocator' method to verify that the allocator of 'Y'
//: is *not* propagated to 'X' and that the allocator used by 'Y'
//: remains unchanged. (C-1)
//:
//: 4 Repeat P-2..3 except that this time configure the allocator property
//: under test to 'true' and verify that the allocator of 'Y' *is*
//: propagated to 'X'. Also verify that all memory is released to the
//: allocator that was in use by 'X' prior to the assignment. (C-2..5)
//
// Testing:
// propagate_on_container_move_assignment
// ------------------------------------------------------------------------
if (verbose) printf("\nMOVE-ASSIGNMENT OPERATOR: ALLOCATOR PROPAGATION"
"\n===============================================\n");
if (verbose)
printf("\n'propagate_on_container_move_assignment::value == false'\n");
testCase18_propagate_on_container_move_assignment_dispatch<false, false>();
testCase18_propagate_on_container_move_assignment_dispatch<false, true>();
if (verbose)
printf("\n'propagate_on_container_move_assignment::value == true'\n");
testCase18_propagate_on_container_move_assignment_dispatch<true, false>();
testCase18_propagate_on_container_move_assignment_dispatch<true, true>();
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase18(bool isMovableContainer)
{
// ------------------------------------------------------------------------
// MOVE MANIPULATORS:
//
// Concerns:
//: 1 Each of the methods under test correctly forwards its arguments
//: to the corresponding method of the underlying 'CONTAINER' when
//: that container provides those "move" methods, and to the expected
//: alternate methods otherwise.
//:
//: 2 The reference returned from the assignment operator is to the target
//: object (i.e., '*this').
//:
//: 3 'emplace_back' returns a reference to the inserted element.
//
// Plan:
//: 1 Instantiate this test method for the two instrumented helper
//: container classes: 'NonMovableVector' and 'MovableVector'.
//:
//: 2 Use loop-based tests that iterate for a small number of values.
//: Use 3 different values for the 'push' and assignment tests. The
//: 'emplace' tests a different number of parameters on each test.
//: Those require 10 iterations to address each of the 10 overloads
//: used when CPP11 support is not available.
//:
//: 3 For each test create a "control" object that has the expected
//: value of the object under test. Create the control object using
//: the previously tested (non-moveable) 'push' method.
//:
//: 4 Invoke the method under test on the object under test. Confirm
//: that the expected enumerated value was set in the global variable.
//: Confirm that the test object has the expected value. Confirm that
//: the expected value is returned (if any).
//
// Testing:
// operator=(MovableRef stack)
// emplace(Args&&.. args)
// push(MovableRef value)
// ------------------------------------------------------------------------
typedef typename CONTAINER::value_type VALUE;
enum { k_MAX_NUM_PARAMS = 10 };
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
const bool is_special_container =
SpecialContainerTrait<CONTAINER>::is_special_container;
const TestValues VALUES;
if (verbose) {
P_(bsls::NameOf<CONTAINER>())
P_(bsls::NameOf<VALUE>())
P_(is_special_container)
P (TYPE_ALLOC)
}
ASSERT(is_special_container);
if (verbose) { printf("Movable 'push'"); }
{
Obj mX; const Obj& X = mX; // test object for 'push'
Obj mY; const Obj& Y = mY; // control object for 'push'
CalledMethod expectedPushMethod = isMovableContainer
? e_PUSH_BACK_MOVE
: e_PUSH_BACK_CREF;
for (int i = 0; i < 3; ++i) {
if (veryVerbose) { P(i) }
VALUE value = VALUES[i];
VALUE valueToBeMoved = value;
setupCalledMethodCheck();
mX.push(MoveUtil::move(valueToBeMoved));
ASSERT(isCalledMethodCheckPassed<CONTAINER>(expectedPushMethod));
setupCalledMethodCheck();
mY.push( value);
ASSERT(isCalledMethodCheckPassed<CONTAINER>(e_PUSH_BACK_CREF));
ASSERT(Y == X);
}
}
if (verbose) { printf("Movable 'operator='"); }
{
CalledMethod expectedAssignMethod = isMovableContainer
? e_ASSIGN_MOVE
: e_ASSIGN_CREF;
Obj mX; const Obj& X = mX; // test object for 'push'
for (int i = 0; i < 3; ++i) {
if (veryVerbose) { P(i) }
VALUE value = VALUES[i];
Obj mU; const Obj& U = mU; // test object
Obj mV; const Obj& V = mV; // control object
mX.push(value);
Obj mT(X); // sacrifice object
Obj *mR = 0;
setupCalledMethodCheck();
mR = &(mU = MoveUtil::move(mT));
ASSERTV(bsls::Util::addressOf(U) == mR);
ASSERTV(
i,
bsls::NameOf<CONTAINER>(),
expectedAssignMethod,
getCalledMethod(),
isCalledMethodCheckPassed<CONTAINER>(expectedAssignMethod));
ASSERT(U == X);
setupCalledMethodCheck();
mV = X;
ASSERTV(
i,
bsls::NameOf<CONTAINER>(),
expectedAssignMethod,
getCalledMethod(),
isCalledMethodCheckPassed<CONTAINER>(e_ASSIGN_CREF));
ASSERT(V == X);
ASSERT(U == V);
}
}
if (verbose) { printf("'emplace'"); }
{
Obj mA; const Obj& A = mA; // test object for 'emplace'
Obj mB; const Obj& B = mB; // control object for 'emplace'
for (int value = 0; value < k_MAX_NUM_PARAMS; ++value) {
if (veryVerbose) { P(value) }
CalledMethod expectedEmplacePush =
static_cast<CalledMethod>(static_cast<int>(e_EMPLACE_0)
<< value);
setupCalledMethodCheck();
VALUE *addressOfResult = 0;
switch (value) {
case 0: {
VALUE& result = mA.emplace();
addressOfResult = bsls::Util::addressOf(result);
} break;
case 1: {
VALUE& result = mA.emplace(0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 2: {
VALUE& result = mA.emplace(0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 3: {
VALUE& result = mA.emplace(0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 4: {
VALUE& result = mA.emplace(0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 5: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 6: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 7: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 8: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 9: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
case 10: {
VALUE& result = mA.emplace(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
addressOfResult = bsls::Util::addressOf(result);
} break;
default:
ASSERT(!"'value' not in range '[0, k_MAX_NUM_PARAMS]'");
}
const VALUE *ADDRESS_OF_TOP = bsls::Util::addressOf(A.top());
ASSERTV(ADDRESS_OF_TOP == addressOfResult);
ASSERTV(
value,
bsls::NameOf<CONTAINER>(),
expectedEmplacePush,
getCalledMethod(),
isCalledMethodCheckPassed<CONTAINER>(expectedEmplacePush));
// Track expected value of 'A'. Note that the 'emplace' methods of
// '(Non)?MovableVector' append 'VALUE(1)' regardless the number
// and value of their arguments.
mB.push(VALUE(1));
ASSERTV(A.size(), B.size(), B == A);
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase17(bool isMovableContainer)
{
// ------------------------------------------------------------------------
// MOVE CONSTRUCTORS:
// Ensure that we can construct any object of the class, having other
// object of the class as the source. To provide backward compatibility,
// copy copnstructor should be used in the absence of move constructor.
// We are going to use two special containers 'NonMovableVector' and
// 'MovableVector', that register called method, to verify it.
//
// Concerns:
//: 1 Appropriate constructor of underlying container (move or copy) is
//: called.
//:
//: 2 The new object has the same value as the source object.
//:
//: 3 All internal representations of a given value can be used to create a
//: new object of equivalent value.
//:
//: 4 The source object is left in a valid but unspecified state.
//:
//: 5 No additional memory is allocated by the target object.
//:
//: 5 If an allocator is NOT supplied to the constructor, the
//: allocator of the source object in effect at the time of construction
//: becomes the object allocator for the resulting object.
//:
//: 6 If an allocator IS supplied to the constructor, that
//: allocator becomes the object allocator for the resulting object.
//:
//: 7 If a null allocator address IS supplied to the constructor, the
//: default allocator in effect at the time of construction becomes
//: the object allocator for the resulting object.
//:
//: 8 Supplying an allocator to the constructor has no effect on subsequent
//: object values.
//:
//: 9 Subsequent changes to or destruction of the source object have no
//: effect on the move-constructed object and vice-versa.
//:
//:10 Every object releases any allocated memory at destruction.
//
// Plan:
//: 1 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid source object values.
//:
//: 2 Specify a set of (unique) valid value ('CONTAINER') objects.
//:
//: 2 For each row (representing a distinct object value, 'V') in the table
//: described in P-1:
//:
//: 1 Execute an inner loop creating three distinct objects, in turn,
//: each object having the same value, 'V', but configured differently
//: identified by 'CONFIG':
//:
//: 'a': passing a source object without passing an allocator;
//:
//: 'b': passing a source object and an explicit null allocator;
//:
//: 'c': passing a source object and the address of a test allocator
//: distinct from the default and source object's allocators.
//:
//: 'd': passing a value object without passing an allocator;
//:
//: 'e': passing a value object and an explicit null allocator;
//:
//: 'f': passing a value object and the address of a test allocator
//: distinct from the default and source object's allocators.
//:
//: 2 For each of the four iterations in P-2.1:
//:
//: 1 Use the value constructor with 'sa' allocator to create dynamic
//: source object 'mX' and control object 'mZ', each having the value
//: 'V'.
//:
//: 2 Create a 'bslma_TestAllocator' object, and install it as the
//: default allocator (note that a ubiquitous test allocator is
//: already installed as the global allocator).
//:
//: 3 Choose the move constructor depending on 'CONFIG' to dynamically
//: create an object, 'mY', using movable reference of 'mX'.
//:
//: 4 Verify that the appropriate constructor of underlying container
//: has been called. Note that this check is skipped for all classes
//: except special containers 'NonMovableVector' and 'MovableVector'.
//: (C-1)
//:
//: 5 Use the appropriate test allocator to verify that no additional
//: memory is allocated by the target object. (C-5)
//:
//: 6 Use the helper function 'use_same_allocator' to verify each
//: underlying attribute capable of allocating memory to ensure
//: that its object allocator is properly installed. (C-6..9)
//:
//: 7 Use the helper function 'use_same_comparator' to verify that the
//: target object, 'mY', has the same comparator as that of 'mZ', to
//: ensure that new object comprator is properly installed. (C-2..3)
//:
//: 8 Add some values to the source and target object separately.
//: Verify that they change independently. Destroy source object.
//: Verify that target object is unaffected. (C-4, 10)
//:
//: 9 Delete the target object and let the control object go out of
//: scope to verify, that all memory has been released. (C-11)
//
// Testing:
// stack(MovableRef container)
// stack(MovableRef container, bslma::Allocator *bA)
// stack(MovableRef stack)
// stack(MovableRef stack, bslma::Allocator *bA)
// ------------------------------------------------------------------------
typedef typename CONTAINER::value_type VALUE;
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
const bool is_special_container =
SpecialContainerTrait<CONTAINER>::is_special_container;
if (verbose) {
P_(bsls::NameOf<CONTAINER>())
P_(bsls::NameOf<VALUE>())
P_(is_special_container)
P (TYPE_ALLOC)
}
{ ASSERT(is_special_container);
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
const TestValues VALUES;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line; // source line number
const char *const SPEC = DATA[ti].d_spec;
if (veryVerbose) {
T_ P_(LINE) P(SPEC);
}
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator sa("source" , veryVeryVeryVerbose);
for (char cfg = 'a'; cfg <= 'e'; ++cfg) {
const char CONFIG = cfg; // how we call the constructor
if (veryVerbose) {
T_ T_ P(CONFIG);
}
// Create source object
Obj *pX = new Obj(&sa);
Obj& mX = gg(pX, SPEC);
const Obj& X = mX;
// Create control object
Obj mZ; const Obj& Z = gg(&mZ, SPEC);
// Create value ('CONTAINER') object
CONTAINER mC(&sa);
const CONTAINER& C = CONTAINER::GG(&mC, SPEC);
// Install default allocator.
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocator ta("target", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
setupCalledMethodCheck();
CalledMethod expectedCtor;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(MoveUtil::move(mX));
objAllocatorPtr = isMovableContainer
? &sa
: &da;
expectedCtor = isMovableContainer
? e_CTOR_MOV_SANS_ALLOC
: e_CTOR_CPY_SANS_ALLOC;
} break;
case 'b': {
objPtr = new (fa) Obj(MoveUtil::move(mX),
(bslma::Allocator *)0);
objAllocatorPtr = &da;
expectedCtor = isMovableContainer
? e_CTOR_MOV_AVEC_ALLOC
: e_CTOR_CPY_AVEC_ALLOC;
} break;
case 'c': {
objPtr = new (fa) Obj(MoveUtil::move(mX), &ta);
objAllocatorPtr = &ta;
expectedCtor = isMovableContainer
? e_CTOR_MOV_AVEC_ALLOC
: e_CTOR_CPY_AVEC_ALLOC;
} break;
case 'd': {
objPtr = new (fa) Obj(MoveUtil::move(mC));
objAllocatorPtr = isMovableContainer
? &sa
: &da;
expectedCtor = isMovableContainer
? e_CTOR_MOV_SANS_ALLOC
: e_CTOR_CPY_SANS_ALLOC;
} break;
case 'e': {
objPtr = new (fa) Obj(MoveUtil::move(mC),
(bslma::Allocator *)0);
objAllocatorPtr = &da;
expectedCtor = isMovableContainer
? e_CTOR_MOV_AVEC_ALLOC
: e_CTOR_CPY_AVEC_ALLOC;
} break;
case 'f': {
objPtr = new (fa) Obj(MoveUtil::move(mC), &ta);
objAllocatorPtr = &ta;
expectedCtor = isMovableContainer
? e_CTOR_MOV_AVEC_ALLOC
: e_CTOR_CPY_AVEC_ALLOC;
} break;
default: {
ASSERTV(LINE, SPEC, CONFIG, !"Bad constructor config.");
return; // RETURN
} break;
}
Obj& mY = *objPtr; const Obj& Y = mY;
ASSERTV(
bsls::NameOf<CONTAINER>(),
LINE,
SPEC,
expectedCtor,
getCalledMethod(),
true == isCalledMethodCheckPassed<CONTAINER>(expectedCtor));
ASSERTV(LINE, SPEC, CONFIG, sizeof(Obj) == fa.numBytesInUse());
// Verify correctness of the contents moving.
ASSERTV(LINE, SPEC, CONFIG, Z == Y);
// Verify any attribute allocators are installed properly.
ASSERTV(LINE, SPEC, CONFIG, use_same_allocator(
mY,
TYPE_ALLOC,
objAllocatorPtr));
// Verify independence of the target object from the source
// one.
size_t sourceSize = X.size();
size_t targetSize = Y.size();
mX.push(VALUES[0]);
ASSERTV(LINE, SPEC, CONFIG, sourceSize != X.size());
ASSERTV(LINE, SPEC, CONFIG, targetSize == Y.size());
sourceSize = X.size();
mY.push(VALUES[0]);
ASSERTV(LINE, SPEC, CONFIG, sourceSize == X.size());
ASSERTV(LINE, SPEC, CONFIG, targetSize != Y.size());
targetSize = Y.size();
const VALUE top = Y.top();
// Reclaim dynamically allocated source object.
delete pX;
ASSERTV(LINE, SPEC, CONFIG, top == Y.top());
ASSERTV(LINE, SPEC, CONFIG, targetSize == Y.size());
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
ASSERTV(LINE, SPEC, CONFIG, fa.numBlocksInUse(),
0 == fa.numBlocksInUse());
ASSERTV(LINE, SPEC, CONFIG, ta.numBlocksInUse(),
0 == ta.numBlocksInUse());
}
ASSERTV(LINE, SPEC, da.numBlocksInUse(), 0 == da.numBlocksInUse());
ASSERTV(LINE, SPEC, sa.numBlocksInUse(), 0 == sa.numBlocksInUse());
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase12()
{
// ------------------------------------------------------------------------
// TESTING INEQUALITY OPERATORS
//
// Concern:
// That the inequality operators function correctly.
//
// Plan:
// Load 2 stack objects according to two SPEC's via the 'ggg' function,
// and compare them. It turns out that 'strcmp' comparing the two
// 'SPEC's will correspond directly to the result of inequality
// operators, which is very convenient.
//
// Repeat the test a second time, with the second stack object created
// with a different allocator than the first, to verify that creation
// via different allocators has no impact on value.
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
bslma::TestAllocator ta("testA", veryVeryVeryVerbose);
bslma::TestAllocator tb("testB", veryVeryVeryVerbose);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (veryVerbose) printf(" %s ---------------------------", cont);
{
// Create first object
for (int ti = 0; ti < NUM_DATA; ++ti) {
const char *const SPECX = DATA[ti].d_spec;
Obj mX(&ta); const Obj& X = gg(&mX, SPECX);
for (int tj = 0; tj < NUM_DATA; ++tj) {
const char *const SPECY = DATA[tj].d_spec;
Obj mY(&ta); const Obj& Y = gg(&mY, SPECY);
const int CMP = ti == tj
? 0
: strcmp(SPECX, SPECY) > 0 ? 1 : -1;
const bool EQ = X == Y;
const bool NE = X != Y;
const bool LT = X < Y;
const bool LE = X <= Y;
const bool GT = X > Y;
const bool GE = X >= Y;
ASSERTV(cont, SPECX, SPECY, EQ == (Y == X));
ASSERTV(cont, SPECX, SPECY, NE == (Y != X));
ASSERTV(cont, SPECX, SPECY, LT == (Y > X));
ASSERTV(cont, SPECX, SPECY, LE == (Y >= X));
ASSERTV(cont, SPECX, SPECY, GT == (Y < X));
ASSERTV(cont, SPECX, SPECY, GE == (Y <= X));
ASSERTV(cont, SPECX, SPECY, LT == !GE);
ASSERTV(cont, SPECX, SPECY, GT == !LE);
ASSERTV(cont, SPECX, SPECY, !(LT && GT));
ASSERTV(cont, SPECX, SPECY, LE || GE);
if (0 == CMP) {
ASSERTV(cont, SPECX, SPECY, !LT && !GT);
ASSERTV(cont, SPECX, SPECY, LE && GE);
}
else {
ASSERTV(cont, SPECX, SPECY, LT || GT);
}
ASSERTV(cont, SPECX, SPECY, CMP, (CMP < 0) == LT);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP < 0) == !GE);
ASSERTV(cont, SPECX, SPECY, CMP, !((CMP == 0) && LT));
ASSERTV(cont, SPECX, SPECY, CMP, !((CMP == 0) && GT));
ASSERTV(cont, SPECX, SPECY, CMP, (CMP > 0) == GT);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP > 0) == !LE);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP == 0) == EQ);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP != 0) == NE);
}
// Do it all over again, this time using a different allocator
// for 'mY' to verify changing the allocator has no impact on
// comparisons. Note we are re-testing the equality comparators
// so this memory allocation aspect is tested for them too.
for (int tj = 0; tj < NUM_DATA; ++tj) {
const char *const SPECY = DATA[tj].d_spec;
Obj mY(g(SPECY), &tb); const Obj& Y = mY;
const int CMP = ti == tj
? 0
: strcmp(SPECX, SPECY) > 0 ? 1 : -1;
const bool EQ = X == Y;
const bool NE = X != Y;
const bool LT = X < Y;
const bool LE = X <= Y;
const bool GT = X > Y;
const bool GE = X >= Y;
ASSERTV(cont, SPECX, SPECY, EQ == (Y == X));
ASSERTV(cont, SPECX, SPECY, NE == (Y != X));
ASSERTV(cont, SPECX, SPECY, LT == (Y > X));
ASSERTV(cont, SPECX, SPECY, LE == (Y >= X));
ASSERTV(cont, SPECX, SPECY, GT == (Y < X));
ASSERTV(cont, SPECX, SPECY, GE == (Y <= X));
ASSERTV(cont, SPECX, SPECY, LT == !GE);
ASSERTV(cont, SPECX, SPECY, GT == !LE);
ASSERTV(cont, SPECX, SPECY, !(LT && GT));
ASSERTV(cont, SPECX, SPECY, LE || GE);
if (EQ) {
ASSERTV(cont, SPECX, SPECY, !LT && !GT);
ASSERTV(cont, SPECX, SPECY, LE && GE);
}
else {
ASSERTV(cont, SPECX, SPECY, LT || GT);
}
ASSERTV(cont, SPECX, SPECY, CMP, (CMP < 0) == LT);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP < 0) == !GE);
ASSERTV(cont, SPECX, SPECY, CMP, !((CMP == 0) && LT));
ASSERTV(cont, SPECX, SPECY, CMP, !((CMP == 0) && GT));
ASSERTV(cont, SPECX, SPECY, CMP, (CMP > 0) == GT);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP > 0) == !LE);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP == 0) == EQ);
ASSERTV(cont, SPECX, SPECY, CMP, (CMP != 0) == NE);
}
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase11()
{
// ------------------------------------------------------------------------
// TESTING TYPE TRAITS
//
// Concern:
//: 1 The object has the necessary type traits.
//
// Plan:
//: 1 Use 'BSLMF_ASSERT' to verify all the type traits exists. (C-1)
//
// Testing:
// CONCERN: The object has the necessary type traits
// ------------------------------------------------------------------------
// Verify set defines the expected traits.
enum { CONTAINER_USES_ALLOC =
bslma::UsesBslmaAllocator<CONTAINER>::value };
BSLMF_ASSERT(
((int) CONTAINER_USES_ALLOC == bslma::UsesBslmaAllocator<Obj>::value));
// Verify stack does not define other common traits.
BSLMF_ASSERT((0 == bslalg::HasStlIterators<Obj>::value));
BSLMF_ASSERT((0 == bsl::is_trivially_copyable<Obj>::value));
BSLMF_ASSERT((0 == bslmf::IsBitwiseEqualityComparable<Obj>::value));
BSLMF_ASSERT((0 == bslmf::IsBitwiseMoveable<Obj>::value));
BSLMF_ASSERT((0 == bslmf::HasPointerSemantics<Obj>::value));
BSLMF_ASSERT((0 == bsl::is_trivially_default_constructible<Obj>::value));
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase10()
{
// ------------------------------------------------------------------------
// TESTING BSLMA ALLOCATOR
//
// Concern:
//: 1 A standard compliant allocator can be used instead of
//: 'bsl::allocator'.
//:
//: 2 Methods that uses the allocator (e.g., variations of constructor,
//: 'insert' and 'swap') can successfully populate the object.
//:
//: 3 'KEY' types that allocate memory uses the default allocator instead
//: of the object allocator.
//:
//: 4 Every object releases any allocated memory at destruction.
//
// Plan:
//: 1 Using a loop base approach, create a list of specs and their
//: expected value. For each spec:
//:
//: 1 Create an object using a standard allocator through multiple ways,
//: including: range-based constructor, copy constructor, range-based
//: insert, multiple inserts, and swap.
//:
//: 2 Verify the value of each objects is as expected.
//:
//: 3 For types that allocate memory, verify memory for the elements
//: comes from the default allocator.
//
// Testing:
// CONCERN: 'set' is compatible with a standard allocator.
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const size_t NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
for (size_t ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char *const SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(DATA[ti].d_spec);
const TestValues EXP(DATA[ti].d_spec, &scratch);
TestValues values(SPEC, &scratch);
bslma::TestAllocator ta("test", veryVeryVeryVerbose);
bslma::TestAllocatorMonitor tam(&ta);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocatorMonitor dam(&da);
{
container_type tmpCont(&ta);
for (size_t tk = 0; tk < LENGTH; ++tk) {
tmpCont.push_back(values[tk]);
}
Obj mX(tmpCont, &ta); const Obj& X = mX;
verifyStack(X, EXP, LENGTH, L_, &ta);
Obj mY(X, &ta); const Obj& Y = mY;
verifyStack(Y, EXP, LENGTH, L_, &ta);
Obj mZ(&ta); const Obj& Z = mZ;
mZ.swap(mX);
verifyStack(Z, EXP, LENGTH, L_, &ta);
ASSERTV(LINE, X.empty());
ASSERTV(LINE, 0 == X.size());
}
ASSERT(tam.isTotalUp() || 0 == LENGTH);
ASSERT(tam.isInUseSame());
tam.reset();
{
Obj mX(&ta); const Obj& X = mX;
for (size_t tj = 0; tj < LENGTH; ++tj) {
mX.push(values[tj]);
ASSERTV(LINE, tj, LENGTH, values[tj] == X.top());
}
verifyStack(X, EXP, LENGTH, L_, &ta);
}
ASSERT(tam.isTotalUp() || 0 == LENGTH);
ASSERT(tam.isInUseSame());
ASSERT(dam.isTotalSame());
{
container_type tmpCont;
for (size_t tk = 0; tk < LENGTH; ++tk) {
tmpCont.push_back(values[tk]);
}
Obj mX(tmpCont); const Obj& X = mX;
verifyStack(X, EXP, LENGTH, L_);
Obj mY(X); const Obj& Y = mY;
verifyStack(Y, EXP, LENGTH, L_);
Obj mZ; const Obj& Z = mZ;
mZ.swap(mX);
verifyStack(Z, EXP, LENGTH, L_);
ASSERTV(LINE, X.empty());
ASSERTV(LINE, 0 == X.size());
}
ASSERTV(cont, dam.isTotalUp() == (emptyWillAlloc() || LENGTH > 0));
dam.reset();
{
Obj mX; const Obj& X = mX;
for (size_t tj = 0; tj < LENGTH; ++tj) {
mX.push(values[tj]);
ASSERTV(LINE, tj, LENGTH, values[tj] == X.top());
}
verifyStack(X, EXP, LENGTH, L_);
}
ASSERTV(cont, dam.isTotalUp() == (emptyWillAlloc() || LENGTH > 0));
ASSERTV(LINE, da.numBlocksInUse(), 0 == da.numBlocksInUse());
}
}
template <class CONTAINER>
template <bool PROPAGATE_ON_CONTAINER_COPY_ASSIGNMENT_FLAG,
bool OTHER_FLAGS>
void TestDriver<CONTAINER>::
testCase9_propagate_on_container_copy_assignment_dispatch()
{
typedef typename CONTAINER::value_type VALUE;
// Set the three properties of 'bsltf::StdStatefulAllocator' that are not
// under test in this test case to 'false'.
typedef bsltf::StdStatefulAllocator<
VALUE,
OTHER_FLAGS,
PROPAGATE_ON_CONTAINER_COPY_ASSIGNMENT_FLAG,
OTHER_FLAGS,
OTHER_FLAGS> StdAlloc;
typedef bsl::deque<VALUE, StdAlloc> CObj;
typedef bsl::stack<VALUE, CObj> Obj;
const bool PROPAGATE = PROPAGATE_ON_CONTAINER_COPY_ASSIGNMENT_FLAG;
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
};
const int NUM_SPECS = static_cast<const int>(sizeof SPECS / sizeof *SPECS);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
// Create control and source objects.
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const ISPEC = SPECS[ti];
const size_t ILENGTH = strlen(ISPEC);
TestValues IVALUES(ISPEC);
bslma::TestAllocator oas("source", veryVeryVeryVerbose);
bslma::TestAllocator oat("target", veryVeryVeryVerbose);
StdAlloc mas(&oas);
StdAlloc mat(&oat);
StdAlloc scratch(&da);
const CObj CI(IVALUES.begin(), IVALUES.end(), scratch);
const Obj W(CI, scratch); // control
// Create target object.
for (int tj = 0; tj < NUM_SPECS; ++tj) {
const char *const JSPEC = SPECS[tj];
const size_t JLENGTH = strlen(JSPEC);
TestValues JVALUES(JSPEC);
{
Obj mY(CI, mas); const Obj& Y = mY;
if (veryVerbose) { T_ P_(ISPEC) P_(Y) P(W) }
const CObj CJ(JVALUES.begin(), JVALUES.end(), scratch);
Obj mX(CJ, mat); const Obj& X = mX;
bslma::TestAllocatorMonitor oasm(&oas);
bslma::TestAllocatorMonitor oatm(&oat);
Obj *mR = &(mX = Y);
ASSERTV(ISPEC, JSPEC, W, X, W == X);
ASSERTV(ISPEC, JSPEC, W, Y, W == Y);
ASSERTV(ISPEC, JSPEC, mR, &mX, mR == &mX);
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(ISPEC, JSPEC, PROPAGATE,
!PROPAGATE == (mat == X.get_allocator()));
ASSERTV(ISPEC, JSPEC, PROPAGATE,
PROPAGATE == (mas == X.get_allocator()));
ASSERTV(ISPEC, JSPEC, mas == Y.get_allocator());
#endif
if (PROPAGATE) {
ASSERTV(ISPEC, JSPEC, 0 == oat.numBlocksInUse());
}
else {
ASSERTV(ISPEC, JSPEC, oasm.isInUseSame());
}
}
ASSERTV(ISPEC, 0 == oas.numBlocksInUse());
ASSERTV(ISPEC, 0 == oat.numBlocksInUse());
}
}
ASSERTV(0 == da.numBlocksInUse());
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase9_propagate_on_container_copy_assignment()
{
// ------------------------------------------------------------------------
// COPY-ASSIGNMENT OPERATOR: ALLOCATOR PROPAGATION
//
// Concerns:
//: 1 If the 'propagate_on_container_copy_assignment' trait is 'false', the
//: allocator used by the target object remains unchanged (i.e., the
//: source object's allocator is *not* propagated).
//:
//: 2 If the 'propagate_on_container_copy_assignment' trait is 'true', the
//: allocator used by the target object is updated to be a copy of that
//: used by the source object (i.e., the source object's allocator *is*
//: propagated).
//:
//: 3 The allocator used by the source object remains unchanged whether or
//; not it is propagated to the target object.
//:
//: 4 If the allocator is propagated from the source object to the target
//: object, all memory allocated from the target object's original
//: allocator is released.
//:
//: 5 The effect of the 'propagate_on_container_copy_assignment' trait is
//: independent of the other three allocator propagation traits.
//
// Plan:
//: 1 Specify a set S of object values with varied differences, ordered by
//: increasing length, to be used in the following tests.
//:
//: 2 Create two 'bsltf::StdStatefulAllocator' objects with their
//: 'propagate_on_container_copy_assignment' property configured to
//: 'false'. In two successive iterations of P-3, first configure the
//: three properties not under test to be 'false', then configure them
//: all to be 'true'.
//:
//: 3 For each value '(x, y)' in the cross product S x S: (C-1)
//:
//: 1 Initialize an object 'X' from 'x' using one of the allocators from
//: P-2.
//:
//: 2 Initialize two objects from 'y', a control object 'W' using a
//: scratch allocator and an object 'Y' using the other allocator from
//: P-2.
//:
//: 3 Copy-assign 'Y' to 'X' and use 'operator==' to verify that both
//: 'X' and 'Y' subsequently have the same value as 'W'.
//:
//: 4 Use the 'get_allocator' method to verify that the allocator of 'Y'
//: is *not* propagated to 'X' and that the allocator used by 'Y'
//: remains unchanged. (C-1)
//:
//: 4 Repeat P-2..3 except that this time configure the allocator property
//: under test to 'true' and verify that the allocator of 'Y' *is*
//: propagated to 'X'. Also verify that all memory is released to the
//: allocator that was in use by 'X' prior to the assignment. (C-2..5)
//
// Testing:
// propagate_on_container_copy_assignment
// ------------------------------------------------------------------------
if (verbose) printf("\nCOPY-ASSIGNMENT OPERATOR: ALLOCATOR PROPAGATION"
"\n===============================================\n");
if (verbose)
printf("\n'propagate_on_container_copy_assignment::value == false'\n");
testCase9_propagate_on_container_copy_assignment_dispatch<false, false>();
testCase9_propagate_on_container_copy_assignment_dispatch<false, true>();
if (verbose)
printf("\n'propagate_on_container_copy_assignment::value == true'\n");
testCase9_propagate_on_container_copy_assignment_dispatch<true, false>();
testCase9_propagate_on_container_copy_assignment_dispatch<true, true>();
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase9()
{
// ------------------------------------------------------------------------
// COPY-ASSIGNMENT OPERATOR:
// Ensure that we can assign the value of any object of the class to any
// object of the class, such that the two objects subsequently have the
// same value.
//
// Concerns:
//: 1 The assignment operator can change the value of any modifiable target
//: object to that of any source object.
//:
//: 2 The allocator address held by the target object is unchanged.
//:
//: 3 Any memory allocation is from the target object's allocator.
//:
//: 4 The signature and return type are standard.
//:
//: 5 The reference returned is to the target object (i.e., '*this').
//:
//: 6 The value of the source object is not modified.
//:
//: 7 The allocator address held by the source object is unchanged.
//:
//: 8 QoI: Assigning a source object having the default-constructed value
//: allocates no memory.
//:
//: 9 Any memory allocation is exception neutral.
//:
//:10 Assigning an object to itself behaves as expected (alias-safety).
//:
//:11 Every object releases any allocated memory at destruction.
//
// Plan:
//: 1 Use the address of 'operator=' to initialize a member-function
//: pointer having the appropriate signature and return type for the
//: copy-assignment operator defined in this component. (C-4)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the default
//: allocator (note that a ubiquitous test allocator is already installed
//: as the global allocator).
//:
//: 3 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values.
//:
//: 4 For each row 'R1' (representing a distinct object value, 'V') in the
//: table described in P-3: (C-1..2, 5..8, 11)
//:
//: 1 Use the value constructor and a "scratch" allocator to create two
//: 'const' 'Obj', 'Z' and 'ZZ', each having the value 'V'.
//:
//: 2 Execute an inner loop that iterates over each row 'R2'
//: (representing a distinct object value, 'W') in the table described
//: in P-3:
//:
//: 3 For each of the iterations (P-4.2): (C-1..2, 5..8, 11)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable 'Obj',
//: 'mX', having the value 'W'.
//:
//: 3 Assign 'mX' from 'Z' in the presence of injected exceptions
//: (using the 'bslma::TestAllocator_EXCEPTION_TEST_*' macros).
//:
//: 4 Verify that the address of the return value is the same as that
//: of 'mX'. (C-5)
//:
//: 5 Use the equality-comparison operator to verify that: (C-1, 6)
//:
//: 1 The target object, 'mX', now has the same value as that of 'Z'.
//: (C-1)
//:
//: 2 'Z' still has the same value as that of 'ZZ'. (C-6)
//:
//: 6 Use the 'allocator' accessor of both 'mX' and 'Z' to verify that
//: the respective allocator addresses held by the target and source
//: objects are unchanged. (C-2, 7)
//:
//: 7 Use the appropriate test allocators to verify that: (C-8, 11)
//:
//: 1 For an object that (a) is initialized with a value that did NOT
//: require memory allocation, and (b) is then assigned a value
//: that DID require memory allocation, the target object DOES
//: allocate memory from its object allocator only (irrespective of
//: the specific number of allocations or the total amount of
//: memory allocated); also cross check with what is expected for
//: 'mX' and 'Z'.
//:
//: 2 An object that is assigned a value that did NOT require memory
//: allocation, does NOT allocate memory from its object allocator;
//: also cross check with what is expected for 'Z'.
//:
//: 3 No additional memory is allocated by the source object. (C-8)
//:
//: 4 All object memory is released when the object is destroyed.
//: (C-11)
//:
//: 5 Repeat steps similar to those described in P-4 except that, this
//: time, there is no inner loop (as in P-4.2); instead, the source
//: object, 'Z', is a reference to the target object, 'mX', and both 'mX'
//: and 'ZZ' are initialized to have the value 'V'. For each row
//: (representing a distinct object value, 'V') in the table described in
//: P-3: (C-9)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable 'Obj'
//: 'mX'; also use the value constructor and a distinct "scratch"
//: allocator to create a 'const' 'Obj' 'ZZ'.
//:
//: 3 Let 'Z' be a reference providing only 'const' access to 'mX'.
//:
//: 4 Assign 'mX' from 'Z' in the presence of injected exceptions (using
//: the 'bslma::TestAllocator_EXCEPTION_TEST_*' macros). (C-9)
//:
//: 5 Verify that the address of the return value is the same as that of
//: 'mX'.
//:
//: 6 Use the equality-comparison operator to verify that the target
//: object, 'mX', still has the same value as that of 'ZZ'.
//:
//: 7 Use the 'allocator' accessor of 'mX' to verify that it is still the
//: object allocator.
//:
//: 8 Use the appropriate test allocators to verify that:
//:
//: 1 Any memory that is allocated is from the object allocator.
//:
//: 2 No additional (e.g., temporary) object memory is allocated when
//: assigning an object value that did NOT initially require
//: allocated memory.
//:
//: 3 All object memory is released when the object is destroyed.
//:
//: 6 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-3)
//
// Testing:
// set& operator=(const set& rhs);
// ------------------------------------------------------------------------
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) printf("\nCompare each pair of similar and different"
" values (u, ua, v, va) in S X A X S X A"
" without perturbation.\n");
{
// Create first object
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const char *const SPEC1 = DATA[ti].d_spec;
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mZ(&scratch); const Obj& Z = gg(&mZ, SPEC1);
Obj mZZ(&scratch); const Obj& ZZ = gg(&mZZ, SPEC1);
// Ensure the first row of the table contains the
// default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
ASSERTV(LINE1, Obj(&scratch) == Z);
firstFlag = false;
}
// Create second object
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const char *const SPEC2 = DATA[tj].d_spec;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
{
Obj mX(&oa); const Obj& X = gg(&mX, SPEC2);
ASSERTV(LINE1, LINE2, (Z == X) == (LINE1 == LINE2));
bslma::TestAllocatorMonitor oam(&oa), sam(&scratch);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj *mR = &(mX = Z);
ASSERTV(LINE1, LINE2, Z == X);
ASSERTV(LINE1, LINE2, mR == &mX);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERTV(LINE1, LINE2, ZZ == Z);
// ASSERTV(LINE1, LINE2, &oa == X.get_allocator());
// ASSERTV(LINE1, LINE2, &scratch == Z.get_allocator());
ASSERTV(LINE1, LINE2, sam.isInUseSame());
ASSERTV(LINE1, LINE2, 0 == da.numBlocksTotal());
}
// Verify all memory is released on object destruction.
ASSERTV(LINE1, LINE2, oa.numBlocksInUse(),
0 == oa.numBlocksInUse());
}
// self-assignment
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
{
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mX(&oa); const Obj& X = gg(&mX, SPEC1);
Obj mZZ(&scratch); const Obj& ZZ = gg(&mZZ, SPEC1);
const Obj& Z = mX;
ASSERTV(LINE1, ZZ == Z);
bslma::TestAllocatorMonitor oam(&oa), sam(&scratch);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj *mR = &(mX = Z);
ASSERTV(LINE1, ZZ == Z);
ASSERTV(LINE1, mR == &X);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
// ASSERTV(LINE1, &oa == Z.get_allocator());
ASSERTV(LINE1, sam.isTotalSame());
ASSERTV(LINE1, oam.isTotalSame());
ASSERTV(LINE1, 0 == da.numBlocksTotal());
}
// Verify all object memory is released on destruction.
ASSERTV(LINE1, oa.numBlocksInUse(), 0 == oa.numBlocksInUse());
}
}
}
template <class CONTAINER>
template <bool PROPAGATE_ON_CONTAINER_SWAP_FLAG,
bool OTHER_FLAGS>
void TestDriver<CONTAINER>::testCase8_propagate_on_container_swap_dispatch()
{
typedef typename CONTAINER::value_type VALUE;
// Set the three properties of 'bsltf::StdStatefulAllocator' that are not
// under test in this test case to 'false'.
typedef bsltf::StdStatefulAllocator<VALUE,
OTHER_FLAGS,
OTHER_FLAGS,
PROPAGATE_ON_CONTAINER_SWAP_FLAG,
OTHER_FLAGS> StdAlloc;
typedef bsl::deque<VALUE, StdAlloc> CObj;
typedef bsl::stack<VALUE, CObj> Obj;
const bool PROPAGATE = PROPAGATE_ON_CONTAINER_SWAP_FLAG;
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
};
const int NUM_SPECS = static_cast<const int>(sizeof SPECS / sizeof *SPECS);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const ISPEC = SPECS[ti];
const size_t ILENGTH = strlen(ISPEC);
TestValues IVALUES(ISPEC);
bslma::TestAllocator xoa("x-original", veryVeryVeryVerbose);
bslma::TestAllocator yoa("y-original", veryVeryVeryVerbose);
StdAlloc xma(&xoa);
StdAlloc yma(&yoa);
StdAlloc scratch(&da);
const CObj CI(IVALUES.begin(), IVALUES.end(), scratch);
const Obj ZZ(CI, scratch); // control
for (int tj = 0; tj < NUM_SPECS; ++tj) {
const char *const JSPEC = SPECS[tj];
const size_t JLENGTH = strlen(JSPEC);
TestValues JVALUES(JSPEC);
const CObj CJ(JVALUES.begin(), JVALUES.end(), scratch);
const Obj WW(CJ, scratch); // control
{
Obj mX(CI, xma); const Obj& X = mX;
if (veryVerbose) { T_ P_(ISPEC) P_(X) P(ZZ) }
Obj mY(CJ, yma); const Obj& Y = mY;
ASSERTV(ISPEC, JSPEC, ZZ, X, ZZ == X);
ASSERTV(ISPEC, JSPEC, WW, Y, WW == Y);
// member 'swap'
{
bslma::TestAllocatorMonitor dam(&da);
bslma::TestAllocatorMonitor xoam(&xoa);
bslma::TestAllocatorMonitor yoam(&yoa);
mX.swap(mY);
ASSERTV(ISPEC, JSPEC, WW, X, WW == X);
ASSERTV(ISPEC, JSPEC, ZZ, Y, ZZ == Y);
if (PROPAGATE) {
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(ISPEC, JSPEC, yma == X.get_allocator());
ASSERTV(ISPEC, JSPEC, xma == Y.get_allocator());
#endif
ASSERTV(ISPEC, JSPEC, dam.isTotalSame());
ASSERTV(ISPEC, JSPEC, xoam.isTotalSame());
ASSERTV(ISPEC, JSPEC, yoam.isTotalSame());
}
// TBD no 'get_allocator' in 'stack'
#if 0
else {
ASSERTV(ISPEC, JSPEC, xma == X.get_allocator());
ASSERTV(ISPEC, JSPEC, yma == Y.get_allocator());
}
#endif
}
// free function 'swap'
{
bslma::TestAllocatorMonitor dam(&da);
bslma::TestAllocatorMonitor xoam(&xoa);
bslma::TestAllocatorMonitor yoam(&yoa);
swap(mX, mY);
ASSERTV(ISPEC, JSPEC, ZZ, X, ZZ == X);
ASSERTV(ISPEC, JSPEC, WW, Y, WW == Y);
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(ISPEC, JSPEC, xma == X.get_allocator());
ASSERTV(ISPEC, JSPEC, yma == Y.get_allocator());
#endif
if (PROPAGATE) {
ASSERTV(ISPEC, JSPEC, dam.isTotalSame());
ASSERTV(ISPEC, JSPEC, xoam.isTotalSame());
ASSERTV(ISPEC, JSPEC, yoam.isTotalSame());
}
}
}
ASSERTV(ISPEC, 0 == xoa.numBlocksInUse());
ASSERTV(ISPEC, 0 == yoa.numBlocksInUse());
}
}
ASSERTV(0 == da.numBlocksInUse());
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase8_propagate_on_container_swap()
{
// ------------------------------------------------------------------------
// SWAP MEMBER AND FREE FUNCTIONS: ALLOCATOR PROPAGATION
//
// Concerns:
//: 1 If the 'propagate_on_container_swap' trait is 'false', the
//: allocators used by the source and target objects remain unchanged
//: (i.e., the allocators are *not* exchanged).
//:
//: 2 If the 'propagate_on_container_swap' trait is 'true', the
//: allocator used by the target (source) object is updated to be a copy
//: of that used by the source (target) object (i.e., the allocators
//: *are* exchanged).
//:
//: 3 If the allocators are propagated (i.e., exchanged), there is no
//: additional allocation from any allocator.
//:
//: 4 The effect of the 'propagate_on_container_swap' trait is independent
//: of the other three allocator propagation traits.
//:
//: 5 Following the swap operation, neither object holds on to memory
//: allocated from the other object's allocator.
//
// Plan:
//: 1 Specify a set S of object values with varied differences, ordered by
//: increasing length, to be used in the following tests.
//:
//: 2 Create two 'bsltf::StdStatefulAllocator' objects with their
//: 'propagate_on_container_swap' property configured to 'false'. In two
//: successive iterations of P-3, first configure the three properties
//: not under test to be 'false', then configure them all to be 'true'.
//:
//: 3 For each value '(x, y)' in the cross product S x S: (C-1)
//:
//: 1 Initialize two objects from 'x', a control object 'ZZ' using a
//: scratch allocator and an object 'X' using one of the allocators
//: from P-2.
//:
//: 2 Initialize two objects from 'y', a control object 'WW' using a
//: scratch allocator and an object 'Y' using the other allocator from
//: P-2.
//:
//: 3 Using both member 'swap' and free function 'swap', swap 'X' with
//: 'Y' and use 'operator==' to verify that 'X' and 'Y' have the
//: expected values.
//:
//: 4 Use the 'get_allocator' method to verify that the allocators of 'X'
//: and 'Y' are *not* exchanged. (C-1)
//:
//: 4 Repeat P-2..3 except that this time configure the allocator property
//: under test to 'true' and verify that the allocators of 'X' and 'Y'
//: *are* exchanged. Also verify that there is no additional allocation
//: from any allocator. (C-2..5)
//
// Testing:
// propagate_on_container_swap
// ------------------------------------------------------------------------
if (verbose)
printf("\nSWAP MEMBER AND FREE FUNCTIONS: ALLOCATOR PROPAGATION"
"\n=====================================================\n");
if (verbose) printf("\n'propagate_on_container_swap::value == false'\n");
testCase8_propagate_on_container_swap_dispatch<false, false>();
testCase8_propagate_on_container_swap_dispatch<false, true>();
if (verbose) printf("\n'propagate_on_container_swap::value == true'\n");
testCase8_propagate_on_container_swap_dispatch<true, false>();
testCase8_propagate_on_container_swap_dispatch<true, true>();
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase8()
{
// ------------------------------------------------------------------------
// SWAP MEMBER AND FREE FUNCTIONS
// Ensure that, when member and free 'swap' are implemented, we can
// exchange the values of any two objects that use the same
// allocator.
//
// Concerns:
//: 1 Both functions exchange the values of the (two) supplied objects.
//:
//: 2 The common object allocator address held by both objects is
//: unchanged.
//:
//: 3 If the two objects being swapped uses the same allocators, neither
//: function allocates memory from any allocator.
//:
//: 4 Both functions have standard signatures and return types.
//:
//: 5 Two objects with different allocators may be swapped. In which case,
//: memory may be allocated.
//:
//: 6 Using either function to swap an object with itself does not
//: affect the value of the object (alias-safety).
//:
//: 7 The free 'swap' function is discoverable through ADL (Argument
//: Dependent Lookup).
//:
//: 8 QoI: Asserted precondition violations are detected when enabled.
//
// Plan:
//: 1 Use the addresses of the 'swap' member and free functions defined
//: in this component to initialize, respectively, member-function
//: and free-function pointers having the appropriate signatures and
//: return types. (C-4)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the
//: default allocator (note that a ubiquitous test allocator is
//: already installed as the global allocator).
//:
//: 3 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values (one per row) in
//: terms of their individual attributes, including (a) first, the
//: default value, (b) boundary values corresponding to every range
//: of values that each individual attribute can independently
//: attain, and (c) values that should require allocation from each
//: individual attribute that can independently allocate memory.
//:
//: 2 Additionally, provide a (tri-valued) column, 'MEM', indicating
//: the expectation of memory allocation for all typical
//: implementations of individual attribute types: ('Y') "Yes",
//: ('N') "No", or ('?') "implementation-dependent".
//:
//: 4 For each row 'R1' in the table of P-3: (C-1..2, 6)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable
//: 'Obj', 'mW', having the value described by 'R1'; also use the
//: copy constructor and a "scratch" allocator to create a 'const'
//: 'Obj' 'XX' from 'mW'.
//:
//: 3 Use the member and free 'swap' functions to swap the value of
//: 'mW' with itself; verify, after each swap, that: (C-6)
//:
//: 1 The value is unchanged. (C-6)
//:
//: 2 The allocator address held by the object is unchanged.
//:
//: 3 There was no additional object memory allocation.
//:
//: 4 For each row 'R2' in the table of P-3: (C-1..2)
//:
//: 1 Use the copy constructor and 'oa' to create a modifiable
//: 'Obj', 'mX', from 'XX' (P-4.2).
//:
//: 2 Use the value constructor and 'oa' to create a modifiable
//: 'Obj', 'mY', and having the value described by 'R2'; also use
//: the copy constructor to create, using a "scratch" allocator,
//: a 'const' 'Obj', 'YY', from 'Y'.
//:
//: 3 Use, in turn, the member and free 'swap' functions to swap
//: the values of 'mX' and 'mY'; verify, after each swap, that:
//: (C-1..2)
//:
//: 1 The values have been exchanged. (C-1)
//:
//: 2 The common object allocator address held by 'mX' and 'mY'
//: is unchanged in both objects. (C-2)
//:
//: 3 There was no additional object memory allocation.
//:
//: 5 Create a new object allocator, 'oaz'
//:
//: 6 Repeat P-4.4.2 with 'oaz' under the presence of exception.
//:
//: 5 Verify that the free 'swap' function is discoverable through ADL:
//: (C-6)
//:
//: 1 Create a set of attribute values, 'A', distinct from the values
//: corresponding to the default-constructed object, choosing
//: values that allocate memory if possible.
//:
//: 2 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 3 Use the default constructor and 'oa' to create a modifiable
//: 'Obj' 'mX' (having default attribute values); also use the copy
//: constructor and a "scratch" allocator to create a 'const' 'Obj'
//: 'XX' from 'mX'.
//:
//: 4 Use the value constructor and 'oa' to create a modifiable 'Obj'
//: 'mY' having the value described by the 'Ai' attributes; also
//: use the copy constructor and a "scratch" allocator to create a
//: 'const' 'Obj' 'YY' from 'mY'.
//:
//: 5 Use the 'invokeAdlSwap' helper function template to swap the
//: values of 'mX' and 'mY', using the free 'swap' function defined
//: in this component, then verify that: (C-7)
//:
//: 1 The values have been exchanged.
//:
//: 2 There was no additional object memory allocation. (C-7)
//:
//: 6 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-3)
//:
//: 7 Verify that, in appropriate build modes, defensive checks are
//: triggered when an attempt is made to swap objects that do not
//: refer to the same allocator, but not when the allocators are the
//: same (using the 'BSLS_ASSERTTEST_*' macros). (C-7)
//
// Testing:
// void swap(set& other);
// void swap(set<K, C, A>& a, set<K, C, A>& b);
// ------------------------------------------------------------------------
if (verbose) printf("\nSWAP MEMBER AND FREE FUNCTIONS"
"\n==============================\n");
if (verbose) printf(
"\nAssign the address of each function to a variable.\n");
{
typedef void (Obj::*funcPtr)(Obj&);
typedef void (*freeFuncPtr)(Obj&, Obj&);
// Verify that the signatures and return types are standard.
funcPtr memberSwap = &Obj::swap;
freeFuncPtr freeSwap = bsl::swap;
(void) memberSwap; // quash potential compiler warnings
(void) freeSwap;
}
if (verbose) printf(
"\nCreate a test allocator and install it as the default.\n");
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) printf(
"\nUse a table of distinct object values and expected memory usage.\n");
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const char *const SPEC1 = DATA[ti].d_spec;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mW(&oa); const Obj& W = gg(&mW, SPEC1);
const Obj XX(W, &scratch);
// Ensure the first row of the table contains the
// default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
ASSERTV(LINE1, Obj() == W);
firstFlag = false;
}
// member 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
mW.swap(mW);
ASSERTV(LINE1, XX == W);
// ASSERTV(LINE1, &oa == W.get_allocator());
ASSERTV(LINE1, oam.isTotalSame());
}
// free function 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
swap(mW, mW);
ASSERTV(LINE1, XX == W);
// ASSERTV(LINE1, &oa == W.get_allocator());
ASSERTV(LINE1, oam.isTotalSame());
}
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const char *const SPEC2 = DATA[tj].d_spec;
Obj mX(XX, &oa); const Obj& X = mX;
Obj mY(&oa); const Obj& Y = gg(&mY, SPEC2);
const Obj YY(Y, &scratch);
// member 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
mX.swap(mY);
ASSERTV(LINE1, LINE2, YY == X);
ASSERTV(LINE1, LINE2, XX == Y);
// ASSERTV(LINE1, LINE2, &oa == X.get_allocator());
// ASSERTV(LINE1, LINE2, &oa == Y.get_allocator());
ASSERTV(LINE1, LINE2, oam.isTotalSame());
}
// free function 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
swap(mX, mY);
ASSERTV(LINE1, LINE2, XX == X);
ASSERTV(LINE1, LINE2, YY == Y);
// ASSERTV(LINE1, LINE2, &oa == X.get_allocator());
// ASSERTV(LINE1, LINE2, &oa == Y.get_allocator());
ASSERTV(LINE1, LINE2, oam.isTotalSame());
}
bslma::TestAllocator oaz("z_object", veryVeryVeryVerbose);
Obj mZ(&oaz); const Obj& Z = gg(&mZ, SPEC2);
const Obj ZZ(Z, &scratch);
// member 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
bslma::TestAllocatorMonitor oazm(&oaz);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
ExceptionGuard<Obj> guardX(&X, L_, &scratch);
ExceptionGuard<Obj> guardZ(&Z, L_, &scratch);
mX.swap(mZ);
guardX.release();
guardZ.release();
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERTV(LINE1, LINE2, ZZ == X);
ASSERTV(LINE1, LINE2, XX == Z);
// ASSERTV(LINE1, LINE2, &oa == X.get_allocator());
// ASSERTV(LINE1, LINE2, &oaz == Z.get_allocator());
if (0 == X.size()) {
ASSERTV(LINE1, LINE2, emptyWillAlloc()||oam.isTotalSame());
}
else {
ASSERTV(LINE1, LINE2, oam.isTotalUp());
}
if (0 == Z.size()) {
ASSERTV(LINE1, LINE2, emptyWillAlloc() ||
oazm.isTotalSame());
}
else {
ASSERTV(LINE1, LINE2, oazm.isTotalUp());
}
}
// free function 'swap'
{
bslma::TestAllocatorMonitor oam(&oa);
bslma::TestAllocatorMonitor oazm(&oaz);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
ExceptionGuard<Obj> guardX(&X, L_, &scratch);
ExceptionGuard<Obj> guardZ(&Z, L_, &scratch);
swap(mX, mZ);
guardX.release();
guardZ.release();
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERTV(LINE1, LINE2, XX == X);
ASSERTV(LINE1, LINE2, ZZ == Z);
// ASSERTV(LINE1, LINE2, &oa == X.get_allocator());
// ASSERTV(LINE1, LINE2, &oaz == Z.get_allocator());
if (0 == X.size()) {
ASSERTV(LINE1, LINE2, emptyWillAlloc()||oam.isTotalSame());
}
else {
ASSERTV(LINE1, LINE2, oam.isTotalUp());
}
if (0 == Z.size()) {
ASSERTV(LINE1, LINE2, emptyWillAlloc() ||
oazm.isTotalSame());
}
else {
ASSERTV(LINE1, LINE2, oazm.isTotalUp());
}
}
}
}
if (verbose) printf(
"\nInvoke free 'swap' function in a context where ADL is used.\n");
{
// 'A' values: Should cause memory allocation if possible.
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mX(&oa); const Obj& X = mX;
const Obj XX(X, &scratch);
Obj mY(&oa); const Obj& Y = gg(&mY, "ABC");
const Obj YY(Y, &scratch);
bslma::TestAllocatorMonitor oam(&oa);
invokeAdlSwap(mX, mY);
ASSERTV(YY == X);
ASSERTV(XX == Y);
ASSERT(oam.isTotalSame());
}
}
template <class CONTAINER>
template <bool SELECT_ON_CONTAINER_COPY_CONSTRUCTION_FLAG,
bool OTHER_FLAGS>
void TestDriver<CONTAINER>::
testCase7_select_on_container_copy_construction_dispatch()
{
typedef typename CONTAINER::value_type VALUE;
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
// Set the three properties of 'bsltf::StdStatefulAllocator' that are not
// under test in this test case to 'false'.
typedef bsltf::StdStatefulAllocator<
VALUE,
SELECT_ON_CONTAINER_COPY_CONSTRUCTION_FLAG,
OTHER_FLAGS,
OTHER_FLAGS,
OTHER_FLAGS> StdAlloc;
typedef bsl::deque<VALUE, StdAlloc> CObj;
typedef bsl::stack<VALUE, CObj> Obj;
const bool PROPAGATE = SELECT_ON_CONTAINER_COPY_CONSTRUCTION_FLAG;
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
};
const int NUM_SPECS = static_cast<const int>(sizeof SPECS / sizeof *SPECS);
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const SPEC = SPECS[ti];
const size_t LENGTH = strlen(SPEC);
TestValues VALUES(SPEC);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
StdAlloc ma(&oa);
StdAlloc scratch(&da);
{
const CObj C(VALUES.begin(), VALUES.end(), scratch);
const Obj W(C, ma); // control
ASSERTV(ti, LENGTH == W.size()); // same lengths
if (veryVerbose) { printf("\tControl Obj: "); P(W); }
Obj mX(C, ma); const Obj& X = mX;
if (veryVerbose) { printf("\t\tDynamic Obj: "); P(X); }
bslma::TestAllocatorMonitor dam(&da);
bslma::TestAllocatorMonitor oam(&oa);
const Obj Y(X);
ASSERTV(SPEC, W == Y);
ASSERTV(SPEC, W == X);
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(SPEC, PROPAGATE, PROPAGATE == (ma == Y.get_allocator()));
ASSERTV(SPEC, PROPAGATE, ma == X.get_allocator());
#endif
if (PROPAGATE) {
ASSERTV(SPEC, 0 != TYPE_ALLOC || dam.isInUseSame());
ASSERTV(SPEC, 0 == LENGTH || oam.isInUseUp());
}
else {
ASSERTV(SPEC, 0 == LENGTH || dam.isInUseUp());
ASSERTV(SPEC, oam.isTotalSame());
}
}
ASSERTV(SPEC, 0 == da.numBlocksInUse());
ASSERTV(SPEC, 0 == oa.numBlocksInUse());
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase7_select_on_container_copy_construction()
{
// ------------------------------------------------------------------------
// COPY CONSTRUCTOR: ALLOCATOR PROPAGATION
//
// Concerns:
//: 1 The allocator of a source object using a standard allocator is
//: propagated to the newly constructed object according to the
//: 'select_on_container_copy_construction' method of the allocator.
//:
//: 2 In the absence of a 'select_on_container_copy_construction' method,
//: the allocator of a source object using a standard allocator is always
//: propagated to the newly constructed object (C++03 semantics).
//:
//: 3 The effect of the 'select_on_container_copy_construction' trait is
//: independent of the other three allocator propagation traits.
//
// Plan:
//: 1 Specify a set S of object values with varied differences, ordered by
//: increasing length, to be used in the following tests.
//:
//: 2 Create a 'bsltf::StdStatefulAllocator' with its
//: 'select_on_container_copy_construction' property configured to
//: 'false'. In two successive iterations of P-3..5, first configure the
//: three properties not under test to be 'false', then confgiure them
//: all to be 'true'.
//:
//: 3 For each value in S, initialize objects 'W' (a control) and 'X' using
//: the allocator from P-2.
//:
//: 4 Copy construct 'Y' from 'X' and use 'operator==' to verify that both
//: 'X' and 'Y' subsequently have the same value as 'W'.
//:
//: 5 Use the 'get_allocator' method to verify that the allocator of 'X'
//: is *not* propagated to 'Y'.
//:
//: 6 Repeat P-2..5 except that this time configure the allocator property
//: under test to 'true' and verify that the allocator of 'X' *is*
//: propagated to 'Y'. (C-1)
//:
//: 7 Repeat P-2..5 except that this time use a 'StatefulStlAllocator',
//: which does not define a 'select_on_container_copy_construction'
//: method, and verify that the allocator of 'X' is *always* propagated
//: to 'Y'. (C-2..3)
//
// Testing:
// select_on_container_copy_construction
// ------------------------------------------------------------------------
if (verbose) printf("\n'select_on_container_copy_construction' "
"propagates *default* allocator.\n");
testCase7_select_on_container_copy_construction_dispatch<false, false>();
testCase7_select_on_container_copy_construction_dispatch<false, true>();
if (verbose) printf("\n'select_on_container_copy_construction' "
"propagates allocator of source object.\n");
testCase7_select_on_container_copy_construction_dispatch<true, false>();
testCase7_select_on_container_copy_construction_dispatch<true, true>();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\nVerify C++03 semantics (allocator has no "
"'select_on_container_copy_construction' method).\n");
typedef typename CONTAINER::value_type VALUE;
typedef StatefulStlAllocator<VALUE> Allocator;
typedef bsl::deque<VALUE, Allocator> CObj;
typedef bsl::stack<VALUE, CObj> Obj;
{
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
};
const int NUM_SPECS =
static_cast<const int>(sizeof SPECS / sizeof *SPECS);
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const SPEC = SPECS[ti];
const size_t LENGTH = strlen(SPEC);
TestValues VALUES(SPEC);
const int ALLOC_ID = ti + 73;
Allocator a; a.setId(ALLOC_ID);
const CObj C(VALUES.begin(), VALUES.end(), a);
const Obj W(C, a); // control
ASSERTV(ti, LENGTH == W.size()); // same lengths
if (veryVerbose) { printf("\tControl Obj: "); P(W); }
Obj mX(C, a); const Obj& X = mX;
if (veryVerbose) { printf("\t\tDynamic Obj: "); P(X); }
const Obj Y(X);
ASSERTV(SPEC, W == Y);
ASSERTV(SPEC, W == X);
// TBD no 'get_allocator' in 'stack'
#if 0
ASSERTV(SPEC, ALLOC_ID == Y.get_allocator().id());
#endif
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase7()
{
// ------------------------------------------------------------------------
// TESTING COPY CONSTRUCTOR:
//: 1 The new object's value is the same as that of the original object
//: (relying on the equality operator) and created with the correct
//: capacity.
//:
//: 2 The value of the original object is left unaffected.
//:
//: 3 Subsequent changes in or destruction of the source object have no
//: effect on the copy-constructed object.
//:
//: 4 Subsequent changes ('insert's) on the created object have no
//: effect on the original and change the capacity of the new object
//: correctly.
//:
//: 5 The object has its internal memory management system hooked up
//: properly so that *all* internally allocated memory draws from a
//: user-supplied allocator whenever one is specified.
//:
//: 6 The function is exception neutral w.r.t. memory allocation.
//
// Plan:
//: 1 Specify a set S of object values with substantial and varied
//: differences, ordered by increasing length, to be used in the
//: following tests.
//:
//: 2 For each value in S, initialize objects w and x, copy construct y
//: from x and use 'operator==' to verify that both x and y subsequently
//: have the same value as w. Let x go out of scope and again verify
//: that w == y. (C-1..4)
//:
//: 3 For each value in S initialize objects w and x, and copy construct y
//: from x. Change the state of y, by using the *primary* *manipulator*
//: 'push'. Using the 'operator!=' verify that y differs from x and
//: w, and verify that the capacity of y changes correctly. (C-5)
//:
//: 4 Perform tests performed as P-2: (C-6)
//: 1 While passing a testAllocator as a parameter to the new object and
//: ascertaining that the new object gets its memory from the provided
//: testAllocator.
//: 2 Verify neither of global and default allocator is used to supply
//: memory. (C-6)
//:
//: 5 Perform tests as P-2 in the presence of exceptions during memory
//: allocations using a 'bslma::TestAllocator' and varying its
//: *allocation* *limit*. (C-7)
//
// Testing:
// set(const set& original);
// set(const set& original, const A& allocator);
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const char *val = ValueName<value_type>::name();
if (verbose) { P_(cont); P_(val); P(typeAlloc()); }
const TestValues VALUES; // contains 52 distinct increasing values
bslma::TestAllocator da(veryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocator oa(veryVeryVerbose);
{
static const char *SPECS[] = {
"",
"A",
"BC",
"CDE",
"DEAB",
"EABCD",
"ABCDEFG",
"HFGEDCBA",
"CFHEBIDGA",
"BENCKHGMALJDFOI",
"IDMLNEFHOPKGBCJA",
"OIQGDNPMLKBACHFEJ"
};
const int NUM_SPECS = sizeof SPECS / sizeof *SPECS;
for (int ti = 0; ti < NUM_SPECS; ++ti) {
const char *const SPEC = SPECS[ti];
const size_t LENGTH = strlen(SPEC);
if (verbose) {
printf("\nFor an object of length " ZU ":\n", LENGTH);
P(SPEC);
}
// Create control object 'W'.
Obj mW; const Obj& W = gg(&mW, SPEC);
ASSERTV(ti, LENGTH == W.size()); // same lengths
Obj mX(&oa); const Obj& X = gg(&mX, SPEC);
ASSERT(W == X);
{ // Testing concern 1..4.
if (veryVerbose) { printf("\t\t\tRegular Case :"); }
Obj *pX = new Obj(&oa);
gg(pX, SPEC);
const Obj Y0(*pX);
ASSERTV(SPEC, W == Y0);
ASSERTV(SPEC, W == X);
// ASSERTV(SPEC, Y0.get_allocator() ==
// bslma::Default::defaultAllocator());
delete pX;
ASSERTV(SPEC, W == Y0);
}
{ // Testing concern 5.
if (veryVerbose) printf("\t\t\tInsert into created obj, "
"without test allocator:\n");
Obj mY1(X); const Obj& Y1 = mY1;
mY1.push(VALUES['Z' - 'A']);
ASSERTV(SPEC, Y1.size() == LENGTH + 1);
ASSERTV(SPEC, W != Y1);
ASSERTV(SPEC, X != Y1);
ASSERTV(SPEC, W == X);
}
{ // Testing concern 5 with test allocator.
if (veryVerbose)
printf("\t\t\tInsert into created obj, "
"with test allocator:\n");
bslma::TestAllocatorMonitor dam(&da);
bslma::TestAllocatorMonitor oam(&oa);
Obj mY11(X, &oa); const Obj& Y11 = mY11;
ASSERT(dam.isTotalSame());
ASSERTV(cont, LENGTH, oam.isTotalSame(), emptyWillAlloc(),
oam.isTotalSame() == (!emptyWillAlloc() && 0 == LENGTH));
mY11.push(VALUES['Z' - 'A']);
ASSERT(dam.isTotalSame());
ASSERTV(SPEC, Y11.size() == LENGTH + 1);
ASSERTV(SPEC, W != Y11);
ASSERTV(SPEC, X != Y11);
// ASSERTV(SPEC, Y11.get_allocator() == X.get_allocator());
}
{ // Exception checking.
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
bslma::TestAllocatorMonitor dam(&da);
bslma::TestAllocatorMonitor oam(&oa);
const Obj Y2(X, &oa);
if (veryVerbose) {
printf("\t\t\tException Case :\n");
}
ASSERT(dam.isTotalSame());
ASSERT(oam.isTotalUp() || (!emptyWillAlloc() &&
0 == LENGTH));
ASSERTV(SPEC, W == Y2);
ASSERTV(SPEC, W == X);
// ASSERTV(SPEC, Y2.get_allocator() == X.get_allocator());
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase6()
{
// ---------------------------------------------------------------------
// TESTING EQUALITY OPERATORS:
// Concerns:
//: 1 Two objects, 'X' and 'Y', compare equal if and only if they contain
//: the same values.
//:
//: 2 No non-salient attributes (i.e., 'allocator') participate.
//:
//: 3 'true == (X == X)' (i.e., identity)
//:
//: 4 'false == (X != X)' (i.e., identity)
//:
//: 5 'X == Y' if and only if 'Y == X' (i.e., commutativity)
//:
//: 6 'X != Y' if and only if 'Y != X' (i.e., commutativity)
//:
//: 7 'X != Y' if and only if '!(X == Y)'
//
// Plan:
//: 1 Use the respective addresses of 'operator==' and 'operator!=' to
//: initialize function pointers having the appropriate signatures and
//: return types for the two homogeneous, free equality- comparison
//: operators defined in this component. (C-8..9, 12..13)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the default
//: allocator (note that a ubiquitous test allocator is already installed
//: as the global allocator).
//:
//: 3 Using the table-driven technique, specify a set of distinct
//: specifications for the 'gg' function.
//:
//: 4 For each row 'R1' in the table of P-3: (C-1..7)
//:
//: 1 Create a single object, using a comparator that can be disabled and
//: a"scratch" allocator, and use it to verify the reflexive
//: (anti-reflexive) property of equality (inequality) in the presence
//: of aliasing. (C-3..4)
//:
//: 2 For each row 'R2' in the table of P-3: (C-1..2, 5..7)
//:
//: 1 Record, in 'EXP', whether or not distinct objects created from
//: 'R1' and 'R2', respectively, are expected to have the same value.
//:
//: 2 For each of two configurations, 'a' and 'b': (C-1..2, 5..7)
//:
//: 1 Create two (object) allocators, 'oax' and 'oay'.
//:
//: 2 Create an object 'X', using 'oax', having the value 'R1'.
//:
//: 3 Create an object 'Y', using 'oax' in configuration 'a' and
//: 'oay' in configuration 'b', having the value 'R2'.
//:
//: 4 Disable the comparator so that it will cause an error if it's
//: used.
//:
//: 5 Verify the commutativity property and expected return value for
//: both '==' and '!=', while monitoring both 'oax' and 'oay' to
//: ensure that no object memory is ever allocated by either
//: operator. (C-1..2, 5..7, 10)
//:
//: 5 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-11)
//
// Testing:
// bool operator==(const set<K, C, A>& lhs, const set<K, C, A>& rhs);
// bool operator!=(const set<K, C, A>& lhs, const set<K, C, A>& rhs);
// ------------------------------------------------------------------------
if (verbose) printf("\nEQUALITY-COMPARISON OPERATORS"
"\n=============================\n");
if (verbose)
printf("\nAssign the address of each operator to a variable.\n");
{
typedef bool (*operatorPtr)(const Obj&, const Obj&);
// Verify that the signatures and return types are standard.
operatorPtr operatorEq = operator==;
operatorPtr operatorNe = operator!=;
(void) operatorEq; // quash potential compiler warnings
(void) operatorNe;
}
const int NUM_DATA = DEFAULT_NUM_DATA;
const DefaultDataRow (&DATA)[NUM_DATA] = DEFAULT_DATA;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocatorMonitor dam(&da);
if (verbose) printf("\nCompare every value with every value.\n");
{
// Create first object
for (int ti = 0; ti < NUM_DATA; ++ti) {
const char *const SPEC1 = DATA[ti].d_spec;
const size_t LENGTH1 = strlen(DATA[ti].d_spec);
if (veryVerbose) { T_ P(SPEC1) }
// Ensure an object compares correctly with itself (alias test).
{
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mX(&scratch); const Obj& X = gg(&mX, SPEC1);
ASSERTV(SPEC1, X == X);
ASSERTV(SPEC1, !(X != X));
}
for (int tj = 0; tj < NUM_DATA; ++tj) {
const char *const SPEC2 = DATA[tj].d_spec;
const size_t LENGTH2 = strlen(DATA[tj].d_spec);
if (veryVerbose) {
T_ T_ P(SPEC2) }
const bool EXP = ti == tj; // expected equality
for (char cfg = 'a'; cfg <= 'b'; ++cfg) {
const char CONFIG = cfg; // Determines 'Y's allocator.
// Create two distinct test allocators, 'oax' and 'oay'.
bslma::TestAllocator oax("objectx", veryVeryVeryVerbose);
bslma::TestAllocator oay("objecty", veryVeryVeryVerbose);
// Map allocators above to objects 'X' and 'Y' below.
bslma::TestAllocator& xa = oax;
bslma::TestAllocator& ya = 'a' == CONFIG ? oax : oay;
Obj mX(&xa); const Obj& X = gg(&mX, SPEC1);
Obj mY(&ya); const Obj& Y = gg(&mY, SPEC2);
ASSERTV(CONFIG, LENGTH1 == X.size());
ASSERTV(CONFIG, LENGTH2 == Y.size());
// Verify value, commutativity, and no memory allocation.
bslma::TestAllocatorMonitor oaxm(&xa);
bslma::TestAllocatorMonitor oaym(&ya);
ASSERTV(CONFIG, EXP == (X == Y));
ASSERTV(CONFIG, EXP == (Y == X));
ASSERTV(CONFIG, !EXP == (X != Y));
ASSERTV(CONFIG, !EXP == (Y != X));
ASSERTV(CONFIG, oaxm.isTotalSame());
ASSERTV(CONFIG, oaym.isTotalSame());
}
}
}
}
ASSERT(dam.isTotalSame());
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase4()
{
// ------------------------------------------------------------------------
// BASIC ACCESSORS
// Ensure each basic accessor:
// - top
// - size
// properly interprets object state.
//
// Concerns:
//: 1 Each accessor returns the value of the correct property of the
//: object.
//:
//: 2 Each accessor method is declared 'const'.
//:
//: 3 No accessor allocates any memory.
//:
//
// Plan:
//: 1 For each set of 'SPEC' of different length:
//:
//: 1 Default construct the object with various configuration:
//:
//: 2 Add in a series of objects.
//:
//: 3 Verify 'top' yields the expected result.
//
// Testing:
// const_iterator cbegin();
// const_iterator cend();
// size_type size() const;
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const char *val = ValueName<value_type>::name();
if (verbose) { P_(cont); P_(val); P(typeAlloc()); }
const TestValues VALUES; // contains 52 distinct increasing values
static const struct {
int d_line; // source line number
const char *d_spec; // specification string
const char *d_results; // expected results
} DATA[] = {
//line spec result
//---- -------- ------
{ L_, "", "" },
{ L_, "A", "A" },
{ L_, "AB", "AB" },
{ L_, "ABC", "ABC" },
{ L_, "ABCD", "ABCD" },
{ L_, "ABCDE", "ABCDE" }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) { printf(
"\nCreate objects with various allocator configurations.\n"); }
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char *const SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(DATA[ti].d_results);
const TestValues EXP(DATA[ti].d_results);
if (verbose) { P_(LINE) P_(LENGTH) P(SPEC); }
for (char cfg = 'a'; cfg <= 'd'; ++cfg) {
const char CONFIG = cfg;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa1("supplied1", veryVeryVeryVerbose);
bslma::TestAllocator sa2("supplied2", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
bslma::TestAllocator& oa = 'a' == CONFIG || 'b' == CONFIG
? da
: 'c' == CONFIG
? sa1
: sa2;
bslma::TestAllocator& noa = &oa != &da ? da : sa1;
bslma::TestAllocatorMonitor oam(&oa);
bslma::TestAllocatorMonitor noam(&noa);
Obj& mX = 'a' == CONFIG
? * new (fa) Obj()
: 'b' == CONFIG
? * new (fa) Obj((bslma::Allocator *) 0)
: 'c' == CONFIG
? * new (fa) Obj(&sa1)
: * new (fa) Obj(&sa2);
ASSERT( oam.isTotalUp() == emptyWillAlloc());
ASSERT(noam.isTotalSame());
const Obj& X = gg(&mX, SPEC);
ASSERT(&X == &mX);
oam.reset();
// --------------------------------------------------------
// Verify basic accessors
// ASSERTV(LINE, SPEC, CONFIG, &oa == X.get_allocator());
ASSERTV(LINE, SPEC, CONFIG, LENGTH == X.size());
if (LENGTH > 0) {
ASSERTV(LINE, SPEC, CONFIG, EXP[LENGTH - 1] == mX.top());
ASSERTV(LINE, SPEC, CONFIG, EXP[LENGTH - 1] == X.top());
}
else {
bsls::AssertTestHandlerGuard hG;
ASSERT_SAFE_FAIL(mX.top());
}
ASSERTV(LINE, LENGTH, X.empty(), (0 == LENGTH) == mX.empty());
ASSERTV(LINE, LENGTH, X.empty(), (0 == LENGTH) == X.empty());
ASSERT( oam.isTotalSame());
ASSERT(noam.isTotalSame());
fa.deleteObject(&mX);
}
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase3()
{
// ------------------------------------------------------------------------
// TESTING PRIMITIVE GENERATOR FUNCTIONS gg AND ggg:
// Having demonstrated that our primary manipulators work as expected
// under normal conditions
//
// Concerns:
//: 1 Valid generator syntax produces expected results
//:
//: 2 Invalid syntax is detected and reported.
//
// Plan:
//: 1 For each of an enumerated sequence of 'spec' values, ordered by
//: increasing 'spec' length:
//:
//: 1 Use the primitive generator function 'gg' to set the state of a
//: newly created object.
//:
//: 2 Verify that 'gg' returns a valid reference to the modified argument
//: object.
//:
//: 3 Use the basic accessors to verify that the value of the object is
//: as expected. (C-1)
//:
//: 2 For each of an enumerated sequence of 'spec' values, ordered by
//: increasing 'spec' length, use the primitive generator function 'ggg'
//: to set the state of a newly created object.
//:
//: 1 Verify that 'ggg' returns the expected value corresponding to the
//: location of the first invalid value of the 'spec'. (C-2)
//
// Testing:
// set<K,A>& gg(set<K,A> *object, const char *spec);
// int ggg(set<K,A> *object, const char *spec, int verbose = 1);
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const char *val = ValueName<value_type>::name();
if (verbose) { P_(cont); P(val); }
bslma::TestAllocator oa(veryVeryVerbose);
bslma::TestAllocator da(veryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) printf("\nTesting generator on valid specs.\n");
{
static const struct {
int d_line; // source line number
const char *d_spec; // specification string
const char *d_results; // expected element values
} DATA[] = {
//line spec results
//---- -------- -------
{ L_, "", "" },
{ L_, "A", "A" },
{ L_, "B", "B" },
{ L_, "AB", "AB" },
{ L_, "CD", "CD" },
{ L_, "ABC", "ABC" },
{ L_, "ABCD", "ABCD" },
{ L_, "ABCDE", "ABCDE" },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_line;
const char *const SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(DATA[ti].d_results);
const TestValues EXP(DATA[ti].d_results);
const int curLen = (int)strlen(SPEC);
bslma::TestAllocatorMonitor oam(&oa);
bslma::TestAllocatorMonitor dam(&da);
Obj mX(&oa);
const Obj& X = gg(&mX, SPEC);
LOOP3_ASSERT(oam.isTotalUp(), emptyWillAlloc(), LENGTH,
oam.isTotalUp() == (emptyWillAlloc() || LENGTH > 0));
ASSERT(dam.isTotalSame());
const Obj& Y = g( SPEC);
ASSERT(&mX == &X);
ASSERT(Y == X);
if (curLen != oldLen) {
if (verbose) printf("\tof length %d:\n", curLen);
ASSERTV(LINE, oldLen <= curLen); // non-decreasing
oldLen = curLen;
}
ASSERTV(LINE, LENGTH == X.size());
ASSERTV(LINE, LENGTH == Y.size());
emptyNVerifyStack(&mX, EXP, LENGTH, L_);
emptyNVerifyStack(const_cast<Obj *>(&Y), EXP, LENGTH, L_);
}
}
if (verbose) printf("\nTesting generator on invalid specs.\n");
{
static const struct {
int d_line; // source line number
const char *d_spec; // specification string
int d_index; // offending character index
} DATA[] = {
//line spec index
//---- -------- -----
{ L_, "", -1, }, // control
{ L_, "A", -1, }, // control
{ L_, " ", 0, },
{ L_, ".", 0, },
{ L_, "E", -1, }, // control
{ L_, "a", 0, },
{ L_, "z", 0, },
{ L_, "AE", -1, }, // control
{ L_, "aE", 0, },
{ L_, "Ae", 1, },
{ L_, ".~", 0, },
{ L_, "~!", 0, },
{ L_, " ", 0, },
{ L_, "ABC", -1, }, // control
{ L_, " BC", 0, },
{ L_, "A C", 1, },
{ L_, "AB ", 2, },
{ L_, "?#:", 0, },
{ L_, " ", 0, },
{ L_, "ABCDE", -1, }, // control
{ L_, "aBCDE", 0, },
{ L_, "ABcDE", 2, },
{ L_, "ABCDe", 4, },
{ L_, "AbCdE", 1, }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_line;
const char *const SPEC = DATA[ti].d_spec;
const int INDEX = DATA[ti].d_index;
const int LENGTH = static_cast<int>(strlen(SPEC));
Obj mX(&oa);
if (LENGTH != oldLen) {
if (verbose) printf("\tof length %d:\n", LENGTH);
ASSERTV(LINE, oldLen <= LENGTH); // non-decreasing
oldLen = LENGTH;
}
if (veryVerbose) printf("\t\tSpec = \"%s\"\n", SPEC);
int RESULT = ggg(&mX, SPEC, veryVerbose);
ASSERTV(LINE, INDEX == RESULT);
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase2()
{
// ------------------------------------------------------------------------
// TESTING CONSTRUCTORS AND PRIMARY MANIPULATORS (BOOTSTRAP):
// The basic concern is that the default constructor, the destructor,
// and, under normal conditions (i.e., no aliasing), the primary
// manipulators
// - push
// - pop
//
// Concerns:
//: 1 An object created with the default constructor (with or without a
//: supplied allocator) has the contractually specified default value.
//:
//: 2 If an allocator is NOT supplied to the default constructor, the
//: default allocator in effect at the time of construction becomes the
//: object allocator for the resulting object.
//:
//: 3 If an allocator IS supplied to the default constructor, that
//: allocator becomes the object allocator for the resulting object.
//:
//: 4 Supplying a null allocator address has the same effect as not
//: supplying an allocator.
//:
//: 5 Supplying an allocator to the default constructor has no effect on
//: subsequent object values.
//:
//: 6 Any memory allocation is from the object allocator.
//:
//: 7 There is no temporary allocation from any allocator.
//:
//: 8 Every object releases any allocated memory at destruction.
//:
//: 9 QoI: The default constructor allocates no memory (only true if the
//: underlying container is 'vector').
//:
//:10 'insert' adds an additional element to the object if the element
//: being inserted does not already exist.
//:
//:11 'push' pushes a sequence of objects into the stack, and 'pop' will
//: recover those same values in reverse order.
//:
//:12 Any argument can be 'const'.
//:
//:13 Any memory allocation is exception neutral.
//:
//:14 All version of the copy c'tor produce an object with the same value
//: as the original, and allocate memory from the appropriate allocator.
//:
//:15 All versions of the c'tor from container produce an object with the
//: appropriate value, and allocate memory from the appropriate
//: allocator.
//
// Plan:
//: 1 For each value of increasing length, 'L':
//:
//: 2 Using a loop-based approach, default-construct three distinct
//: objects, in turn, but configured differently: (a) without passing
//: an allocator, (b) passing a null allocator address explicitly, and
//: (c) passing the address of a test allocator distinct from the
//: default. For each of these three iterations: (C-1..14)
//:
//: 1 Create three 'bslma::TestAllocator' objects, and install one as
//: as the current default allocator (note that a ubiquitous test
//: allocator is already installed as the global allocator).
//:
//: 2 Use the default constructor to dynamically create an object
//: 'X', with its object allocator configured appropriately (see
//: P-2); use a distinct test allocator for the object's footprint.
//:
//: 3 Use the (as yet unproven) 'get_allocator' to ensure that its
//: object allocator is properly installed. (C-2..4)
//:
//: 4 Use the appropriate test allocators to verify that no memory is
//: allocated by the default constructor. (C-9)
//:
//: 5 Use the individual (as yet unproven) salient attribute accessors
//: to verify the default-constructed value. (C-1)
//:
//: 6 Insert 'L - 1' elements in order of increasing value into the
//: container.
//:
//: 7 Insert the 'L'th value in the presense of exception and use the
//: (as yet unproven) basic accessors to verify the container has the
//: expected values. Verify the number of allocation is as expected.
//: (C-5..6, 13..14)
//:
//: 8 Verify that no temporary memory is allocated from the object
//: allocator. (C-7)
//:
//: 9 Make a copy of the object using the appropriate copy c'tor.
//:
//: 10 Verify that all object memory is released when the object is
//: destroyed. (Implicit in test allocator). (C-8)
//: 11 Verify that calling 'pop' on an empty stack will fail an assert
//: in safe mode.
//
// Testing:
// stack;
// stack(bslma_Allocator *);
// ~stack();
// push(const value_type& value);
// stack(const CONTAINER& container, bslma_allocator *);
// stack(const stack& stack, bslma_allocator *);
// ------------------------------------------------------------------------
const char *cont = ContainerName<container_type>::name();
const char *val = ValueName<value_type>::name();
if (verbose) { P_(cont); P_(val); P(typeAlloc()); }
const TestValues VALUES; // contains 52 distinct increasing values
const size_t MAX_LENGTH = 9;
for (size_t ti = 0; ti < MAX_LENGTH; ++ti) {
const size_t LENGTH = ti;
for (char cfg = 'a'; cfg <= 'c'; ++cfg) {
const char CONFIG = cfg; // how we specify the allocator
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
// ----------------------------------------------------------------
if (veryVerbose) {
printf("\n\tTesting default constructor.\n");
}
Obj *objPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj();
} break;
case 'b': {
objPtr = new (fa) Obj((bslma::Allocator *) 0);
} break;
case 'c': {
objPtr = new (fa) Obj(&sa);
} break;
default: {
ASSERTV(CONFIG, !"Bad allocator config.");
return; // RETURN
} break;
}
Obj& mX = *objPtr; const Obj& X = mX;
bslma::TestAllocator& oa = 'c' == CONFIG ? sa : da;
// Verify any attribute allocators are installed properly.
// ASSERTV(LENGTH, CONFIG, &oa == X.get_allocator());
// Verify no allocation from the object/non-object allocators.
ASSERTV(CONFIG, emptyWillAlloc() == !!oa.numBlocksTotal());
ASSERTV(LENGTH, CONFIG, 0 == X.size());
ASSERTV(LENGTH, CONFIG, X.empty());
{
bsls::AssertTestHandlerGuard hG;
ASSERT_SAFE_FAIL(mX.pop());
}
// ----------------------------------------------------------------
if (veryVerbose) { printf("\n\tTesting 'push' (bootstrap).\n"); }
for (size_t tj = 0; tj + 1 < LENGTH; ++tj) {
mX.push(VALUES[tj]);
ASSERTV(LENGTH, tj, CONFIG, VALUES[tj] == mX.top());
ASSERTV(LENGTH, tj, CONFIG, VALUES[tj] == X.top());
}
if (LENGTH > 1) {
ASSERTV(CONFIG, oa.numBlocksTotal() > 0);
}
if (0 < LENGTH) {
ASSERTV(LENGTH, CONFIG, LENGTH - 1 == X.size());
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
// insert the last element with an exception guard
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
ExceptionGuard<Obj> guard(&X, L_, &scratch);
mX.push(VALUES[LENGTH - 1]);
guard.release();
// Verify no temporary memory is allocated from the object
// allocator.
if (1 == LENGTH && !typeAlloc()) {
// If the vector grows, the old vector will be
// deallocated, so only do this test on '1 == LENGTH'.
ASSERTV(LENGTH, CONFIG, oa.numBlocksTotal(),
oa.numBlocksInUse(),
oa.numBlocksTotal() == oa.numBlocksInUse());
}
ASSERTV(LENGTH, CONFIG, VALUES[LENGTH - 1] == mX.top());
ASSERTV(LENGTH, CONFIG, VALUES[LENGTH - 1] == X.top());
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERTV(LENGTH, CONFIG, LENGTH == X.size());
}
// Test copy c'tors
{
bslma::TestAllocatorMonitor oaMonitor(&oa);
Obj *copyPtr;
switch (CONFIG) {
case 'a': {
copyPtr = new (fa) Obj(X);
} break;
case 'b': {
copyPtr = new (fa) Obj(X, (bslma::Allocator *) 0);
} break;
case 'c': {
copyPtr = new (fa) Obj(X, &sa);
} break;
default: {
ASSERTV(CONFIG, !"Bad allocator config.");
return; // RETURN
} break;
}
ASSERT(X == *copyPtr);
ASSERT((0 < LENGTH || emptyWillAlloc()) ==
oaMonitor.isTotalUp());
emptyAndVerify(copyPtr, VALUES, LENGTH, L_);
fa.deleteObject(copyPtr);
}
// Test container c'tors
{
bslma::TestAllocatorMonitor oaMonitor(&oa);
bslma::TestAllocator ca;
CONTAINER c(&ca); const CONTAINER& C = c;
// We have to insert the values one at a time, 'vector' has a
// problem with range inserts of function ptrs.
for (size_t tk = 0; tk < LENGTH; ++tk) {
c.push_back(VALUES[tk]);
}
Obj *cCopyPtr;
switch (CONFIG) {
case 'a': {
cCopyPtr = new (fa) Obj(C);
} break;
case 'b': {
cCopyPtr = new (fa) Obj(C, (bslma::Allocator *) 0);
} break;
case 'c': {
cCopyPtr = new (fa) Obj(C, &sa);
} break;
default: {
ASSERTV(CONFIG, !"Bad allocator config.");
return; // RETURN
} break;
}
ASSERT(X == *cCopyPtr);
ASSERT((0 < LENGTH || emptyWillAlloc()) ==
oaMonitor.isTotalUp());
if ('a' == CONFIG) {
// Sometimes don't do this, just so we test the case where
// we destroy a non-empty object.
emptyAndVerify(cCopyPtr, VALUES, LENGTH, L_);
}
fa.deleteObject(cCopyPtr);
}
emptyAndVerify(&mX, VALUES, LENGTH, L_);
if (&oa != &da) {
ASSERT(0 == da.numBlocksTotal());
}
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase1_NoAlloc(int *testValues,
size_t numValues)
{
// ------------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Execute each method to verify functionality for simple case.
//
// Testing:
// BREATHING TEST
// ------------------------------------------------------------------------
// Sanity check.
ASSERTV(0 < numValues);
ASSERTV(8 > numValues);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Default construct an empty set.\n");
}
{
Obj x; const Obj& X = x;
ASSERTV(0 == X.size());
ASSERTV(true == X.empty());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test use of allocators.\n");
}
{
Obj o1; const Obj& O1 = o1;
for (size_t i = 0; i < numValues; ++i) {
o1.push(value_type(testValues[i]));
}
ASSERTV(numValues == O1.size());
Obj o2(O1); const Obj& O2 = o2;
ASSERTV(numValues == O1.size());
ASSERTV(numValues == O2.size());
Obj o3; const Obj& O3 = o3;
ASSERTV(numValues == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(0 == O3.size());
o1.swap(o3);
ASSERTV(0 == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(numValues == O3.size());
ASSERTV(0 == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(numValues == O3.size());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test primary manipulators/accessors on every permutation.\n");
}
native_std::sort(testValues, testValues + numValues);
do {
// For each possible permutation of values, insert values, iterate over
// the resulting container, find values, and then erase values.
Obj x; const Obj& X = x;
for (size_t i = 0; i < numValues; ++i) {
Obj y(X); const Obj& Y = y;
ASSERTV(X == Y);
ASSERTV(!(X != Y));
// Test 'insert'.
value_type value(testValues[i]);
x.push(value);
ASSERTV(testValues[i] == x.top());
// Test size, empty.
ASSERTV(i + 1 == X.size());
ASSERTV(false == X.empty());
ASSERTV(X != Y);
ASSERTV(!(X == Y));
y = x;
ASSERTV(X == Y);
ASSERTV(!(X != Y));
}
ASSERTV(X.size() == numValues);
for (int i = static_cast<int>(numValues) - 1; i >= 0; --i) {
testValues[i] = X.top();
x.pop();
}
ASSERTV(X.size() == 0);
} while (native_std::next_permutation(testValues,
testValues + numValues));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test class comparison operators.\n");
}
{
// Iterate over possible selections of elements to add to two
// containers, 'X' and 'Y' then compare the results of the comparison
// operators to the comparison between two containers equivalent to
// the underlying containers in the stack objects.
for (size_t i = 0; i < numValues; ++i) {
for (size_t j = 0; j < numValues; ++j) {
for (size_t length = 0; length < numValues; ++length) {
for (size_t m = 0; m < j; ++m) {
Obj x; const Obj& X = x;
Obj y; const Obj& Y = y;
CONTAINER xx;
const CONTAINER& XX = xx;
CONTAINER yy;
const CONTAINER& YY = yy;
for (size_t k = 0; k < j; ++k) {
size_t xIndex = (i + length) % numValues;
size_t yIndex = (j + length) % numValues;
x.push( testValues[xIndex]);
xx.push_back(testValues[xIndex]);
if (k < m) {
y.push( testValues[yIndex]);
yy.push_back(testValues[yIndex]);
}
}
ASSERTV((X == Y) == (XX == YY));
ASSERTV((X != Y) == (XX != YY));
ASSERTV((X < Y) == (XX < YY));
ASSERTV((X > Y) == (XX > YY));
ASSERTV((X <= Y) == (XX <= YY));
ASSERTV((X >= Y) == (XX >= YY));
ASSERTV((X == Y) == !(X != Y));
ASSERTV((X != Y) == !(X == Y));
ASSERTV((X < Y) == !(X >= Y));
ASSERTV((X > Y) == !(X <= Y));
ASSERTV((X <= Y) == !(X > Y));
ASSERTV((X >= Y) == !(X < Y));
ASSERTV((Y == X) == (YY == XX));
ASSERTV((Y != X) == (YY != XX));
ASSERTV((Y < X) == (YY < XX));
ASSERTV((Y > X) == (YY > XX));
ASSERTV((Y <= X) == (YY <= XX));
ASSERTV((Y >= X) == (YY >= XX));
ASSERTV((Y == X) == !(Y != X));
ASSERTV((Y != X) == !(Y == X));
ASSERTV((Y < X) == !(Y >= X));
ASSERTV((Y > X) == !(Y <= X));
ASSERTV((Y <= X) == !(Y > X));
ASSERTV((Y >= X) == !(Y < X));
}
}
}
}
}
}
template <class CONTAINER>
void TestDriver<CONTAINER>::testCase1(int *testValues,
size_t numValues)
{
// ------------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Execute each method to verify functionality for simple case.
//
// Testing:
// BREATHING TEST
// ------------------------------------------------------------------------
bslma::TestAllocator defaultAllocator("defaultAllocator");
bslma::DefaultAllocatorGuard defaultGuard(&defaultAllocator);
bslma::TestAllocator objectAllocator("objectAllocator");
// Sanity check.
ASSERTV(0 < numValues);
ASSERTV(8 > numValues);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Default construct an empty set.\n");
}
{
Obj x(&objectAllocator); const Obj& X = x;
ASSERTV(0 == X.size());
ASSERTV(true == X.empty());
ASSERTV(0 == defaultAllocator.numBytesInUse());
ASSERTV(emptyWillAlloc() == (0 != objectAllocator.numBytesInUse()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test use of allocators.\n");
}
{
bslma::TestAllocatorMonitor defaultMonitor(&defaultAllocator);
bslma::TestAllocator objectAllocator1("objectAllocator1");
bslma::TestAllocator objectAllocator2("objectAllocator2");
Obj o1(&objectAllocator1); const Obj& O1 = o1;
// ASSERTV(&objectAllocator1 == O1.get_allocator().mechanism());
for (size_t i = 0; i < numValues; ++i) {
o1.push(value_type(testValues[i]));
}
ASSERTV(numValues == O1.size());
ASSERTV(0 < objectAllocator1.numBytesInUse());
ASSERTV(0 == objectAllocator2.numBytesInUse());
Obj o2(O1, &objectAllocator2); const Obj& O2 = o2;
// ASSERTV(&objectAllocator2 == O2.get_allocator().mechanism());
ASSERTV(numValues == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(0 < objectAllocator1.numBytesInUse());
ASSERTV(0 < objectAllocator2.numBytesInUse());
Obj o3(&objectAllocator1); const Obj& O3 = o3;
// ASSERTV(&objectAllocator1 == O3.get_allocator().mechanism());
bslma::TestAllocatorMonitor monitor1(&objectAllocator1);
ASSERTV(numValues == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(0 == O3.size());
ASSERTV(monitor1.isInUseSame());
ASSERTV(monitor1.isTotalSame());
ASSERTV(0 < objectAllocator1.numBytesInUse());
ASSERTV(0 < objectAllocator2.numBytesInUse());
o1.swap(o3);
ASSERTV(0 == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(numValues == O3.size());
ASSERTV(monitor1.isInUseSame());
ASSERTV(monitor1.isTotalSame());
ASSERTV(0 < objectAllocator1.numBytesInUse());
ASSERTV(0 < objectAllocator2.numBytesInUse());
o3.swap(o2);
ASSERTV(0 == O1.size());
ASSERTV(numValues == O2.size());
ASSERTV(numValues == O3.size());
ASSERTV(!monitor1.isInUseUp()); // Memory usage may go down depending
// on implementation
ASSERTV(monitor1.isTotalUp());
ASSERTV(0 < objectAllocator1.numBytesInUse());
ASSERTV(0 < objectAllocator2.numBytesInUse());
// ASSERTV(&objectAllocator1 == O1.get_allocator().mechanism());
// ASSERTV(&objectAllocator2 == O2.get_allocator().mechanism());
// ASSERTV(&objectAllocator1 == O3.get_allocator().mechanism());
ASSERTV(! defaultMonitor.isTotalUp());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test primary manipulators/accessors on every permutation.\n");
}
native_std::sort(testValues, testValues + numValues);
do {
// For each possible permutation of values, insert values, iterate over
// the resulting container, find values, and then erase values.
bslma::TestAllocatorMonitor defaultMonitor(&defaultAllocator);
Obj x(&objectAllocator); const Obj& X = x;
for (size_t i = 0; i < numValues; ++i) {
Obj y(X, &objectAllocator); const Obj& Y = y;
ASSERTV(X == Y);
ASSERTV(!(X != Y));
// Test 'insert'.
value_type value(testValues[i]);
x.push(value);
ASSERTV(testValues[i] == x.top());
// Test size, empty.
ASSERTV(i + 1 == X.size());
ASSERTV(false == X.empty());
ASSERTV(X != Y);
ASSERTV(!(X == Y));
y = x;
ASSERTV(X == Y);
ASSERTV(!(X != Y));
}
ASSERTV(X.size() == numValues);
ASSERTV(0 != objectAllocator.numBytesInUse());
ASSERTV(0 == defaultAllocator.numBytesInUse());
for (int i = static_cast<int>(numValues) - 1; i >= 0; --i) {
testValues[i] = (int) X.top();
x.pop();
}
ASSERTV(X.size() == 0);
ASSERTV(! defaultMonitor.isTotalUp());
} while (native_std::next_permutation(testValues,
testValues + numValues));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (veryVerbose) {
printf("Test class comparison operators.\n");
}
{
// Iterate over possible selections of elements to add to two
// containers, 'X' and 'Y' then compare the results of the comparison
// operators to the comparison between two containers equivalent to
// the underlying containers in the stack objects.
for (size_t i = 0; i < numValues; ++i) {
for (size_t j = 0; j < numValues; ++j) {
for (size_t length = 0; length < numValues; ++length) {
for (size_t m = 0; m < j; ++m) {
Obj x(&objectAllocator); const Obj& X = x;
Obj y(&objectAllocator); const Obj& Y = y;
CONTAINER xx(&objectAllocator);
const CONTAINER& XX = xx;
CONTAINER yy(&objectAllocator);
const CONTAINER& YY = yy;
for (size_t k = 0; k < j; ++k) {
size_t xIndex = (i + length) % numValues;
size_t yIndex = (j + length) % numValues;
x.push( testValues[xIndex]);
xx.push_back(testValues[xIndex]);
if (k < m) {
y.push( testValues[yIndex]);
yy.push_back(testValues[yIndex]);
}
}
ASSERTV((X == Y) == (XX == YY));
ASSERTV((X != Y) == (XX != YY));
ASSERTV((X < Y) == (XX < YY));
ASSERTV((X > Y) == (XX > YY));
ASSERTV((X <= Y) == (XX <= YY));
ASSERTV((X >= Y) == (XX >= YY));
ASSERTV((X == Y) == !(X != Y));
ASSERTV((X != Y) == !(X == Y));
ASSERTV((X < Y) == !(X >= Y));
ASSERTV((X > Y) == !(X <= Y));
ASSERTV((X <= Y) == !(X > Y));
ASSERTV((X >= Y) == !(X < Y));
ASSERTV((Y == X) == (YY == XX));
ASSERTV((Y != X) == (YY != XX));
ASSERTV((Y < X) == (YY < XX));
ASSERTV((Y > X) == (YY > XX));
ASSERTV((Y <= X) == (YY <= XX));
ASSERTV((Y >= X) == (YY >= XX));
ASSERTV((Y == X) == !(Y != X));
ASSERTV((Y != X) == !(Y == X));
ASSERTV((Y < X) == !(Y >= X));
ASSERTV((Y > X) == !(Y <= X));
ASSERTV((Y <= X) == !(Y > X));
ASSERTV((Y >= X) == !(Y < X));
}
}
}
}
}
}
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
bool intLessThan(int a, int b)
{
return a < b;
}
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
veryVeryVeryVerbose = argc > 5;
printf("TEST " __FILE__ " CASE %d\n", test);
bslma::TestAllocator globalAllocator("global", veryVeryVeryVerbose);
bslma::Default::setGlobalAllocator(&globalAllocator);
bslma::TestAllocator defaultAllocator("default", veryVeryVeryVerbose);
ASSERT(0 == bslma::Default::setDefaultAllocator(&defaultAllocator));
switch (test) { case 0:
case 19: {
// --------------------------------------------------------------------
// 'noexcept' SPECIFICATION
// --------------------------------------------------------------------
if (verbose) printf("\n" "'noexcept' SPECIFICATION" "\n"
"------------------------" "\n");
TestDriver<bsl::vector<int> >::testCase19();
} break;
case 18: {
// --------------------------------------------------------------------
// MOVE MANIPULATORS
// --------------------------------------------------------------------
if (verbose) printf("\n" "MOVE MANIPULATORS" "\n"
"-----------------" "\n");
// TestDriver< MovableVector<int> >::testCase18(true);
// TestDriver<NonMovableVector<int> >::testCase18(false);
typedef signed char SC;
typedef size_t SZ;
typedef bsltf::TemplateTestFacility::ObjectPtr TTF_OP;
// typedef bsltf::TemplateTestFacility::MethodPtr TTF_MP;
typedef bsltf::EnumeratedTestType::Enum ETT;
typedef bsltf::SimpleTestType STT;
typedef bsltf::AllocTestType ATT;
typedef bsltf::BitwiseMoveableTestType BMTT;
typedef bsltf::AllocBitwiseMoveableTestType ABMTT;
typedef bsltf::NonTypicalOverloadsTestType NTOTT;
TestDriver< MovableVector< int> >::testCase18(true );
TestDriver<NonMovableVector< int> >::testCase18(false);
TestDriver< MovableVector< SC> >::testCase18(true );
TestDriver<NonMovableVector< SC> >::testCase18(false);
TestDriver< MovableVector< SZ> >::testCase18(true );
TestDriver<NonMovableVector< SZ> >::testCase18(false);
TestDriver< MovableVector<TTF_OP> >::testCase18(true );
TestDriver<NonMovableVector<TTF_OP> >::testCase18(false);
// TestDriver< MovableVector<TTF_MP> >::testCase18(true );
// TestDriver<NonMovableVector<TTF_MP> >::testCase18(false);
TestDriver< MovableVector< ETT> >::testCase18(true );
TestDriver<NonMovableVector< ETT> >::testCase18(false);
TestDriver< MovableVector< STT> >::testCase18(true );
TestDriver<NonMovableVector< STT> >::testCase18(false);
TestDriver< MovableVector< ATT> >::testCase18(true );
TestDriver<NonMovableVector< ATT> >::testCase18(false);
TestDriver< MovableVector< BMTT> >::testCase18(true );
TestDriver<NonMovableVector< BMTT> >::testCase18(false);
TestDriver< MovableVector< ABMTT> >::testCase18(true );
TestDriver<NonMovableVector< ABMTT> >::testCase18(false);
TestDriver< MovableVector< NTOTT> >::testCase18(true );
TestDriver<NonMovableVector< NTOTT> >::testCase18(false);
#ifndef BSLS_PLATFORM_OS_WINDOWS
typedef bsltf::TemplateTestFacility::ObjectPtr TTF_FP;
TestDriver< MovableVector<TTF_FP> >::testCase18(true );
TestDriver<NonMovableVector<TTF_FP> >::testCase18(false);
#endif
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
if (verbose) printf("\n" "Move Only Type" "\n"
"--------------" "\n");
// typedef bsltf::MoveOnlyAllocTestType MOATT;
// TestDriver<MOATT, MovableVector<MOATT> >::testCase18MoveOnlyType();
#endif // !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
// 'propagate_on_container_move_assignment' testing
// TBD enable this
#if 0
RUN_EACH_TYPE(TestDriver,
testCase18_propagate_on_container_move_assignment,
TEST_TYPES_REGULAR(deque));
RUN_EACH_TYPE(TestDriver,
testCase18_propagate_on_container_move_assignment,
TEST_TYPES_MOVABLE(deque));
#endif
} break;
case 17: {
// --------------------------------------------------------------------
// MOVE CONSTRUCTORS
// --------------------------------------------------------------------
if (verbose) printf("\n" "MOVE CONSTRUCTORS" "\n"
"-----------------" "\n");
// TestDriver< MovableVector<int> >::testCase17(true);
// TestDriver<NonMovableVector<int> >::testCase17(false);
typedef signed char SC;
typedef size_t SZ;
typedef bsltf::TemplateTestFacility::ObjectPtr TTF_OP;
typedef bsltf::TemplateTestFacility::MethodPtr TTF_MP;
typedef bsltf::EnumeratedTestType::Enum ETT;
typedef bsltf::SimpleTestType STT;
typedef bsltf::AllocTestType ATT;
typedef bsltf::BitwiseMoveableTestType BMTT;
typedef bsltf::AllocBitwiseMoveableTestType ABMTT;
typedef bsltf::NonTypicalOverloadsTestType NTOTT;
TestDriver< MovableVector< int> >::testCase17(true );
TestDriver<NonMovableVector< int> >::testCase17(false);
TestDriver< MovableVector< SC> >::testCase17(true );
TestDriver<NonMovableVector< SC> >::testCase17(false);
TestDriver< MovableVector< SZ> >::testCase17(true );
TestDriver<NonMovableVector< SZ> >::testCase17(false);
TestDriver< MovableVector<TTF_OP> >::testCase17(true );
TestDriver<NonMovableVector<TTF_OP> >::testCase17(false);
TestDriver< MovableVector<TTF_MP> >::testCase17(true );
TestDriver<NonMovableVector<TTF_MP> >::testCase17(false);
TestDriver< MovableVector< ETT> >::testCase17(true );
TestDriver<NonMovableVector< ETT> >::testCase17(false);
TestDriver< MovableVector< STT> >::testCase17(true );
TestDriver<NonMovableVector< STT> >::testCase17(false);
TestDriver< MovableVector< ATT> >::testCase17(true );
TestDriver<NonMovableVector< ATT> >::testCase17(false);
TestDriver< MovableVector< BMTT> >::testCase17(true );
TestDriver<NonMovableVector< BMTT> >::testCase17(false);
TestDriver< MovableVector< ABMTT> >::testCase17(true );
TestDriver<NonMovableVector< ABMTT> >::testCase17(false);
TestDriver< MovableVector< NTOTT> >::testCase17(true );
TestDriver<NonMovableVector< NTOTT> >::testCase17(false);
#ifndef BSLS_PLATFORM_OS_WINDOWS
typedef bsltf::TemplateTestFacility::ObjectPtr TTF_FP;
TestDriver< MovableVector<TTF_FP> >::testCase17(true );
TestDriver<NonMovableVector<TTF_FP> >::testCase17(false);
#endif
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
if (verbose) printf("\n" "Move Only Type" "\n"
"--------------" "\n");
// typedef bsltf::MoveOnlyAllocTestType MOATT;
// TestDriver< MovableVector<MOATT> >::testCase17MoveOnlyType();
#endif // !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
} break;
case 16: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concern:
// Demonstrate the use of the stack.
//
// Plan:
// Create the class 'ToDoList', which implements a list of chores to
// be done, using the 'stack' container adapter, and demonstrate the
// use of 'ToDoList'.
// --------------------------------------------------------------------
// Then, create an object of type 'ToDoList'.
ToDoList toDoList;
// Next, a few tasks are requested:
toDoList.enqueueTask("Change the car's oil.");
toDoList.enqueueTask("Pay the bills.");
// Then, the husband watches the Yankee's game on TV. Upon returning
// to the list he consults the list to see what task is up next:
ASSERT(!strcmp("Pay the bills.", toDoList.currentTask()));
// Next, he sees that he has to pay the bills. When the bills are
// finished, he flushes that task from the list:
ASSERT(false == toDoList.finishTask());
// Then, he consults the list for the next task.
ASSERT(!strcmp("Change the car's oil.", toDoList.currentTask()));
// Next, he sees he has to change the car's oil. Before he can get
// started, another request comes:
toDoList.enqueueTask("Get some hot dogs.");
ASSERT(!strcmp("Get some hot dogs.", toDoList.currentTask()));
// Then, he drives the car to the convenience store and picks up some
// hot dogs and buns. Upon returning home, he gives the hot dogs to
// his wife, updates the list, and consults it for the next task.
ASSERT(false == toDoList.finishTask());
ASSERT(!strcmp("Change the car's oil.", toDoList.currentTask()));
// Next, he finishes the oil change, updates the list, and consults it
// for the next task.
ASSERT(true == toDoList.finishTask());
ASSERT(!strcmp("<EMPTY>", toDoList.currentTask()));
// Finally, the wife has been informed that everything is done, and she
// makes another request:
toDoList.enqueueTask("Clean the rain gutters.");
} break;
case 15: {
// --------------------------------------------------------------------
// TESTING EMPTY, SIZE
//
// Concern:
// That the 'empty()' and 'size()' accessors work according to their
// specifications.
//
// Plan:
// Manipulate a 'stack' object, and observe that 'empty()' and
// 'size()' return the expected values.
// --------------------------------------------------------------------
stack<int> mX; const stack<int>& X = mX;
ASSERT(mX.empty()); ASSERT(X.empty());
ASSERT(0 == mX.size()); ASSERT(0 == X.size());
for (int i = 7; i < 22; ++i) {
mX.push(i);
ASSERT(! mX.empty()); ASSERT(! X.empty());
ASSERT(i - 6 == (int) mX.size()); ASSERT(i - 6 == (int) X.size());
ASSERT(i == X.top());
mX.top() = static_cast<int>(X.size()); // 'top()' returns a ref to
// modifiable
ASSERT((int) X.size() == X.top());
}
for (size_t i = X.size(); i > 0; --i, mX.pop()) {
ASSERT(! mX.empty()); ASSERT(! X.empty());
ASSERT(i == X.size());
ASSERT(X.top() == static_cast<int>(i));
}
ASSERT(mX.empty()); ASSERT(X.empty());
ASSERT(0 == mX.size()); ASSERT(0 == X.size());
} break;
case 14: {
// --------------------------------------------------------------------
// TESTING NON ALLOCATOR SUPPORTING TYPE
// --------------------------------------------------------------------
typedef stack<int, NonAllocCont<int> > IStack;
IStack mX; const IStack& X = mX;
ASSERT(X.empty());
mX.push(3);
mX.push(4);
mX.push(5);
ASSERT(! X.empty());
ASSERT(3 == X.size());
ASSERT(5 == X.top());
IStack mY(X); const IStack& Y = mY;
ASSERT(X == Y); ASSERT(!(X != Y));
ASSERT(X <= Y); ASSERT(!(X > Y));
ASSERT(X >= Y); ASSERT(!(X < Y));
mY.pop();
mY.push(6);
ASSERT(X != Y); ASSERT(!(X == Y));
ASSERT(X < Y); ASSERT(!(X >= Y));
ASSERT(X <= Y); ASSERT(!(X > Y));
} break;
case 13: {
// --------------------------------------------------------------------
// TESTING CONTAINER OVERRIDE
// --------------------------------------------------------------------
// Verify that a stack with no container specified is the same as one
// we 'deque' specified.
typedef stack<int> IStack;
typedef stack<int, deque<int> > IDStack;
BSLMF_ASSERT((bsl::is_same<IStack, IDStack>::value));
// Verify that if a container is specified, the first template
// argument is ignored.
typedef stack<void, vector<int> > VIVStack;
typedef stack<double, vector<int> > DIVStack;
BSLMF_ASSERT((bsl::is_same<VIVStack::value_type, int>::value));
BSLMF_ASSERT((bsl::is_same<DIVStack::value_type, int>::value));
VIVStack vivs; const VIVStack& VIVS = vivs;
vivs.push(4); ASSERT(4 == VIVS.top());
vivs.push(7); ASSERT(7 == VIVS.top());
ASSERT(2 == VIVS.size());
ASSERT(!VIVS.empty());
vivs.pop(); ASSERT(4 == VIVS.top());
} break;
case 12: {
// --------------------------------------------------------------------
// TESTING INEQUALITY OPERATORS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Inequality Operators\n"
"\n============================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase12,
TEST_TYPES_INEQUAL_COMPARABLE(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase12,
TEST_TYPES_INEQUAL_COMPARABLE(vector));
} break;
case 11: {
// --------------------------------------------------------------------
// TESTING TYPE TRAITS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Type Traits\n"
"\n===================\n");
// Verify the bslma-allocator trait is not defined for non
// bslma-allocators.
typedef bsltf::StdTestAllocator<bsltf::AllocTestType> StlAlloc;
typedef bsltf::AllocTestType ATT;
typedef deque< ATT, StlAlloc> WeirdAllocDeque;
typedef vector<ATT, StlAlloc> WeirdAllocVector;
typedef bsl::stack<ATT, WeirdAllocDeque > WeirdAllocDequeStack;
typedef bsl::stack<ATT, WeirdAllocVector> WeirdAllocVectorStack;
typedef bsl::stack<int, NonAllocCont<int> > NonAllocStack;
if (verbose) printf("NonAllocCont --------------------------------\n");
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
NonAllocCont<int> >::value));
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
NonAllocStack>::value));
TestDriver<NonAllocCont<int> >::testCase11();
if (verbose) printf("deque ---------------------------------------\n");
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
WeirdAllocDeque>::value));
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
WeirdAllocDequeStack>::value));
RUN_EACH_TYPE(TestDriver, testCase11, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
WeirdAllocVector>::value));
BSLMF_ASSERT((0 == bslma::UsesBslmaAllocator<
WeirdAllocVectorStack>::value));
RUN_EACH_TYPE(TestDriver, testCase11, TEST_TYPES_REGULAR(vector));
} break;
case 10: {
// --------------------------------------------------------------------
// TESTING STL ALLOCATOR
// --------------------------------------------------------------------
if (verbose) printf("\nTesting STL ALLOCTOR\n"
"\n====================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase10,TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase10,TEST_TYPES_REGULAR(vector));
} break;
case 9: {
// --------------------------------------------------------------------
// ASSIGNMENT OPERATOR
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Assignment Operator"
"\n===========================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase9, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase9, TEST_TYPES_REGULAR(vector));
// 'propagate_on_container_copy_assignment' testing
// TBD enable this
#if 0
RUN_EACH_TYPE(TestDriver,
testCase9_propagate_on_container_copy_assignment,
TEST_TYPES_REGULAR(deque));
RUN_EACH_TYPE(TestDriver,
testCase9_propagate_on_container_copy_assignment,
TEST_TYPES_MOVABLE(deque));
#endif
} break;
case 8: {
// --------------------------------------------------------------------
// MANIPULATOR AND FREE FUNCTION 'swap'
// --------------------------------------------------------------------
if (verbose) printf("\nMANIPULATOR AND FREE FUNCTION 'swap'"
"\n====================================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase8, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase8, TEST_TYPES_REGULAR(vector));
// 'propagate_on_container_swap' testing
// TBD enable this
#if 0
RUN_EACH_TYPE(TestDriver,
testCase8_propagate_on_container_swap,
TEST_TYPES_REGULAR(deque));
RUN_EACH_TYPE(TestDriver,
testCase8_propagate_on_container_swap,
TEST_TYPES_MOVABLE(deque));
#endif
} break;
case 7: {
// --------------------------------------------------------------------
// COPY CONSTRUCTOR
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Copy Constructors"
"\n=========================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase7, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase7, TEST_TYPES_REGULAR(vector));
// 'select_on_container_copy_construction' testing
if (verbose) printf("\nCOPY CONSTRUCTOR: ALLOCATOR PROPAGATION"
"\n=======================================\n");
// TBD enable this
#if 0
RUN_EACH_TYPE(TestDriver,
testCase7_select_on_container_copy_construction,
TEST_TYPES_REGULAR(deque));
RUN_EACH_TYPE(TestDriver,
testCase7_select_on_container_copy_construction,
TEST_TYPES_MOVABLE(deque));
#endif
} break;
case 6: {
// --------------------------------------------------------------------
// EQUALITY OPERATORS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Equality Operators"
"\n==========================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase6, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase6, TEST_TYPES_REGULAR(vector));
} break;
case 5: {
// --------------------------------------------------------------------
// TESTING OUTPUT (<<) OPERATOR
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Output (<<) Operator"
"\n============================\n");
if (verbose)
printf("There is no output operator for this component.\n");
} break;
case 4: {
// --------------------------------------------------------------------
// BASIC ACCESSORS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Basic Accessors"
"\n=======================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase4, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase4, TEST_TYPES_REGULAR(vector));
} break;
case 3: {
// --------------------------------------------------------------------
// GENERATOR FUNCTIONS 'gg' and 'ggg'
// --------------------------------------------------------------------
if (verbose) printf("\nTesting 'gg'"
"\n============\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase3, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase3, TEST_TYPES_REGULAR(vector));
} break;
case 2: {
// --------------------------------------------------------------------
// PRIMARY MANIPULATORS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting C'tors and Primary Manipulators\n"
"=======================================\n");
if (verbose) printf("deque ---------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase2, TEST_TYPES_REGULAR(deque));
if (verbose) printf("vector --------------------------------------\n");
RUN_EACH_TYPE(TestDriver, testCase2, TEST_TYPES_REGULAR(vector));
if (verbose) printf("NonAllocCont --------------------------------\n");
// RUN_EACH_TYPE(TestDriver, testCase2, TEST_TYPES_REGULAR(NonAllocCont));
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Run each method with arbitrary inputs and verify the behavior is
//: as expected.
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
{
int INT_VALUES[] = { INT_MIN, -2, -1, 0, 1, 2, INT_MAX };
int NUM_INT_VALUES = sizeof(INT_VALUES) / sizeof(*INT_VALUES);
if (verbose) printf("deque:\n");
TestDriver<bsl::deque<int> >::testCase1(INT_VALUES,
NUM_INT_VALUES);
if (verbose) printf("vector:\n");
TestDriver<bsl::vector<int> >::testCase1(INT_VALUES,
NUM_INT_VALUES);
if (verbose) printf("deque<double>:\n");
TestDriver<bsl::deque<double> >::testCase1(INT_VALUES,
NUM_INT_VALUES);
if (verbose) printf("NonAllocCont<int>:\n");
TestDriver<NonAllocCont<int> >::testCase1_NoAlloc(INT_VALUES,
NUM_INT_VALUES);
#if 0
// add once 'list' is in bslstl, add it
if (verbose) printf("list:\n");
TestDriver<bsl::list<int> >::testCase1(INT_VALUES,
NUM_INT_VALUES);
#endif
}
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
// CONCERN: In no case does memory come from the global allocator.
ASSERTV(globalAllocator.numBlocksTotal(),
0 == globalAllocator.numBlocksTotal());
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 37.389124 | 79 | 0.527254 | eddiepierce |
334ddc2ac61746fa777a1e3134aec36a47bbdbc4 | 1,025 | cc | C++ | tests/pyre.lib/grid/product_iteration.cc | avalentino/pyre | 7e1f0287eb7eba1c6d1ef385e5160079283ac363 | [
"BSD-3-Clause"
] | 25 | 2018-04-23T01:45:39.000Z | 2021-12-10T06:01:23.000Z | tests/pyre.lib/grid/product_iteration.cc | avalentino/pyre | 7e1f0287eb7eba1c6d1ef385e5160079283ac363 | [
"BSD-3-Clause"
] | 53 | 2018-05-31T04:55:00.000Z | 2021-10-07T21:41:32.000Z | tests/pyre.lib/grid/product_iteration.cc | avalentino/pyre | 7e1f0287eb7eba1c6d1ef385e5160079283ac363 | [
"BSD-3-Clause"
] | 12 | 2018-04-23T22:50:40.000Z | 2022-02-20T17:27:23.000Z | // -*- c++ -*-
//
// michael a.g. aïvázis <michael.aivazis@para-sim.com>
// (c) 1998-2021 all rights reserved
// support
#include <cassert>
// get the grid
#include <pyre/grid.h>
// type alias
using product_t = pyre::grid::product_t<4>;
// exercise iterating over products
int main(int argc, char * argv[])
{
// initialize the journal
pyre::journal::init(argc, argv);
pyre::journal::application("product_iteration");
// make a channel
pyre::journal::debug_t channel("pyre.grid.product");
// make one
product_t p {0, 1, 2, 3};
// show me
channel
<< "product before: " << p
<< pyre::journal::endl(__HERE__);
// fill
for (auto & f : p) {
// with a specific value
f = 42;
}
// show me
channel
<< "product after: " << p
<< pyre::journal::endl(__HERE__);
// check
for (const auto f : p) {
// that we get what we expect
assert(( f == 42 ));
}
// all done
return 0;
}
// end of file
| 19.339623 | 56 | 0.552195 | avalentino |
3353681f4be9746c055cfc4add9289605ead21b8 | 2,060 | cpp | C++ | Source/Filtering/imstkQuadricDecimate.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 15 | 2021-09-20T17:33:52.000Z | 2022-02-12T09:49:57.000Z | Source/Filtering/imstkQuadricDecimate.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | null | null | null | Source/Filtering/imstkQuadricDecimate.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 3 | 2021-10-06T19:55:41.000Z | 2022-02-17T21:59:16.000Z | /*=========================================================================
Library: iMSTK
Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
& Imaging in Medicine, Rensselaer Polytechnic Institute.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "imstkQuadricDecimate.h"
#include "imstkSurfaceMesh.h"
#include "imstkLogger.h"
#include "imstkGeometryUtilities.h"
#include <vtkQuadricDecimation.h>
namespace imstk
{
QuadricDecimate::QuadricDecimate() :
m_VolumePreserving(true), m_TargetReduction(0.6)
{
setRequiredInputType<SurfaceMesh>(0);
setNumInputPorts(1);
setNumOutputPorts(1);
setOutput(std::make_shared<SurfaceMesh>());
}
void
QuadricDecimate::setInputMesh(std::shared_ptr<SurfaceMesh> inputMesh)
{
setInput(inputMesh, 0);
}
void
QuadricDecimate::requestUpdate()
{
std::shared_ptr<SurfaceMesh> inputMesh = std::dynamic_pointer_cast<SurfaceMesh>(getInput(0));
if (inputMesh == nullptr)
{
LOG(WARNING) << "No inputMesh to clean";
return;
}
vtkSmartPointer<vtkPolyData> inputMeshVtk = GeometryUtils::copyToVtkPolyData(std::dynamic_pointer_cast<SurfaceMesh>(inputMesh));
vtkNew<vtkQuadricDecimation> filter;
filter->SetInputData(inputMeshVtk);
filter->SetVolumePreservation(m_VolumePreserving);
filter->SetTargetReduction(m_TargetReduction);
filter->Update();
setOutput(GeometryUtils::copyToSurfaceMesh(filter->GetOutput()));
}
} // namespace imstk | 31.212121 | 132 | 0.689806 | Kitware |
3353ff81d09048c05d9b81e88a697c3030074d58 | 7,859 | cc | C++ | source/common/http/codec_client.cc | spenceral/envoy | 5333b928d8bcffa26ab19bf018369a835f697585 | [
"Apache-2.0"
] | 1 | 2020-10-27T21:20:41.000Z | 2020-10-27T21:20:41.000Z | source/common/http/codec_client.cc | spenceral/envoy | 5333b928d8bcffa26ab19bf018369a835f697585 | [
"Apache-2.0"
] | 137 | 2020-11-19T03:32:36.000Z | 2022-03-28T21:14:14.000Z | source/common/http/codec_client.cc | baojr/envoy | fe62d976a26faa46efc590a48a734f11ee6545f9 | [
"Apache-2.0"
] | 1 | 2021-05-18T14:12:17.000Z | 2021-05-18T14:12:17.000Z | #include "common/http/codec_client.h"
#include <cstdint>
#include <memory>
#include "envoy/http/codec.h"
#include "common/common/enum_to_int.h"
#include "common/config/utility.h"
#include "common/http/exception.h"
#include "common/http/http1/codec_impl.h"
#include "common/http/http2/codec_impl.h"
#include "common/http/status.h"
#include "common/http/utility.h"
#ifdef ENVOY_ENABLE_QUIC
#include "common/quic/codec_impl.h"
#endif
namespace Envoy {
namespace Http {
CodecClient::CodecClient(Type type, Network::ClientConnectionPtr&& connection,
Upstream::HostDescriptionConstSharedPtr host,
Event::Dispatcher& dispatcher)
: type_(type), host_(host), connection_(std::move(connection)),
idle_timeout_(host_->cluster().idleTimeout()) {
if (type_ != Type::HTTP3) {
// Make sure upstream connections process data and then the FIN, rather than processing
// TCP disconnects immediately. (see https://github.com/envoyproxy/envoy/issues/1679 for
// details)
connection_->detectEarlyCloseWhenReadDisabled(false);
}
connection_->addConnectionCallbacks(*this);
connection_->addReadFilter(Network::ReadFilterSharedPtr{new CodecReadFilter(*this)});
if (idle_timeout_) {
idle_timer_ = dispatcher.createTimer([this]() -> void { onIdleTimeout(); });
enableIdleTimer();
}
// We just universally set no delay on connections. Theoretically we might at some point want
// to make this configurable.
connection_->noDelay(true);
}
CodecClient::~CodecClient() {
ASSERT(connect_called_, "CodecClient::connect() is not called through out the life time.");
}
void CodecClient::connect() {
connect_called_ = true;
ASSERT(codec_ != nullptr);
// In general, codecs are handed new not-yet-connected connections, but in the
// case of ALPN, the codec may be handed an already connected connection.
if (!connection_->connecting()) {
ASSERT(connection_->state() == Network::Connection::State::Open);
connected_ = true;
} else {
ENVOY_CONN_LOG(debug, "connecting", *connection_);
connection_->connect();
}
}
void CodecClient::close() { connection_->close(Network::ConnectionCloseType::NoFlush); }
void CodecClient::deleteRequest(ActiveRequest& request) {
connection_->dispatcher().deferredDelete(request.removeFromList(active_requests_));
if (codec_client_callbacks_) {
codec_client_callbacks_->onStreamDestroy();
}
if (numActiveRequests() == 0) {
enableIdleTimer();
}
}
RequestEncoder& CodecClient::newStream(ResponseDecoder& response_decoder) {
ActiveRequestPtr request(new ActiveRequest(*this, response_decoder));
request->encoder_ = &codec_->newStream(*request);
request->encoder_->getStream().addCallbacks(*request);
LinkedList::moveIntoList(std::move(request), active_requests_);
disableIdleTimer();
return *active_requests_.front()->encoder_;
}
void CodecClient::onEvent(Network::ConnectionEvent event) {
if (event == Network::ConnectionEvent::Connected) {
ENVOY_CONN_LOG(debug, "connected", *connection_);
connection_->streamInfo().setDownstreamSslConnection(connection_->ssl());
connected_ = true;
}
if (event == Network::ConnectionEvent::RemoteClose) {
remote_closed_ = true;
}
// HTTP/1 can signal end of response by disconnecting. We need to handle that case.
if (type_ == Type::HTTP1 && event == Network::ConnectionEvent::RemoteClose &&
!active_requests_.empty()) {
Buffer::OwnedImpl empty;
onData(empty);
}
if (event == Network::ConnectionEvent::RemoteClose ||
event == Network::ConnectionEvent::LocalClose) {
ENVOY_CONN_LOG(debug, "disconnect. resetting {} pending requests", *connection_,
active_requests_.size());
disableIdleTimer();
idle_timer_.reset();
StreamResetReason reason = StreamResetReason::ConnectionFailure;
if (connected_) {
reason = StreamResetReason::ConnectionTermination;
if (protocol_error_) {
if (Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.return_502_for_upstream_protocol_errors")) {
reason = StreamResetReason::ProtocolError;
connection_->streamInfo().setResponseFlag(
StreamInfo::ResponseFlag::UpstreamProtocolError);
}
}
}
while (!active_requests_.empty()) {
// Fake resetting all active streams so that reset() callbacks get invoked.
active_requests_.front()->encoder_->getStream().resetStream(reason);
}
}
}
void CodecClient::responsePreDecodeComplete(ActiveRequest& request) {
ENVOY_CONN_LOG(debug, "response complete", *connection_);
if (codec_client_callbacks_) {
codec_client_callbacks_->onStreamPreDecodeComplete();
}
deleteRequest(request);
// HTTP/2 can send us a reset after a complete response if the request was not complete. Users
// of CodecClient will deal with the premature response case and we should not handle any
// further reset notification.
request.encoder_->getStream().removeCallbacks(request);
}
void CodecClient::onReset(ActiveRequest& request, StreamResetReason reason) {
ENVOY_CONN_LOG(debug, "request reset", *connection_);
if (codec_client_callbacks_) {
codec_client_callbacks_->onStreamReset(reason);
}
deleteRequest(request);
}
void CodecClient::onData(Buffer::Instance& data) {
const Status status = codec_->dispatch(data);
if (!status.ok()) {
ENVOY_CONN_LOG(debug, "Error dispatching received data: {}", *connection_, status.message());
// Don't count 408 responses where we have no active requests as protocol errors
if (!isPrematureResponseError(status) ||
(!active_requests_.empty() ||
getPrematureResponseHttpCode(status) != Code::RequestTimeout)) {
host_->cluster().stats().upstream_cx_protocol_error_.inc();
protocol_error_ = true;
}
close();
}
// All data should be consumed at this point if the connection remains open.
ASSERT(data.length() == 0 || connection_->state() != Network::Connection::State::Open,
absl::StrCat("extraneous bytes after response complete: ", data.length()));
}
CodecClientProd::CodecClientProd(Type type, Network::ClientConnectionPtr&& connection,
Upstream::HostDescriptionConstSharedPtr host,
Event::Dispatcher& dispatcher,
Random::RandomGenerator& random_generator)
: CodecClient(type, std::move(connection), host, dispatcher) {
switch (type) {
case Type::HTTP1: {
codec_ = std::make_unique<Http1::ClientConnectionImpl>(
*connection_, host->cluster().http1CodecStats(), *this, host->cluster().http1Settings(),
host->cluster().maxResponseHeadersCount());
break;
}
case Type::HTTP2: {
codec_ = std::make_unique<Http2::ClientConnectionImpl>(
*connection_, *this, host->cluster().http2CodecStats(), random_generator,
host->cluster().http2Options(), Http::DEFAULT_MAX_REQUEST_HEADERS_KB,
host->cluster().maxResponseHeadersCount(), Http2::ProdNghttp2SessionFactory::get());
break;
}
case Type::HTTP3: {
#ifdef ENVOY_ENABLE_QUIC
auto& quic_session = dynamic_cast<Quic::EnvoyQuicClientSession&>(*connection_);
codec_ = std::make_unique<Quic::QuicHttpClientConnectionImpl>(
quic_session, *this, host->cluster().http3CodecStats(), host->cluster().http3Options(),
Http::DEFAULT_MAX_REQUEST_HEADERS_KB, host->cluster().maxResponseHeadersCount());
// Initialize the session after max request header size is changed in above http client
// connection creation.
quic_session.Initialize();
break;
#else
// Should be blocked by configuration checking at an earlier point.
NOT_REACHED_GCOVR_EXCL_LINE;
#endif
}
}
connect();
}
} // namespace Http
} // namespace Envoy
| 37.070755 | 97 | 0.706451 | spenceral |
335429284fd1efb27cd28cc4ff339f1d8a761c44 | 1,173 | hh | C++ | src/plugin/graphics/3d/api/bugengine/plugin.graphics.3d/shader/shader.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 4 | 2015-05-13T16:28:36.000Z | 2017-05-24T15:34:14.000Z | src/plugin/graphics/3d/api/bugengine/plugin.graphics.3d/shader/shader.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/3d/api/bugengine/plugin.graphics.3d/shader/shader.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 1 | 2017-03-21T08:28:07.000Z | 2017-03-21T08:28:07.000Z | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_3D_SHADER_SHADER_SCRIPT_HH_
#define BE_3D_SHADER_SHADER_SCRIPT_HH_
/**************************************************************************************************/
#include <bugengine/plugin.graphics.3d/stdafx.h>
#include <bugengine/resource/description.script.hh>
namespace BugEngine {
namespace Shaders {
class Node;
class IShaderBuilder;
class Output;
enum Stage
{
VertexStage,
GeometryStage,
TesselationControlStage,
TessalationEvaluationStage,
FragmentStage
};
} // namespace Shaders
class be_api(3D) ShaderProgramDescription : public Resource::Description
{
BE_NOCOPY(ShaderProgramDescription);
private:
minitl::vector< ref< Shaders::Output > > m_outputs;
protected:
ShaderProgramDescription(minitl::vector< ref< Shaders::Output > > outputs);
~ShaderProgramDescription();
public:
virtual void buildSource(Shaders::IShaderBuilder & builder) const;
};
} // namespace BugEngine
/**************************************************************************************************/
#endif
| 24.957447 | 101 | 0.599318 | bugengine |
3354a84bee3d35265cbe663d2405c9cfa1adef30 | 11,427 | hpp | C++ | libraries/boost/include/boost/hana/tuple.hpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 918 | 2016-12-22T02:53:08.000Z | 2022-03-22T06:21:35.000Z | libraries/boost/include/boost/hana/tuple.hpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 594 | 2018-09-06T02:03:01.000Z | 2022-03-23T19:18:26.000Z | libraries/boost/include/boost/hana/tuple.hpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 349 | 2018-09-06T05:02:09.000Z | 2022-03-12T11:07:17.000Z | /*!
@file
Defines `boost::hana::tuple`.
@copyright Louis Dionne 2013-2017
@copyright Jason Rice 2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_TUPLE_HPP
#define BOOST_HANA_TUPLE_HPP
#include <boost/hana/fwd/tuple.hpp>
#include <boost/hana/basic_tuple.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/detail/decay.hpp>
#include <boost/hana/detail/fast_and.hpp>
#include <boost/hana/detail/index_if.hpp>
#include <boost/hana/detail/intrinsics.hpp>
#include <boost/hana/detail/operators/adl.hpp>
#include <boost/hana/detail/operators/comparable.hpp>
#include <boost/hana/detail/operators/iterable.hpp>
#include <boost/hana/detail/operators/monad.hpp>
#include <boost/hana/detail/operators/orderable.hpp>
#include <boost/hana/fwd/at.hpp>
#include <boost/hana/fwd/core/make.hpp>
#include <boost/hana/fwd/drop_front.hpp>
#include <boost/hana/fwd/index_if.hpp>
#include <boost/hana/fwd/is_empty.hpp>
#include <boost/hana/fwd/length.hpp>
#include <boost/hana/fwd/optional.hpp>
#include <boost/hana/fwd/unpack.hpp>
#include <boost/hana/type.hpp> // required by fwd decl of tuple_t
#include <cstddef>
#include <type_traits>
#include <utility>
BOOST_HANA_NAMESPACE_BEGIN
namespace detail {
template <typename Xs, typename Ys, std::size_t ...n>
constexpr void assign(Xs& xs, Ys&& ys, std::index_sequence<n...>) {
int sequence[] = {int{}, ((void)(
hana::at_c<n>(xs) = hana::at_c<n>(static_cast<Ys&&>(ys))
), int{})...};
(void)sequence;
}
struct from_index_sequence_t { };
template <typename Tuple, typename ...Yn>
struct is_same_tuple : std::false_type { };
template <typename Tuple>
struct is_same_tuple<typename detail::decay<Tuple>::type, Tuple>
: std::true_type
{ };
template <bool SameTuple, bool SameNumberOfElements, typename Tuple, typename ...Yn>
struct enable_tuple_variadic_ctor;
template <typename ...Xn, typename ...Yn>
struct enable_tuple_variadic_ctor<false, true, hana::tuple<Xn...>, Yn...>
: std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Yn&&)...>::value
>
{ };
}
//////////////////////////////////////////////////////////////////////////
// tuple
//////////////////////////////////////////////////////////////////////////
template <>
struct tuple<>
: detail::operators::adl<tuple<>>
, detail::iterable_operators<tuple<>>
{
constexpr tuple() { }
using hana_tag = tuple_tag;
};
template <typename ...Xn>
struct tuple
: detail::operators::adl<tuple<Xn...>>
, detail::iterable_operators<tuple<Xn...>>
{
basic_tuple<Xn...> storage_;
using hana_tag = tuple_tag;
private:
template <typename Other, std::size_t ...n>
explicit constexpr tuple(detail::from_index_sequence_t, std::index_sequence<n...>, Other&& other)
: storage_(hana::at_c<n>(static_cast<Other&&>(other))...)
{ }
public:
template <typename ...dummy, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, dummy...)...>::value
>::type>
constexpr tuple()
: storage_()
{ }
template <typename ...dummy, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Xn const&, dummy...)...>::value
>::type>
constexpr tuple(Xn const& ...xn)
: storage_(xn...)
{ }
template <typename ...Yn, typename = typename detail::enable_tuple_variadic_ctor<
detail::is_same_tuple<tuple, Yn...>::value,
sizeof...(Xn) == sizeof...(Yn), tuple, Yn...
>::type>
constexpr tuple(Yn&& ...yn)
: storage_(static_cast<Yn&&>(yn)...)
{ }
template <typename ...Yn, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Yn const&)...>::value
>::type>
constexpr tuple(tuple<Yn...> const& other)
: tuple(detail::from_index_sequence_t{},
std::make_index_sequence<sizeof...(Xn)>{},
other.storage_)
{ }
template <typename ...Yn, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Yn&&)...>::value
>::type>
constexpr tuple(tuple<Yn...>&& other)
: tuple(detail::from_index_sequence_t{},
std::make_index_sequence<sizeof...(Xn)>{},
static_cast<tuple<Yn...>&&>(other).storage_)
{ }
// The three following constructors are required to make sure that
// the tuple(Yn&&...) constructor is _not_ preferred over the copy
// constructor for unary tuples containing a type that is constructible
// from tuple<...>. See test/tuple/cnstr.trap.cpp
template <typename ...dummy, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Xn const&, dummy...)...>::value
>::type>
constexpr tuple(tuple const& other)
: tuple(detail::from_index_sequence_t{},
std::make_index_sequence<sizeof...(Xn)>{},
other.storage_)
{ }
template <typename ...dummy, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Xn const&, dummy...)...>::value
>::type>
constexpr tuple(tuple& other)
: tuple(const_cast<tuple const&>(other))
{ }
template <typename ...dummy, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_CONSTRUCTIBLE(Xn, Xn&&, dummy...)...>::value
>::type>
constexpr tuple(tuple&& other)
: tuple(detail::from_index_sequence_t{},
std::make_index_sequence<sizeof...(Xn)>{},
static_cast<tuple&&>(other).storage_)
{ }
template <typename ...Yn, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_ASSIGNABLE(Xn&, Yn const&)...>::value
>::type>
constexpr tuple& operator=(tuple<Yn...> const& other) {
detail::assign(this->storage_, other.storage_,
std::make_index_sequence<sizeof...(Xn)>{});
return *this;
}
template <typename ...Yn, typename = typename std::enable_if<
detail::fast_and<BOOST_HANA_TT_IS_ASSIGNABLE(Xn&, Yn&&)...>::value
>::type>
constexpr tuple& operator=(tuple<Yn...>&& other) {
detail::assign(this->storage_, static_cast<tuple<Yn...>&&>(other).storage_,
std::make_index_sequence<sizeof...(Xn)>{});
return *this;
}
};
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
namespace detail {
template <>
struct comparable_operators<tuple_tag> {
static constexpr bool value = true;
};
template <>
struct orderable_operators<tuple_tag> {
static constexpr bool value = true;
};
template <>
struct monad_operators<tuple_tag> {
static constexpr bool value = true;
};
}
//////////////////////////////////////////////////////////////////////////
// Foldable
//////////////////////////////////////////////////////////////////////////
template <>
struct unpack_impl<tuple_tag> {
template <typename F>
static constexpr decltype(auto) apply(tuple<>&&, F&& f)
{ return static_cast<F&&>(f)(); }
template <typename F>
static constexpr decltype(auto) apply(tuple<>&, F&& f)
{ return static_cast<F&&>(f)(); }
template <typename F>
static constexpr decltype(auto) apply(tuple<> const&, F&& f)
{ return static_cast<F&&>(f)(); }
template <typename Xs, typename F>
static constexpr decltype(auto) apply(Xs&& xs, F&& f) {
return hana::unpack(static_cast<Xs&&>(xs).storage_, static_cast<F&&>(f));
}
};
template <>
struct length_impl<tuple_tag> {
template <typename ...Xs>
static constexpr auto apply(tuple<Xs...> const&)
{ return hana::size_c<sizeof...(Xs)>; }
};
//////////////////////////////////////////////////////////////////////////
// Iterable
//////////////////////////////////////////////////////////////////////////
template <>
struct at_impl<tuple_tag> {
template <typename Xs, typename N>
static constexpr decltype(auto) apply(Xs&& xs, N const&) {
constexpr std::size_t index = N::value;
return hana::at_c<index>(static_cast<Xs&&>(xs).storage_);
}
};
template <>
struct drop_front_impl<tuple_tag> {
template <std::size_t N, typename Xs, std::size_t ...i>
static constexpr auto helper(Xs&& xs, std::index_sequence<i...>) {
return hana::make<tuple_tag>(hana::at_c<i+N>(static_cast<Xs&&>(xs))...);
}
template <typename Xs, typename N>
static constexpr auto apply(Xs&& xs, N const&) {
constexpr std::size_t len = decltype(hana::length(xs))::value;
return helper<N::value>(static_cast<Xs&&>(xs), std::make_index_sequence<
N::value < len ? len - N::value : 0
>{});
}
};
template <>
struct is_empty_impl<tuple_tag> {
template <typename ...Xs>
static constexpr auto apply(tuple<Xs...> const&)
{ return hana::bool_c<sizeof...(Xs) == 0>; }
};
// compile-time optimizations (to reduce the # of function instantiations)
template <std::size_t n, typename ...Xs>
constexpr decltype(auto) at_c(tuple<Xs...> const& xs) {
return hana::at_c<n>(xs.storage_);
}
template <std::size_t n, typename ...Xs>
constexpr decltype(auto) at_c(tuple<Xs...>& xs) {
return hana::at_c<n>(xs.storage_);
}
template <std::size_t n, typename ...Xs>
constexpr decltype(auto) at_c(tuple<Xs...>&& xs) {
return hana::at_c<n>(static_cast<tuple<Xs...>&&>(xs).storage_);
}
template <>
struct index_if_impl<tuple_tag> {
template <typename ...Xs, typename Pred>
static constexpr auto apply(tuple<Xs...> const&, Pred const&)
-> typename detail::index_if<Pred, Xs...>::type
{ return {}; }
};
//////////////////////////////////////////////////////////////////////////
// Sequence
//////////////////////////////////////////////////////////////////////////
template <>
struct Sequence<tuple_tag> {
static constexpr bool value = true;
};
template <>
struct make_impl<tuple_tag> {
template <typename ...Xs>
static constexpr
tuple<typename detail::decay<Xs>::type...> apply(Xs&& ...xs)
{ return {static_cast<Xs&&>(xs)...}; }
};
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_TUPLE_HPP
| 36.507987 | 105 | 0.548613 | SheldonHH |
3359a6ae3816d07eb1feae546979c1f85c2c3098 | 578 | cpp | C++ | src/RE/BSShader/BSShaderMaterial/BSLightingShaderMaterialLandscape.cpp | fireundubh/CommonLibSSE-po3 | cf30265f3cd3aa70a8eeff4d598754439e983ddd | [
"MIT"
] | 1 | 2021-08-30T20:33:43.000Z | 2021-08-30T20:33:43.000Z | src/RE/BSShader/BSShaderMaterial/BSLightingShaderMaterialLandscape.cpp | fireundubh/CommonLibSSE-po3 | cf30265f3cd3aa70a8eeff4d598754439e983ddd | [
"MIT"
] | null | null | null | src/RE/BSShader/BSShaderMaterial/BSLightingShaderMaterialLandscape.cpp | fireundubh/CommonLibSSE-po3 | cf30265f3cd3aa70a8eeff4d598754439e983ddd | [
"MIT"
] | null | null | null | #include "RE/BSShader/BSShaderMaterial/BSLightingShaderMaterialBase/BSLightingShaderMaterialLandscape.h"
namespace RE
{
BSLightingShaderMaterialLandscape* BSLightingShaderMaterialLandscape::CreateMaterial()
{
auto material = malloc<BSLightingShaderMaterialLandscape>();
material->ctor();
return material;
}
BSLightingShaderMaterialLandscape* BSLightingShaderMaterialLandscape::ctor()
{
using func_t = decltype(&BSLightingShaderMaterialLandscape::ctor);
REL::Relocation<func_t> func{ Offset::BSLightingShaderMaterialLandscape::Ctor };
return func(this);
}
} | 28.9 | 104 | 0.811419 | fireundubh |
335acd0f7e0fe3cd4c6f95b7aea5810746f8e5b3 | 31,089 | cc | C++ | src/gb/base/flags_test.cc | jpursey/game-bits | 2daefa2cef5601939dbea50a755b8470e38656ae | [
"MIT"
] | 1 | 2020-07-11T17:03:19.000Z | 2020-07-11T17:03:19.000Z | src/gb/base/flags_test.cc | jpursey/gbits | 4dfedd1297ca368ad1d80a03308fc4da0241f948 | [
"MIT"
] | 2 | 2021-12-10T13:38:51.000Z | 2022-02-22T16:02:24.000Z | src/gb/base/flags_test.cc | jpursey/game-bits | 2daefa2cef5601939dbea50a755b8470e38656ae | [
"MIT"
] | null | null | null | // Copyright (c) 2020 John Pursey
//
// Use of this source code is governed by an MIT-style License that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
#include "gb/base/flags.h"
#include "gtest/gtest.h"
namespace gb {
namespace {
enum BasicEnum {
kBasicEnum_Zero,
kBasicEnum_One,
kBasicEnum_Two,
kBasicEnum_Three,
kBasicEnum_Big = 63,
};
enum SizedEnum : int8_t {
kSizedEnum_Zero,
kSizedEnum_One,
kSizedEnum_Two,
kSizedEnum_Three,
kSizedEnum_Big = 63,
};
enum class ClassEnum : int8_t {
kZero,
kOne,
kTwo,
kThree,
kBig = 63,
};
// Helpers to test parameter passing and implicit conversion.
Flags<BasicEnum> BasicIdentity(Flags<BasicEnum> flags) { return flags; }
Flags<SizedEnum> SizedIdentity(Flags<SizedEnum> flags) { return flags; }
Flags<ClassEnum> ClassIdentity(Flags<ClassEnum> flags) { return flags; }
// Static assert is used to ensure constexpr-ness.
static_assert(Flags<BasicEnum>().IsEmpty(),
"BasicEnum default flags not empty");
static_assert(Flags<BasicEnum>().GetMask() == 0,
"BasicEnum default mask is not zero");
static_assert(Flags<BasicEnum>(1).GetMask() == 1, "BasicEnum 1 is not 1");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero).GetMask() == 1,
"BasicEnum Zero is not 1");
static_assert(Flags<BasicEnum>(kBasicEnum_Big).GetMask() == 1ULL << 63,
"BasicEnum Big is not 1 << 63");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero).IsSet(kBasicEnum_Zero),
"BasicEnum Zero does not have Zero set");
static_assert(!Flags<BasicEnum>(kBasicEnum_Zero).IsSet(kBasicEnum_One),
"BasicEnum Zero has One set");
static_assert(Flags<BasicEnum>({}).GetMask() == 0, "BasicEnum {} is not 0");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}).GetMask() ==
3,
"BasicEnum {Zero,One} is not 3");
static_assert(
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}).IsSet(kBasicEnum_One),
"BasicEnum {Zero,One} does not have One set");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One,
kBasicEnum_Two})
.IsSet({kBasicEnum_Zero, kBasicEnum_Two}),
"BasicEnum {Zero,One,Two} does not have {Zero,Two} set");
static_assert(!Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One})
.IsSet({kBasicEnum_Zero, kBasicEnum_Two}),
"BasicEnum {Zero,One} does have {Zero,Two} set");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One})
.Intersects({kBasicEnum_Zero, kBasicEnum_Two}),
"BasicEnum {Zero,One} does not intersect {Zero,Two}");
static_assert(!Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One})
.Intersects({kBasicEnum_Two, kBasicEnum_Three}),
"BasicEnum {Zero,One} intersects {Two, Three}");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) ==
Flags<BasicEnum>(kBasicEnum_Zero),
"BasicEnum Zero is not equal to Zero");
static_assert(!(Flags<BasicEnum>(kBasicEnum_Zero) ==
Flags<BasicEnum>(kBasicEnum_One)),
"BasicEnum Zero is equal to One");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) !=
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum Zero is equal to One");
static_assert(!(Flags<BasicEnum>(kBasicEnum_Zero) !=
Flags<BasicEnum>(kBasicEnum_Zero)),
"BasicEnum Zero is not equal to Zero");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) <
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum Zero is not less than One");
static_assert(!(Flags<BasicEnum>(kBasicEnum_Zero) <
Flags<BasicEnum>(kBasicEnum_Zero)),
"BasicEnum Zero is less than Zero");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) <=
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum Zero is not less or equal to One");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) <=
Flags<BasicEnum>(kBasicEnum_Zero),
"BasicEnum Zero is not less or equal to Zero");
static_assert(!(Flags<BasicEnum>(kBasicEnum_One) <=
Flags<BasicEnum>(kBasicEnum_Zero)),
"BasicEnum One is less or equal to Zero");
static_assert(Flags<BasicEnum>(kBasicEnum_One) >
Flags<BasicEnum>(kBasicEnum_Zero),
"BasicEnum One is not greater than Zero");
static_assert(!(Flags<BasicEnum>(kBasicEnum_One) >
Flags<BasicEnum>(kBasicEnum_One)),
"BasicEnum One is greater than One");
static_assert(Flags<BasicEnum>(kBasicEnum_One) >=
Flags<BasicEnum>(kBasicEnum_Zero),
"BasicEnum One is not greater or equal to Zero");
static_assert(Flags<BasicEnum>(kBasicEnum_One) >=
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum One is not greater or equal to One");
static_assert(!(Flags<BasicEnum>(kBasicEnum_Zero) >=
Flags<BasicEnum>(kBasicEnum_One)),
"BasicEnum Zero is greater or equal to One");
static_assert(Flags<BasicEnum>(kBasicEnum_Zero) + kBasicEnum_One ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
"BasicEnum Zero + One is not equal to {Zero, One}");
static_assert(kBasicEnum_Zero + Flags<BasicEnum>(kBasicEnum_One) ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
"BasicEnum Zero + One is not equal to {Zero, One}");
static_assert(
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}) +
Flags<BasicEnum>({kBasicEnum_One, kBasicEnum_Two}) ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One, kBasicEnum_Two}),
"BasicEnum {Zero,One} + {One,Two} is not equal to {Zero,One,Two}");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}) -
Flags<BasicEnum>(kBasicEnum_Zero) ==
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}) -
kBasicEnum_Zero ==
Flags<BasicEnum>(kBasicEnum_One),
"BasicEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}) -
Flags<BasicEnum>(kBasicEnum_Two) ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
"BasicEnum {Zero,One} - Two is not equal to {Zero,One}");
static_assert(Union(kBasicEnum_Zero, Flags<BasicEnum>(kBasicEnum_One)) ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
"BasicEnum Zero union One is not equal to {Zero, One}");
static_assert(
Union(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
Flags<BasicEnum>({kBasicEnum_One, kBasicEnum_Two})) ==
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One, kBasicEnum_Two}),
"BasicEnum {Zero,One} union {One,Two} is not equal to {Zero,One,Two}");
static_assert(Intersect(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_Two})) ==
Flags<BasicEnum>(kBasicEnum_Zero),
"BasicEnum {Zero,One} intersect {Zero,Two} is not equal to Zero");
static_assert(Intersect(Flags<BasicEnum>({kBasicEnum_Zero, kBasicEnum_One}),
Flags<BasicEnum>(kBasicEnum_Two))
.IsEmpty(),
"BasicEnum {Zero,One} intersect Two is not empty");
static_assert(Flags<BasicEnum>({kBasicEnum_One, kBasicEnum_Two}) ==
Flags<BasicEnum>(kBasicEnum_One, kBasicEnum_Two),
"BasicEnum {One,Two} is not equal to (One,Two)");
static_assert(
Flags<BasicEnum>({kBasicEnum_One, kBasicEnum_Two, kBasicEnum_Three}) ==
Flags<BasicEnum>(kBasicEnum_One, kBasicEnum_Two, kBasicEnum_Three),
"BasicEnum {One,Two,Three} is not equal to (One,Two,Three)");
static_assert(
Flags<BasicEnum>({Flags<BasicEnum>{kBasicEnum_Zero, kBasicEnum_One},
kBasicEnum_Two,
Flags<BasicEnum>{kBasicEnum_Three, kBasicEnum_Big}}) ==
Flags<BasicEnum>(Flags<BasicEnum>{kBasicEnum_Zero, kBasicEnum_One},
kBasicEnum_Two,
Flags<BasicEnum>{kBasicEnum_Three, kBasicEnum_Big}),
"BasicEnum {{Zero,One},Two,{Three,Big}} is not equal to "
"({Zero,One},Two,{Three,Big})");
static_assert(Flags<SizedEnum>().IsEmpty(),
"SizedEnum default flags not empty");
static_assert(Flags<SizedEnum>().GetMask() == 0,
"SizedEnum default mask is not zero");
static_assert(Flags<SizedEnum>(1).GetMask() == 1, "SizedEnum 1 is not 1");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero).GetMask() == 1,
"SizedEnum Zero is not 1");
static_assert(Flags<SizedEnum>(kSizedEnum_Big).GetMask() == 1ULL << 63,
"SizedEnum Big is not 1 << 63");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero).IsSet(kSizedEnum_Zero),
"SizedEnum Zero does not have Zero set");
static_assert(!Flags<SizedEnum>(kSizedEnum_Zero).IsSet(kSizedEnum_One),
"SizedEnum Zero has One set");
static_assert(Flags<SizedEnum>({}).GetMask() == 0, "SizedEnum {} is not 0");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}).GetMask() ==
3,
"SizedEnum {Zero,One} is not 3");
static_assert(
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}).IsSet(kSizedEnum_One),
"SizedEnum {Zero,One} does not have One set");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One,
kSizedEnum_Two})
.IsSet({kSizedEnum_Zero, kSizedEnum_Two}),
"SizedEnum {Zero,One,Two} does not have {Zero,Two} set");
static_assert(!Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One})
.IsSet({kSizedEnum_Zero, kSizedEnum_Two}),
"SizedEnum {Zero,One} does have {Zero,Two} set");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One})
.Intersects({kSizedEnum_Zero, kSizedEnum_Two}),
"SizedEnum {Zero,One} does not intersect {Zero,Two}");
static_assert(!Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One})
.Intersects({kSizedEnum_Two, kSizedEnum_Three}),
"SizedEnum {Zero,One} intersects {Two, Three}");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) ==
Flags<SizedEnum>(kSizedEnum_Zero),
"SizedEnum Zero is not equal to Zero");
static_assert(!(Flags<SizedEnum>(kSizedEnum_Zero) ==
Flags<SizedEnum>(kSizedEnum_One)),
"SizedEnum Zero is equal to One");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) !=
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum Zero is equal to One");
static_assert(!(Flags<SizedEnum>(kSizedEnum_Zero) !=
Flags<SizedEnum>(kSizedEnum_Zero)),
"SizedEnum Zero is not equal to Zero");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) <
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum Zero is not less than One");
static_assert(!(Flags<SizedEnum>(kSizedEnum_Zero) <
Flags<SizedEnum>(kSizedEnum_Zero)),
"SizedEnum Zero is less than Zero");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) <=
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum Zero is not less or equal to One");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) <=
Flags<SizedEnum>(kSizedEnum_Zero),
"SizedEnum Zero is not less or equal to Zero");
static_assert(!(Flags<SizedEnum>(kSizedEnum_One) <=
Flags<SizedEnum>(kSizedEnum_Zero)),
"SizedEnum One is less or equal to Zero");
static_assert(Flags<SizedEnum>(kSizedEnum_One) >
Flags<SizedEnum>(kSizedEnum_Zero),
"SizedEnum One is not greater than Zero");
static_assert(!(Flags<SizedEnum>(kSizedEnum_One) >
Flags<SizedEnum>(kSizedEnum_One)),
"SizedEnum One is greater than One");
static_assert(Flags<SizedEnum>(kSizedEnum_One) >=
Flags<SizedEnum>(kSizedEnum_Zero),
"SizedEnum One is not greater or equal to Zero");
static_assert(Flags<SizedEnum>(kSizedEnum_One) >=
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum One is not greater or equal to One");
static_assert(!(Flags<SizedEnum>(kSizedEnum_Zero) >=
Flags<SizedEnum>(kSizedEnum_One)),
"SizedEnum Zero is greater or equal to One");
static_assert(Flags<SizedEnum>(kSizedEnum_Zero) + kSizedEnum_One ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
"SizedEnum Zero + One is not equal to {Zero, One}");
static_assert(kSizedEnum_Zero + Flags<SizedEnum>(kSizedEnum_One) ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
"SizedEnum Zero + One is not equal to {Zero, One}");
static_assert(
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}) +
Flags<SizedEnum>({kSizedEnum_One, kSizedEnum_Two}) ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One, kSizedEnum_Two}),
"SizedEnum {Zero,One} + {One,Two} is not equal to {Zero,One,Two}");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}) -
Flags<SizedEnum>(kSizedEnum_Zero) ==
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}) -
kSizedEnum_Zero ==
Flags<SizedEnum>(kSizedEnum_One),
"SizedEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}) -
Flags<SizedEnum>(kSizedEnum_Two) ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
"SizedEnum {Zero,One} - Two is not equal to {Zero,One}");
static_assert(Union(kSizedEnum_Zero, Flags<SizedEnum>(kSizedEnum_One)) ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
"SizedEnum Zero union One is not equal to {Zero, One}");
static_assert(
Union(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
Flags<SizedEnum>({kSizedEnum_One, kSizedEnum_Two})) ==
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One, kSizedEnum_Two}),
"SizedEnum {Zero,One} union {One,Two} is not equal to {Zero,One,Two}");
static_assert(Intersect(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_Two})) ==
Flags<SizedEnum>(kSizedEnum_Zero),
"SizedEnum {Zero,One} intersect {Zero,Two} is not equal to Zero");
static_assert(Intersect(Flags<SizedEnum>({kSizedEnum_Zero, kSizedEnum_One}),
Flags<SizedEnum>(kSizedEnum_Two))
.IsEmpty(),
"SizedEnum {Zero,One} intersect Two is not empty");
static_assert(Flags<SizedEnum>({kSizedEnum_One, kSizedEnum_Two}) ==
Flags<SizedEnum>(kSizedEnum_One, kSizedEnum_Two),
"SizedEnum {One,Two} is not equal to (One,Two)");
static_assert(
Flags<SizedEnum>({kSizedEnum_One, kSizedEnum_Two, kSizedEnum_Three}) ==
Flags<SizedEnum>(kSizedEnum_One, kSizedEnum_Two, kSizedEnum_Three),
"SizedEnum {One,Two,Three} is not equal to (One,Two,Three)");
static_assert(
Flags<SizedEnum>({Flags<SizedEnum>{kSizedEnum_Zero, kSizedEnum_One},
kSizedEnum_Two,
Flags<SizedEnum>{kSizedEnum_Three, kSizedEnum_Big}}) ==
Flags<SizedEnum>(Flags<SizedEnum>{kSizedEnum_Zero, kSizedEnum_One},
kSizedEnum_Two,
Flags<SizedEnum>{kSizedEnum_Three, kSizedEnum_Big}),
"SizedEnum {{Zero,One},Two,{Three,Big}} is not equal to "
"({Zero,One},Two,{Three,Big})");
static_assert(Flags<ClassEnum>().IsEmpty(),
"ClassEnum default flags not empty");
static_assert(Flags<ClassEnum>().GetMask() == 0,
"ClassEnum default mask is not zero");
static_assert(Flags<ClassEnum>(1).GetMask() == 1, "ClassEnum 1 is not 1");
static_assert(Flags<ClassEnum>(ClassEnum::kZero).GetMask() == 1,
"ClassEnum Zero is not 1");
static_assert(Flags<ClassEnum>(ClassEnum::kBig).GetMask() == 1ULL << 63,
"ClassEnum Big is not 1 << 63");
static_assert(Flags<ClassEnum>(ClassEnum::kZero).IsSet(ClassEnum::kZero),
"ClassEnum Zero does not have Zero set");
static_assert(!Flags<ClassEnum>(ClassEnum::kZero).IsSet(ClassEnum::kOne),
"ClassEnum Zero has One set");
static_assert(Flags<ClassEnum>({}).GetMask() == 0, "ClassEnum {} is not 0");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}).GetMask() ==
3,
"ClassEnum {Zero,One} is not 3");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne})
.IsSet(ClassEnum::kOne),
"ClassEnum {Zero,One} does not have One set");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo})
.IsSet({ClassEnum::kZero, ClassEnum::kTwo}),
"ClassEnum {Zero,One,Two} does not have {Zero,Two} set");
static_assert(!Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne})
.IsSet({ClassEnum::kZero, ClassEnum::kTwo}),
"ClassEnum {Zero,One} does have {Zero,Two} set");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne})
.Intersects({ClassEnum::kZero, ClassEnum::kTwo}),
"ClassEnum {Zero,One} does not intersect {Zero,Two}");
static_assert(!Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne})
.Intersects({ClassEnum::kTwo, ClassEnum::kThree}),
"ClassEnum {Zero,One} intersects {Two, Three}");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) ==
Flags<ClassEnum>(ClassEnum::kZero),
"ClassEnum Zero is not equal to Zero");
static_assert(!(Flags<ClassEnum>(ClassEnum::kZero) ==
Flags<ClassEnum>(ClassEnum::kOne)),
"ClassEnum Zero is equal to One");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) == ClassEnum::kZero,
"ClassEnum Zero is not equal to Zero");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) !=
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum Zero is equal to One");
static_assert(!(Flags<ClassEnum>(ClassEnum::kZero) !=
Flags<ClassEnum>(ClassEnum::kZero)),
"ClassEnum Zero is not equal to Zero");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) != ClassEnum::kOne,
"ClassEnum Zero is equal to One");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) <
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum Zero is not less than One");
static_assert(!(Flags<ClassEnum>(ClassEnum::kZero) <
Flags<ClassEnum>(ClassEnum::kZero)),
"ClassEnum Zero is less than Zero");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) <=
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum Zero is not less or equal to One");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) <=
Flags<ClassEnum>(ClassEnum::kZero),
"ClassEnum Zero is not less or equal to Zero");
static_assert(!(Flags<ClassEnum>(ClassEnum::kOne) <=
Flags<ClassEnum>(ClassEnum::kZero)),
"ClassEnum One is less or equal to Zero");
static_assert(Flags<ClassEnum>(ClassEnum::kOne) >
Flags<ClassEnum>(ClassEnum::kZero),
"ClassEnum One is not greater than Zero");
static_assert(!(Flags<ClassEnum>(ClassEnum::kOne) >
Flags<ClassEnum>(ClassEnum::kOne)),
"ClassEnum One is greater than One");
static_assert(Flags<ClassEnum>(ClassEnum::kOne) >=
Flags<ClassEnum>(ClassEnum::kZero),
"ClassEnum One is not greater or equal to Zero");
static_assert(Flags<ClassEnum>(ClassEnum::kOne) >=
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum One is not greater or equal to One");
static_assert(!(Flags<ClassEnum>(ClassEnum::kZero) >=
Flags<ClassEnum>(ClassEnum::kOne)),
"ClassEnum Zero is greater or equal to One");
static_assert(Flags<ClassEnum>(ClassEnum::kZero) + ClassEnum::kOne ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
"ClassEnum Zero + One is not equal to {Zero, One}");
static_assert(ClassEnum::kZero + Flags<ClassEnum>(ClassEnum::kOne) ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
"ClassEnum Zero + One is not equal to {Zero, One}");
static_assert(
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}) +
Flags<ClassEnum>({ClassEnum::kOne, ClassEnum::kTwo}) ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne, ClassEnum::kTwo}),
"ClassEnum {Zero,One} + {One,Two} is not equal to {Zero,One,Two}");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}) -
Flags<ClassEnum>(ClassEnum::kZero) ==
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}) -
ClassEnum::kZero ==
Flags<ClassEnum>(ClassEnum::kOne),
"ClassEnum {Zero,One} - Zero is not equal to One");
static_assert(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}) -
Flags<ClassEnum>(ClassEnum::kTwo) ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
"ClassEnum {Zero,One} - Two is not equal to {Zero,One}");
static_assert(Union(Flags<ClassEnum>(ClassEnum::kZero),
Flags<ClassEnum>(ClassEnum::kOne)) ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
"ClassEnum Zero union One is not equal to {Zero, One}");
static_assert(
Union(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
Flags<ClassEnum>({ClassEnum::kOne, ClassEnum::kTwo})) ==
Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne, ClassEnum::kTwo}),
"ClassEnum {Zero,One} union {One,Two} is not equal to {Zero,One,Two}");
static_assert(Intersect(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
Flags<ClassEnum>({ClassEnum::kZero,
ClassEnum::kTwo})) ==
Flags<ClassEnum>(ClassEnum::kZero),
"ClassEnum {Zero,One} intersect {Zero,Two} is not equal to Zero");
static_assert(Intersect(Flags<ClassEnum>({ClassEnum::kZero, ClassEnum::kOne}),
Flags<ClassEnum>(ClassEnum::kTwo))
.IsEmpty(),
"ClassEnum {Zero,One} intersect Two is not empty");
static_assert(Flags<ClassEnum>({ClassEnum::kOne, ClassEnum::kTwo}) ==
Flags<ClassEnum>(ClassEnum::kOne, ClassEnum::kTwo),
"ClassEnum {One,Two} is not equal to (One,Two)");
static_assert(
Flags<ClassEnum>({ClassEnum::kOne, ClassEnum::kTwo, ClassEnum::kThree}) ==
Flags<ClassEnum>(ClassEnum::kOne, ClassEnum::kTwo, ClassEnum::kThree),
"ClassEnum {One,Two,Three} is not equal to (One,Two,Three)");
static_assert(
Flags<ClassEnum>({Flags<ClassEnum>{ClassEnum::kZero, ClassEnum::kOne},
ClassEnum::kTwo,
Flags<ClassEnum>{ClassEnum::kThree, ClassEnum::kBig}}) ==
Flags<ClassEnum>(Flags<ClassEnum>{ClassEnum::kZero, ClassEnum::kOne},
ClassEnum::kTwo,
Flags<ClassEnum>{ClassEnum::kThree, ClassEnum::kBig}),
"ClassEnum {{Zero,One},Two,{Three,Big}} is not equal to "
"({Zero,One},Two,{Three,Big})");
TEST(FlagsTest, BasicImplicitParameterConversions) {
EXPECT_EQ(BasicIdentity({}), Flags<BasicEnum>({}));
EXPECT_EQ(BasicIdentity(kBasicEnum_One), Flags<BasicEnum>(kBasicEnum_One));
EXPECT_EQ(BasicIdentity({kBasicEnum_One, kBasicEnum_Two}),
Flags<BasicEnum>(kBasicEnum_One, kBasicEnum_Two));
}
TEST(FlagsTest, BasicSet) {
Flags<BasicEnum> flags;
flags.Set(kBasicEnum_Zero);
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero));
flags.Set({kBasicEnum_One, kBasicEnum_Two});
EXPECT_EQ(flags,
Flags<BasicEnum>(kBasicEnum_Zero, kBasicEnum_One, kBasicEnum_Two));
flags.Set({kBasicEnum_One, kBasicEnum_Three});
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero, kBasicEnum_One,
kBasicEnum_Two, kBasicEnum_Three));
}
TEST(FlagsTest, BasicClear) {
Flags<BasicEnum> flags(kBasicEnum_Zero);
flags.Clear();
EXPECT_TRUE(flags.IsEmpty());
flags.Set({kBasicEnum_One, kBasicEnum_Two});
flags.Clear(kBasicEnum_One);
EXPECT_EQ(flags, kBasicEnum_Two);
}
TEST(FlagsTest, BasicAssign) {
Flags<BasicEnum> flags;
flags = kBasicEnum_Zero;
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero));
flags = {kBasicEnum_One, kBasicEnum_Two};
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_One, kBasicEnum_Two));
}
TEST(FlagsTest, BasicAddAssign) {
Flags<BasicEnum> flags;
flags += kBasicEnum_Zero;
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero));
flags += {kBasicEnum_One, kBasicEnum_Two};
EXPECT_EQ(flags,
Flags<BasicEnum>(kBasicEnum_Zero, kBasicEnum_One, kBasicEnum_Two));
flags += {kBasicEnum_One, kBasicEnum_Three};
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero, kBasicEnum_One,
kBasicEnum_Two, kBasicEnum_Three));
flags += {};
EXPECT_EQ(flags, Flags<BasicEnum>(kBasicEnum_Zero, kBasicEnum_One,
kBasicEnum_Two, kBasicEnum_Three));
}
TEST(FlagsTest, BasicSubAssign) {
Flags<BasicEnum> flags(kBasicEnum_Zero);
flags -= kBasicEnum_Zero;
EXPECT_TRUE(flags.IsEmpty());
flags.Set({kBasicEnum_One, kBasicEnum_Two, kBasicEnum_Three});
flags -= {kBasicEnum_One, kBasicEnum_Three};
EXPECT_EQ(flags, kBasicEnum_Two);
flags -= {};
EXPECT_EQ(flags, kBasicEnum_Two);
}
TEST(FlagsTest, SizedImplicitParameterConversions) {
EXPECT_EQ(SizedIdentity({}), Flags<SizedEnum>({}));
EXPECT_EQ(SizedIdentity(kSizedEnum_One), Flags<SizedEnum>(kSizedEnum_One));
EXPECT_EQ(SizedIdentity({kSizedEnum_One, kSizedEnum_Two}),
Flags<SizedEnum>(kSizedEnum_One, kSizedEnum_Two));
}
TEST(FlagsTest, SizedSet) {
Flags<SizedEnum> flags;
flags.Set(kSizedEnum_Zero);
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero));
flags.Set({kSizedEnum_One, kSizedEnum_Two});
EXPECT_EQ(flags,
Flags<SizedEnum>(kSizedEnum_Zero, kSizedEnum_One, kSizedEnum_Two));
flags.Set({kSizedEnum_One, kSizedEnum_Three});
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero, kSizedEnum_One,
kSizedEnum_Two, kSizedEnum_Three));
}
TEST(FlagsTest, SizedClear) {
Flags<SizedEnum> flags(kSizedEnum_Zero);
flags.Clear();
EXPECT_TRUE(flags.IsEmpty());
flags.Set({kSizedEnum_One, kSizedEnum_Two});
flags.Clear(kSizedEnum_One);
EXPECT_EQ(flags, kSizedEnum_Two);
}
TEST(FlagsTest, SizedAssign) {
Flags<SizedEnum> flags;
flags = kSizedEnum_Zero;
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero));
flags = {kSizedEnum_One, kSizedEnum_Two};
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_One, kSizedEnum_Two));
}
TEST(FlagsTest, SizedAddAssign) {
Flags<SizedEnum> flags;
flags += kSizedEnum_Zero;
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero));
flags += {kSizedEnum_One, kSizedEnum_Two};
EXPECT_EQ(flags,
Flags<SizedEnum>(kSizedEnum_Zero, kSizedEnum_One, kSizedEnum_Two));
flags += {kSizedEnum_One, kSizedEnum_Three};
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero, kSizedEnum_One,
kSizedEnum_Two, kSizedEnum_Three));
flags += {};
EXPECT_EQ(flags, Flags<SizedEnum>(kSizedEnum_Zero, kSizedEnum_One,
kSizedEnum_Two, kSizedEnum_Three));
}
TEST(FlagsTest, SizedSubAssign) {
Flags<SizedEnum> flags(kSizedEnum_Zero);
flags -= kSizedEnum_Zero;
EXPECT_TRUE(flags.IsEmpty());
flags.Set({kSizedEnum_One, kSizedEnum_Two, kSizedEnum_Three});
flags -= {kSizedEnum_One, kSizedEnum_Three};
EXPECT_EQ(flags, kSizedEnum_Two);
flags -= {};
EXPECT_EQ(flags, kSizedEnum_Two);
}
TEST(FlagsTest, ClassImplicitParameterConversions) {
EXPECT_EQ(ClassIdentity({}), Flags<ClassEnum>({}));
EXPECT_EQ(ClassIdentity(ClassEnum::kOne), Flags<ClassEnum>(ClassEnum::kOne));
EXPECT_EQ(ClassIdentity({ClassEnum::kOne, ClassEnum::kTwo}),
Flags<ClassEnum>(ClassEnum::kOne, ClassEnum::kTwo));
}
TEST(FlagsTest, ClassSet) {
Flags<ClassEnum> flags;
flags.Set(ClassEnum::kZero);
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero));
flags.Set({ClassEnum::kOne, ClassEnum::kTwo});
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo));
flags.Set({ClassEnum::kOne, ClassEnum::kThree});
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo, ClassEnum::kThree));
}
TEST(FlagsTest, ClassClear) {
Flags<ClassEnum> flags(ClassEnum::kZero);
flags.Clear();
EXPECT_TRUE(flags.IsEmpty());
flags.Set({ClassEnum::kOne, ClassEnum::kTwo});
flags.Clear(ClassEnum::kOne);
EXPECT_EQ(flags, ClassEnum::kTwo);
}
TEST(FlagsTest, ClassAssign) {
Flags<ClassEnum> flags;
flags = ClassEnum::kZero;
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero));
flags = {ClassEnum::kOne, ClassEnum::kTwo};
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kOne, ClassEnum::kTwo));
}
TEST(FlagsTest, ClassAddAssign) {
Flags<ClassEnum> flags;
flags += ClassEnum::kZero;
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero));
flags += {ClassEnum::kOne, ClassEnum::kTwo};
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo));
flags += {ClassEnum::kOne, ClassEnum::kThree};
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo, ClassEnum::kThree));
flags += {};
EXPECT_EQ(flags, Flags<ClassEnum>(ClassEnum::kZero, ClassEnum::kOne,
ClassEnum::kTwo, ClassEnum::kThree));
}
TEST(FlagsTest, ClassSubAssign) {
Flags<ClassEnum> flags(ClassEnum::kZero);
flags -= ClassEnum::kZero;
EXPECT_TRUE(flags.IsEmpty());
flags.Set({ClassEnum::kOne, ClassEnum::kTwo, ClassEnum::kThree});
flags -= {ClassEnum::kOne, ClassEnum::kThree};
EXPECT_EQ(flags, ClassEnum::kTwo);
flags -= {};
EXPECT_EQ(flags, ClassEnum::kTwo);
}
} // namespace
} // namespace gb
| 49.347619 | 80 | 0.650455 | jpursey |
335ca6fb8a6661b107a94f833bbb91c34917de01 | 482 | cpp | C++ | vox.render/profiling/profiler_spy.cpp | ArcheGraphics/Arche-cpp | da6770edd4556a920b3f7298f38176107caf7e3a | [
"MIT"
] | 8 | 2022-02-15T12:54:57.000Z | 2022-03-30T16:35:58.000Z | vox.render/profiling/profiler_spy.cpp | yangfengzzz/DigitalArche | da6770edd4556a920b3f7298f38176107caf7e3a | [
"MIT"
] | null | null | null | vox.render/profiling/profiler_spy.cpp | yangfengzzz/DigitalArche | da6770edd4556a920b3f7298f38176107caf7e3a | [
"MIT"
] | null | null | null | // Copyright (c) 2022 Feng Yang
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "profiler_spy.h"
namespace vox {
ProfilerSpy::ProfilerSpy(const std::string &p_name) :
name(p_name),
start(std::chrono::steady_clock::now()) {
}
ProfilerSpy::~ProfilerSpy() {
end = std::chrono::steady_clock::now();
Profiler::save(*this);
}
}
| 22.952381 | 73 | 0.709544 | ArcheGraphics |
335cf0ef3cfb3c0478f8f48740f0f2ca47759b91 | 836 | cpp | C++ | Data Structures and Libraries/Linear Data Structures with Built-in Libraries/10264 The Most Potent Corner.cpp | satvik007/UvaRevision | b2473130eb17435ac55132083e85262491db3d1b | [
"MIT"
] | null | null | null | Data Structures and Libraries/Linear Data Structures with Built-in Libraries/10264 The Most Potent Corner.cpp | satvik007/UvaRevision | b2473130eb17435ac55132083e85262491db3d1b | [
"MIT"
] | null | null | null | Data Structures and Libraries/Linear Data Structures with Built-in Libraries/10264 The Most Potent Corner.cpp | satvik007/UvaRevision | b2473130eb17435ac55132083e85262491db3d1b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <ll> vi;
int n;
vi a, b;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
while(cin >> n){
a.resize(1 << n); b.resize(a.size());
for(int i=0; i<a.size(); i++) cin >> a[i];
for(int i=0; i<(1<<n); i++){
int sum = 0;
for(int j=0; (i ^ (1<<j)) < a.size(); j++){
sum += a[(i ^ (1<<j))];
}
b[i] = sum;
}
int max1 = -1;
for(int i=0; i<a.size(); i++){
for(int j=0; (i ^ (1<<j)) < a.size(); j++){
max1 = max(max1, (int)b[i] + (int)b[i^(1<<j)]);
}
}
cout << max1 << "\n";
}
return 0;
}
| 24.588235 | 63 | 0.404306 | satvik007 |
335f2459bf433f0f369bf98d4226422b110deaf2 | 2,805 | cpp | C++ | src/utilities/Convertible.cpp | gle8098/succotash | 7f4189418301b4f9322a4cfa6dc205fcbe999d40 | [
"MIT"
] | 2 | 2020-05-19T10:52:20.000Z | 2020-10-26T18:39:22.000Z | src/utilities/Convertible.cpp | gle8098/succotash | 7f4189418301b4f9322a4cfa6dc205fcbe999d40 | [
"MIT"
] | 2 | 2020-04-27T08:27:22.000Z | 2020-05-06T17:27:06.000Z | src/utilities/Convertible.cpp | gle8098/succotash | 7f4189418301b4f9322a4cfa6dc205fcbe999d40 | [
"MIT"
] | null | null | null | #include "Convertible.hpp"
#include <functional>
#include <stdexcept>
namespace succotash::utilities {
//------------------------------------------------------------------------------
// Local functions which are not for export
//------------------------------------------------------------------------------
inline void ThrowErrorImpl(const char* value, const char* desc) {
char buffer[1024];
snprintf(buffer, sizeof(buffer), "Value '%s' exception, %s", value, desc);
throw std::runtime_error(buffer);
}
template <typename T, typename Func>
inline T ConvertStdlib(const char* value, Func func, const char* error_desc) {
char* error;
long result = func(value, &error);
if (*value == '\0' || *error != '\0') {
ThrowErrorImpl(value, error_desc);
}
return result;
}
//------------------------------------------------------------------------------
// Private methods
//------------------------------------------------------------------------------
void Convertible::ThrowError(const char* desc) const {
ThrowErrorImpl(this->value_, desc);
}
//------------------------------------------------------------------------------
// Public methods
//------------------------------------------------------------------------------
Convertible::Convertible(const char* value)
: value_(value) {
}
// String
std::string Convertible::ToString() const {
return std::string(value_);
}
// Basic numbers
int Convertible::ToInt() const {
return ToLong();
}
unsigned int Convertible::ToUInt() const {
return ToULong();
}
long Convertible::ToLong() const {
auto parser = std::bind(&strtol, std::placeholders::_1,
std::placeholders::_2, 0);
return ConvertStdlib<long>(value_, parser,"couldn't convert to int/long");
}
unsigned long Convertible::ToULong() const {
auto parser = std::bind(&strtoul, std::placeholders::_1,
std::placeholders::_2, 0);
return ConvertStdlib<unsigned long>(value_, parser,
"couldn't convert to uint/ulong");
}
// Numbers with floating precision
float Convertible::ToFloat() const {
auto parser = &strtof;
return ConvertStdlib<float>(value_, parser, "couldn't convert to float");
}
double Convertible::ToDouble() const {
auto parser = &strtod;
return ConvertStdlib<double>(value_, parser, "couldn't convert to double");
}
// Bool
bool Convertible::ToBool() const {
std::string_view value(value_);
if (value == "true" || value == "True") {
return true;
} else if (value == "false" || value == "False") {
return false;
} else {
ThrowError("couldn't convert to bool");
return false;
}
}
// Operators
bool Convertible::operator==(const std::string& rhs) const {
return rhs == value_;
}
} // namespace succotash::utilities | 26.214953 | 80 | 0.547594 | gle8098 |
3362d8f4beef1376eb5dba1aaad9fe6cb430e9fe | 872 | hpp | C++ | modules/classes/HoldQueue1.hpp | PercyPanJX/Scheduling-and-Deadlock-Avoidance | d51d6a7b3da7333559592e7381add1c0ef25fb2e | [
"Apache-2.0"
] | null | null | null | modules/classes/HoldQueue1.hpp | PercyPanJX/Scheduling-and-Deadlock-Avoidance | d51d6a7b3da7333559592e7381add1c0ef25fb2e | [
"Apache-2.0"
] | null | null | null | modules/classes/HoldQueue1.hpp | PercyPanJX/Scheduling-and-Deadlock-Avoidance | d51d6a7b3da7333559592e7381add1c0ef25fb2e | [
"Apache-2.0"
] | 1 | 2020-07-24T20:07:23.000Z | 2020-07-24T20:07:23.000Z | /*
* HoldQueue1.hpp
*
* Created on: 2018/5/13
* Author: Qun Cheng
* Author: Jiaxuan(Percy) Pan
*/
#ifndef HOLDQUEUE1_HPP_
#define HOLDQUEUE1_HPP_
#include "HoldQueue2.hpp"
class HoldQueue1{
std::list<Job> q;
public:
HoldQueue1(){}
bool empty(){
return q.empty();
}
Job front(){
return q.front();
}
void pop(){
q.pop_front();
}
void print(){
for(Job j : q){
j.print();
}
}
void push(Job in){
if(q.empty()){
q.push_back(in);
return;
}
list<Job>::iterator it;
it = q.begin();
while(it != q.end()){
if(in.getRuntime() < it->getRuntime()){
q.insert(it, in);
return;
}
it++;
}
if(in.getRuntime() < it->getRuntime()){
q.insert(it, in);
return;
}
q.push_back(in);
return;
}
};
#endif /* HOLDQUEUE1_HPP_ */
| 12.823529 | 43 | 0.516055 | PercyPanJX |
33644ce440a5f006d9304c5e93ae4520c2eb71f8 | 4,892 | cc | C++ | validator/cpp/htmlparser/renderer.cc | li-cai/amphtml | 78fed1a5551cae5486717acbd45878a1e36343a0 | [
"Apache-2.0"
] | 3 | 2016-02-25T15:32:53.000Z | 2021-01-21T16:11:38.000Z | validator/cpp/htmlparser/renderer.cc | ColombiaOnline/amphtml | 92f8b2681933d3904c64f1d162f6e25dc8fb617c | [
"Apache-2.0"
] | 93 | 2020-03-05T19:09:47.000Z | 2021-05-13T15:12:03.000Z | validator/cpp/htmlparser/renderer.cc | ColombiaOnline/amphtml | 92f8b2681933d3904c64f1d162f6e25dc8fb617c | [
"Apache-2.0"
] | 1 | 2018-04-03T08:10:10.000Z | 2018-04-03T08:10:10.000Z | #include <algorithm>
#include "atomutil.h"
#include "elements.h"
#include "renderer.h"
#include "strings.h"
namespace htmlparser {
namespace {
inline void WriteToBuffer(const std::string& str, std::stringbuf* buf) {
buf->sputn(str.c_str(), str.size());
}
// Writes str surrounded by quotes to buf. Normally it will use double quotes,
// but if str contains a double quote, it will use single quotes.
// It is used for writing the identifiers in a doctype declaration.
// In valid HTML, they can't contains both types of quotes.
inline void WriteQuoted(const std::string& str, std::stringbuf* buf) {
char quote = '"';
if (str.find('\"') != std::string::npos) {
quote = '\'';
}
buf->sputc(quote);
WriteToBuffer(str, buf);
buf->sputc(quote);
}
} // namespace.
RenderError Renderer::Render(Node* node, std::stringbuf* buf) {
switch (node->Type()) {
case NodeType::ERROR_NODE:
return RenderError::ERROR_NODE_NO_RENDER;
case NodeType::TEXT_NODE:
Strings::Escape(node->Data().data(), buf);
return RenderError::NO_ERROR;
case NodeType::DOCUMENT_NODE:
for (Node* c = node->FirstChild(); c; c = c->NextSibling()) {
auto err = Render(c, buf);
if (err != RenderError::NO_ERROR) {
return err;
}
}
return RenderError::NO_ERROR;
case NodeType::ELEMENT_NODE:
// No-op.
break;
case NodeType::COMMENT_NODE:
WriteToBuffer("<!--", buf);
WriteToBuffer(node->Data().data(), buf);
WriteToBuffer("-->", buf);
return RenderError::NO_ERROR;
case NodeType::DOCTYPE_NODE: {
WriteToBuffer("<!DOCTYPE ", buf);
WriteToBuffer(node->Data().data(), buf);
std::string p;
std::string s;
for (auto& attr : node->Attributes()) {
std::string key = attr.key;
std::string value = attr.value;
if (key == "public") {
p = value;
} else if (key == "system") {
s = value;
}
}
if (!p.empty()) {
WriteToBuffer(" PUBLIC ", buf);
WriteQuoted(p, buf);
if (!s.empty()) {
buf->sputc(' ');
WriteQuoted(s, buf);
}
} else if (!s.empty()) {
WriteToBuffer(" SYSTEM ", buf);
WriteQuoted(s, buf);
}
buf->sputc('>');
return RenderError::NO_ERROR;
}
default:
return RenderError::UNKNOWN_NODE_TYPE;
}
// Render the <xxx> opening tag.
buf->sputc('<');
WriteToBuffer(node->DataAtom() == Atom::UNKNOWN ?
node->Data().data() : AtomUtil::ToString(node->DataAtom()),
buf);
for (auto& attr : node->Attributes()) {
std::string ns = attr.name_space;
std::string k = attr.key;
std::string v = attr.value;
buf->sputc(' ');
if (!ns.empty()) {
WriteToBuffer(ns, buf);
buf->sputc(':');
}
WriteToBuffer(k, buf);
if (!v.empty()) {
WriteToBuffer("=\"", buf);
Strings::Escape(v, buf);
buf->sputc('"');
}
}
if (auto ve = std::find(kVoidElements.begin(),
kVoidElements.end(),
node->DataAtom());
ve != kVoidElements.end()) {
if (node->FirstChild()) {
return RenderError::VOID_ELEMENT_CHILD_NODE;
}
WriteToBuffer(">", buf);
return RenderError::NO_ERROR;
}
buf->sputc('>');
// Add initial newline where there is danger of a newline being ignored.
if (Node* c = node->FirstChild();
c && c->Type() == NodeType::TEXT_NODE && Strings::StartsWith(
c->Data(), "\n")) {
if (node->DataAtom() == Atom::PRE ||
node->DataAtom() == Atom::LISTING ||
node->DataAtom() == Atom::TEXTAREA) {
buf->sputc('\n');
}
}
// Render any child nodes.
if (std::find(kRawTextNodes.begin(),
kRawTextNodes.end(),
node->DataAtom()) != kRawTextNodes.end()) {
for (Node* c = node->FirstChild(); c; c = c->NextSibling()) {
if (c->Type() == NodeType::TEXT_NODE) {
WriteToBuffer(c->Data().data(), buf);
} else {
auto err = Render(c, buf);
if (err != RenderError::NO_ERROR) {
return err;
}
}
}
if (node->DataAtom() == Atom::PLAINTEXT) {
// Don't render anything else. <plaintext> must be the last element
// in the file, with no closing tag.
return RenderError::PLAIN_TEXT_ABORT;
}
} else {
for (Node* c = node->FirstChild(); c; c = c->NextSibling()) {
auto err = Render(c, buf);
if (err != RenderError::NO_ERROR) {
return err;
}
}
}
// Render the </xxx> closing tag.
WriteToBuffer("</", buf);
WriteToBuffer(node->DataAtom() == Atom::UNKNOWN ?
node->Data().data() : AtomUtil::ToString(node->DataAtom()),
buf);
buf->sputc('>');
return RenderError::NO_ERROR;
}
} // namespace htmlparser.
| 28.44186 | 78 | 0.55601 | li-cai |
3364b3d7bf5e8c34701a087abd3890bbd3554559 | 5,878 | cpp | C++ | src/rpg_setup.cpp | MarianoGnu/liblcf | 02c640335ad13f2d815409a171045c42b23f7b86 | [
"MIT"
] | null | null | null | src/rpg_setup.cpp | MarianoGnu/liblcf | 02c640335ad13f2d815409a171045c42b23f7b86 | [
"MIT"
] | null | null | null | src/rpg_setup.cpp | MarianoGnu/liblcf | 02c640335ad13f2d815409a171045c42b23f7b86 | [
"MIT"
] | null | null | null | /*
* This file is part of liblcf. Copyright (c) 2018 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
#include "lcf_options.h"
#include "rpg_actor.h"
#include "rpg_event.h"
#include "rpg_map.h"
#include "rpg_mapinfo.h"
#include "rpg_system.h"
#include "rpg_save.h"
#include "rpg_chipset.h"
#include "rpg_parameters.h"
#include "data.h"
void RPG::SaveActor::Setup(int actor_id) {
const RPG::Actor& actor = Data::actors[actor_id - 1];
ID = actor.ID;
name = actor.name;
title = actor.title;
sprite_name = actor.character_name;
sprite_id = actor.character_index;
sprite_flags = actor.transparent ? 3 : 0;
face_name = actor.face_name;
face_id = actor.face_index;
level = actor.initial_level;
exp = 0;
hp_mod = 0;
sp_mod = 0;
attack_mod = 0;
defense_mod = 0;
spirit_mod = 0;
agility_mod = 0;
skills_size = 0;
skills.clear();
equipped.clear();
equipped.push_back(actor.initial_equipment.weapon_id);
equipped.push_back(actor.initial_equipment.shield_id);
equipped.push_back(actor.initial_equipment.armor_id);
equipped.push_back(actor.initial_equipment.helmet_id);
equipped.push_back(actor.initial_equipment.accessory_id);
current_hp = 0;
current_sp = 0;
battle_commands.resize(7, -1);
status.resize(Data::states.size());
changed_battle_commands = false;
class_id = -1;
two_weapon = actor.two_weapon;
lock_equipment = actor.lock_equipment;
auto_battle = actor.auto_battle;
super_guard = actor.super_guard;
}
void RPG::SaveInventory::Setup() {
party = Data::system.party;
party_size = party.size();
}
void RPG::SaveMapEvent::Setup(const RPG::Event& event) {
ID = event.ID;
position_x = event.x;
position_y = event.y;
}
void RPG::SaveMapInfo::Setup() {
position_x = 0;
position_y = 0;
lower_tiles.resize(144);
upper_tiles.resize(144);
for (int i = 0; i < 144; i++) {
lower_tiles[i] = i;
upper_tiles[i] = i;
}
}
void RPG::SaveMapInfo::Setup(const RPG::Map& map) {
chipset_id = map.chipset_id;
parallax_name = map.parallax_name;
parallax_horz = map.parallax_loop_x;
parallax_vert = map.parallax_loop_y;
parallax_horz_auto = map.parallax_auto_loop_x;
parallax_vert_auto = map.parallax_auto_loop_y;
parallax_horz_speed = map.parallax_sx;
parallax_vert_speed = map.parallax_sy;
}
void RPG::SaveSystem::Setup() {
const RPG::System& system = Data::system;
frame_count = 0;
graphics_name = system.system_name;
face_name = "";
face_id = -1;
face_right = false;
face_flip = false;
transparent = false;
music_stopping = false;
title_music = system.title_music;
battle_music = system.battle_music;
battle_end_music = system.battle_end_music;
inn_music = system.inn_music;
// current_music
// unknown1_music FIXME
// unknown2_music FIXME
// stored_music
boat_music = system.boat_music;
ship_music = system.ship_music;
airship_music = system.airship_music;
gameover_music = system.gameover_music;
cursor_se = system.cursor_se;
decision_se = system.decision_se;
cancel_se = system.cancel_se;
buzzer_se = system.buzzer_se;
battle_se = system.battle_se;
escape_se = system.escape_se;
enemy_attack_se = system.enemy_attack_se;
enemy_damaged_se = system.enemy_damaged_se;
actor_damaged_se = system.actor_damaged_se;
dodge_se = system.dodge_se;
enemy_death_se = system.enemy_death_se;
item_se = system.item_se;
transition_out = system.transition_out;
transition_in = system.transition_in;
battle_start_fadeout = system.battle_start_fadeout;
battle_start_fadein = system.battle_start_fadein;
battle_end_fadeout = system.battle_end_fadeout;
battle_end_fadein = system.battle_end_fadein;
message_stretch = system.message_stretch;
font_id = system.font_id;
teleport_allowed = true;
escape_allowed = true;
save_allowed = true;
menu_allowed = true;
background = "";
save_count = 0;
save_slot = -1;
}
void RPG::Save::Setup() {
system.Setup();
screen = RPG::SaveScreen();
pictures.clear();
pictures.resize(50);
for (int i = 1; i <= (int)pictures.size(); i++) {
pictures[i - 1].ID = i;
}
actors.clear();
actors.resize(Data::actors.size());
for (int i = 1; i <= (int) actors.size(); i++)
actors[i - 1].Setup(i);
map_info.Setup();
party_location.move_speed = 4;
boat_location.vehicle = RPG::SaveVehicleLocation::VehicleType_skiff;
ship_location.vehicle = RPG::SaveVehicleLocation::VehicleType_ship;
airship_location.vehicle = RPG::SaveVehicleLocation::VehicleType_airship;
if (targets.empty()) {
targets.resize(1);
}
}
void RPG::Actor::Setup() {
int max_final_level = 0;
if (Data::system.ldb_id == 2003) {
max_final_level = 99;
if (final_level == -1) {
final_level = max_final_level;
}
exp_base = exp_base == -1 ? 300 : exp_base;
exp_inflation = exp_inflation == -1 ? 300 : exp_inflation;
}
else {
max_final_level = 50;
if (final_level == -1) {
final_level = max_final_level;
}
exp_base = exp_base == -1 ? 30 : exp_base;
exp_inflation = exp_inflation == -1 ? 30 : exp_inflation;
}
parameters.Setup(max_final_level);
}
void RPG::Chipset::Init() {
terrain_data.resize(162, 1);
passable_data_lower.resize(162, 15);
passable_data_upper.resize(144, 15);
passable_data_upper.front() = 31;
}
void RPG::System::Init() {
party.resize(1, 1);
menu_commands.resize(1, 1);
}
void RPG::Parameters::Setup(int final_level) {
if (maxhp.size() < final_level) maxhp.resize(final_level, 1);
if (maxsp.size() < final_level) maxsp.resize(final_level, 0);
if (attack.size() < final_level) attack.resize(final_level, 1);
if (defense.size() < final_level) defense.resize(final_level, 1);
if (spirit.size() < final_level) spirit.resize(final_level, 1);
if (agility.size() < final_level) agility.resize(final_level, 1);
}
| 28.259615 | 77 | 0.732052 | MarianoGnu |
3365a5ad57e6c45f7114f0b79dd29353013c7b01 | 2,490 | cpp | C++ | Codeforces/915C/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Codeforces/915C/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/915C/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <iomanip>
#include <climits>
#include <vector>
#include <set>
#include <queue>
#define SIZE 10
using namespace std;
int arr[SIZE];
int main()
{
ios::sync_with_stdio(false);
string origNum, maxNum;
cin >> origNum >> maxNum;
memset(arr, 0, sizeof(arr));
for (int i = 0; i < origNum.length(); i++)
{
arr[origNum[i] - '0']++;
}
/*
if (origNum.length() > maxNum.length())
{
int delta = origNum.length() - maxNum.length();
string tmp = "";
while (delta--)
{
tmp += '0';
}
maxNum = tmp + maxNum;
}
*/
if (maxNum.length() == origNum.length())
{
for (int i = 0; i < origNum.length(); i++)
{
if (arr[maxNum[i] - '0'] > 0)
{
arr[maxNum[i] - '0']--;
string tmp = "";
for (int j = 0; j <= 9; j++)
{
for (int k = 0; k < arr[j]; k++)
{
tmp += (char)(j + '0');
}
}
bool canSelect = true;
for (int j = i + 1; j < origNum.length(); j++)
{
if (maxNum[j] > tmp[j - i - 1])
{
canSelect = true;
break;
}
else if (maxNum[j] < tmp[j - i - 1])
{
canSelect = false;
break;
}
}
if (canSelect)
{
cout << maxNum[i];
continue;
}
else
{
arr[maxNum[i] - '0']++;
}
}
bool quitFlag = false;
for (int j = maxNum[i] - '0' - 1; j >= 0; j--)
{
if (arr[j] > 0)
{
cout << j;
arr[j]--;
quitFlag = true;
break;
}
}
if (quitFlag)
break;
}
}
for (int i = 9; i >= 0; i--)
{
while (arr[i])
{
cout << i;
arr[i]--;
}
}
cout << endl;
return 0;
}
| 22.035398 | 62 | 0.323293 | codgician |
3365b0a0467138b16194c86b4580da019d4859d4 | 703 | cpp | C++ | backend/tests/test-helib-fp-int8_t-multByConst.cpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 40 | 2018-12-03T13:01:06.000Z | 2022-02-23T13:04:12.000Z | backend/tests/test-helib-fp-int8_t-multByConst.cpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 63 | 2018-09-11T14:13:31.000Z | 2020-01-14T16:12:39.000Z | backend/tests/test-helib-fp-int8_t-multByConst.cpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 7 | 2019-07-10T14:48:31.000Z | 2022-03-23T09:12:11.000Z | #include <memory>
#include <algorithm>
#include <cassert>
#include <cstdint>
#include "circuit-repo.hpp"
#include "circuit-test-util.hpp"
#include "context-helib.hpp"
int main(void) {
using namespace SHEEP;
ContextHElib_Fp<int8_t> ctx;
std::vector<ContextHElib_Fp<int8_t>::Plaintext> pt_input = {55, -42, 120};
ContextHElib_Fp<int8_t>::Ciphertext ct = ctx.encrypt(pt_input);
long const_val = 2;
// Perform operation
ContextHElib_Fp<int8_t>::Ciphertext ct_out =
ctx.MultByConstant(ct, const_val);
// Decrypt
std::vector<ContextHElib_Fp<int8_t>::Plaintext> pt_out = ctx.decrypt(ct_out);
assert(pt_out[0] == 110);
assert(pt_out[1] == -84);
assert(pt_out[2] == -16);
}
| 22.677419 | 79 | 0.70128 | vkurilin |
3365bc9ea0ff7a332d8d478b2da52f7d8acda705 | 11,408 | cpp | C++ | wallet/swaps/swap_offers_board.cpp | DavidBurkett/beam | c352f54fb18136188d4470d2178a95b1deb335c2 | [
"Apache-2.0"
] | null | null | null | wallet/swaps/swap_offers_board.cpp | DavidBurkett/beam | c352f54fb18136188d4470d2178a95b1deb335c2 | [
"Apache-2.0"
] | null | null | null | wallet/swaps/swap_offers_board.cpp | DavidBurkett/beam | c352f54fb18136188d4470d2178a95b1deb335c2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Beam Team
//
// 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 "swap_offers_board.h"
#include "p2p/protocol_base.h"
namespace beam::wallet
{
SwapOffersBoard::SwapOffersBoard(FlyClient::INetwork& network, IWalletMessageEndpoint& messageEndpoint)
: m_network(network),
m_messageEndpoint(messageEndpoint)
{
for (auto channel : m_channelsMap)
{
m_network.BbsSubscribe(channel.second, m_lastTimestamp, this);
}
}
const std::map<AtomicSwapCoin, BbsChannel> SwapOffersBoard::m_channelsMap =
{
{AtomicSwapCoin::Bitcoin, proto::Bbs::s_MaxChannels},
{AtomicSwapCoin::Litecoin, proto::Bbs::s_MaxChannels + 1},
{AtomicSwapCoin::Qtum, proto::Bbs::s_MaxChannels + 2}
};
void SwapOffersBoard::OnMsg(proto::BbsMsg &&msg)
{
if (msg.m_Message.empty() || msg.m_Message.size() < MsgHeader::SIZE)
return;
SwapOfferToken token;
SwapOfferConfirmation confirmation;
try
{
MsgHeader header(msg.m_Message.data());
if (header.V0 != 0 ||
header.V1 != 0 ||
header.V2 != m_protocolVersion ||
header.type != 0)
{
LOG_WARNING() << "offer board message version unsupported";
return;
}
// message body
Deserializer d;
d.reset(msg.m_Message.data() + header.SIZE, header.size);
d & token;
d & confirmation.m_Signature;
}
catch(...)
{
LOG_WARNING() << "offer board message deserialization exception";
return;
}
auto newOffer = token.Unpack();
confirmation.m_offerData = toByteBuffer(token);
if (!confirmation.IsValid(newOffer.m_publisherId.m_Pk))
{
LOG_WARNING() << "offer board message signature is invalid";
return;
}
if (newOffer.m_coin >= AtomicSwapCoin::Unknown || newOffer.m_status > SwapOfferStatus::Failed)
{
LOG_WARNING() << "offer board message is invalid";
return;
}
auto it = m_offersCache.find(newOffer.m_txId);
// New offer
if (it == m_offersCache.end())
{
m_offersCache[newOffer.m_txId] = newOffer;
if (newOffer.m_status == SwapOfferStatus::Pending)
{
notifySubscribers(ChangeAction::Added, std::vector<SwapOffer>{newOffer});
}
else
{
// Don't push irrelevant offers to subscribers
}
}
// Existing offer update
else
{
SwapOfferStatus existingStatus = m_offersCache[newOffer.m_txId].m_status;
// Normal case
if (existingStatus == SwapOfferStatus::Pending)
{
if (newOffer.m_status != SwapOfferStatus::Pending)
{
m_offersCache[newOffer.m_txId].m_status = newOffer.m_status;
notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{newOffer});
}
}
// Transaction state has changed asynchronously while board was offline.
// Incomplete offer with SwapOfferStatus!=Pending was created.
// If offer with SwapOfferStatus::Pending is still exist in network,
// it need to be updated to latest status.
else
{
if (newOffer.m_status == SwapOfferStatus::Pending)
{
sendUpdateToNetwork(newOffer.m_txId, newOffer.m_publisherId, newOffer.m_coin, existingStatus);
}
}
}
}
/**
* Watches for system state to remove stuck expired offers from board.
* Notify only subscribers. Doesn't push any updates to network.
*/
void SwapOffersBoard::onSystemStateChanged(const Block::SystemState::ID& stateID)
{
Height currentHeight = stateID.m_Height;
for (auto& pair : m_offersCache)
{
if (pair.second.m_status != SwapOfferStatus::Pending) continue; // has to be already removed from board
auto peerResponseTime = pair.second.GetParameter<Height>(TxParameterID::PeerResponseTime);
auto minHeight = pair.second.GetParameter<Height>(TxParameterID::MinHeight);
if (peerResponseTime && minHeight)
{
auto expiresHeight = *minHeight + *peerResponseTime;
if (expiresHeight <= currentHeight)
{
pair.second.m_status = SwapOfferStatus::Expired;
notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{pair.second});
}
}
}
}
void SwapOffersBoard::onTransactionChanged(ChangeAction action, const std::vector<TxDescription>& items)
{
if (action != ChangeAction::Removed)
{
for (const auto& item : items)
{
if (item.m_txType != TxType::AtomicSwap) continue;
switch (item.m_status)
{
case TxStatus::InProgress:
updateOffer(item.m_txId, SwapOfferStatus::InProgress);
break;
case TxStatus::Failed:
{
auto reason = item.GetParameter<TxFailureReason>(TxParameterID::InternalFailureReason);
SwapOfferStatus status = SwapOfferStatus::Failed;
if (reason && *reason == TxFailureReason::TransactionExpired)
{
status = SwapOfferStatus::Expired;
}
updateOffer(item.m_txId, status);
break;
}
case TxStatus::Canceled:
updateOffer(item.m_txId, SwapOfferStatus::Canceled);
break;
default:
// ignore
break;
}
}
}
}
void SwapOffersBoard::updateOffer(const TxID& offerTxID, SwapOfferStatus newStatus)
{
if (newStatus == SwapOfferStatus::Pending) return;
auto offerIt = m_offersCache.find(offerTxID);
if (offerIt != m_offersCache.end())
{
AtomicSwapCoin coin = offerIt->second.m_coin;
WalletID publisherId = offerIt->second.m_publisherId;
SwapOfferStatus currentStatus = offerIt->second.m_status;
if (currentStatus == SwapOfferStatus::Pending)
{
m_offersCache[offerTxID].m_status = newStatus;
notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{m_offersCache[offerTxID]});
sendUpdateToNetwork(offerTxID, publisherId, coin, newStatus);
}
}
else
{
// Case: updateOffer() had been called before offer appeared on board.
// Here we don't know if offer exists in network at all. So board doesn't send any update to network.
// Board stores incomplete offer to notify network when original Pending offer will be received from network.
SwapOffer incompleteOffer(offerTxID);
incompleteOffer.m_status = newStatus;
m_offersCache[offerTxID] = incompleteOffer;
}
}
auto SwapOffersBoard::getOffersList() const -> std::vector<SwapOffer>
{
std::vector<SwapOffer> offers;
for (auto offer : m_offersCache)
{
SwapOfferStatus status = offer.second.m_status;
if (status == SwapOfferStatus::Pending)
{
offers.push_back(offer.second);
}
}
return offers;
}
auto SwapOffersBoard::getChannel(AtomicSwapCoin coin) const -> BbsChannel
{
auto it = m_channelsMap.find(coin);
assert(it != std::cend(m_channelsMap));
return it->second;
}
void SwapOffersBoard::publishOffer(const SwapOffer& offer) const
{
auto swapCoin = offer.GetParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
auto isBeamSide = offer.GetParameter<bool>(TxParameterID::AtomicSwapIsBeamSide);
auto amount = offer.GetParameter<Amount>(TxParameterID::Amount);
auto swapAmount = offer.GetParameter<Amount>(TxParameterID::AtomicSwapAmount);
auto responseTime = offer.GetParameter<Height>(TxParameterID::PeerResponseTime);
auto minimalHeight = offer.GetParameter<Height>(TxParameterID::MinHeight);
if (!swapCoin || !isBeamSide || !amount || !swapAmount || !responseTime || !minimalHeight)
{
LOG_WARNING() << offer.m_txId << " Can't publish invalid offer.\n\t";
return;
}
LOG_INFO() << offer.m_txId << " Publish offer.\n\t"
<< "isBeamSide: " << (*isBeamSide ? "false" : "true") << "\n\t"
<< "swapCoin: " << std::to_string(*swapCoin) << "\n\t"
<< "amount: " << *amount << "\n\t"
<< "swapAmount: " << *swapAmount << "\n\t"
<< "responseTime: " << *responseTime << "\n\t"
<< "minimalHeight: " << *minimalHeight;
beam::wallet::SwapOfferToken token(offer);
m_messageEndpoint.SendAndSign(toByteBuffer(token), getChannel(*swapCoin), offer.m_publisherId, m_protocolVersion);
}
void SwapOffersBoard::sendUpdateToNetwork(const TxID& offerID, const WalletID& publisherID, AtomicSwapCoin coin, SwapOfferStatus newStatus) const
{
LOG_INFO() << offerID << " Update offer status to " << std::to_string(newStatus);
beam::wallet::SwapOfferToken token(SwapOffer(offerID, newStatus, publisherID, coin));
m_messageEndpoint.SendAndSign(toByteBuffer(token), getChannel(coin), publisherID, m_protocolVersion);
}
void SwapOffersBoard::Subscribe(ISwapOffersObserver* observer)
{
assert(std::find(m_subscribers.begin(), m_subscribers.end(), observer) == m_subscribers.end());
m_subscribers.push_back(observer);
}
void SwapOffersBoard::Unsubscribe(ISwapOffersObserver* observer)
{
auto it = std::find(m_subscribers.begin(), m_subscribers.end(), observer);
assert(it != m_subscribers.end());
m_subscribers.erase(it);
}
void SwapOffersBoard::notifySubscribers(ChangeAction action, const std::vector<SwapOffer>& offers) const
{
for (auto sub : m_subscribers)
{
sub->onSwapOffersChanged(action, std::vector<SwapOffer>{offers});
}
}
} // namespace beam::wallet
| 37.526316 | 149 | 0.579856 | DavidBurkett |
3365dfa70b4ebb775aa8effd904b37fe9c221358 | 3,005 | hpp | C++ | libHCore/inc/time.hpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 15 | 2021-11-22T07:31:22.000Z | 2022-02-22T22:53:51.000Z | libHCore/inc/time.hpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 1 | 2021-11-26T19:27:40.000Z | 2021-11-26T19:27:40.000Z | libHCore/inc/time.hpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 5 | 2021-11-20T18:21:24.000Z | 2021-12-26T12:32:47.000Z |
#ifndef TIME_HPP
#define TIME_HPP
#include <chrono>
using namespace std::chrono;
using timeStamp = time_point<steady_clock,microseconds>;
using timeStampSeconds = time_point<steady_clock,seconds>;
extern timeStamp programStart;
timeStamp getCurrentTimeMicro();
timeStamp getTimeInFuture(uint64_t usec);
int64_t timeSince(timeStamp t0);
int64_t timeTo(timeStamp t0);
int64_t getTimeDifference(timeStamp t0, timeStamp t1);
int64_t timeSinceStart(timeStamp t0);
int64_t unixTime(timeStamp t0);
#endif
/*
#ifndef TIME_HPP
#define TIME_HPP
#include <chrono>
#include <time.h>
using namespace std::chrono;
static inline int fastfloor(float fp) {
int i = static_cast<int>(fp);
return (fp < i) ? (i - 1) : (i);
}
nanoseconds timespecToDuration(timespec ts);
time_point<system_clock, nanoseconds>timespecToTimePoint(timespec ts);
struct timeStamp{
timespec time;
timeStamp operator-(timeStamp &t1){
if(t1.time.tv_nsec > time.tv_nsec){
time.tv_sec--;
time.tv_nsec = 999999999 + time.tv_nsec - t1.time.tv_nsec;
}
else{
time.tv_nsec -= t1.time.tv_nsec;
}
time.tv_sec -= t1.time.tv_sec;
return *this;
}
timeStamp operator+(timeStamp &t1){
if(t1.time.tv_nsec + time.tv_nsec > 999999999){
}
else{
time.tv_sec += t1.time.tv_sec;
time.tv_nsec += t1.time.tv_nsec;
}
return *this;
}
timeStamp operator-(uint64_t usec){
long nsec = usec * 1000;
int secx = fastfloor(usec / 1000000);
time.tv_sec -= secx;
nsec -= secx * 1000000000;
if(nsec > time.tv_nsec){
time.tv_sec--;
time.tv_nsec = 999999999 + time.tv_nsec - nsec;
}
else{
time.tv_nsec -= nsec;
}
return *this;
}
timeStamp operator+(uint64_t usec){
long nsec = usec * 1000;
int secx = fastfloor(usec / 1000000);
time.tv_sec -= secx;
nsec -= secx * 1000000000;
if(nsec + time.tv_nsec > 999999999){
time.tv_sec++;
time.tv_nsec = (nsec + time.tv_nsec) - 999999999;
}
else{
time.tv_nsec += nsec;
}
return *this;
}
friend bool operator> (const timeStamp t1, const timeStamp t2){
if(t1.time.tv_sec > t2.time.tv_sec)
return true;
else
return false;
if(t1.time.tv_nsec > t2.time.tv_nsec)
return true;
else
return false;
}
int64_t micros(){
return time.tv_sec * 1000000 + time.tv_nsec / 1000;
}
};
extern timeStamp programStart;
timeStamp getCurrentTimeMicro();
timeStamp getTimeInFuture(uint64_t usec);
int64_t timeSince(timeStamp t0);
int64_t timeTo(timeStamp t0);
int64_t getTimeDifference(timeStamp t0, timeStamp t1);
int64_t timeSinceStart(timeStamp t0);
int64_t unixTime(timeStamp t0);
#endif
*/ | 22.095588 | 70 | 0.607654 | adeliktas |
3367bee0403b76726145b57b717270d602017c5b | 15,126 | cc | C++ | chromeos/services/secure_channel/ble_advertiser_impl.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/services/secure_channel/ble_advertiser_impl.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/services/secure_channel/ble_advertiser_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/secure_channel/ble_advertiser_impl.h"
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/timer/timer.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/secure_channel/bluetooth_helper.h"
#include "chromeos/services/secure_channel/error_tolerant_ble_advertisement_impl.h"
#include "chromeos/services/secure_channel/shared_resource_scheduler.h"
#include "chromeos/services/secure_channel/timer_factory.h"
namespace chromeos {
namespace secure_channel {
BleAdvertiserImpl::ActiveAdvertisementRequest::ActiveAdvertisementRequest(
DeviceIdPair device_id_pair,
ConnectionPriority connection_priority,
std::unique_ptr<base::OneShotTimer> timer)
: device_id_pair(device_id_pair),
connection_priority(connection_priority),
timer(std::move(timer)) {}
BleAdvertiserImpl::ActiveAdvertisementRequest::~ActiveAdvertisementRequest() =
default;
// static
BleAdvertiserImpl::Factory* BleAdvertiserImpl::Factory::test_factory_ = nullptr;
// static
std::unique_ptr<BleAdvertiser> BleAdvertiserImpl::Factory::Create(
Delegate* delegate,
BluetoothHelper* bluetooth_helper,
BleSynchronizerBase* ble_synchronizer_base,
TimerFactory* timer_factory,
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner) {
if (test_factory_) {
return test_factory_->CreateInstance(delegate, bluetooth_helper,
ble_synchronizer_base, timer_factory,
sequenced_task_runner);
}
return base::WrapUnique(
new BleAdvertiserImpl(delegate, bluetooth_helper, ble_synchronizer_base,
timer_factory, sequenced_task_runner));
}
// static
void BleAdvertiserImpl::Factory::SetFactoryForTesting(Factory* test_factory) {
test_factory_ = test_factory;
}
BleAdvertiserImpl::Factory::~Factory() = default;
// static
const int64_t BleAdvertiserImpl::kNumSecondsPerAdvertisementTimeslot = 10;
BleAdvertiserImpl::BleAdvertiserImpl(
Delegate* delegate,
BluetoothHelper* bluetooth_helper,
BleSynchronizerBase* ble_synchronizer_base,
TimerFactory* timer_factory,
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner)
: BleAdvertiser(delegate),
bluetooth_helper_(bluetooth_helper),
ble_synchronizer_base_(ble_synchronizer_base),
timer_factory_(timer_factory),
sequenced_task_runner_(sequenced_task_runner),
shared_resource_scheduler_(std::make_unique<SharedResourceScheduler>()) {}
BleAdvertiserImpl::~BleAdvertiserImpl() = default;
void BleAdvertiserImpl::AddAdvertisementRequest(
const DeviceIdPair& request,
ConnectionPriority connection_priority) {
requests_already_removed_due_to_failed_advertisement_.erase(request);
if (base::Contains(all_requests_, request)) {
PA_LOG(ERROR) << "BleAdvertiserImpl::AddAdvertisementRequest(): Tried to "
<< "add advertisement request which was already present. "
<< "Request: " << request
<< ", Priority: " << connection_priority;
NOTREACHED();
}
all_requests_.insert(request);
shared_resource_scheduler_->ScheduleRequest(request, connection_priority);
// If an existing request is active but has a lower priority than
// |connection_priority|, that request should be replaced by |request|.
bool was_replaced =
ReplaceLowPriorityAdvertisementIfPossible(connection_priority);
if (was_replaced)
return;
UpdateAdvertisementState();
}
void BleAdvertiserImpl::UpdateAdvertisementRequestPriority(
const DeviceIdPair& request,
ConnectionPriority connection_priority) {
if (base::Contains(requests_already_removed_due_to_failed_advertisement_,
request))
return;
if (!base::Contains(all_requests_, request)) {
PA_LOG(ERROR) << "BleAdvertiserImpl::UpdateAdvertisementRequestPriority(): "
<< "Tried to update request priority for a request, but that "
<< "request was not present. Request: " << request
<< ", Priority: " << connection_priority;
NOTREACHED();
}
base::Optional<size_t> index_for_active_request =
GetIndexForActiveRequest(request);
if (!index_for_active_request) {
// If the request is not currently active, update its priority in the
// scheduler.
shared_resource_scheduler_->UpdateRequestPriority(request,
connection_priority);
// If an existing request is active but has a lower priority than
// |connection_priority|, that request should be replaced by |request|.
ReplaceLowPriorityAdvertisementIfPossible(connection_priority);
return;
}
std::unique_ptr<ActiveAdvertisementRequest>& active_request =
active_advertisement_requests_[*index_for_active_request];
// If there is an active advertisement and no pending advertisements, update
// the active advertisement priority and return.
if (shared_resource_scheduler_->empty()) {
active_request->connection_priority = connection_priority;
return;
}
// If there is an active advertisement and the new priority of the request
// is still at least as high as the highest priority of all pending
// requests, update the active advertisement priority and return.
if (connection_priority >=
*shared_resource_scheduler_->GetHighestPriorityOfScheduledRequests()) {
active_request->connection_priority = connection_priority;
return;
}
// The active advertisement's priority has been reduced, and it is now lower
// than the priority of at least one pending request. Thus, stop the existing
// advertisement and reschedule the request for later.
StopAdvertisementRequestAndUpdateActiveRequests(
*index_for_active_request,
true /* replaced_by_higher_priority_advertisement */,
false /* was_removed */);
}
void BleAdvertiserImpl::RemoveAdvertisementRequest(
const DeviceIdPair& request) {
// If the request has already been deleted, then this was invoked by a failure
// callback following a failure to generate an advertisement.
auto it = requests_already_removed_due_to_failed_advertisement_.find(request);
if (it != requests_already_removed_due_to_failed_advertisement_.end()) {
requests_already_removed_due_to_failed_advertisement_.erase(it);
return;
}
if (!base::Contains(all_requests_, request)) {
PA_LOG(ERROR) << "BleAdvertiserImpl::RemoveAdvertisementRequest(): Tried "
<< "to remove an advertisement request, but that request was "
<< "not present. Request: " << request;
NOTREACHED();
}
all_requests_.erase(request);
base::Optional<size_t> index_for_active_request =
GetIndexForActiveRequest(request);
// If the request is not currently active, remove it from the scheduler and
// return.
if (!index_for_active_request) {
shared_resource_scheduler_->RemoveScheduledRequest(request);
return;
}
// The active advertisement should be stopped and not rescheduled.
StopAdvertisementRequestAndUpdateActiveRequests(
*index_for_active_request,
false /* replaced_by_higher_priority_advertisement */,
true /* was_removed */);
}
bool BleAdvertiserImpl::ReplaceLowPriorityAdvertisementIfPossible(
ConnectionPriority connection_priority) {
base::Optional<size_t> index_with_lower_priority =
GetIndexWithLowerPriority(connection_priority);
if (!index_with_lower_priority)
return false;
StopAdvertisementRequestAndUpdateActiveRequests(
*index_with_lower_priority,
true /* replaced_by_higher_priority_advertisement */,
false /* was_removed */);
return true;
}
base::Optional<size_t> BleAdvertiserImpl::GetIndexWithLowerPriority(
ConnectionPriority connection_priority) {
ConnectionPriority lowest_priority = ConnectionPriority::kHigh;
base::Optional<size_t> index_with_lowest_priority;
// Loop through |active_advertisement_requests_|, searching for the entry with
// the lowest priority.
for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) {
if (!active_advertisement_requests_[i])
continue;
if (active_advertisement_requests_[i]->connection_priority <
lowest_priority) {
lowest_priority = active_advertisement_requests_[i]->connection_priority;
index_with_lowest_priority = i;
}
}
// If |index_with_lowest_priority| was never set, all active advertisement
// requests have high priority, so they should not be replaced with the new
// connection attempt.
if (!index_with_lowest_priority)
return base::nullopt;
// If the lowest priority in |active_advertisement_requests_| is at least as
// high as |connection_priority|, this slot shouldn't be replaced with the
// new connection attempt.
if (lowest_priority >= connection_priority)
return base::nullopt;
return *index_with_lowest_priority;
}
void BleAdvertiserImpl::UpdateAdvertisementState() {
for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) {
// If there are any empty slots in |active_advertisement_requests_| and
// |shared_resource_scheduler_| contains pending requests, remove the
// pending request and make it active.
if (!active_advertisement_requests_[i] &&
!shared_resource_scheduler_->empty()) {
AddActiveAdvertisementRequest(i);
}
// If there are any empty slots in |active_advertisements_| and
// |active_advertisement_requests_| contains a request for an advertisement,
// generate a new active advertisement.
if (active_advertisement_requests_[i] && !active_advertisements_[i])
AttemptToAddActiveAdvertisement(i);
}
}
void BleAdvertiserImpl::AddActiveAdvertisementRequest(size_t index_to_add) {
// Retrieve the next request from the scheduler.
std::pair<DeviceIdPair, ConnectionPriority> request_with_priority =
*shared_resource_scheduler_->GetNextScheduledRequest();
// Create a timer, and have it go off in kNumSecondsPerAdvertisementTimeslot
// seconds.
std::unique_ptr<base::OneShotTimer> timer =
timer_factory_->CreateOneShotTimer();
timer->Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kNumSecondsPerAdvertisementTimeslot),
base::BindOnce(
&BleAdvertiserImpl::StopAdvertisementRequestAndUpdateActiveRequests,
base::Unretained(this), index_to_add,
false /* replaced_by_higher_priority_advertisement */,
false /* was_removed */));
active_advertisement_requests_[index_to_add] =
std::make_unique<ActiveAdvertisementRequest>(request_with_priority.first,
request_with_priority.second,
std::move(timer));
}
void BleAdvertiserImpl::AttemptToAddActiveAdvertisement(size_t index_to_add) {
const DeviceIdPair pair =
active_advertisement_requests_[index_to_add]->device_id_pair;
std::unique_ptr<DataWithTimestamp> service_data =
bluetooth_helper_->GenerateForegroundAdvertisement(pair);
// If an advertisement could not be created, the request is immediately
// removed. It's also tracked to prevent future operations from referencing
// the removed request.
if (!service_data) {
RemoveAdvertisementRequest(pair);
requests_already_removed_due_to_failed_advertisement_.insert(pair);
// Schedules AttemptToNotifyFailureToGenerateAdvertisement() to run
// after the tasks in the current sequence. This is done to avoid invoking
// an advertisement generation failure callback on the same call stack that
// added the advertisement request in the first place.
sequenced_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&BleAdvertiserImpl::AttemptToNotifyFailureToGenerateAdvertisement,
weak_factory_.GetWeakPtr(), pair));
return;
}
active_advertisements_[index_to_add] =
ErrorTolerantBleAdvertisementImpl::Factory::Create(
pair, std::move(service_data), ble_synchronizer_base_);
}
base::Optional<size_t> BleAdvertiserImpl::GetIndexForActiveRequest(
const DeviceIdPair& request) {
for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) {
auto& active_request = active_advertisement_requests_[i];
if (active_request && active_request->device_id_pair == request)
return i;
}
return base::nullopt;
}
void BleAdvertiserImpl::StopAdvertisementRequestAndUpdateActiveRequests(
size_t index,
bool replaced_by_higher_priority_advertisement,
bool was_removed) {
// Stop the actual advertisement at this index, if there is one.
StopActiveAdvertisement(index);
// Make a copy of the request to stop from |active_advertisement_requests_|,
// then reset the original version which resided in the array.
std::unique_ptr<ActiveAdvertisementRequest> request_to_stop =
std::move(active_advertisement_requests_[index]);
// If the request was not removed by a client, this request is being stopped
// either due to a timeout or due to a higher-priority request taking its
// spot. In these two cases, the request should be rescheduled, and the
// delegate should be notified that the timeslot ended.
if (!was_removed) {
shared_resource_scheduler_->ScheduleRequest(
request_to_stop->device_id_pair, request_to_stop->connection_priority);
NotifyAdvertisingSlotEnded(request_to_stop->device_id_pair,
replaced_by_higher_priority_advertisement);
}
UpdateAdvertisementState();
}
void BleAdvertiserImpl::StopActiveAdvertisement(size_t index) {
auto& active_advertisement = active_advertisements_[index];
if (!active_advertisement)
return;
// If |active_advertisement| is already in the process of stopping, there is
// nothing to do.
if (active_advertisement->HasBeenStopped())
return;
active_advertisement->Stop(
base::BindOnce(&BleAdvertiserImpl::OnActiveAdvertisementStopped,
base::Unretained(this), index));
}
void BleAdvertiserImpl::OnActiveAdvertisementStopped(size_t index) {
active_advertisements_[index].reset();
UpdateAdvertisementState();
}
void BleAdvertiserImpl::AttemptToNotifyFailureToGenerateAdvertisement(
const DeviceIdPair& device_id_pair) {
// If the request is not found, then that request has either been removed
// again or re-scheduled after it failed to generate an advertisement, but
// before this task could execute.
if (!base::Contains(requests_already_removed_due_to_failed_advertisement_,
device_id_pair)) {
return;
}
NotifyFailureToGenerateAdvertisement(device_id_pair);
}
} // namespace secure_channel
} // namespace chromeos
| 38.48855 | 83 | 0.741108 | Ron423c |
336a74ffe49d50fe6f417490dd822e9a5b42d1b7 | 1,420 | cpp | C++ | aws-cpp-sdk-ssm/source/model/LabelParameterVersionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ssm/source/model/LabelParameterVersionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-ssm/source/model/LabelParameterVersionResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ssm/model/LabelParameterVersionResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SSM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
LabelParameterVersionResult::LabelParameterVersionResult() :
m_parameterVersion(0)
{
}
LabelParameterVersionResult::LabelParameterVersionResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_parameterVersion(0)
{
*this = result;
}
LabelParameterVersionResult& LabelParameterVersionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("InvalidLabels"))
{
Array<JsonView> invalidLabelsJsonList = jsonValue.GetArray("InvalidLabels");
for(unsigned invalidLabelsIndex = 0; invalidLabelsIndex < invalidLabelsJsonList.GetLength(); ++invalidLabelsIndex)
{
m_invalidLabels.push_back(invalidLabelsJsonList[invalidLabelsIndex].AsString());
}
}
if(jsonValue.ValueExists("ParameterVersion"))
{
m_parameterVersion = jsonValue.GetInt64("ParameterVersion");
}
return *this;
}
| 27.307692 | 122 | 0.764085 | Neusoft-Technology-Solutions |
336b38c40225cee0bbdf06e838432a167b048ea0 | 7,082 | cc | C++ | src/unix/ibus/key_event_handler.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 1 | 2021-02-24T07:03:26.000Z | 2021-02-24T07:03:26.000Z | src/unix/ibus/key_event_handler.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 108 | 2018-05-29T17:33:53.000Z | 2019-07-22T00:01:54.000Z | src/unix/ibus/key_event_handler.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 1 | 2021-12-29T08:15:14.000Z | 2021-12-29T08:15:14.000Z | // Copyright 2010-2018, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google 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.
#include "unix/ibus/key_event_handler.h"
#include "base/logging.h"
#include "base/port.h"
#include "base/singleton.h"
namespace mozc {
namespace ibus {
namespace {
bool IsModifierToBeSentOnKeyUp(const commands::KeyEvent &key_event) {
if (key_event.modifier_keys_size() == 0) {
return false;
}
if (key_event.modifier_keys_size() == 1 &&
key_event.modifier_keys(0) == commands::KeyEvent::CAPS) {
return false;
}
return true;
}
} // namespace
KeyEventHandler::KeyEventHandler() : key_translator_(new KeyTranslator) {
Clear();
}
bool KeyEventHandler::GetKeyEvent(
guint keyval, guint keycode, guint modifiers,
config::Config::PreeditMethod preedit_method,
bool layout_is_jp, commands::KeyEvent *key) {
DCHECK(key);
key->Clear();
if (!key_translator_->Translate(
keyval, keycode, modifiers, preedit_method, layout_is_jp, key)) {
LOG(ERROR) << "Translate failed";
return false;
}
const bool is_key_up = ((modifiers & IBUS_RELEASE_MASK) != 0);
return ProcessModifiers(is_key_up, keyval, key);
}
void KeyEventHandler::Clear() {
is_non_modifier_key_pressed_ = false;
currently_pressed_modifiers_.clear();
modifiers_to_be_sent_.clear();
}
bool KeyEventHandler::ProcessModifiers(bool is_key_up, guint keyval,
commands::KeyEvent *key_event) {
// Manage modifier key event.
// Modifier key event is sent on key up if non-modifier key has not been
// pressed since key down of modifier keys and no modifier keys are pressed
// anymore.
// Following examples are expected behaviors.
//
// E.g.) Shift key is special. If Shift + printable key is pressed, key event
// does NOT have shift modifiers. It is handled by KeyTranslator class.
// <Event from ibus> <Event to server>
// Shift down | None
// "a" down | A
// "a" up | None
// Shift up | None
//
// E.g.) Usual key is sent on key down. Modifier keys are not sent if usual
// key is sent.
// <Event from ibus> <Event to server>
// Ctrl down | None
// "a" down | Ctrl+a
// "a" up | None
// Ctrl up | None
//
// E.g.) Modifier key is sent on key up.
// <Event from ibus> <Event to server>
// Shift down | None
// Shift up | Shift
//
// E.g.) Multiple modifier keys are sent on the last key up.
// <Event from ibus> <Event to server>
// Shift down | None
// Control down | None
// Shift up | None
// Control up | Control+Shift
//
// Essentialy we cannot handle modifier key evnet perfectly because
// - We cannot get current keyboard status with ibus. If some modifiers
// are pressed or released without focusing the target window, we
// cannot handle it.
// E.g.)
// <Event from ibus> <Event to server>
// Ctrl down | None
// (focuses out, Ctrl up, focuses in)
// Shift down | None
// Shift up | None (But we should send Shift key)
// To avoid a inconsistent state as much as possible, we clear states
// when key event without modifier keys is sent.
const bool is_modifier_only =
!(key_event->has_key_code() || key_event->has_special_key());
// We may get only up/down key event when a user moves a focus.
// This code handles such situation as much as possible.
// This code has a bug. If we send Shift + 'a', KeyTranslator removes a shift
// modifier and converts 'a' to 'A'. This codes does NOT consider these
// situation since we don't have enough data to handle it.
// TODO(hsumita): Moves the logic about a handling of Shift or Caps keys from
// KeyTranslator to MozcEngine.
if (key_event->modifier_keys_size() == 0) {
Clear();
}
if (!currently_pressed_modifiers_.empty() && !is_modifier_only) {
is_non_modifier_key_pressed_ = true;
}
if (is_non_modifier_key_pressed_) {
modifiers_to_be_sent_.clear();
}
if (is_key_up) {
currently_pressed_modifiers_.erase(keyval);
if (!is_modifier_only) {
return false;
}
if (!currently_pressed_modifiers_.empty() ||
modifiers_to_be_sent_.empty()) {
is_non_modifier_key_pressed_ = false;
return false;
}
if (is_non_modifier_key_pressed_) {
return false;
}
DCHECK(!is_non_modifier_key_pressed_);
// Modifier key event fires
key_event->mutable_modifier_keys()->Clear();
for (std::set<commands::KeyEvent::ModifierKey>::const_iterator it =
modifiers_to_be_sent_.begin();
it != modifiers_to_be_sent_.end();
++it) {
key_event->add_modifier_keys(*it);
}
modifiers_to_be_sent_.clear();
} else if (is_modifier_only) {
// TODO(hsumita): Supports a key sequence below.
// - Ctrl down
// - a down
// - Alt down
// We should add Alt key to |currently_pressed_modifiers|, but current
// implementation does NOT do it.
if (currently_pressed_modifiers_.empty() ||
!modifiers_to_be_sent_.empty()) {
for (size_t i = 0; i < key_event->modifier_keys_size(); ++i) {
modifiers_to_be_sent_.insert(key_event->modifier_keys(i));
}
}
currently_pressed_modifiers_.insert(keyval);
return false;
}
// Clear modifier data just in case if |key| has no modifier keys.
if (!IsModifierToBeSentOnKeyUp(*key_event)) {
Clear();
}
return true;
}
} // namespace ibus
} // namespace mozc
| 35.059406 | 79 | 0.670291 | sousuke0422 |
336b462ccee7e5caea92825ff3340f8f06560b62 | 1,868 | hpp | C++ | include/rba/RBASoundContent.hpp | NaohiroNISHIGUCHI/RBA | ac86e4ffa643b8050b25161c951bb43f4e36235a | [
"Apache-2.0"
] | 2 | 2020-07-17T11:13:48.000Z | 2020-07-30T09:37:08.000Z | include/rba/RBASoundContent.hpp | NaohiroNISHIGUCHI/RBA | ac86e4ffa643b8050b25161c951bb43f4e36235a | [
"Apache-2.0"
] | null | null | null | include/rba/RBASoundContent.hpp | NaohiroNISHIGUCHI/RBA | ac86e4ffa643b8050b25161c951bb43f4e36235a | [
"Apache-2.0"
] | 3 | 2020-06-25T07:19:19.000Z | 2020-06-26T13:06:13.000Z | // Copyright (c) 2018 DENSO CORPORATION. All rights reserved.
/**
* Sound content class
*/
#ifndef RBASOUNDCONTENT_HPP
#define RBASOUNDCONTENT_HPP
#ifdef _MSC_VER
#ifdef _WINDLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT
#endif
#include <list>
#include <string>
#include "RBAContentLoserType.hpp"
namespace rba
{
class RBASoundContentState;
class RBAZone;
/**
* @class RBASoundContent
* Define the object of sound content.<br>
* Sound content has plural status.
* When sound contents connected to a zone, active status is output.
* Object has zone definitions, that can output itself.
* Each object can define plural zone which can output sound contents.
*/
class DLL_EXPORT RBASoundContent
{
protected:
RBASoundContent()=default;
RBASoundContent(const RBASoundContent&)=delete;
RBASoundContent(RBASoundContent&&)=delete;
RBASoundContent& operator=(const RBASoundContent&)=delete;
RBASoundContent& operator=(RBASoundContent&&)=delete;
~RBASoundContent()=default;
public:
/**
* @brief Returns the name of the sound content.
* @return Sound content name
*/
virtual std::string getName() const=0;
/**
* @brief Returns the state of the sound content.
* @return List of the sound content state
*/
virtual const std::list<const RBASoundContentState*>& getContentStates() const=0;
/**
* @brief Returns the zone of the sound content.
* @return List of the zone
*/
virtual const std::list<const RBAZone*>& getZones() const=0;
/**
* @brief Returns the loser type.
* @return Loser type
*/
virtual RBAContentLoserType getLoserType() const=0;
public:
/**
* @brief Defines the default loser type.
*/
const static RBAContentLoserType LOSER_TYPE_EDEFAULT =
RBAContentLoserType::NEVER_GIVEUP;
};
}
#endif
| 22.238095 | 83 | 0.728587 | NaohiroNISHIGUCHI |
336ef2fb6bfaec758b0a786ded531b6e095dcf91 | 3,858 | cc | C++ | obj/pillar.cc | vinijabes/simutrans | cb90d7e29e8f7910936d98733fe9fe5f24893535 | [
"Artistic-1.0"
] | null | null | null | obj/pillar.cc | vinijabes/simutrans | cb90d7e29e8f7910936d98733fe9fe5f24893535 | [
"Artistic-1.0"
] | null | null | null | obj/pillar.cc | vinijabes/simutrans | cb90d7e29e8f7910936d98733fe9fe5f24893535 | [
"Artistic-1.0"
] | null | null | null | /*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include <string.h>
#include "../simworld.h"
#include "../simobj.h"
#include "../simmem.h"
#include "../display/simimg.h"
#include "../bauer/brueckenbauer.h"
#include "../descriptor/bridge_desc.h"
#include "../boden/grund.h"
#include "../dataobj/loadsave.h"
#include "../obj/pillar.h"
#include "../obj/bruecke.h"
#include "../dataobj/environment.h"
pillar_t::pillar_t(loadsave_t *file) : obj_t()
{
desc = NULL;
asymmetric = false;
rdwr(file);
}
pillar_t::pillar_t(koord3d pos, player_t *player, const bridge_desc_t *desc, bridge_desc_t::img_t img, int hoehe) : obj_t(pos)
{
this->desc = desc;
this->dir = (uint8)img;
set_yoff(-hoehe);
set_owner( player );
asymmetric = desc->has_pillar_asymmetric();
calc_image();
}
void pillar_t::calc_image()
{
bool hide = false;
int height = get_yoff();
if( grund_t *gr = welt->lookup(get_pos()) ) {
slope_t::type slope = gr->get_grund_hang();
if( desc->has_pillar_asymmetric() ) {
if( dir == bridge_desc_t::NS_Pillar ) {
height += ( (corner_sw(slope) + corner_se(slope) ) * TILE_HEIGHT_STEP )/2;
}
else {
height += ( ( corner_se(slope) + corner_ne(slope) ) * TILE_HEIGHT_STEP ) / 2;
}
if( height > 0 ) {
hide = true;
}
}
else {
// on slope use mean height ...
height += ( ( corner_se(slope) + corner_ne(slope) + corner_sw(slope) + corner_se(slope) ) * TILE_HEIGHT_STEP ) / 4;
}
}
image = hide ? IMG_EMPTY : desc->get_background( (bridge_desc_t::img_t)dir, get_pos().z-height/TILE_HEIGHT_STEP >= welt->get_snowline() || welt->get_climate( get_pos().get_2d() ) == arctic_climate );
}
/**
* @return Einen Beschreibungsstring fuer das Objekt, der z.B. in einem
* Beobachtungsfenster angezeigt wird.
*/
void pillar_t::show_info()
{
planquadrat_t *plan=welt->access(get_pos().get_2d());
for(unsigned i=0; i<plan->get_boden_count(); i++ ) {
grund_t *bd=plan->get_boden_bei(i);
if(bd->ist_bruecke()) {
bruecke_t* br = bd->find<bruecke_t>();
if(br && br->get_desc()==desc) {
br->show_info();
}
}
}
}
void pillar_t::rdwr(loadsave_t *file)
{
xml_tag_t p( file, "pillar_t" );
obj_t::rdwr(file);
if(file->is_saving()) {
const char *s = desc->get_name();
file->rdwr_str(s);
file->rdwr_byte(dir);
}
else {
char s[256];
file->rdwr_str(s, lengthof(s));
file->rdwr_byte(dir);
desc = bridge_builder_t::get_desc(s);
if(desc==0) {
if(strstr(s,"ail")) {
desc = bridge_builder_t::get_desc("ClassicRail");
dbg->warning("pillar_t::rdwr()","Unknown bridge %s replaced by ClassicRail",s);
}
else if(strstr(s,"oad")) {
desc = bridge_builder_t::get_desc("ClassicRoad");
dbg->warning("pillar_t::rdwr()","Unknown bridge %s replaced by ClassicRoad",s);
}
}
asymmetric = desc && desc->has_pillar_asymmetric();
if( file->is_version_less(112, 7) && env_t::pak_height_conversion_factor==2 ) {
switch(dir) {
case bridge_desc_t::OW_Pillar: dir = bridge_desc_t::OW_Pillar2; break;
case bridge_desc_t::NS_Pillar: dir = bridge_desc_t::NS_Pillar2; break;
}
}
}
}
void pillar_t::rotate90()
{
obj_t::rotate90();
// may need to hide/show asymmetric pillars
// this is done now in calc_image, which is called after karte_t::rotate anyway
// we cannot decide this here, since welt->lookup(get_pos())->get_grund_hang() cannot be called
// since we are in the middle of the rotation process
// the rotated image parameter is just one in front/back
switch(dir) {
case bridge_desc_t::NS_Pillar: dir=bridge_desc_t::OW_Pillar ; break;
case bridge_desc_t::OW_Pillar: dir=bridge_desc_t::NS_Pillar ; break;
case bridge_desc_t::NS_Pillar2: dir=bridge_desc_t::OW_Pillar2 ; break;
case bridge_desc_t::OW_Pillar2: dir=bridge_desc_t::NS_Pillar2 ; break;
}
}
| 26.606897 | 202 | 0.666407 | vinijabes |
336f1b15eae0ec9e0b76c2b529b9a3c57d7e2b3e | 2,988 | hpp | C++ | include/veriblock/signutil.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | include/veriblock/signutil.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | include/veriblock/signutil.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Xenios SEZC
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __SIGNUTIL__HPP__
#define __SIGNUTIL__HPP__
#include <stdexcept>
#include <vector>
#include "slice.hpp"
#include "blob.hpp"
namespace altintegration {
static const size_t PRIVATE_KEY_SIZE = 32;
static const size_t PUBLIC_KEY_COMPRESSED_SIZE = 33;
static const size_t PUBLIC_KEY_UNCOMPRESSED_SIZE = 65;
using PrivateKey = Blob<PRIVATE_KEY_SIZE>;
using PublicKey = Blob<PUBLIC_KEY_UNCOMPRESSED_SIZE>;
using Signature = std::vector<uint8_t>;
// VBK encoded keys are plain byte arrays
using PrivateKeyVbk = std::vector<uint8_t>;
using PublicKeyVbk = std::vector<uint8_t>;
/**
* Convert VBK encoded private key to the PrivateKey type.
* @param key VBK encoded private key
* @throws std::out_of_range if key is malformed
* @return PrivateKey for inner use
*/
PrivateKey privateKeyFromVbk(PrivateKeyVbk key);
/**
* Convert VBK encoded public key to the PublicKey type.
* @param key VBK encoded public key
* @throws std::out_of_range if key is malformed
* @return PublicKey for inner use
*/
PublicKey publicKeyFromVbk(PublicKeyVbk key);
/**
* Convert PublicKey type to VBK encoding.
* @param key PublicKey format public key
* @throws std::out_of_range if key is malformed
* @return byte array with VBK encoded public key
*/
PublicKeyVbk publicKeyToVbk(PublicKey key);
/**
* Derive public key from the private key.
* @param privateKey use this private key to generate public key
* @throws std::out_of_range if privateKey is malformed
* @return PublicKey type generated public key
*/
PublicKey derivePublicKey(PrivateKey privateKey);
/**
* Sign message for VBK usage.
* This function calculates SHA256 of the message and applies
* secp256k1 signature. Result is encoded in VBK format.
* @param message message to sign
* @param privateKey sign with this private key
* @throws std::out_of_range if privateKey is malformed
* @return byte array with VBK encoded signature
*/
Signature veriBlockSign(Slice<const uint8_t> message,
PrivateKey privateKey);
/**
* Verify message previously signed with veriBlockSign.
* This function calculates SHA256 of the message, decodes
* signature from VBK format and verifies signature
* using provided public key. Signature should be formed
* with secp256k1 algorithm. Public key should be derived
* from signer's private key.
* @param message message to verify with
* @param signature VBK encoded signature to verify
* @param publicKey verify signature with this public key
* @throws std::out_of_range if publicKey is malformed
* @return 1 if signature is valid, 0 - otherwise
*/
int veriBlockVerify(Slice<const uint8_t> message,
Signature signature,
PublicKey publicKey);
} // namespace altintegration
#endif //__SIGNUTIL__HPP__
| 32.478261 | 70 | 0.754351 | overcookedpanda |
3370fb7140a0863746381561b69e4f83ba5faa0b | 53,641 | cpp | C++ | legacy/btmux-mux20/mux/src/btech/mech.hitloc.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-07-09T17:37:42.000Z | 2020-07-09T17:37:42.000Z | legacy/btmux-mux20/mux/src/btech/mech.hitloc.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | legacy/btmux-mux20/mux/src/btech/mech.hitloc.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-11-07T00:02:47.000Z | 2020-11-07T00:02:47.000Z |
/*
* $Id: mech.hitloc.c,v 1.1.1.1 2005/01/11 21:18:17 kstevens Exp $
*
* Author: Markus Stenberg <fingon@iki.fi>
*
* Copyright (c) 1996 Markus Stenberg
* Copyright (c) 1998-2002 Thomas Wouters
* Copyright (c) 2000-2002 Cord Awtry
* All rights reserved
*
* Created: Fri Sep 20 19:54:48 1996 fingon
* Last modified: Tue Jun 16 18:23:58 1998 fingon
*
*/
#include <stdio.h>
#include <string.h>
#include "copyright.h"
#include "autoconf.h"
#include "config.h"
#include "db.h"
#include "stringutil.h"
#include "alloc.h"
#include "mech.h"
#include "mech.events.h"
#include "p.mech.utils.h"
#include "p.mech.combat.h"
#include "p.mech.damage.h"
#include "p.aero.bomb.h"
#include "p.mech.update.h"
#include "p.crit.h"
#include "p.glue.h"
#include "mech.notify.h"
#include "p.mech.notify.h"
extern void muxevent_remove_type_data(int, void *);
#define CHECK_ZERO_LOC(mech,a,b) ( GetSectInt(mech, a) > 0 ? a : b )
int FindPunchLocation(int hitGroup)
{
int roll = Number(1, 6);
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 1:
case 2:
return LTORSO;
case 3:
return CTORSO;
case 4:
case 5:
return LARM;
case 6:
return HEAD;
}
case BACK:
case FRONT:
switch (roll) {
case 1:
return LARM;
case 2:
return LTORSO;
case 3:
return CTORSO;
case 4:
return RTORSO;
case 5:
return RARM;
case 6:
return HEAD;
}
break;
case RIGHTSIDE:
switch (roll) {
case 1:
case 2:
return RTORSO;
case 3:
return CTORSO;
case 4:
case 5:
return RARM;
case 6:
return HEAD;
}
}
return CTORSO;
}
int FindKickLocation(int hitGroup)
{
int roll = Number(1, 6);
switch (hitGroup) {
case LEFTSIDE:
return LLEG;
case BACK:
case FRONT:
switch (roll) {
case 1:
case 2:
case 3:
return RLEG;
case 4:
case 5:
case 6:
return LLEG;
}
case RIGHTSIDE:
return RLEG;
}
return RLEG;
}
int get_bsuit_hitloc(MECH * mech)
{
int i;
int table[NUM_BSUIT_MEMBERS];
int last = 0;
for (i = 0; i < NUM_BSUIT_MEMBERS; i++)
if (GetSectInt(mech, i))
table[last++] = i;
if (!last)
return -1;
return table[Number(0, last - 1)];
}
int TransferTarget(MECH * mech, int hitloc)
{
switch (MechType(mech)) {
case CLASS_BSUIT:
return get_bsuit_hitloc(mech);
case CLASS_AERO:
switch (hitloc) {
case AERO_NOSE:
case AERO_LWING:
case AERO_RWING:
case AERO_ENGINE:
case AERO_COCKPIT:
return AERO_FUSEL;
}
break;
case CLASS_MECH:
case CLASS_MW:
switch (hitloc) {
case RARM:
case RLEG:
return RTORSO;
break;
case LARM:
case LLEG:
return LTORSO;
break;
case RTORSO:
case LTORSO:
return CTORSO;
break;
}
break;
}
return -1;
}
int FindSwarmHitLocation(int *iscritical, int *isrear)
{
*isrear = 0;
*iscritical = 1;
switch (Roll()) {
case 12:
case 2:
return HEAD;
case 3:
case 11:
*isrear = 1;
return CTORSO;
case 4:
*isrear = 1;
case 5:
return RTORSO;
case 10:
*isrear = 1;
case 9:
return LTORSO;
case 6:
return RARM;
case 8:
return LARM;
case 7:
return CTORSO;
}
return HEAD;
}
int crittable(MECH * mech, int loc, int tres)
{
int d;
if (MechMove(mech) == MOVE_NONE)
return 0;
if (!GetSectOArmor(mech, loc))
return 1;
if (MechType(mech) != CLASS_MECH && btechconf.btech_vcrit <= 1)
return 0;
d = (100 * GetSectArmor(mech, loc)) / GetSectOArmor(mech, loc);
if (d < tres)
return 1;
if (d == 100) {
if (Number(1, 71) == 23)
return 1;
return 0;
}
if (d < (100 - ((100 - tres) / 2)))
if (Number(1, 11) == 6)
return 1;
return 0;
}
int FindFasaHitLocation(MECH * mech, int hitGroup, int *iscritical,
int *isrear)
{
int roll, hitloc = 0;
int side;
*iscritical = 0;
roll = Roll();
if (MechStatus(mech) & COMBAT_SAFE)
return 0;
if (MechDugIn(mech) && GetSectOInt(mech, TURRET) &&
Number(1, 100) >= 42)
return TURRET;
rollstat.hitrolls[roll - 2]++;
rollstat.tothrolls++;
switch (MechType(mech)) {
case CLASS_BSUIT:
if ((hitloc = get_bsuit_hitloc(mech)) < 0)
return Number(0, NUM_BSUIT_MEMBERS - 1);
case CLASS_MW:
case CLASS_MECH:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
*iscritical = 1;
return LTORSO;
case 3:
return LLEG;
case 4:
case 5:
return LARM;
case 6:
return LLEG;
case 7:
return LTORSO;
case 8:
return CTORSO;
case 9:
return RTORSO;
case 10:
return RARM;
case 11:
return RLEG;
case 12:
return HEAD;
}
case RIGHTSIDE:
switch (roll) {
case 2:
*iscritical = 1;
return RTORSO;
case 3:
return RLEG;
case 4:
case 5:
return RARM;
case 6:
return RLEG;
case 7:
return RTORSO;
case 8:
return CTORSO;
case 9:
return LTORSO;
case 10:
return LARM;
case 11:
return LLEG;
case 12:
return HEAD;
}
case FRONT:
case BACK:
switch (roll) {
case 2:
*iscritical = 1;
return CTORSO;
case 3:
case 4:
return RARM;
case 5:
return RLEG;
case 6:
return RTORSO;
case 7:
return CTORSO;
case 8:
return LTORSO;
case 9:
return LLEG;
case 10:
case 11:
return LARM;
case 12:
return HEAD;
}
}
break;
case CLASS_VEH_GROUND:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
/* A Roll on Determining Critical Hits Table */
*iscritical = 1;
return LSIDE;
case 3:
if (btechconf.btech_tankfriendly) {
if (!Fallen(mech)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is seriously damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is seriously damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is seriously damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down a lot..");
break;
}
LowerMaxSpeed(mech, MP2);
}
return LSIDE;
}
/* Cripple tank */
if (!Fallen(mech)) {
mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is destroyed, imobilizing your vehicle!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your lift fan is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"You are halted in your tracks - literally.");
}
SetMaxSpeed(mech, 0.0);
MakeMechFall(mech);
}
return LSIDE;
case 4:
case 5:
/* MP -1 */
if (!Fallen(mech)) {
mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down..");
break;
}
LowerMaxSpeed(mech, MP1);
}
return LSIDE;
break;
case 6:
case 7:
case 8:
case 9:
/* MP -1 if hover */
return LSIDE;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : LSIDE;
case 11:
if (GetSectInt(mech, TURRET)) {
if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
MechTankCritStatus(mech) |= TURRET_LOCKED;
mech_notify(mech, MECHALL,
"Your turret takes a direct hit and immobilizes!");
}
return TURRET;
} else
return LSIDE;
case 12:
/* A Roll on Determining Critical Hits Table */
*iscritical = 1;
return LSIDE;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
*iscritical = 1;
return RSIDE;
case 3:
if (btechconf.btech_tankfriendly) {
if (!Fallen(mech)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is seriously damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is seriously damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is seriously damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down a lot..");
break;
}
LowerMaxSpeed(mech, MP2);
}
return RSIDE;
}
/* Cripple Tank */
if (!Fallen(mech)) {
mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is destroyed, imobilizing your vehicle!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your lift fan is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"You are halted in your tracks - literally.");
}
SetMaxSpeed(mech, 0.0);
MakeMechFall(mech);
}
return RSIDE;
case 4:
case 5:
/* MP -1 */
if (!Fallen(mech)) {
mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down..");
break;
}
LowerMaxSpeed(mech, MP1);
}
return RSIDE;
case 6:
case 7:
case 8:
return RSIDE;
case 9:
/* MP -1 if hover */
if (!Fallen(mech)) {
if (MechMove(mech) == MOVE_HOVER) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
mech_notify(mech, MECHALL,
"Your air skirt is damaged!!");
LowerMaxSpeed(mech, MP1);
}
}
return RSIDE;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : RSIDE;
case 11:
if (GetSectInt(mech, TURRET)) {
if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
MechTankCritStatus(mech) |= TURRET_LOCKED;
mech_notify(mech, MECHALL,
"Your turret takes a direct hit and immobilizes!");
}
return TURRET;
} else
return RSIDE;
case 12:
/* A Roll on Determining Critical Hits Table */
*iscritical = 1;
return RSIDE;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
/* A Roll on Determining Critical Hits Table */
*iscritical = 1;
return side;
case 3:
if (btechconf.btech_tankshield) {
if (btechconf.btech_tankfriendly) {
if (!Fallen(mech)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is seriously damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is seriously damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is seriously damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down a lot..");
break;
}
LowerMaxSpeed(mech, MP2);
}
return side;
}
/* Cripple tank */
if (!Fallen(mech)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is destroyed, imobilizing your vehicle!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your lift fan is destroyed, imobilizing your vehicle!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"You are halted in your tracks - literally.");
}
SetMaxSpeed(mech, 0.0);
MakeMechFall(mech);
}
}
return side;
case 4:
/* MP -1 */
if (btechconf.btech_tankshield) {
if (!Fallen(mech)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
switch (MechMove(mech)) {
case MOVE_TRACK:
mech_notify(mech, MECHALL,
"One of your tracks is damaged!!");
break;
case MOVE_WHEEL:
mech_notify(mech, MECHALL,
"One of your wheels is damaged!!");
break;
case MOVE_HOVER:
mech_notify(mech, MECHALL,
"Your air skirt is damaged!!");
break;
case MOVE_HULL:
case MOVE_SUB:
case MOVE_FOIL:
mech_notify(mech, MECHALL,
"Your speed slows down..");
break;
}
LowerMaxSpeed(mech, MP1);
}
}
return side;
case 5:
/* MP -1 if Hovercraft */
if (!Fallen(mech)) {
if (MechMove(mech) == MOVE_HOVER) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
mech_notify(mech, MECHALL,
"Your air skirt is damaged!!");
LowerMaxSpeed(mech, MP1);
}
}
return side;
case 6:
case 7:
case 8:
case 9:
return side;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : side;
case 11:
*iscritical = 1;
/* Lock turret into place */
if (GetSectInt(mech, TURRET)) {
if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) {
mech_notify(mech, MECHALL,
"%ch%cyCRITICAL HIT!!%c");
MechTankCritStatus(mech) |= TURRET_LOCKED;
mech_notify(mech, MECHALL,
"Your turret takes a direct hit and immobilizes!");
}
return TURRET;
} else
return side;
case 12:
/* A Roll on Determining Critical Hits Table */
if (crittable(mech, (GetSectInt(mech,
TURRET)) ? TURRET : side,
btechconf.btech_critlevel))
*iscritical = 1;
return (GetSectInt(mech, TURRET)) ? TURRET : side;
}
}
break;
case CLASS_AERO:
switch (hitGroup) {
case FRONT:
switch (roll) {
case 2:
case 12:
return AERO_COCKPIT;
case 3:
case 11:
if (crittable(mech, AERO_NOSE, 90))
LoseWeapon(mech, AERO_NOSE);
return AERO_NOSE;
case 4:
case 10:
if (roll == 10)
DestroyBomb(mech, AERO_FUSEL);
return AERO_FUSEL;
case 5:
return AERO_RWING;
case 9:
return AERO_LWING;
case 6:
case 7:
case 8:
return AERO_NOSE;
}
break;
case LEFTSIDE:
case RIGHTSIDE:
side = ((hitGroup == LEFTSIDE) ? AERO_LWING : AERO_RWING);
switch (roll) {
case 2:
return AERO_COCKPIT;
case 12:
if (crittable(mech, AERO_ENGINE, 99))
*iscritical = 1;
return AERO_ENGINE;
case 3:
case 11:
if (crittable(mech, side, 99))
LoseWeapon(mech, side);
return side;
case 4:
case 10:
if (crittable(mech, AERO_ENGINE, 90))
DestroyHeatSink(mech, AERO_ENGINE);
return AERO_ENGINE;
case 5:
DestroyBomb(mech, AERO_FUSEL);
return AERO_FUSEL;
case 9:
return AERO_NOSE;
case 6:
case 8:
return side;
case 7:
return AERO_FUSEL;
}
break;
case BACK:
switch (roll) {
case 2:
case 12:
if (crittable(mech, AERO_ENGINE, 90))
*iscritical = 1;
return AERO_ENGINE;
case 3:
case 11:
aero_ControlEffect(mech);
return AERO_FUSEL;
case 4:
case 7:
case 10:
if (crittable(mech, AERO_FUSEL, 90))
DestroyHeatSink(mech, AERO_FUSEL);
return AERO_FUSEL;
case 5:
return AERO_RWING;
case 9:
return AERO_LWING;
case 6:
case 8:
return AERO_ENGINE;
}
}
break;
case CLASS_DS:
case CLASS_SPHEROID_DS:
switch (hitGroup) {
case FRONT:
switch (roll) {
case 2:
case 12:
if (crittable(mech, DS_NOSE, 30))
ds_BridgeHit(mech);
return DS_NOSE;
case 3:
case 11:
if (crittable(mech, DS_NOSE, 50))
LoseWeapon(mech, DS_NOSE);
return DS_NOSE;
case 5:
return DS_RWING;
case 6:
case 7:
case 8:
return DS_NOSE;
case 9:
return DS_LWING;
case 4:
case 10:
return (Number(1, 2)) == 1 ? DS_LWING : DS_RWING;
}
case LEFTSIDE:
case RIGHTSIDE:
side = (hitGroup == LEFTSIDE) ? DS_LWING : DS_RWING;
if (Number(1, 2) == 2)
SpheroidToRear(mech, side);
switch (roll) {
case 2:
if (crittable(mech, DS_NOSE, 30))
ds_BridgeHit(mech);
return DS_NOSE;
case 3:
case 11:
if (crittable(mech, side, 60))
LoseWeapon(mech, side);
return side;
case 4:
case 5:
case 6:
case 7:
case 8:
case 10:
return side;
case 9:
return DS_NOSE;
case 12:
if (crittable(mech, side, 60))
*iscritical = 1;
return side;
}
case BACK:
switch (roll) {
case 2:
case 12:
if (crittable(mech, DS_AFT, 60))
*iscritical = 1;
return DS_AFT;
case 3:
case 11:
return DS_AFT;
case 4:
case 7:
case 10:
if (crittable(mech, DS_AFT, 60))
DestroyHeatSink(mech, DS_AFT);
return DS_AFT;
case 5:
hitloc = DS_RWING;
SpheroidToRear(mech, hitloc);
return hitloc;
case 6:
case 8:
return DS_AFT;
case 9:
hitloc = DS_LWING;
SpheroidToRear(mech, hitloc);
return hitloc;
}
}
break;
case CLASS_VTOL:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
*iscritical = 1;
break;
case 4:
case 5:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 6:
case 7:
case 8:
hitloc = LSIDE;
break;
case 9:
/* Destroy Main Weapon but do not destroy armor */
DestroyMainWeapon(mech);
hitloc = 0;
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
*iscritical = 1;
break;
case 4:
case 5:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 6:
case 7:
case 8:
hitloc = RSIDE;
break;
case 9:
/* Destroy Main Weapon but do not destroy armor */
DestroyMainWeapon(mech);
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
hitloc = ROTOR;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 4:
case 5:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 6:
case 7:
case 8:
case 9:
hitloc = side;
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
}
break;
case CLASS_VEH_NAVAL:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
hitloc = LSIDE;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
case 4:
case 5:
hitloc = LSIDE;
break;
case 9:
hitloc = LSIDE;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = LSIDE;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
} else
hitloc = LSIDE;
break;
case 12:
hitloc = LSIDE;
*iscritical = 1;
break;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
case 12:
hitloc = RSIDE;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
hitloc = RSIDE;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = RSIDE;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
} else
hitloc = RSIDE;
break;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
case 12:
hitloc = side;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
hitloc = side;
break;
case 4:
hitloc = side;
break;
case 5:
hitloc = side;
break;
case 6:
case 7:
case 8:
case 9:
hitloc = side;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = side;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
*iscritical = 1;
} else
hitloc = side;
break;
}
break;
}
break;
}
return (hitloc);
}
/* Do L3 FASA motive system crits */
void DoMotiveSystemHit(MECH * mech, int wRollMod)
{
int wRoll;
char strVhlTypeName[30];
wRoll = Roll() + wRollMod;
switch (MechMove(mech)) {
case MOVE_TRACK:
strcpy(strVhlTypeName, "tank");
break;
case MOVE_WHEEL:
strcpy(strVhlTypeName, "vehicle");
wRoll += 2;
break;
case MOVE_HOVER:
strcpy(strVhlTypeName, "hovercraft");
wRoll += 4;
break;
case MOVE_HULL:
strcpy(strVhlTypeName, "ship");
break;
case MOVE_FOIL:
strcpy(strVhlTypeName, "hydrofoil");
wRoll += 4;
break;
case MOVE_SUB:
strcpy(strVhlTypeName, "submarine");
break;
default:
strcpy(strVhlTypeName,
"weird unidentifiable toy (warn a wizard!)");
break;
}
if (wRoll < 8) /* no effect */
return;
mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c");
if (wRoll < 10) { /* minor effect */
MechPilotSkillBase(mech) += 1;
if (Fallen(mech))
mech_notify(mech, MECHALL,
"%cr%chYour destroyed motive system takes another hit!%cn");
else
mech_notify(mech, MECHALL,
tprintf
("%%cr%%chYour motive system takes a minor hit, making it harder to control your %s!%%cn",
strVhlTypeName));
if (MechSpeed(mech) != 0.0)
MechLOSBroadcast(mech, "wobbles slightly.");
} else if (wRoll < 12) { /* moderate effect */
MechPilotSkillBase(mech) += 2;
if (Fallen(mech))
mech_notify(mech, MECHALL,
"%cr%chYour destroyed motive system takes another hit!%cn");
else
mech_notify(mech, MECHALL,
tprintf
("%%cr%%chYour motive system takes a moderate hit, slowing you down and making it harder to control your %s!%%cn",
strVhlTypeName));
if (MechSpeed(mech) != 0.0)
MechLOSBroadcast(mech, "wobbles violently.");
LowerMaxSpeed(mech, MP1);
correct_speed(mech);
} else {
if (Fallen(mech))
mech_notify(mech, MECHALL,
"%cr%chYour destroyed motive system takes another hit!%cn");
else
mech_notify(mech, MECHALL,
tprintf
("%%cr%%chYour motive system is destroyed! Your %s can nolonger move!%%cn",
strVhlTypeName));
if (MechSpeed(mech) > 0)
MechLOSBroadcast(mech,
"shakes violently then begins to slow down.");
SetMaxSpeed(mech, 0.0);
MakeMechFall(mech);
correct_speed(mech);
}
}
int FindAdvFasaVehicleHitLocation(MECH * mech, int hitGroup,
int *iscritical, int *isrear)
{
int roll, hitloc = 0;
int side;
*iscritical = 0;
roll = Roll();
if (MechStatus(mech) & COMBAT_SAFE)
return 0;
if (MechDugIn(mech) && GetSectInt(mech, TURRET) &&
Number(1, 100) >= 42)
return TURRET;
rollstat.hitrolls[roll - 2]++;
rollstat.tothrolls++;
switch (MechType(mech)) {
case CLASS_VEH_GROUND:
switch (hitGroup) {
case LEFTSIDE:
case RIGHTSIDE:
side = (hitGroup == LEFTSIDE ? LSIDE : RSIDE);
switch (roll) {
case 2:
hitloc = side;
*iscritical = 1;
break;
case 3:
hitloc = side;
if (crittable(mech, hitloc, btechconf.btech_critlevel))
DoMotiveSystemHit(mech, 0);
break;
case 4:
hitloc = side;
break;
case 5:
hitloc = FSIDE;
break;
case 6:
case 7:
case 8:
hitloc = side;
break;
case 9:
hitloc = BSIDE;
break;
case 10:
case 11:
hitloc = CHECK_ZERO_LOC(mech, TURRET, side);
break;
case 12:
hitloc = CHECK_ZERO_LOC(mech, TURRET, side);
*iscritical = 1;
break;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
hitloc = side;
*iscritical = 1;
break;
case 3:
hitloc = side;
if (crittable(mech, hitloc, btechconf.btech_critlevel))
DoMotiveSystemHit(mech, 0);
break;
case 4:
hitloc = side;
break;
case 5:
hitloc = (hitGroup == FRONT ? RSIDE : LSIDE);
break;
case 6:
case 7:
case 8:
hitloc = side;
break;
case 9:
hitloc = (hitGroup == FRONT ? LSIDE : RSIDE);
break;
case 10:
case 11:
hitloc =
CHECK_ZERO_LOC(mech, TURRET,
(hitGroup == FRONT ? LSIDE : RSIDE));
break;
case 12:
hitloc =
CHECK_ZERO_LOC(mech, TURRET,
(hitGroup == FRONT ? LSIDE : RSIDE));
*iscritical = 1;
break;
}
break;
}
break;
case CLASS_VTOL:
switch (hitGroup) {
case LEFTSIDE:
case RIGHTSIDE:
side = (hitGroup == LEFTSIDE ? LSIDE : RSIDE);
switch (roll) {
case 2:
hitloc = side;
*iscritical = 1;
break;
case 3:
case 4:
hitloc = side;
break;
case 5:
hitloc = FSIDE;
break;
case 6:
case 7:
case 8:
hitloc = side;
break;
case 9:
hitloc = BSIDE;
break;
case 10:
case 11:
hitloc = ROTOR;
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
break;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
hitloc = side;
*iscritical = 1;
break;
case 3:
hitloc = side;
break;
case 4:
hitloc = side;
break;
case 5:
hitloc = (hitGroup == FRONT ? RSIDE : LSIDE);
break;
case 6:
case 7:
case 8:
hitloc = side;
break;
case 9:
hitloc = (hitGroup == FRONT ? LSIDE : RSIDE);
break;
case 10:
case 11:
hitloc = ROTOR;
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
break;
}
break;
}
break;
}
if (!crittable(mech, hitloc, btechconf.btech_critlevel))
*iscritical = 0;
return hitloc;
}
int FindHitLocation(MECH * mech, int hitGroup, int *iscritical,
int *isrear)
{
int roll, hitloc = 0;
int side;
roll = Roll();
/* We have a varying set of crit charts we can use, so let's see what's been config'd */
switch (MechType(mech)) {
case CLASS_VTOL:
if (btechconf.btech_fasaadvvtolcrit)
return FindAdvFasaVehicleHitLocation(mech, hitGroup,
iscritical, isrear);
else if (btechconf.btech_fasacrit)
return FindFasaHitLocation(mech, hitGroup, iscritical, isrear);
break;
case CLASS_VEH_GROUND:
if (btechconf.btech_fasaadvvhlcrit)
return FindAdvFasaVehicleHitLocation(mech, hitGroup,
iscritical, isrear);
else if (btechconf.btech_fasacrit)
return FindFasaHitLocation(mech, hitGroup, iscritical, isrear);
break;
default:
if (btechconf.btech_fasacrit)
return FindFasaHitLocation(mech, hitGroup, iscritical, isrear);
break;
}
if (MechStatus(mech) & COMBAT_SAFE)
return 0;
if (MechDugIn(mech) && GetSectOInt(mech, TURRET) &&
Number(1, 100) >= 42)
return TURRET;
rollstat.hitrolls[roll - 2]++;
rollstat.tothrolls++;
switch (MechType(mech)) {
case CLASS_BSUIT:
if ((hitloc = get_bsuit_hitloc(mech)) < 0)
return Number(0, NUM_BSUIT_MEMBERS - 1);
case CLASS_MW:
case CLASS_MECH:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
if (crittable(mech, LTORSO, 60))
*iscritical = 1;
return LTORSO;
case 3:
return LLEG;
case 4:
case 5:
return LARM;
case 6:
return LLEG;
case 7:
return LTORSO;
case 8:
return CTORSO;
case 9:
return RTORSO;
case 10:
return RARM;
case 11:
return RLEG;
case 12:
return HEAD;
}
case RIGHTSIDE:
switch (roll) {
case 2:
if (crittable(mech, RTORSO, 60))
*iscritical = 1;
return RTORSO;
case 3:
return RLEG;
case 4:
case 5:
return RARM;
case 6:
return RLEG;
case 7:
return RTORSO;
case 8:
return CTORSO;
case 9:
return LTORSO;
case 10:
return LARM;
case 11:
return LLEG;
case 12:
return HEAD;
}
case FRONT:
case BACK:
switch (roll) {
case 2:
if (crittable(mech, CTORSO, 60))
*iscritical = 1;
return CTORSO;
case 3:
case 4:
return RARM;
case 5:
return RLEG;
case 6:
return RTORSO;
case 7:
return CTORSO;
case 8:
return LTORSO;
case 9:
return LLEG;
case 10:
case 11:
return LARM;
case 12:
return HEAD;
}
}
break;
case CLASS_VEH_GROUND:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
case 12:
if (crittable(mech, LSIDE, 40))
*iscritical = 1;
return LSIDE;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return LSIDE;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : LSIDE;
case 11:
if (GetSectInt(mech, TURRET)) {
if (crittable(mech, TURRET, 50))
*iscritical = 1;
return TURRET;
} else
return LSIDE;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
case 12:
if (crittable(mech, RSIDE, 40))
*iscritical = 1;
return RSIDE;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return RSIDE;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : RSIDE;
case 11:
if (GetSectInt(mech, TURRET)) {
if (crittable(mech, TURRET, 50))
*iscritical = 1;
return TURRET;
} else
return RSIDE;
break;
}
break;
case FRONT:
case BACK:
side = (hitGroup == FRONT ? FSIDE : BSIDE);
switch (roll) {
case 2:
case 12:
if (crittable(mech, FSIDE, 40))
*iscritical = 1;
return side;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return side;
case 10:
return (GetSectInt(mech, TURRET)) ? TURRET : side;
case 11:
if (GetSectInt(mech, TURRET)) {
if (crittable(mech, TURRET, 50))
*iscritical = 1;
return TURRET;
} else
return side;
}
}
break;
case CLASS_AERO:
switch (hitGroup) {
case FRONT:
switch (roll) {
case 2:
case 12:
return AERO_COCKPIT;
case 3:
case 11:
if (crittable(mech, AERO_NOSE, 90))
LoseWeapon(mech, AERO_NOSE);
return AERO_NOSE;
case 4:
case 10:
if (roll == 10)
DestroyBomb(mech, AERO_FUSEL);
return AERO_FUSEL;
case 5:
return AERO_RWING;
case 9:
return AERO_LWING;
case 6:
case 7:
case 8:
return AERO_NOSE;
}
break;
case LEFTSIDE:
case RIGHTSIDE:
side = ((hitGroup == LEFTSIDE) ? AERO_LWING : AERO_RWING);
switch (roll) {
case 2:
return AERO_COCKPIT;
case 12:
if (crittable(mech, AERO_ENGINE, 99))
*iscritical = 1;
return AERO_ENGINE;
case 3:
case 11:
if (crittable(mech, side, 99))
LoseWeapon(mech, side);
return side;
case 4:
case 10:
if (crittable(mech, AERO_ENGINE, 90))
DestroyHeatSink(mech, AERO_ENGINE);
return AERO_ENGINE;
case 5:
DestroyBomb(mech, AERO_FUSEL);
return AERO_FUSEL;
case 9:
return AERO_NOSE;
case 6:
case 8:
return side;
case 7:
return AERO_FUSEL;
}
break;
case BACK:
switch (roll) {
case 2:
case 12:
if (crittable(mech, AERO_ENGINE, 90))
*iscritical = 1;
return AERO_ENGINE;
case 3:
case 11:
aero_ControlEffect(mech);
return AERO_FUSEL;
case 4:
case 7:
case 10:
if (crittable(mech, AERO_FUSEL, 90))
DestroyHeatSink(mech, AERO_FUSEL);
return AERO_FUSEL;
case 5:
return AERO_RWING;
case 9:
return AERO_LWING;
case 6:
case 8:
return AERO_ENGINE;
}
}
break;
case CLASS_DS:
case CLASS_SPHEROID_DS:
switch (hitGroup) {
case FRONT:
switch (roll) {
case 2:
case 12:
if (crittable(mech, DS_NOSE, 30))
ds_BridgeHit(mech);
return DS_NOSE;
case 3:
case 11:
if (crittable(mech, DS_NOSE, 50))
LoseWeapon(mech, DS_NOSE);
return DS_NOSE;
case 5:
return DS_RWING;
case 6:
case 7:
case 8:
return DS_NOSE;
case 9:
return DS_LWING;
case 4:
case 10:
return (Number(1, 2)) == 1 ? DS_LWING : DS_RWING;
}
case LEFTSIDE:
case RIGHTSIDE:
side = (hitGroup == LEFTSIDE) ? DS_LWING : DS_RWING;
if (Number(1, 2) == 2)
SpheroidToRear(mech, side);
switch (roll) {
case 2:
if (crittable(mech, DS_NOSE, 30))
ds_BridgeHit(mech);
return DS_NOSE;
case 3:
case 11:
if (crittable(mech, side, 60))
LoseWeapon(mech, side);
return side;
case 4:
case 5:
case 6:
case 7:
case 8:
case 10:
return side;
case 9:
return DS_NOSE;
case 12:
if (crittable(mech, side, 60))
*iscritical = 1;
return side;
}
case BACK:
switch (roll) {
case 2:
case 12:
if (crittable(mech, DS_AFT, 60))
*iscritical = 1;
return DS_AFT;
case 3:
case 11:
return DS_AFT;
case 4:
case 7:
case 10:
if (crittable(mech, DS_AFT, 60))
DestroyHeatSink(mech, DS_AFT);
return DS_AFT;
case 5:
hitloc = DS_RWING;
SpheroidToRear(mech, hitloc);
return hitloc;
case 6:
case 8:
return DS_AFT;
case 9:
hitloc = DS_LWING;
SpheroidToRear(mech, hitloc);
return hitloc;
}
}
break;
case CLASS_VTOL:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
case 4:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 5:
case 6:
case 7:
case 8:
case 9:
hitloc = LSIDE;
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
case 4:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 5:
case 6:
case 7:
case 8:
case 9:
hitloc = RSIDE;
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
case FRONT:
case BACK:
switch (roll) {
case 2:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDestroyedCrit(mech, NULL, 1);
break;
case 3:
case 4:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 5:
case 6:
case 7:
case 8:
case 9:
hitloc = FSIDE;
break;
case 10:
case 11:
hitloc = ROTOR;
DoVTOLRotorDamagedCrit(mech);
break;
case 12:
hitloc = ROTOR;
*iscritical = 1;
DoVTOLRotorDamagedCrit(mech);
break;
}
break;
}
break;
case CLASS_VEH_NAVAL:
switch (hitGroup) {
case LEFTSIDE:
switch (roll) {
case 2:
hitloc = LSIDE;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
case 4:
case 5:
hitloc = LSIDE;
break;
case 9:
hitloc = LSIDE;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = LSIDE;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
} else
hitloc = LSIDE;
break;
case 12:
hitloc = LSIDE;
*iscritical = 1;
break;
}
break;
case RIGHTSIDE:
switch (roll) {
case 2:
case 12:
hitloc = RSIDE;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
hitloc = RSIDE;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = RSIDE;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
} else
hitloc = RSIDE;
break;
}
break;
case FRONT:
case BACK:
switch (roll) {
case 2:
case 12:
hitloc = FSIDE;
if (crittable(mech, hitloc, 40))
*iscritical = 1;
break;
case 3:
hitloc = FSIDE;
break;
case 4:
hitloc = FSIDE;
break;
case 5:
hitloc = FSIDE;
break;
case 6:
case 7:
case 8:
case 9:
hitloc = FSIDE;
break;
case 10:
if (GetSectInt(mech, TURRET))
hitloc = TURRET;
else
hitloc = FSIDE;
break;
case 11:
if (GetSectInt(mech, TURRET)) {
hitloc = TURRET;
*iscritical = 1;
} else
hitloc = FSIDE;
break;
}
break;
}
break;
}
return (hitloc);
}
int FindAreaHitGroup(MECH * mech, MECH * target)
{
int quadr;
quadr =
AcceptableDegree(FindBearing(MechFX(mech), MechFY(mech),
MechFX(target), MechFY(target)) - MechFacing(target));
#if 1
if ((quadr >= 135) && (quadr <= 225))
return FRONT;
if ((quadr < 45) || (quadr > 315))
return BACK;
if ((quadr >= 45) && (quadr < 135))
return LEFTSIDE;
return RIGHTSIDE;
#else
/* These are 'official' BT arcs */
if (quadr >= 120 && quadr <= 240)
return FRONT;
if (quadr < 30 || quadr > 330)
return BACK;
if (quadr >= 30 && quadr < 120)
return LEFTSIDE;
return RIGHTSIDE;
#endif
}
int FindTargetHitLoc(MECH * mech,
MECH * target, int *isrear, int *iscritical)
{
int hitGroup;
/* *isrear = 0; */
*iscritical = 0;
hitGroup = FindAreaHitGroup(mech, target);
if (hitGroup == BACK)
*isrear = 1;
if (MechType(target) == CLASS_MECH &&
(MechStatus(target) & PARTIAL_COVER))
return FindPunchLocation(hitGroup);
if (MechType(mech) == CLASS_MW && MechType(target) == CLASS_MECH &&
MechZ(mech) <= MechZ(target))
return FindKickLocation(hitGroup);
if (MechType(target) == CLASS_MECH &&
((MechType(mech) == CLASS_BSUIT &&
MechSwarmTarget(mech) == target->mynum)))
return FindSwarmHitLocation(iscritical, isrear);
return FindHitLocation(target, hitGroup, iscritical, isrear);
}
int findNARCHitLoc(MECH * mech, MECH * hitMech, int *tIsRearHit)
{
int tIsRear = 0;
int tIsCritical = 0;
int wHitLoc = FindTargetHitLoc(mech, hitMech, &tIsRear, &tIsCritical);
while (GetSectInt(hitMech, wHitLoc) <= 0) {
wHitLoc = TransferTarget(hitMech, wHitLoc);
if (wHitLoc < 0)
return -1;
}
*tIsRearHit = 0;
if (tIsRear) {
if (MechType(hitMech) == CLASS_MECH)
*tIsRearHit = 1;
else if (wHitLoc == FSIDE)
wHitLoc = BSIDE;
}
return wHitLoc;
}
int FindTCHitLoc(MECH * mech, MECH * target, int *isrear, int *iscritical)
{
int hitGroup;
*isrear = 0;
*iscritical = 0;
hitGroup = FindAreaHitGroup(mech, target);
if (hitGroup == BACK)
*isrear = 1;
if (MechAimType(mech) == MechType(target) && Number(1, 6) >= 3)
switch (MechType(target)) {
case CLASS_MECH:
case CLASS_MW:
switch (MechAim(mech)) {
case RARM:
if (hitGroup != LEFTSIDE)
return RARM;
break;
case LARM:
if (hitGroup != RIGHTSIDE)
return LARM;
break;
case RLEG:
if (hitGroup != LEFTSIDE &&
!(MechStatus(target) & PARTIAL_COVER))
return RLEG;
break;
case LLEG:
if (hitGroup != RIGHTSIDE &&
!(MechStatus(target) & PARTIAL_COVER))
return LLEG;
break;
case RTORSO:
if (hitGroup != LEFTSIDE)
return RTORSO;
break;
case LTORSO:
if (hitGroup != RIGHTSIDE)
return LTORSO;
break;
case CTORSO:
/* if (hitGroup != LEFTSIDE && hitGroup != RIGHTSIDE) */
return CTORSO;
case HEAD:
if (Immobile(target))
return HEAD;
}
break;
case CLASS_AERO:
case CLASS_DS:
switch (MechAim(mech)) {
case AERO_NOSE:
if (hitGroup != BACK)
return AERO_NOSE;
break;
case AERO_LWING:
if (hitGroup != RIGHTSIDE)
return AERO_LWING;
break;
case AERO_RWING:
if (hitGroup != LEFTSIDE)
return AERO_RWING;
break;
case AERO_COCKPIT:
if (hitGroup != BACK)
return AERO_COCKPIT;
break;
case AERO_FUSEL:
if (hitGroup != FRONT)
return AERO_FUSEL;
break;
case AERO_ENGINE:
if (hitGroup != FRONT)
return AERO_ENGINE;
break;
}
case CLASS_VEH_GROUND:
case CLASS_VEH_NAVAL:
case CLASS_VTOL:
switch (MechAim(mech)) {
case RSIDE:
if (hitGroup != LEFTSIDE)
return (RSIDE);
break;
case LSIDE:
if (hitGroup != RIGHTSIDE)
return (LSIDE);
break;
case FSIDE:
if (hitGroup != BACK)
return (FSIDE);
break;
case BSIDE:
if (hitGroup != FRONT)
return (BSIDE);
break;
case TURRET:
return (TURRET);
break;
}
break;
}
if (MechType(target) == CLASS_MECH &&
(MechStatus(target) & PARTIAL_COVER))
return FindPunchLocation(hitGroup);
return FindHitLocation(target, hitGroup, iscritical, isrear);
}
int FindAimHitLoc(MECH * mech, MECH * target, int *isrear, int *iscritical)
{
int hitGroup;
*isrear = 0;
*iscritical = 0;
hitGroup = FindAreaHitGroup(mech, target);
if (hitGroup == BACK)
*isrear = 1;
if (MechType(target) == CLASS_MECH || MechType(target) == CLASS_MW)
switch (MechAim(mech)) {
case RARM:
if (hitGroup != LEFTSIDE)
return (RARM);
break;
case LARM:
if (hitGroup != RIGHTSIDE)
return (LARM);
break;
case RLEG:
if (hitGroup != LEFTSIDE &&
!(MechStatus(target) & PARTIAL_COVER))
return (RLEG);
break;
case LLEG:
if (hitGroup != RIGHTSIDE &&
!(MechStatus(target) & PARTIAL_COVER))
return (LLEG);
break;
case RTORSO:
if (hitGroup != LEFTSIDE)
return (RTORSO);
break;
case LTORSO:
if (hitGroup != RIGHTSIDE)
return (LTORSO);
break;
case CTORSO:
return (CTORSO);
case HEAD:
return (HEAD);
} else if (is_aero(target))
return MechAim(mech);
else
switch (MechAim(mech)) {
case RSIDE:
if (hitGroup != LEFTSIDE)
return (RSIDE);
break;
case LSIDE:
if (hitGroup != RIGHTSIDE)
return (LSIDE);
break;
case FSIDE:
if (hitGroup != BACK)
return (FSIDE);
break;
case BSIDE:
if (hitGroup != FRONT)
return (BSIDE);
break;
case TURRET:
return (TURRET);
break;
}
if (MechType(target) == CLASS_MECH &&
(MechStatus(target) & PARTIAL_COVER))
return FindPunchLocation(hitGroup);
return FindHitLocation(target, hitGroup, iscritical, isrear);
}
| 23.787583 | 122 | 0.489793 | murrayma |
33727831f41b819ff16ff7f11aef09eb0e2644a4 | 587 | cpp | C++ | Quick-Sort.cpp | cirno99/Algorithms | 6425b143f406693caf8f882bdfe5497c81df255a | [
"Unlicense"
] | 1,210 | 2016-08-07T13:32:12.000Z | 2022-03-21T01:01:57.000Z | Quick-Sort.cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 7 | 2016-09-11T11:41:03.000Z | 2017-10-29T02:12:57.000Z | Quick-Sort.cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 514 | 2016-10-17T03:52:16.000Z | 2022-03-19T16:23:33.000Z | #include <cstdio>
#include <cstdlib>
#define MAX_ELEMENT_COUNT 1000000
using namespace std;
int d[MAX_ELEMENT_COUNT];
void qsort(int l, int r)
{
if (l < r)
{
int x = d[r];
int j = l - 1;
for (int i = l; i <= r; i++)
{
if (d[i] <= x)
{
j++;
int temp = d[i];
d[i] = d[j];
d[j] = temp;
}
}
qsort(l, j - 1);
qsort(j + 1, r);
}
}
int main()
{
for (int i = 0; i < MAX_ELEMENT_COUNT; i++)
{
d[i] = rand();
}
qsort(0, MAX_ELEMENT_COUNT - 1);
for (int i = 0; i < MAX_ELEMENT_COUNT; i++)
{
printf("%d\n", d[i]);
}
return 0;
}
| 11.979592 | 44 | 0.49063 | cirno99 |
33742d5fccf1faefb39775097644bbf70fa1b965 | 22,255 | cpp | C++ | fdbserver/workloads/RandomSelector.actor.cpp | dlambrig/foundationdb | f02c3523d6ea3b52cbcce09a4f3e81b020abe9b7 | [
"Apache-2.0"
] | null | null | null | fdbserver/workloads/RandomSelector.actor.cpp | dlambrig/foundationdb | f02c3523d6ea3b52cbcce09a4f3e81b020abe9b7 | [
"Apache-2.0"
] | 4 | 2018-09-12T20:32:19.000Z | 2019-07-27T19:10:01.000Z | fdbserver/workloads/RandomSelector.actor.cpp | dlambrig/foundationdb | f02c3523d6ea3b52cbcce09a4f3e81b020abe9b7 | [
"Apache-2.0"
] | null | null | null | /*
* RandomSelector.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fdbclient/NativeAPI.actor.h"
#include "fdbserver/TesterInterface.actor.h"
#include "fdbclient/ReadYourWrites.h"
#include "fdbserver/workloads/workloads.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
struct RandomSelectorWorkload : TestWorkload {
int minOperationsPerTransaction, maxOperationsPerTransaction, maxKeySpace, maxOffset, minInitialAmount,
maxInitialAmount;
double testDuration;
bool fail;
vector<Future<Void>> clients;
PerfIntCounter transactions, retries;
RandomSelectorWorkload(WorkloadContext const& wcx)
: TestWorkload(wcx), transactions("Transactions"), retries("Retries") {
minOperationsPerTransaction = getOption(options, LiteralStringRef("minOperationsPerTransaction"), 10);
maxOperationsPerTransaction = getOption(options, LiteralStringRef("minOperationsPerTransaction"), 50);
maxKeySpace = getOption(options, LiteralStringRef("maxKeySpace"), 20);
maxOffset = getOption(options, LiteralStringRef("maxOffset"), 5);
minInitialAmount = getOption(options, LiteralStringRef("minInitialAmount"), 5);
maxInitialAmount = getOption(options, LiteralStringRef("maxInitialAmount"), 10);
testDuration = getOption(options, LiteralStringRef("testDuration"), 10.0);
fail = false;
}
std::string description() const override { return "RandomSelector"; }
Future<Void> setup(Database const& cx) override { return randomSelectorSetup(cx->clone(), this); }
Future<Void> start(Database const& cx) override {
clients.push_back(timeout(randomSelectorClient(cx->clone(), this), testDuration, Void()));
return delay(testDuration);
}
Future<bool> check(Database const& cx) override {
clients.clear();
return !fail;
}
void getMetrics(vector<PerfMetric>& m) override {
m.push_back(transactions.getMetric());
m.push_back(retries.getMetric());
}
ACTOR Future<Void> randomSelectorSetup(Database cx, RandomSelectorWorkload* self) {
state Value myValue = StringRef(format("%d", deterministicRandom()->randomInt(0, 10000000)));
state Transaction tr(cx);
state std::string clientID;
clientID = format("%08d", self->clientId);
loop {
try {
for (int i = 0; i < self->maxOffset; i++) {
tr.set(StringRef(clientID + "a/" + format("%010d", i)), myValue);
tr.set(StringRef(clientID + "c/" + format("%010d", i)), myValue);
tr.set(StringRef(clientID + "e/" + format("%010d", i)), myValue);
}
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
tr.reset();
}
}
return Void();
}
ACTOR Future<Void> randomSelectorClient(Database cx, RandomSelectorWorkload* self) {
state int i;
state int j;
state std::string clientID;
state std::string myKeyA;
state std::string myKeyB;
state std::string myValue;
state std::string myRandomIDKey;
state bool onEqualA;
state bool onEqualB;
state int offsetA;
state int offsetB;
state int randomLimit;
state int randomByteLimit;
state bool reverse;
state Error error;
clientID = format("%08d", self->clientId);
loop {
state Transaction tr(cx);
loop {
try {
tr.clear(KeyRangeRef(StringRef(clientID + "b/"), StringRef(clientID + "c/")));
tr.clear(KeyRangeRef(StringRef(clientID + "d/"), StringRef(clientID + "e/")));
for (i = 0;
i < deterministicRandom()->randomInt(self->minInitialAmount, self->maxInitialAmount + 1);
i++) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
tr.set(StringRef(clientID + "b/" + myKeyA), myValue);
tr.set(StringRef(clientID + "d/" + myKeyA), myValue);
//TraceEvent("RYOWInit").detail("Key",myKeyA).detail("Value",myValue);
}
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
state ReadYourWritesTransaction trRYOW(cx);
try {
for (i = 0; i < deterministicRandom()->randomInt(self->minOperationsPerTransaction,
self->maxOperationsPerTransaction + 1);
i++) {
j = deterministicRandom()->randomInt(0, 16);
if (j < 3) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWset").detail("Key",myKeyA).detail("Value",myValue);
trRYOW.set(StringRef(clientID + "b/" + myKeyA), myValue);
loop {
try {
tr.set(StringRef(clientID + "d/" + myKeyA), myValue);
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
} else if (j < 4) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
//TraceEvent("RYOWclear").detail("Key",myKeyA);
trRYOW.clear(StringRef(clientID + "b/" + myKeyA));
loop {
try {
tr.clear(StringRef(clientID + "d/" + myKeyA));
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
} else if (j < 5) {
int a = deterministicRandom()->randomInt(1, self->maxKeySpace + 1);
int b = deterministicRandom()->randomInt(1, self->maxKeySpace + 1);
myKeyA = format("%010d", std::min(a, b) - 1);
myKeyB = format("%010d", std::max(a, b));
//TraceEvent("RYOWclearRange").detail("KeyA",myKeyA).detail("KeyB",myKeyB);
trRYOW.clear(
KeyRangeRef(StringRef(clientID + "b/" + myKeyA), StringRef(clientID + "b/" + myKeyB)));
loop {
try {
tr.clear(KeyRangeRef(StringRef(clientID + "d/" + myKeyA),
StringRef(clientID + "d/" + myKeyB)));
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
} else if (j < 6) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
state Optional<Value> getTest1;
Optional<Value> getTest = wait(trRYOW.get(StringRef(clientID + "b/" + myKeyA)));
getTest1 = getTest;
loop {
try {
Optional<Value> getTest2 = wait(tr.get(StringRef(clientID + "d/" + myKeyA)));
if ((getTest1.present() && (!getTest2.present() || getTest1.get() != getTest2.get())) ||
(!getTest1.present() && getTest2.present())) {
TraceEvent(SevError, "RanSelTestFailure")
.detail("Reason", "The get results did not match")
.detail("KeyA", myKeyA)
.detail("RYOW", getTest1.present() ? printable(getTest1.get()) : "Not Present")
.detail("Regular",
getTest2.present() ? printable(getTest2.get()) : "Not Present");
self->fail = true;
}
tr.reset();
break;
} catch (Error& e) {
wait(tr.onError(e));
tr.reset();
}
}
} else if (j < 7) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWadd").detail("Key",myKeyA).detail("Value", "\\x01");
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::AddValue);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::AddValue);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 8) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWappendIfFits").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::AppendIfFits);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::AppendIfFits);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 9) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWand").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::And);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::And);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 10) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWor").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Or);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Or);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 11) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWxor").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Xor);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Xor);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 12) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWmax").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Max);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Max);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 13) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWmin").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Min);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Min);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 14) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWbytemin").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::ByteMin);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::ByteMin);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else if (j < 15) {
myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1));
myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000));
myValue = format("%d", deterministicRandom()->randomInt(0, 10000000));
//TraceEvent("RYOWbytemax").detail("Key",myKeyA).detail("Value", myValue);
trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::ByteMax);
loop {
try {
tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef());
tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::ByteMax);
wait(tr.commit());
break;
} catch (Error& e) {
error = e;
wait(tr.onError(e));
if (error.code() == error_code_commit_unknown_result) {
Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey)));
if (thing.present())
break;
}
}
}
} else {
int a = deterministicRandom()->randomInt(1, self->maxKeySpace + 1);
int b = deterministicRandom()->randomInt(1, self->maxKeySpace + 1);
myKeyA = format("%010d", std::min(a, b) - 1);
myKeyB = format("%010d", std::max(a, b));
onEqualA = deterministicRandom()->randomInt(0, 2) != 0;
onEqualB = deterministicRandom()->randomInt(0, 2) != 0;
offsetA = deterministicRandom()->randomInt(-1 * self->maxOffset / 2, self->maxOffset / 2);
offsetB = deterministicRandom()->randomInt(-1 * self->maxOffset / 2, self->maxOffset / 2);
randomLimit = deterministicRandom()->randomInt(0, 2 * self->maxOffset + self->maxKeySpace);
randomByteLimit =
deterministicRandom()->randomInt(0, (self->maxOffset + self->maxKeySpace) * 512);
reverse = deterministicRandom()->random01() > 0.5 ? false : true;
//TraceEvent("RYOWgetRange").detail("KeyA", myKeyA).detail("KeyB", myKeyB).detail("OnEqualA",onEqualA).detail("OnEqualB",onEqualB).detail("OffsetA",offsetA).detail("OffsetB",offsetB).detail("RandomLimit",randomLimit).detail("RandomByteLimit", randomByteLimit).detail("Reverse", reverse);
state Standalone<RangeResultRef> getRangeTest1;
Standalone<RangeResultRef> getRangeTest =
wait(trRYOW.getRange(KeySelectorRef(StringRef(clientID + "b/" + myKeyA), onEqualA, offsetA),
KeySelectorRef(StringRef(clientID + "b/" + myKeyB), onEqualB, offsetB),
randomLimit,
false,
reverse));
getRangeTest1 = getRangeTest;
loop {
try {
Standalone<RangeResultRef> getRangeTest2 = wait(
tr.getRange(KeySelectorRef(StringRef(clientID + "d/" + myKeyA), onEqualA, offsetA),
KeySelectorRef(StringRef(clientID + "d/" + myKeyB), onEqualB, offsetB),
randomLimit,
false,
reverse));
bool fail = false;
if (getRangeTest1.size() != getRangeTest2.size()) {
TraceEvent(SevError, "RanSelTestFailure")
.detail("Reason", "The getRange results did not match sizes")
.detail("Size1", getRangeTest1.size())
.detail("Size2", getRangeTest2.size())
.detail("Limit", randomLimit)
.detail("ByteLimit", randomByteLimit)
.detail("Bytes1", getRangeTest1.expectedSize())
.detail("Bytes2", getRangeTest2.expectedSize())
.detail("Reverse", reverse);
fail = true;
self->fail = true;
}
for (int k = 0; k < std::min(getRangeTest1.size(), getRangeTest2.size()); k++) {
if (getRangeTest1[k].value != getRangeTest2[k].value) {
std::string keyA = printable(getRangeTest1[k].key);
std::string valueA = printable(getRangeTest1[k].value);
std::string keyB = printable(getRangeTest2[k].key);
std::string valueB = printable(getRangeTest2[k].value);
TraceEvent(SevError, "RanSelTestFailure")
.detail("Reason", "The getRange results did not match contents")
.detail("KeyA", keyA)
.detail("ValueA", valueA)
.detail("KeyB", keyB)
.detail("ValueB", valueB)
.detail("Reverse", reverse);
fail = true;
self->fail = true;
}
}
if (fail) {
std::string outStr1 = "";
for (int k = 0; k < getRangeTest1.size(); k++) {
outStr1 = outStr1 + printable(getRangeTest1[k].key) + " " +
format("%d", getRangeTest1[k].value.size()) + " ";
}
std::string outStr2 = "";
for (int k = 0; k < getRangeTest2.size(); k++) {
outStr2 = outStr2 + printable(getRangeTest2[k].key) + " " +
format("%d", getRangeTest2[k].value.size()) + " ";
}
TraceEvent("RanSelTestLog").detail("RYOW", outStr1).detail("Normal", outStr2);
}
tr.reset();
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
}
}
wait(trRYOW.commit());
++self->transactions;
state Transaction finalTransaction(cx);
loop {
try {
state Standalone<RangeResultRef> finalTest1 = wait(finalTransaction.getRange(
KeyRangeRef(StringRef(clientID + "b/"), StringRef(clientID + "c/")), self->maxKeySpace));
Standalone<RangeResultRef> finalTest2 = wait(finalTransaction.getRange(
KeyRangeRef(StringRef(clientID + "d/"), StringRef(clientID + "e/")), self->maxKeySpace));
if (finalTest1.size() != finalTest2.size()) {
TraceEvent(SevError, "RanSelTestFailure")
.detail("Reason", "The final results did not match sizes");
self->fail = true;
}
for (int k = 0; k < finalTest1.size(); k++)
if (finalTest1[k].value != finalTest2[k].value) {
TraceEvent(SevError, "RanSelTestFailure")
.detail("Reason", "The final results did not match contents")
.detail("KeyA", printable(finalTest1[k].key))
.detail("ValueA", printable(finalTest1[k].value))
.detail("KeyB", printable(finalTest2[k].key))
.detail("ValueB", printable(finalTest2[k].value))
.detail("Reverse", reverse);
self->fail = true;
}
break;
} catch (Error& e) {
wait(finalTransaction.onError(e));
}
}
} catch (Error& e) {
wait(trRYOW.onError(e));
++self->retries;
}
}
}
};
WorkloadFactory<RandomSelectorWorkload> RandomSelectorWorkloadFactory("RandomSelector");
| 39.599644 | 293 | 0.597079 | dlambrig |
33755a50eb1476a6e77c3e9b7b8f35bbc38bf95a | 3,532 | cpp | C++ | tests/distance_test.cpp | xjdr/VectorSearch | ab2c14c8f49d840a69ee1c93ec2c334704f59153 | [
"MIT"
] | null | null | null | tests/distance_test.cpp | xjdr/VectorSearch | ab2c14c8f49d840a69ee1c93ec2c334704f59153 | [
"MIT"
] | null | null | null | tests/distance_test.cpp | xjdr/VectorSearch | ab2c14c8f49d840a69ee1c93ec2c334704f59153 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "../vsearch/distance.h"
#include "../vsearch/vsearch.pb.h"
#include <iostream>
#include <fstream>
#include <string>
class DistanceTest : public testing::Test {
};
TEST(DistanceTest, DistanceTest_L2_Test_Far) {
float pX[] = {1.3, 1.3};
float pY[] = {6.6, 6.2};
float r = vsearch::Distance::ComputeL2Distance(pX, pY, 2);
EXPECT_FLOAT_EQ(r, 52.1);
}
TEST(DistanceTest, DistanceTest_L2_Test_Close) {
float pX[] = {1.3, 1.3};
float pY[] = {1.29, 1.28};
float r = vsearch::Distance::ComputeL2Distance(pX, pY, 2);
EXPECT_FLOAT_EQ(r, 0.00049999903);
}
TEST(DistanceTest, DistanceTest_Cosine_Test_Far) {
float pX[] = {1.3, 1.3};
float pY[] = {6.6, 6.2};
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2);
EXPECT_FLOAT_EQ(r, -15.639999);
}
TEST(DistanceTest, DistanceTest_Cosine_Test_Close) {
float pX[] = {1.3, 1.3};
float pY[] = {1.29, 1.28};
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2);
EXPECT_FLOAT_EQ(r, -2.3409998);
}
TEST(DistanceTest, DistanceTest_Cosine_Test_S2D_Far) {
float pX[] = {1.3, 1.3};
float pY[] = {6.6, 6.2};
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2);
EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 16.639999);
}
TEST(DistanceTest, DistanceTest_Cosine_Test_S2D_Close) {
float pX[] = {1.3, 1.3};
float pY[] = {1.29, 1.28};
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2);
EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 3.3409998);
}
TEST(DistanceTest, DistanceTest_L2_Test_Tensor) {
vsearch::Index i;
std::ifstream file;
std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt");
file.open(s.c_str(), std::fstream::in);
if(!i.ParseFromIstream(&file)) {
std::cerr << "Boooo" << std::endl;
}
float pX[i.index(0).size()];
float pY[i.index(1).size()];
std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size());
std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size());
float r = vsearch::Distance::ComputeL2Distance(pX, pY, i.index(0).size());
EXPECT_FLOAT_EQ(r, 369.71799);
}
TEST(DistanceTest, DistanceTest_Cosine_Test_Tensor) {
vsearch::Index i;
std::ifstream file;
std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt");
file.open(s.c_str(), std::fstream::in);
if(!i.ParseFromIstream(&file)) {
std::cerr << "Boooo" << std::endl;
}
float pX[i.index(0).size()];
float pY[i.index(1).size()];
std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size());
std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size());
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, i.index(0).size());
EXPECT_FLOAT_EQ(r, -1435.8535);
}
TEST(DistanceTest, DistanceTest_CosineDistance_Test_Tensor) {
vsearch::Index i;
std::ifstream file;
std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt");
file.open(s.c_str(), std::fstream::in);
if (!i.ParseFromIstream(&file)) {
std::cerr << "Boooo" << std::endl;
}
float pX[i.index(0).size()];
float pY[i.index(1).size()];
std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size());
std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size());
float r = vsearch::Distance::ComputeCosineDistance(pX, pY, i.index(0).size());
EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 1436.8535);
}
| 33.320755 | 86 | 0.669309 | xjdr |
337677706c3aa68ffd78265ced8be2125a993e25 | 1,892 | cpp | C++ | src/util/BalanceTests.cpp | fonero-project/fonero-core | 75d6bcadf36df2bfe10c4b7777281540566f1f34 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/util/BalanceTests.cpp | fonero-project/fonero-core | 75d6bcadf36df2bfe10c4b7777281540566f1f34 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/util/BalanceTests.cpp | fonero-project/fonero-core | 75d6bcadf36df2bfe10c4b7777281540566f1f34 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 Fonero Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "lib/catch.hpp"
#include "util/types.h"
using namespace fonero;
bool
addBalance(int64_t balance, int64_t delta, int64_t resultBalance,
int64_t maxBalance = std::numeric_limits<int64_t>::max())
{
auto r = fonero::addBalance(balance, delta, maxBalance);
REQUIRE(balance == resultBalance);
return r;
}
TEST_CASE("balance", "[balance]")
{
auto const max = std::numeric_limits<int64_t>::max();
auto const min = std::numeric_limits<int64_t>::min();
REQUIRE(addBalance(0, 0, 0));
REQUIRE(addBalance(0, 10, 10));
REQUIRE(addBalance(10, 0, 10));
REQUIRE(addBalance(10, 10, 20));
REQUIRE(!addBalance(0, -5, 0));
REQUIRE(addBalance(10, -10, 0));
REQUIRE(addBalance(10, -9, 1));
REQUIRE(!addBalance(10, -11, 10));
REQUIRE(!addBalance(5, 5, 5, 9));
REQUIRE(!addBalance(0, 1, 0, 0));
REQUIRE(addBalance(0, 1, 1, max));
REQUIRE(!addBalance(0, max, 0, 0));
REQUIRE(addBalance(0, max, max, max));
REQUIRE(!addBalance(max, 1, max, 0));
REQUIRE(!addBalance(max, 1, max, max));
REQUIRE(!addBalance(max, max, max, 0));
REQUIRE(!addBalance(max, max, max, max));
REQUIRE(!addBalance(0, -1, 0, 0));
REQUIRE(!addBalance(0, -1, 0, max));
REQUIRE(!addBalance(0, min, 0, 0));
REQUIRE(!addBalance(0, -max, 0, 0));
REQUIRE(!addBalance(0, min, 0, max));
REQUIRE(!addBalance(0, -max, 0, max));
REQUIRE(!addBalance(max, -1, max, 0));
REQUIRE(addBalance(max, -1, max - 1, max));
REQUIRE(!addBalance(max, min, max, 0));
REQUIRE(addBalance(max, -max, 0, 0));
REQUIRE(!addBalance(max, min, max, max));
REQUIRE(addBalance(max, -max, 0, max));
}
| 34.4 | 74 | 0.638478 | fonero-project |
337698b6aedd957da61d9b6c57a7325651b7ace2 | 34,406 | cc | C++ | Geometry/HGCalGeometry/src/HGCalGeometry.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 1 | 2020-07-12T11:51:32.000Z | 2020-07-12T11:51:32.000Z | Geometry/HGCalGeometry/src/HGCalGeometry.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 3 | 2020-02-19T08:33:16.000Z | 2020-03-13T10:02:19.000Z | Geometry/HGCalGeometry/src/HGCalGeometry.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 1 | 2018-01-22T10:20:10.000Z | 2018-01-22T10:20:10.000Z | /* for High Granularity Calorimeter
* This geometry is essentially driven by topology,
* which is thus encapsulated in this class.
* This makes this geometry not suitable to be loaded
* by regular CaloGeometryLoader<T>
*/
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "DataFormats/GeometrySurface/interface/Plane.h"
#include "Geometry/HGCalGeometry/interface/HGCalGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloGenericDetId.h"
#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
#include "TrackingTools/GeomPropagators/interface/AnalyticalPropagator.h"
#include <cmath>
#include <Math/Transform3D.h>
#include <Math/EulerAngles.h>
typedef CaloCellGeometry::Tr3D Tr3D;
typedef std::vector<float> ParmVec;
//#define EDM_ML_DEBUG
HGCalGeometry::HGCalGeometry(const HGCalTopology& topology_)
: m_topology(topology_),
m_validGeomIds(topology_.totalGeomModules()),
mode_(topology_.geomMode()),
m_det(topology_.detector()),
m_subdet(topology_.subDetector()),
twoBysqrt3_(2.0 / std::sqrt(3.0)) {
if (m_det == DetId::HGCalHSc) {
m_cellVec2 = CellVec2(topology_.totalGeomModules());
} else {
m_cellVec = CellVec(topology_.totalGeomModules());
}
m_validIds.reserve(m_topology.totalModules());
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Expected total # of Geometry Modules " << m_topology.totalGeomModules();
#endif
}
HGCalGeometry::~HGCalGeometry() {}
void HGCalGeometry::fillNamedParams(DDFilteredView fv) {}
void HGCalGeometry::initializeParms() {}
void HGCalGeometry::localCorners(Pt3DVec& lc, const CCGFloat* pv, unsigned int i, Pt3D& ref) {
if (m_det == DetId::HGCalHSc) {
FlatTrd::localCorners(lc, pv, ref);
} else {
FlatHexagon::localCorners(lc, pv, ref);
}
}
void HGCalGeometry::newCell(
const GlobalPoint& f1, const GlobalPoint& f2, const GlobalPoint& f3, const CCGFloat* parm, const DetId& detId) {
DetId geomId = getGeometryDetId(detId);
int cells(0);
HGCalTopology::DecodedDetId id = m_topology.decode(detId);
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
cells = m_topology.dddConstants().numberCellsHexagon(id.iSec1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCalDetId(detId) << " GEOM " << HGCalDetId(geomId);
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
cells = 1;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCScintillatorDetId(detId) << " GEOM "
<< HGCScintillatorDetId(geomId);
#endif
} else {
cells = m_topology.dddConstants().numberCellsHexagon(id.iLay, id.iSec1, id.iSec2, false);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCSiliconDetId(detId) << " GEOM " << HGCSiliconDetId(geomId);
#endif
}
const uint32_t cellIndex(m_topology.detId2denseGeomId(geomId));
if (m_det == DetId::HGCalHSc) {
m_cellVec2.at(cellIndex) = FlatTrd(cornersMgr(), f1, f2, f3, parm);
} else {
m_cellVec.at(cellIndex) = FlatHexagon(cornersMgr(), f1, f2, f3, parm);
}
m_validGeomIds.at(cellIndex) = geomId;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Store for DetId " << std::hex << detId.rawId() << " GeomId " << geomId.rawId()
<< std::dec << " Index " << cellIndex << " cells " << cells;
unsigned int nOld = m_validIds.size();
#endif
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
for (int cell = 0; cell < cells; ++cell) {
id.iCell1 = cell;
DetId idc = m_topology.encode(id);
if (m_topology.valid(idc)) {
m_validIds.emplace_back(idc);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Valid Id [" << cell << "] " << HGCalDetId(idc);
#endif
}
}
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
DetId idc = m_topology.encode(id);
if (m_topology.valid(idc)) {
m_validIds.emplace_back(idc);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Valid Id [0] " << HGCScintillatorDetId(idc);
#endif
} else {
edm::LogWarning("HGCalGeom") << "Check " << HGCScintillatorDetId(idc) << " from " << HGCScintillatorDetId(detId)
<< " ERROR ???";
}
} else {
#ifdef EDM_ML_DEBUG
unsigned int cellAll(0), cellSelect(0);
#endif
for (int u = 0; u < 2 * cells; ++u) {
for (int v = 0; v < 2 * cells; ++v) {
if (((v - u) < cells) && (u - v) <= cells) {
id.iCell1 = u;
id.iCell2 = v;
DetId idc = m_topology.encode(id);
#ifdef EDM_ML_DEBUG
++cellAll;
#endif
if (m_topology.dddConstants().cellInLayer(id.iSec1, id.iSec2, u, v, id.iLay, true)) {
m_validIds.emplace_back(idc);
#ifdef EDM_ML_DEBUG
++cellSelect;
edm::LogVerbatim("HGCalGeom") << "Valid Id [" << u << ", " << v << "] " << HGCSiliconDetId(idc);
#endif
}
}
}
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "HGCalGeometry keeps " << cellSelect << " out of " << cellAll << " for wafer "
<< id.iSec1 << ":" << id.iSec2 << " in "
<< " layer " << id.iLay;
#endif
}
#ifdef EDM_ML_DEBUG
if (m_det == DetId::HGCalHSc) {
edm::LogVerbatim("HGCalGeom") << "HGCalGeometry::newCell-> [" << cellIndex << "]"
<< " front:" << f1.x() << '/' << f1.y() << '/' << f1.z() << " back:" << f2.x() << '/'
<< f2.y() << '/' << f2.z() << " eta|phi " << m_cellVec2[cellIndex].etaPos() << ":"
<< m_cellVec2[cellIndex].phiPos();
} else {
edm::LogVerbatim("HGCalGeom") << "HGCalGeometry::newCell-> [" << cellIndex << "]"
<< " front:" << f1.x() << '/' << f1.y() << '/' << f1.z() << " back:" << f2.x() << '/'
<< f2.y() << '/' << f2.z() << " eta|phi " << m_cellVec[cellIndex].etaPos() << ":"
<< m_cellVec[cellIndex].phiPos();
}
unsigned int nNew = m_validIds.size();
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
edm::LogVerbatim("HGCalGeom") << "ID: " << HGCalDetId(detId) << " with valid DetId from " << nOld << " to " << nNew;
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
edm::LogVerbatim("HGCalGeom") << "ID: " << HGCScintillatorDetId(detId) << " with valid DetId from " << nOld
<< " to " << nNew;
} else if (m_topology.isHFNose()) {
edm::LogVerbatim("HGCalGeom") << "ID: " << HFNoseDetId(detId) << " with valid DetId from " << nOld << " to "
<< nNew;
} else {
edm::LogVerbatim("HGCalGeom") << "ID: " << HGCSiliconDetId(detId) << " with valid DetId from " << nOld << " to "
<< nNew;
}
edm::LogVerbatim("HGCalGeom") << "Cell[" << cellIndex << "] " << std::hex << geomId.rawId() << ":"
<< m_validGeomIds[cellIndex].rawId() << std::dec;
#endif
}
std::shared_ptr<const CaloCellGeometry> HGCalGeometry::getGeometry(const DetId& detId) const {
if (detId == DetId())
return nullptr; // nothing to get
DetId geomId = getGeometryDetId(detId);
const uint32_t cellIndex(m_topology.detId2denseGeomId(geomId));
const GlobalPoint pos = (detId != geomId) ? getPosition(detId) : GlobalPoint();
return cellGeomPtr(cellIndex, pos);
}
bool HGCalGeometry::present(const DetId& detId) const {
if (detId == DetId())
return false;
DetId geomId = getGeometryDetId(detId);
const uint32_t index(m_topology.detId2denseGeomId(geomId));
return (nullptr != getGeometryRawPtr(index));
}
GlobalPoint HGCalGeometry::getPosition(const DetId& detid) const {
unsigned int cellIndex = indexFor(detid);
GlobalPoint glob;
unsigned int maxSize = ((mode_ == HGCalGeometryMode::Trapezoid) ? m_cellVec2.size() : m_cellVec.size());
if (cellIndex < maxSize) {
HGCalTopology::DecodedDetId id = m_topology.decode(detid);
std::pair<float, float> xy;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true);
const HepGeom::Point3D<float> lcoord(xy.first, xy.second, 0);
glob = m_cellVec[cellIndex].getPosition(lcoord);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getPosition:: index " << cellIndex << " Local " << lcoord.x() << ":"
<< lcoord.y() << " ID " << id.iCell1 << ":" << id.iSec1 << " Global " << glob;
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
const HepGeom::Point3D<float> lcoord(0, 0, 0);
glob = m_cellVec2[cellIndex].getPosition(lcoord);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getPositionTrap:: index " << cellIndex << " Local " << lcoord.x() << ":"
<< lcoord.y() << " ID " << id.iLay << ":" << id.iSec1 << ":" << id.iCell1
<< " Global " << glob;
#endif
} else {
xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false, true);
const HepGeom::Point3D<float> lcoord(xy.first, xy.second, 0);
glob = m_cellVec[cellIndex].getPosition(lcoord);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getPositionWafer:: index " << cellIndex << " Local " << lcoord.x() << ":"
<< lcoord.y() << " ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":"
<< id.iCell1 << ":" << id.iCell2 << " Global " << glob;
#endif
}
}
return glob;
}
GlobalPoint HGCalGeometry::getWaferPosition(const DetId& detid) const {
unsigned int cellIndex = indexFor(detid);
GlobalPoint glob;
unsigned int maxSize = ((mode_ == HGCalGeometryMode::Trapezoid) ? m_cellVec2.size() : m_cellVec.size());
if (cellIndex < maxSize) {
const HepGeom::Point3D<float> lcoord(0, 0, 0);
if (mode_ == HGCalGeometryMode::Trapezoid) {
glob = m_cellVec2[cellIndex].getPosition(lcoord);
} else {
glob = m_cellVec[cellIndex].getPosition(lcoord);
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getPositionTrap:: ID " << std::hex << detid.rawId() << std::dec << " index "
<< cellIndex << " Global " << glob;
#endif
}
return glob;
}
double HGCalGeometry::getArea(const DetId& detid) const {
HGCalGeometry::CornersVec corners = getNewCorners(detid);
double area(0);
if (corners.size() > 1) {
int n = corners.size() - 1;
int j = n - 1;
for (int i = 0; i < n; ++i) {
area += ((corners[j].x() + corners[i].x()) * (corners[i].y() - corners[j].y()));
j = i;
}
}
return (0.5 * area);
}
HGCalGeometry::CornersVec HGCalGeometry::getCorners(const DetId& detid) const {
unsigned int ncorner = ((m_det == DetId::HGCalHSc) ? FlatTrd::ncorner_ : FlatHexagon::ncorner_);
HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0));
unsigned int cellIndex = indexFor(detid);
HGCalTopology::DecodedDetId id = m_topology.decode(detid);
if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) {
GlobalPoint v = getPosition(detid);
std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1);
float dr = k_half * (rr.second - rr.first);
float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell];
float dz = id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ];
float r = v.perp();
float fi = v.phi();
static const int signr[] = {1, 1, -1, -1, 1, 1, -1, -1};
static const int signf[] = {-1, 1, 1, -1, -1, 1, 1, -1};
static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1};
for (unsigned int i = 0; i < ncorner; ++i) {
co[i] = GlobalPoint((r + signr[i] * dr) * cos(fi + signf[i] * dfi),
(r + signr[i] * dr) * sin(fi + signf[i] * dfi),
(v.z() + signz[i] * dz));
}
} else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) {
std::pair<float, float> xy;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true);
float dx = m_cellVec[cellIndex].param()[FlatHexagon::k_r];
float dy = k_half * m_cellVec[cellIndex].param()[FlatHexagon::k_R];
float dz = m_cellVec[cellIndex].param()[FlatHexagon::k_dZ];
static const int signx[] = {0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, 1};
static const int signy[] = {-2, -1, 1, 2, 1, -1, -2, -1, 1, 2, 1, -1};
static const int signz[] = {-1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1};
for (unsigned int i = 0; i < ncorner; ++i) {
const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, signz[i] * dz);
co[i] = m_cellVec[cellIndex].getPosition(lcoord);
}
} else {
xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false);
float dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r];
float dy = k_fac1 * m_cellVec[cellIndex].param()[FlatHexagon::k_R];
float dz = -id.zSide * m_cellVec[cellIndex].param()[FlatHexagon::k_dZ];
static const int signx[] = {1, -1, -2, -1, 1, 2, 1, -1, -2, -1, 1, 2};
static const int signy[] = {1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0};
static const int signz[] = {-1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1};
for (unsigned int i = 0; i < ncorner; ++i) {
const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, signz[i] * dz);
co[i] = m_cellVec[cellIndex].getPosition(lcoord);
}
}
}
return co;
}
HGCalGeometry::CornersVec HGCalGeometry::get8Corners(const DetId& detid) const {
unsigned int ncorner = FlatTrd::ncorner_;
HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0));
unsigned int cellIndex = indexFor(detid);
HGCalTopology::DecodedDetId id = m_topology.decode(detid);
if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) {
GlobalPoint v = getPosition(detid);
std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1);
float dr = k_half * (rr.second - rr.first);
float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell];
float dz = id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ];
float r = v.perp();
float fi = v.phi();
static const int signr[] = {1, 1, -1, -1, 1, 1, -1, -1};
static const int signf[] = {-1, 1, 1, -1, -1, 1, 1, -1};
static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1};
for (unsigned int i = 0; i < ncorner; ++i) {
co[i] = GlobalPoint((r + signr[i] * dr) * cos(fi + signf[i] * dfi),
(r + signr[i] * dr) * sin(fi + signf[i] * dfi),
(v.z() + signz[i] * dz));
}
} else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) {
std::pair<float, float> xy;
float dx(0);
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true);
dx = m_cellVec[cellIndex].param()[FlatHexagon::k_r];
} else {
xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false);
dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r];
}
static const int signx[] = {-1, -1, 1, 1, -1, -1, 1, 1};
static const int signy[] = {-1, 1, 1, -1, -1, 1, 1, -1};
static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1};
float dz = m_cellVec[cellIndex].param()[FlatHexagon::k_dZ];
for (unsigned int i = 0; i < ncorner; ++i) {
const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dx, signz[i] * dz);
co[i] = m_cellVec[cellIndex].getPosition(lcoord);
}
}
return co;
}
HGCalGeometry::CornersVec HGCalGeometry::getNewCorners(const DetId& detid) const {
unsigned int ncorner = (m_det == DetId::HGCalHSc) ? 5 : 7;
HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0));
unsigned int cellIndex = indexFor(detid);
HGCalTopology::DecodedDetId id = m_topology.decode(detid);
if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) {
GlobalPoint v = getPosition(detid);
std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1);
float dr = k_half * (rr.second - rr.first);
float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell];
float dz = -id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ];
float r = v.perp();
float fi = v.phi();
static const int signr[] = {1, 1, -1, -1};
static const int signf[] = {-1, 1, 1, -1};
for (unsigned int i = 0; i < ncorner - 1; ++i) {
co[i] = GlobalPoint(
(r + signr[i] * dr) * cos(fi + signf[i] * dfi), (r + signr[i] * dr) * sin(fi + signf[i] * dfi), (v.z() + dz));
}
co[ncorner - 1] = GlobalPoint(0, 0, -2 * dz);
} else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) {
std::pair<float, float> xy;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true);
} else {
xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false);
}
float dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r];
float dy = k_fac1 * m_cellVec[cellIndex].param()[FlatHexagon::k_R];
float dz = -id.zSide * m_cellVec[cellIndex].param()[FlatHexagon::k_dZ];
static const int signx[] = {1, -1, -2, -1, 1, 2};
static const int signy[] = {1, 1, 0, -1, -1, 0};
for (unsigned int i = 0; i < ncorner - 1; ++i) {
const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, dz);
co[i] = m_cellVec[cellIndex].getPosition(lcoord);
}
co[ncorner - 1] = GlobalPoint(0, 0, -2 * dz);
}
return co;
}
DetId HGCalGeometry::neighborZ(const DetId& idin, const GlobalVector& momentum) const {
DetId idnew;
HGCalTopology::DecodedDetId id = m_topology.decode(idin);
int lay = ((momentum.z() * id.zSide > 0) ? (id.iLay + 1) : (id.iLay - 1));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "neighborz1:: ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":"
<< id.iCell1 << ":" << id.iCell2 << " New Layer " << lay << " Range "
<< m_topology.dddConstants().firstLayer() << ":"
<< m_topology.dddConstants().lastLayer(true) << " pz " << momentum.z();
#endif
if ((lay >= m_topology.dddConstants().firstLayer()) && (lay <= m_topology.dddConstants().lastLayer(true)) &&
(momentum.z() != 0.0)) {
GlobalPoint v = getPosition(idin);
double z = id.zSide * m_topology.dddConstants().waferZ(lay, true);
double grad = (z - v.z()) / momentum.z();
GlobalPoint p(v.x() + grad * momentum.x(), v.y() + grad * momentum.y(), z);
double r = p.perp();
auto rlimit = topology().dddConstants().rangeR(z, true);
if (r >= rlimit.first && r <= rlimit.second)
idnew = getClosestCell(p);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "neighborz1:: Position " << v << " New Z " << z << ":" << grad << " new position "
<< p << " r-limit " << rlimit.first << ":" << rlimit.second;
#endif
}
return idnew;
}
DetId HGCalGeometry::neighborZ(const DetId& idin,
const MagneticField* bField,
int charge,
const GlobalVector& momentum) const {
DetId idnew;
HGCalTopology::DecodedDetId id = m_topology.decode(idin);
int lay = ((momentum.z() * id.zSide > 0) ? (id.iLay + 1) : (id.iLay - 1));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "neighborz2:: ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":"
<< id.iCell1 << ":" << id.iCell2 << " New Layer " << lay << " Range "
<< m_topology.dddConstants().firstLayer() << ":"
<< m_topology.dddConstants().lastLayer(true) << " pz " << momentum.z();
#endif
if ((lay >= m_topology.dddConstants().firstLayer()) && (lay <= m_topology.dddConstants().lastLayer(true)) &&
(momentum.z() != 0.0)) {
GlobalPoint v = getPosition(idin);
double z = id.zSide * m_topology.dddConstants().waferZ(lay, true);
FreeTrajectoryState fts(v, momentum, charge, bField);
Plane::PlanePointer nPlane = Plane::build(Plane::PositionType(0, 0, z), Plane::RotationType());
AnalyticalPropagator myAP(bField, alongMomentum, 2 * M_PI);
TrajectoryStateOnSurface tsos = myAP.propagate(fts, *nPlane);
GlobalPoint p;
auto rlimit = topology().dddConstants().rangeR(z, true);
if (tsos.isValid()) {
p = tsos.globalPosition();
double r = p.perp();
if (r >= rlimit.first && r <= rlimit.second)
idnew = getClosestCell(p);
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "neighborz2:: Position " << v << " New Z " << z << ":" << charge << ":"
<< tsos.isValid() << " new position " << p << " r limits " << rlimit.first << ":"
<< rlimit.second;
#endif
}
return idnew;
}
DetId HGCalGeometry::getClosestCell(const GlobalPoint& r) const {
unsigned int cellIndex = getClosestCellIndex(r);
if ((cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) ||
(cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc)) {
HGCalTopology::DecodedDetId id = m_topology.decode(m_validGeomIds[cellIndex]);
HepGeom::Point3D<float> local;
if (r.z() > 0) {
local = HepGeom::Point3D<float>(r.x(), r.y(), 0);
id.zSide = 1;
} else {
local = HepGeom::Point3D<float>(-r.x(), r.y(), 0);
id.zSide = -1;
}
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
const auto& kxy = m_topology.dddConstants().assignCell(local.x(), local.y(), id.iLay, id.iType, true);
id.iCell1 = kxy.second;
id.iSec1 = kxy.first;
id.iType = m_topology.dddConstants().waferTypeT(kxy.first);
if (id.iType != 1)
id.iType = -1;
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
id.iLay = m_topology.dddConstants().getLayer(r.z(), true);
const auto& kxy = m_topology.dddConstants().assignCellTrap(r.x(), r.y(), r.z(), id.iLay, true);
id.iSec1 = kxy[0];
id.iCell1 = kxy[1];
id.iType = kxy[2];
} else {
id.iLay = m_topology.dddConstants().getLayer(r.z(), true);
const auto& kxy = m_topology.dddConstants().assignCellHex(local.x(), local.y(), id.iLay, true);
id.iSec1 = kxy[0];
id.iSec2 = kxy[1];
id.iType = kxy[2];
id.iCell1 = kxy[3];
id.iCell2 = kxy[4];
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getClosestCell: local " << local << " Id " << id.zSide << ":" << id.iLay << ":"
<< id.iSec1 << ":" << id.iSec2 << ":" << id.iType << ":" << id.iCell1 << ":"
<< id.iCell2;
#endif
//check if returned cell is valid
if (id.iCell1 >= 0)
return m_topology.encode(id);
}
//if not valid or out of bounds return a null DetId
return DetId();
}
HGCalGeometry::DetIdSet HGCalGeometry::getCells(const GlobalPoint& r, double dR) const {
HGCalGeometry::DetIdSet dss;
return dss;
}
std::string HGCalGeometry::cellElement() const {
if (m_subdet == HGCEE || m_det == DetId::HGCalEE)
return "HGCalEE";
else if (m_subdet == HGCHEF || m_det == DetId::HGCalHSi)
return "HGCalHEFront";
else if (m_subdet == HGCHEB || m_det == DetId::HGCalHSc)
return "HGCalHEBack";
else
return "Unknown";
}
unsigned int HGCalGeometry::indexFor(const DetId& detId) const {
unsigned int cellIndex = ((m_det == DetId::HGCalHSc) ? m_cellVec2.size() : m_cellVec.size());
if (detId != DetId()) {
DetId geomId = getGeometryDetId(detId);
cellIndex = m_topology.detId2denseGeomId(geomId);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "indexFor " << std::hex << detId.rawId() << ":" << geomId.rawId() << std::dec
<< " index " << cellIndex;
#endif
}
return cellIndex;
}
unsigned int HGCalGeometry::sizeForDenseIndex() const { return m_topology.totalGeomModules(); }
const CaloCellGeometry* HGCalGeometry::getGeometryRawPtr(uint32_t index) const {
// Modify the RawPtr class
if (m_det == DetId::HGCalHSc) {
if (m_cellVec2.size() < index)
return nullptr;
const CaloCellGeometry* cell(&m_cellVec2[index]);
return (nullptr == cell->param() ? nullptr : cell);
} else {
if (m_cellVec2.size() < index)
return nullptr;
const CaloCellGeometry* cell(&m_cellVec[index]);
return (nullptr == cell->param() ? nullptr : cell);
}
}
std::shared_ptr<const CaloCellGeometry> HGCalGeometry::cellGeomPtr(uint32_t index) const {
if ((index >= m_cellVec.size() && m_det != DetId::HGCalHSc) ||
(index >= m_cellVec2.size() && m_det == DetId::HGCalHSc) || (m_validGeomIds[index].rawId() == 0))
return nullptr;
static const auto do_not_delete = [](const void*) {};
if (m_det == DetId::HGCalHSc) {
auto cell = std::shared_ptr<const CaloCellGeometry>(&m_cellVec2[index], do_not_delete);
if (nullptr == cell->param())
return nullptr;
return cell;
} else {
auto cell = std::shared_ptr<const CaloCellGeometry>(&m_cellVec[index], do_not_delete);
if (nullptr == cell->param())
return nullptr;
return cell;
}
}
std::shared_ptr<const CaloCellGeometry> HGCalGeometry::cellGeomPtr(uint32_t index, const GlobalPoint& pos) const {
if ((index >= m_cellVec.size() && m_det != DetId::HGCalHSc) ||
(index >= m_cellVec2.size() && m_det == DetId::HGCalHSc) || (m_validGeomIds[index].rawId() == 0))
return nullptr;
if (pos == GlobalPoint())
return cellGeomPtr(index);
if (m_det == DetId::HGCalHSc) {
auto cell = std::make_shared<FlatTrd>(m_cellVec2[index]);
cell->setPosition(pos);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "cellGeomPtr " << index << ":" << cell;
#endif
if (nullptr == cell->param())
return nullptr;
return cell;
} else {
auto cell = std::make_shared<FlatHexagon>(m_cellVec[index]);
cell->setPosition(pos);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "cellGeomPtr " << index << ":" << cell;
#endif
if (nullptr == cell->param())
return nullptr;
return cell;
}
}
void HGCalGeometry::addValidID(const DetId& id) {
edm::LogError("HGCalGeom") << "HGCalGeometry::addValidID is not implemented";
}
unsigned int HGCalGeometry::getClosestCellIndex(const GlobalPoint& r) const {
return ((m_det == DetId::HGCalHSc) ? getClosestCellIndex(r, m_cellVec2) : getClosestCellIndex(r, m_cellVec));
}
template <class T>
unsigned int HGCalGeometry::getClosestCellIndex(const GlobalPoint& r, const std::vector<T>& vec) const {
float phip = r.phi();
float zp = r.z();
float dzmin(9999), dphimin(9999), dphi10(0.175);
unsigned int cellIndex = vec.size();
for (unsigned int k = 0; k < vec.size(); ++k) {
float dphi = phip - vec[k].phiPos();
while (dphi > M_PI)
dphi -= 2 * M_PI;
while (dphi <= -M_PI)
dphi += 2 * M_PI;
if (std::abs(dphi) < dphi10) {
float dz = std::abs(zp - vec[k].getPosition().z());
if (dz < (dzmin + 0.001)) {
dzmin = dz;
if (std::abs(dphi) < (dphimin + 0.01)) {
cellIndex = k;
dphimin = std::abs(dphi);
} else {
if (cellIndex >= vec.size())
cellIndex = k;
}
}
}
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "getClosestCellIndex::Input " << zp << ":" << phip << " Index " << cellIndex;
if (cellIndex < vec.size())
edm::LogVerbatim("HGCalGeom") << " Cell z " << vec[cellIndex].getPosition().z() << ":" << dzmin << " phi "
<< vec[cellIndex].phiPos() << ":" << dphimin;
#endif
return cellIndex;
}
// FIXME: Change sorting algorithm if needed
namespace {
struct rawIdSort {
bool operator()(const DetId& a, const DetId& b) { return (a.rawId() < b.rawId()); }
};
} // namespace
void HGCalGeometry::sortDetIds(void) {
m_validIds.shrink_to_fit();
std::sort(m_validIds.begin(), m_validIds.end(), rawIdSort());
}
void HGCalGeometry::getSummary(CaloSubdetectorGeometry::TrVec& trVector,
CaloSubdetectorGeometry::IVec& iVector,
CaloSubdetectorGeometry::DimVec& dimVector,
CaloSubdetectorGeometry::IVec& dinsVector) const {
unsigned int numberOfCells = m_topology.totalGeomModules(); // total Geom Modules both sides
unsigned int numberOfShapes = k_NumberOfShapes;
unsigned int numberOfParametersPerShape = ((m_det == DetId::HGCalHSc) ? (unsigned int)(k_NumberOfParametersPerTrd)
: (unsigned int)(k_NumberOfParametersPerHex));
trVector.reserve(numberOfCells * numberOfTransformParms());
iVector.reserve(numberOfCells);
dimVector.reserve(numberOfShapes * numberOfParametersPerShape);
dinsVector.reserve(numberOfCells);
for (unsigned itr = 0; itr < m_topology.dddConstants().getTrFormN(); ++itr) {
HGCalParameters::hgtrform mytr = m_topology.dddConstants().getTrForm(itr);
int layer = mytr.lay;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
for (int wafer = 0; wafer < m_topology.dddConstants().sectors(); ++wafer) {
if (m_topology.dddConstants().waferInLayer(wafer, layer, true)) {
HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(wafer, true, true);
ParmVec params(numberOfParametersPerShape, 0);
params[FlatHexagon::k_dZ] = vol.dz;
params[FlatHexagon::k_r] = vol.cellSize;
params[FlatHexagon::k_R] = twoBysqrt3_ * params[FlatHexagon::k_r];
dimVector.insert(dimVector.end(), params.begin(), params.end());
}
}
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
int indx = m_topology.dddConstants().layerIndex(layer, true);
for (int md = m_topology.dddConstants().getParameter()->firstModule_[indx];
md <= m_topology.dddConstants().getParameter()->lastModule_[indx];
++md) {
HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(md, true, true);
ParmVec params(numberOfParametersPerShape, 0);
params[FlatTrd::k_dZ] = vol.dz;
params[FlatTrd::k_Theta] = params[FlatTrd::k_Phi] = 0;
params[FlatTrd::k_dY1] = params[FlatTrd::k_dY2] = vol.h;
params[FlatTrd::k_dX1] = params[FlatTrd::k_dX3] = vol.bl;
params[FlatTrd::k_dX2] = params[FlatTrd::k_dX4] = vol.tl;
params[FlatTrd::k_Alp1] = params[FlatTrd::k_Alp2] = vol.alpha;
params[FlatTrd::k_Cell] = vol.cellSize;
dimVector.insert(dimVector.end(), params.begin(), params.end());
}
} else {
for (int wafer = 0; wafer < m_topology.dddConstants().sectors(); ++wafer) {
if (m_topology.dddConstants().waferInLayer(wafer, layer, true)) {
HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(wafer, true, true);
ParmVec params(numberOfParametersPerShape, 0);
params[FlatHexagon::k_dZ] = vol.dz;
params[FlatHexagon::k_r] = vol.cellSize;
params[FlatHexagon::k_R] = twoBysqrt3_ * params[FlatHexagon::k_r];
dimVector.insert(dimVector.end(), params.begin(), params.end());
}
}
}
}
for (unsigned int i(0); i < numberOfCells; ++i) {
DetId detId = m_validGeomIds[i];
int layer(0);
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
layer = HGCalDetId(detId).layer();
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
layer = HGCScintillatorDetId(detId).layer();
} else if (m_topology.isHFNose()) {
layer = HFNoseDetId(detId).layer();
} else {
layer = HGCSiliconDetId(detId).layer();
}
dinsVector.emplace_back(m_topology.detId2denseGeomId(detId));
iVector.emplace_back(layer);
Tr3D tr;
auto ptr = cellGeomPtr(i);
if (nullptr != ptr) {
ptr->getTransform(tr, (Pt3DVec*)nullptr);
if (Tr3D() == tr) { // there is no rotation
const GlobalPoint& gp(ptr->getPosition());
tr = HepGeom::Translate3D(gp.x(), gp.y(), gp.z());
}
const CLHEP::Hep3Vector tt(tr.getTranslation());
trVector.emplace_back(tt.x());
trVector.emplace_back(tt.y());
trVector.emplace_back(tt.z());
if (6 == numberOfTransformParms()) {
const CLHEP::HepRotation rr(tr.getRotation());
const ROOT::Math::Transform3D rtr(
rr.xx(), rr.xy(), rr.xz(), tt.x(), rr.yx(), rr.yy(), rr.yz(), tt.y(), rr.zx(), rr.zy(), rr.zz(), tt.z());
ROOT::Math::EulerAngles ea;
rtr.GetRotation(ea);
trVector.emplace_back(ea.Phi());
trVector.emplace_back(ea.Theta());
trVector.emplace_back(ea.Psi());
}
}
}
}
DetId HGCalGeometry::getGeometryDetId(DetId detId) const {
DetId geomId;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
geomId = static_cast<DetId>(HGCalDetId(detId).geometryCell());
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
geomId = static_cast<DetId>(HGCScintillatorDetId(detId).geometryCell());
} else if (m_topology.isHFNose()) {
geomId = static_cast<DetId>(HFNoseDetId(detId).geometryCell());
} else {
geomId = static_cast<DetId>(HGCSiliconDetId(detId).geometryCell());
}
return geomId;
}
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(HGCalGeometry);
| 44.166881 | 120 | 0.602627 | tklijnsma |
3377c4fe87b370c2b62636485d384f0a7bfa2d26 | 2,764 | hpp | C++ | include/sprout/range/adaptor/reversed.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/range/adaptor/reversed.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/range/adaptor/reversed.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_RANGE_ADAPTOR_REVERSED_HPP
#define SPROUT_RANGE_ADAPTOR_REVERSED_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/container/traits.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/iterator/reverse_iterator.hpp>
#include <sprout/range/adaptor/detail/adapted_range_default.hpp>
#include <sprout/type_traits/lvalue_reference.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/utility/lvalue_forward.hpp>
namespace sprout {
namespace adaptors {
//
// reversed_range
//
template<typename Range>
class reversed_range
: public sprout::adaptors::detail::adapted_range_default<
Range,
sprout::reverse_iterator<typename sprout::container_traits<Range>::iterator>
>
{
public:
typedef sprout::adaptors::detail::adapted_range_default<
Range,
sprout::reverse_iterator<typename sprout::container_traits<Range>::iterator>
> base_type;
typedef typename base_type::range_type range_type;
typedef typename base_type::iterator iterator;
public:
SPROUT_CONSTEXPR reversed_range() SPROUT_DEFAULTED_DEFAULT_CONSTRUCTOR_DECL
reversed_range(reversed_range const&) = default;
explicit SPROUT_CONSTEXPR reversed_range(range_type& range)
: base_type(
iterator(sprout::end(range)),
iterator(sprout::begin(range))
)
{}
};
//
// reversed_forwarder
//
class reversed_forwarder {};
//
// reversed
//
namespace {
SPROUT_STATIC_CONSTEXPR sprout::adaptors::reversed_forwarder reversed = {};
} // anonymous-namespace
//
// operator|
//
template<typename Range>
inline SPROUT_CONSTEXPR sprout::adaptors::reversed_range<
typename std::remove_reference<typename sprout::lvalue_reference<Range>::type>::type
>
operator|(Range&& lhs, sprout::adaptors::reversed_forwarder) {
return sprout::adaptors::reversed_range<
typename std::remove_reference<typename sprout::lvalue_reference<Range>::type>::type
>(
sprout::lvalue_forward<Range>(lhs)
);
}
} // namespace adaptors
//
// container_construct_traits
//
template<typename Range>
struct container_construct_traits<sprout::adaptors::reversed_range<Range> >
: public sprout::container_construct_traits<typename sprout::adaptors::reversed_range<Range>::base_type>
{};
} // namespace sprout
#endif // #ifndef SPROUT_RANGE_ADAPTOR_REVERSED_HPP
| 31.05618 | 106 | 0.709479 | thinkoid |
33782bfb7cfbdce14ac6dbc52b9be958ce0ed8dc | 181 | cpp | C++ | VisceralCombatEngine/src/VCE/Renderer/RenderCommand.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null | VisceralCombatEngine/src/VCE/Renderer/RenderCommand.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null | VisceralCombatEngine/src/VCE/Renderer/RenderCommand.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null | #include "vcepch.h"
#include "RenderCommand.h"
#include "Platform/OpenGL/OpenGLRendererAPI.h"
namespace VCE {
RendererAPI* RenderCommand::s_RendererAPI = new OpenGLRendererAPI;
} | 22.625 | 67 | 0.790055 | celestialkey |
3378ca8ab9cff2eb2f2ba1cbcba5f8f9e8d4bc8d | 797 | cpp | C++ | 0139 Word Break/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | 1 | 2019-12-19T04:13:15.000Z | 2019-12-19T04:13:15.000Z | 0139 Word Break/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | null | null | null | 0139 Word Break/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);//dp表示字符之间的隔板,n个字符有n+1个隔板
dp[0] = true;//dp[0]是s[0]前面的隔板
for (int i = 1; i <= s.size(); i ++)
{
for (int j = i; j >= 0; j --)
{
if(dict.count(s.substr(j,i - j)) && dp[j])
{
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};
int main(){
string s = "leetcode";
vector<string> wordDict{"leet", "code"};
cout << Solution().wordBreak(s, wordDict) << endl;
return 0;
} | 25.709677 | 70 | 0.460477 | Aden-Tao |
337a5ca724a532b719ac2574692b24f9b9005041 | 1,236 | cpp | C++ | joins/src/generators/uniform_generator.cpp | wagjamin/HashJoins | 143ef7a90d8226ce26b8a5e2ec1be33af0f00d74 | [
"MIT"
] | 1 | 2022-01-08T05:55:07.000Z | 2022-01-08T05:55:07.000Z | joins/src/generators/uniform_generator.cpp | wagjamin/HashJoins | 143ef7a90d8226ce26b8a5e2ec1be33af0f00d74 | [
"MIT"
] | null | null | null | joins/src/generators/uniform_generator.cpp | wagjamin/HashJoins | 143ef7a90d8226ce26b8a5e2ec1be33af0f00d74 | [
"MIT"
] | 1 | 2020-05-08T03:58:17.000Z | 2020-05-08T03:58:17.000Z | //
// Benjamin Wagner 2018
//
#include "generators/uniform_generator.h"
#include <random>
namespace generators {
uniform_generator::uniform_generator(size_t min, uint64_t max, uint64_t count):
built(false), min(min), max(max), count (count), data() {
// Generate a pseudo random seed value
std::random_device rd;
seed = rd();
}
uniform_generator::uniform_generator(size_t min, uint64_t max, uint64_t count, uint64_t seed):
built(false), min(min), max(max), count (count), seed(seed), data()
{}
void uniform_generator::build() {
std::mt19937 gen(seed);
std::uniform_int_distribution<uint64_t> dis(min, max);
data.reserve(count);
built = true;
for(uint64_t i = 0; i < count; ++i){
uint64_t val = dis(gen);
data.emplace_back(val, i);
}
}
std::vector<std::tuple<uint64_t, uint64_t>> uniform_generator::get_vec_copy() {
if(!built){
throw std::logic_error("copying may not be called before distribution has been built.");
}
return data;
}
uint64_t uniform_generator::get_count() {
return count;
}
} // namespace generators
| 24.235294 | 100 | 0.604369 | wagjamin |
337b718539ddfe0f1fc0481bc8ceb14308fa1609 | 29,280 | cpp | C++ | include/aegis/impl/guild.cpp | willem640/aegis.cpp | 8b560dc641c5c941c9474bec171999ca4b2c4108 | [
"X11"
] | null | null | null | include/aegis/impl/guild.cpp | willem640/aegis.cpp | 8b560dc641c5c941c9474bec171999ca4b2c4108 | [
"X11"
] | null | null | null | include/aegis/impl/guild.cpp | willem640/aegis.cpp | 8b560dc641c5c941c9474bec171999ca4b2c4108 | [
"X11"
] | null | null | null | //
// guild.cpp
// *********
//
// Copyright (c) 2019 Sharon W (sharon at aegis dot gg)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//
#include "aegis/guild.hpp"
#include <string>
#include <memory>
#include "aegis/core.hpp"
#include "aegis/member.hpp"
#include "aegis/channel.hpp"
#include "aegis/error.hpp"
#include "aegis/shards/shard.hpp"
#include "aegis/ratelimit/ratelimit.hpp"
namespace aegis
{
using json = nlohmann::json;
AEGIS_DECL guild::guild(const int32_t _shard_id, const snowflake _id, core * _bot, asio::io_context & _io)
: shard_id(_shard_id)
, guild_id(_id)
, _bot(_bot)
, _io_context(_io)
{
}
AEGIS_DECL guild::~guild()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
//TODO: remove guilds from members elsewhere when bot is removed from guild
// if (get_bot().get_state() != Shutdown)
// for (auto & v : members)
// v.second->leave(guild_id);
#endif
}
AEGIS_DECL core & guild::get_bot() const noexcept
{
return *_bot;
}
#if !defined(AEGIS_DISABLE_ALL_CACHE)
AEGIS_DECL member * guild::self() const
{
return get_bot().self();
}
AEGIS_DECL void guild::add_member(member * _member) noexcept
{
members.emplace(_member->_member_id, _member);
}
AEGIS_DECL void guild::remove_member(snowflake member_id) noexcept
{
auto _member = members.find(member_id);
if (_member == members.end())
{
AEGIS_DEBUG(get_bot().log, "Unable to remove member [{}] from guild [{}] (does not exist)", member_id, guild_id);
return;
}
_member->second->leave(guild_id);
members.erase(member_id);
}
AEGIS_DECL bool guild::member_has_role(snowflake member_id, snowflake role_id) const noexcept
{
std::shared_lock<shared_mutex> l(_m);
auto _member = find_member(member_id);
if (_member == nullptr)
return false;
auto & gi = _member->get_guild_info(guild_id);
auto it = std::find_if(std::begin(gi.roles), std::end(gi.roles), [&](const snowflake & id)
{
if (id == role_id)
return true;
return false;
});
if (it != std::end(gi.roles))
return true;
return false;
}
AEGIS_DECL void guild::load_presence(const json & obj) noexcept
{
json user = obj["user"];
auto _member = _find_member(user["id"]);
if (_member == nullptr)
return;
using user_status = aegis::gateway::objects::presence::user_status;
const std::string & sts = obj["status"];
if (sts == "idle")
_member->_status = user_status::Idle;
else if (sts == "dnd")
_member->_status = user_status::DoNotDisturb;
else if (sts == "online")
_member->_status = user_status::Online;
else
_member->_status = user_status::Offline;
}
AEGIS_DECL void guild::load_role(const json & obj) noexcept
{
snowflake role_id = obj["id"];
if (!roles.count(role_id))
roles.emplace(role_id, gateway::objects::role());
auto & _role = roles[role_id];
_role.role_id = role_id;
_role.hoist = obj["hoist"];
_role.managed = obj["managed"];
_role.mentionable = obj["mentionable"];
_role._permission = permission(obj["permissions"].get<uint64_t>());
_role.position = obj["position"];
if (!obj["name"].is_null()) _role.name = obj["name"].get<std::string>();
_role.color = obj["color"];
}
AEGIS_DECL const snowflake guild::get_owner() const noexcept
{
return owner_id;
}
AEGIS_DECL member * guild::find_member(snowflake member_id) const noexcept
{
std::shared_lock<shared_mutex> l(_m);
auto m = members.find(member_id);
if (m == members.end())
return nullptr;
return m->second;
}
AEGIS_DECL member * guild::_find_member(snowflake member_id) const noexcept
{
auto m = members.find(member_id);
if (m == members.end())
return nullptr;
return m->second;
}
AEGIS_DECL channel * guild::find_channel(snowflake channel_id) const noexcept
{
std::shared_lock<shared_mutex> l(_m);
auto m = channels.find(channel_id);
if (m == channels.end())
return nullptr;
return m->second;
}
AEGIS_DECL channel * guild::_find_channel(snowflake channel_id) const noexcept
{
auto m = channels.find(channel_id);
if (m == channels.end())
return nullptr;
return m->second;
}
AEGIS_DECL permission guild::get_permissions(snowflake member_id, snowflake channel_id) noexcept
{
if (!members.count(member_id) || !channels.count(channel_id))
return 0;
return get_permissions(find_member(member_id), find_channel(channel_id));
}
AEGIS_DECL permission guild::get_permissions(member * _member, channel * _channel) noexcept
{
if (_member == nullptr || _channel == nullptr)
return 0;
int64_t _base_permissions = base_permissions(_member);
return compute_overwrites(_base_permissions, *_member, *_channel);
}
AEGIS_DECL int64_t guild::base_permissions(member & _member) const noexcept
{
try
{
if (owner_id == _member._member_id)
return ~0;
auto & role_everyone = get_role(guild_id);
int64_t permissions = role_everyone._permission.get_allow_perms();
auto g = _member.get_guild_info(guild_id);
for (auto & rl : g.roles)
permissions |= get_role(rl)._permission.get_allow_perms();
if (permissions & 0x8)//admin
return ~0;
return permissions;
}
catch (std::out_of_range &)
{
return 0;
}
catch (std::exception & e)
{
_bot->log->error(fmt::format("guild::base_permissions() [{}]", e.what()));
return 0;
}
catch (...)
{
_bot->log->error("guild::base_permissions uncaught");
return 0;
}
}
AEGIS_DECL int64_t guild::compute_overwrites(int64_t _base_permissions, member & _member, channel & _channel) const noexcept
{
try
{
if (_base_permissions & 0x8)//admin
return ~0;
int64_t permissions = _base_permissions;
if (_channel.overrides.count(guild_id))
{
auto & overwrite_everyone = _channel.overrides[guild_id];
permissions &= ~overwrite_everyone.deny;
permissions |= overwrite_everyone.allow;
}
auto & overwrites = _channel.overrides;
int64_t allow = 0;
int64_t deny = 0;
auto g = _member.get_guild_info(guild_id);
for (auto & rl : g.roles)
{
if (rl == guild_id)
continue;
if (overwrites.count(rl))
{
auto & ow_role = overwrites[rl];
allow |= ow_role.allow;
deny |= ow_role.deny;
}
}
permissions &= ~deny;
permissions |= allow;
if (overwrites.count(_member._member_id))
{
auto & ow_role = overwrites[_member._member_id];
permissions &= ~ow_role.deny;
permissions |= ow_role.allow;
}
return permissions;
}
catch (std::exception &)
{
return 0;
}
}
AEGIS_DECL const gateway::objects::role & guild::get_role(int64_t r) const
{
std::shared_lock<shared_mutex> l(_m);
for (auto & kv : roles)
if (kv.second.role_id == r)
return kv.second;
throw std::out_of_range(fmt::format("G: {} role:[{}] does not exist", guild_id, r));
}
AEGIS_DECL void guild::remove_role(snowflake role_id)
{
std::unique_lock<shared_mutex> l(_m);
try
{
for (auto & kv : members)
{
auto g = kv.second->get_guild_info(guild_id);
for (auto & rl : g.roles)
{
if (rl == role_id)
{
auto it = std::find(g.roles.begin(), g.roles.end(), role_id);
if (it != g.roles.end())
g.roles.erase(it);
break;
}
}
}
roles.erase(role_id);
}
catch (std::out_of_range &)
{
}
}
AEGIS_DECL int32_t guild::get_member_count() const noexcept
{
return static_cast<int32_t>(members.size());
}
AEGIS_DECL void guild::load(const json & obj, shards::shard * _shard) noexcept
{
//uint64_t application_id = obj->get("application_id").convert<uint64_t>();
snowflake g_id = obj["id"];
shard_id = _shard->get_id();
is_init = false;
core & bot = get_bot();
try
{
json voice_states;
if (!obj["name"].is_null()) name = obj["name"].get<std::string>();
if (!obj["icon"].is_null()) icon = obj["icon"].get<std::string>();
if (!obj["splash"].is_null()) splash = obj["splash"].get<std::string>();
owner_id = obj["owner_id"];
region = obj["region"].get<std::string>();
if (!obj["afk_channel_id"].is_null()) afk_channel_id = obj["afk_channel_id"];
afk_timeout = obj["afk_timeout"];//in seconds
if (obj.count("embed_enabled") && !obj["embed_enabled"].is_null()) embed_enabled = obj["embed_enabled"];
//_guild.embed_channel_id = obj->get("embed_channel_id").convert<uint64_t>();
verification_level = obj["verification_level"];
default_message_notifications = obj["default_message_notifications"];
mfa_level = obj["mfa_level"];
if (obj.count("joined_at") && !obj["joined_at"].is_null()) joined_at = obj["joined_at"].get<std::string>();
if (obj.count("large") && !obj["large"].is_null()) large = obj["large"];
if (obj.count("unavailable") && !obj["unavailable"].is_null())
unavailable = obj["unavailable"];
else
unavailable = false;
if (obj.count("member_count") && !obj["member_count"].is_null()) member_count = obj["member_count"];
if (obj.count("voice_states") && !obj["voice_states"].is_null()) voice_states = obj["voice_states"];
if (obj.count("roles"))
{
const json & roles = obj["roles"];
for (auto & role : roles)
{
load_role(role);
}
}
if (obj.count("members"))
{
const json & members = obj["members"];
for (auto & member : members)
{
snowflake member_id = member["user"]["id"];
auto _member = bot.member_create(member_id);
std::unique_lock<shared_mutex> l(_member->mtx());
_member->load(this, member, _shard);
this->members.emplace(member_id, _member);
}
}
if (obj.count("channels"))
{
const json & channels = obj["channels"];
for (auto & channel_obj : channels)
{
snowflake channel_id = channel_obj["id"];
auto _channel = bot.channel_create(channel_id);
_channel->load_with_guild(*this, channel_obj, _shard);
_channel->guild_id = guild_id;
_channel->_guild = this;
this->channels.emplace(channel_id, _channel);
}
}
if (obj.count("presences"))
{
const json & presences = obj["presences"];
for (auto & presence : presences)
{
load_presence(presence);
}
}
if (obj.count("emojis"))
{
const json & emojis = obj["emojis"];
/*for (auto & emoji : emojis)
{
//loadEmoji(emoji, _guild);
}*/
}
if (obj.count("features"))
{
const json & features = obj["features"];
}
/*
for (auto & feature : features)
{
//??
}
for (auto & voicestate : voice_states)
{
//no voice yet
}*/
}
catch (std::exception&e)
{
spdlog::get("aegis")->error("Shard#{} : Error processing guild[{}] {}", _shard->get_id(), g_id, (std::string)e.what());
}
}
#else
AEGIS_DECL void guild::load(const json & obj, shards::shard * _shard) noexcept
{
//uint64_t application_id = obj->get("application_id").convert<uint64_t>();
snowflake g_id = obj["id"];
shard_id = _shard->get_id();
core & bot = get_bot();
try
{
if (obj.count("channels"))
{
const json & channels = obj["channels"];
for (auto & channel_obj : channels)
{
snowflake channel_id = channel_obj["id"];
auto _channel = bot.channel_create(channel_id);
_channel->load_with_guild(*this, channel_obj, _shard);
_channel->guild_id = guild_id;
_channel->_guild = this;
this->channels.emplace(channel_id, _channel);
}
}
}
catch (std::exception&e)
{
spdlog::get("aegis")->error("Shard#{} : Error processing guild[{}] {}", _shard->get_id(), g_id, (std::string)e.what());
}
}
#endif
AEGIS_DECL void guild::remove_channel(snowflake channel_id) noexcept
{
auto it = channels.find(channel_id);
if (it == channels.end())
{
AEGIS_DEBUG(get_bot().log, "Unable to remove channel [{}] from guild [{}] (does not exist)", channel_id, guild_id);
return;
}
channels.erase(it);
}
AEGIS_DECL channel * guild::get_channel(snowflake id) const noexcept
{
std::shared_lock<shared_mutex> l(_m);
auto it = channels.find(id);
if (it == channels.end())
return nullptr;
return it->second;
}
/**\todo Incomplete. Signature may change. Location may change.
*/
AEGIS_DECL aegis::future<gateway::objects::guild> guild::get_guild()
{
return _bot->get_ratelimit().post_task<gateway::objects::guild>({ fmt::format("/guilds/{}", guild_id), rest::Get });
}
AEGIS_DECL aegis::future<gateway::objects::guild> guild::modify_guild(lib::optional<std::string> name, lib::optional<std::string> voice_region, lib::optional<int> verification_level,
lib::optional<int> default_message_notifications, lib::optional<int> explicit_content_filter, lib::optional<snowflake> afk_channel_id, lib::optional<int> afk_timeout,
lib::optional<std::string> icon, lib::optional<snowflake> owner_id, lib::optional<std::string> splash)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if ((!perms().can_manage_guild()) || (owner_id.has_value() && owner_id != self()->_member_id))
return aegis::make_exception_future<gateway::objects::guild>(error::no_permission);
#endif
json obj;
if (name.has_value())
obj["name"] = name.value();
if (voice_region.has_value())
obj["region"] = voice_region.value();
if (verification_level.has_value())
obj["verification_level"] = verification_level.value();
if (default_message_notifications.has_value())
obj["default_message_notifications"] = default_message_notifications.value();
if (verification_level.has_value())
obj["explicit_content_filter"] = verification_level.value();
if (afk_channel_id.has_value())
obj["afk_channel_id"] = afk_channel_id.value();
if (afk_timeout.has_value())
obj["afk_timeout"] = afk_timeout.value();
if (icon.has_value())
obj["icon"] = icon.value();
if (owner_id.has_value())//requires OWNER
obj["owner_id"] = owner_id.value();
if (splash.has_value())//VIP only
obj["splash"] = splash.value();
return _bot->get_ratelimit().post_task<gateway::objects::guild>({ fmt::format("/guilds/{}", guild_id), rest::Patch, obj.dump() });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
//requires OWNER
if (owner_id != self()->_member_id)
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}", guild_id), rest::Delete });
}
AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_text_channel(const std::string & name,
int64_t parent_id, bool nsfw, const std::vector<gateway::objects::permission_overwrite> & permission_overwrites)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
//requires MANAGE_CHANNELS
if (!perms().can_manage_channels())
return aegis::make_exception_future<gateway::objects::channel>(error::no_permission);
#endif
json obj;
obj["name"] = name;
obj["type"] = 0;
obj["parent_id"] = parent_id;
obj["nsfw"] = nsfw;
obj["permission_overwrites"] = json::array();
for (auto & p_ow : permission_overwrites)
{
obj["permission_overwrites"].push_back(p_ow);
}
return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() });
}
AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_voice_channel(const std::string & name,
int32_t bitrate, int32_t user_limit, int64_t parent_id,
const std::vector<gateway::objects::permission_overwrite> & permission_overwrites)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_channels())
return aegis::make_exception_future<gateway::objects::channel>(error::no_permission);
#endif
json obj;
obj["name"] = name;
obj["type"] = 2;
obj["bitrate"] = bitrate;
obj["user_limit"] = user_limit;
obj["parent_id"] = parent_id;
obj["permission_overwrites"] = json::array();
for (auto & p_ow : permission_overwrites)
{
obj["permission_overwrites"].push_back(p_ow);
}
return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() });
}
AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_category_channel(const std::string & name,
int64_t parent_id, const std::vector<gateway::objects::permission_overwrite> & permission_overwrites)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_channels())
return aegis::make_exception_future<gateway::objects::channel>(error::no_permission);
#endif
json obj;
obj["name"] = name;
obj["type"] = 4;
obj["permission_overwrites"] = json::array();
for (auto & p_ow : permission_overwrites)
{
obj["permission_overwrites"].push_back(p_ow);
}
return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() });
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_channel_positions()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_channels())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
AEGIS_DECL aegis::future<gateway::objects::member> guild::modify_guild_member(snowflake user_id, lib::optional<std::string> nick, lib::optional<bool> mute,
lib::optional<bool> deaf, lib::optional<std::vector<snowflake>> roles, lib::optional<snowflake> channel_id)
{
json obj;
#if !defined(AEGIS_DISABLE_ALL_CACHE)
permission perm = perms();
if (nick.has_value())
{
if (!perm.can_manage_names())
return aegis::make_exception_future<gateway::objects::member>(error::no_permission);
obj["nick"] = nick.value();//requires MANAGE_NICKNAMES
}
if (mute.has_value())
{
if (!perm.can_voice_mute())
return aegis::make_exception_future<gateway::objects::member>(error::no_permission);
obj["mute"] = mute.value();//requires MUTE_MEMBERS
}
if (deaf.has_value())
{
if (!perm.can_voice_deafen())
return aegis::make_exception_future<gateway::objects::member>(error::no_permission);
obj["deaf"] = deaf.value();//requires DEAFEN_MEMBERS
}
if (roles.has_value())
{
if (!perm.can_manage_roles())
return aegis::make_exception_future<gateway::objects::member>(error::no_permission);
obj["roles"] = roles.value();//requires MANAGE_ROLES
}
if (channel_id.has_value())
{
//TODO: This needs to calculate whether or not the bot has access to the voice channel as well
if (!perm.can_voice_move())
return aegis::make_exception_future<gateway::objects::member>(error::no_permission);
obj["channel_id"] = channel_id.value();//requires MOVE_MEMBERS
}
#else
if (nick.has_value())
obj["nick"] = nick.value();//requires MANAGE_NICKNAMES
if (mute.has_value())
obj["mute"] = mute.value();//requires MUTE_MEMBERS
if (deaf.has_value())
obj["deaf"] = deaf.value();//requires DEAFEN_MEMBERS
if (roles.has_value())
obj["roles"] = roles.value();//requires MANAGE_ROLES
if (channel_id.has_value())
obj["channel_id"] = channel_id.value();//requires MOVE_MEMBERS
#endif
return _bot->get_ratelimit().post_task<gateway::objects::member>({ fmt::format("/guilds/{}/members/{}", guild_id, user_id), rest::Patch, obj.dump() });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_my_nick(const std::string & newname)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_change_name())
return aegis::make_exception_future(error::no_permission);
#endif
json obj = { { "nick", newname } };
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/@me/nick", guild_id), rest::Patch, obj.dump() });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::add_guild_member_role(snowflake user_id, snowflake role_id)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}/roles/{}", guild_id, user_id, role_id), rest::Put });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_member_role(snowflake user_id, snowflake role_id)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}/roles/{}", guild_id, user_id, role_id), rest::Delete });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_member(snowflake user_id)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_kick())
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}", guild_id, user_id), rest::Delete });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::create_guild_ban(snowflake user_id, int8_t delete_message_days, const std::string & reason)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_ban())
return aegis::make_exception_future(error::no_permission);
#endif
std::string query_params = fmt::format("?delete-message-days={}", delete_message_days);
if (!reason.empty())
query_params += fmt::format("&reason={}", utility::url_encode(reason));
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/bans/{}", guild_id, user_id), rest::Put, {}, {}, {}, {}, query_params });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_ban(snowflake user_id)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_ban())
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/bans/{}", guild_id, user_id), rest::Delete });
}
AEGIS_DECL aegis::future<gateway::objects::role> guild::create_guild_role(const std::string & name, permission _perms, int32_t color, bool hoist, bool mentionable)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future<gateway::objects::role>(error::no_permission);
#endif
json obj = { { "name", name },{ "permissions", _perms },{ "color", color },{ "hoist", hoist },{ "mentionable", mentionable } };
return _bot->get_ratelimit().post_task<gateway::objects::role>({ fmt::format("/guilds/{}/roles", guild_id), rest::Post, obj.dump() });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_role_positions(snowflake role_id, int16_t position)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future(error::no_permission);
#endif
json obj = { { "id", role_id },{ "position", position } };
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/roles", guild_id), rest::Patch, obj.dump() });
}
AEGIS_DECL aegis::future<gateway::objects::role> guild::modify_guild_role(snowflake role_id, const std::string & name, permission _perms, int32_t color, bool hoist, bool mentionable)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future<gateway::objects::role>(error::no_permission);
#endif
json obj = { { "name", name },{ "permissions", _perms },{ "color", color },{ "hoist", hoist },{ "mentionable", mentionable } };
return _bot->get_ratelimit().post_task<gateway::objects::role>({ fmt::format("/guilds/{}/roles/{}", guild_id, role_id), rest::Post, obj.dump() });
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild_role(snowflake role_id)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_roles())
return aegis::make_exception_future(error::no_permission);
#endif
return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/roles/{}", guild_id, role_id), rest::Delete });
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_prune_count(int16_t days)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_kick())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::begin_guild_prune(int16_t days)
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_kick())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_invites()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_integrations()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::create_guild_integration()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_integration()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild_integration()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::sync_guild_integration()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_embed()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
/**\todo Incomplete. Signature may change
*/
AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_embed()
{
#if !defined(AEGIS_DISABLE_ALL_CACHE)
if (!perms().can_manage_guild())
return aegis::make_exception_future(error::no_permission);
#endif
return aegis::make_exception_future(error::not_implemented);
}
AEGIS_DECL aegis::future<rest::rest_reply> guild::leave()
{
return _bot->get_ratelimit().post_task({ fmt::format("/users/@me/guilds/{0}", guild_id), rest::Delete });
}
}
| 32.533333 | 186 | 0.645048 | willem640 |
337d99d360949b5d94b5b3af654da0c7c8ce1e4b | 1,597 | hpp | C++ | src/core/level/graph.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | src/core/level/graph.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | src/core/level/graph.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | #pragma once
#include <vector>
#include <spdlog/spdlog.h>
struct graphNode {
graphNode(int x, int y) : x(x), y(y) {}
int x;
int y;
};
struct graphEdge {
graphEdge(int neighbourIndex, float dist) : neighbourIndex(neighbourIndex), dist(dist) {}
int neighbourIndex;
float dist;
};
class Graph {
public:
Graph();
~Graph();
//Getters
int getNodesCount();
graphNode getNode(int nodeIndex);
int nodeIndex(int x, int y);
std::vector<int> getStartNodes();
int getStartNodeRandom();
int getEndNode();
std::vector<graphEdge>* getNeighbours(int nodeIndex);
//Setters
int addNode(int x, int y); //Returns the index at which the node was inserted
void addStartNode(int nodeIndex);
void addEndNode(int nodeIndex);
void addNeighbourTo(int node, int neighbour, float dist);
void addNeighbourTo(int node, int neighbour, float dist, bool checkRepetitions);
void addNeighbouring(int node1, int node2, float dist);
void addNeighbouring(int node1, int node2, float dist, bool checkRepetitions);
bool isNeighbourOf(int node, int potentialNeighbour);
float distEstimator(int node1);
float distEstimator(int node1, int node2);
int pickNextNode(int currentNode, int previousNode); //WARNING : should only be used if it is a stochastic graph ! (i.e. wheights of edges starting from a given node always add up to 1)
//std::vector<int> trajectory(int startNode, int endNode);
private:
std::vector<graphNode> nodes;
std::vector<int> startNodeIndexes;
int endNodeIndex;
std::vector<std::vector<graphEdge>*> adjencyLists;
//void addNodeToList(graphEdgeList** list, int value, float dist);
}; | 32.591837 | 186 | 0.745773 | guillaume-haerinck |
337ff47c0be48b980a20638b4332ce25cd37f980 | 1,765 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_LegendBody.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_LegendBody.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_LegendBody.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #include "ag_LegendBody.h"
#include <QApplication>
/*!
\file
This file contains the implementation of the LegendBody class.
*/
namespace ag {
//------------------------------------------------------------------------------
// DEFINITION OF STATIC CLASS MEMBERS
//------------------------------------------------------------------------------
int LegendBody::d_ticLength(2);
QSize LegendBody::d_keySize(20, 10);
QSize LegendBody::d_labelOffset(5, 5);
//! Returns the length of a tic.
/*!
\return Length of tic.
*/
int LegendBody::ticLength()
{
return d_ticLength;
}
//! Returns the size of a key.
/*!
\return Size of key.
*/
QSize const& LegendBody::keySize()
{
return d_keySize;
}
//! Returns the offset of the labels.
/*!
\return Offset of labels.
*/
QSize const& LegendBody::labelOffset()
{
return d_labelOffset;
}
//------------------------------------------------------------------------------
// DEFINITION OF CLASS MEMBERS
//------------------------------------------------------------------------------
//! Constructor.
/*!
\param parent Parent.
*/
LegendBody::LegendBody(
ViewerType type,
QWidget* parent)
: QWidget(parent),
d_type(type)
{
}
//! Destructor.
/*!
*/
LegendBody::~LegendBody()
{
}
ViewerType LegendBody::viewerType() const
{
return d_type;
}
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
} // namespace ag
| 16.495327 | 80 | 0.415297 | quanpands |
33815308bd8d30f2771ee2020bb087d87e69c96d | 22,259 | cpp | C++ | extras/jbcoin-libpp/extras/jbcoind/src/jbcoin/json/impl/json_reader.cpp | trongnmchainos/validator-keys-tool | cae131d6ab46051c0f47509b79b6efc47a70eec0 | [
"BSL-1.0"
] | 2 | 2020-03-03T12:46:29.000Z | 2020-11-14T09:52:14.000Z | extras/jbcoin-libpp/extras/jbcoind/src/jbcoin/json/impl/json_reader.cpp | trongnmchainos/validator-keys-tool | cae131d6ab46051c0f47509b79b6efc47a70eec0 | [
"BSL-1.0"
] | null | null | null | extras/jbcoin-libpp/extras/jbcoind/src/jbcoin/json/impl/json_reader.cpp | trongnmchainos/validator-keys-tool | cae131d6ab46051c0f47509b79b6efc47a70eec0 | [
"BSL-1.0"
] | 1 | 2020-03-03T12:46:30.000Z | 2020-03-03T12:46:30.000Z | //------------------------------------------------------------------------------
/*
This file is part of jbcoind: https://github.com/jbcoin/jbcoind
Copyright (c) 2012, 2013 Jbcoin Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <jbcoin/basics/contract.h>
#include <jbcoin/json/json_reader.h>
#include <algorithm>
#include <string>
#include <cctype>
namespace Json
{
// Implementation of class Reader
// ////////////////////////////////
static
std::string
codePointToUTF8 (unsigned int cp)
{
std::string result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f)
{
result.resize (1);
result[0] = static_cast<char> (cp);
}
else if (cp <= 0x7FF)
{
result.resize (2);
result[1] = static_cast<char> (0x80 | (0x3f & cp));
result[0] = static_cast<char> (0xC0 | (0x1f & (cp >> 6)));
}
else if (cp <= 0xFFFF)
{
result.resize (3);
result[2] = static_cast<char> (0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char> ((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char> ((0xf & (cp >> 12)));
}
else if (cp <= 0x10FFFF)
{
result.resize (4);
result[3] = static_cast<char> (0x80 | (0x3f & cp));
result[2] = static_cast<char> (0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char> (0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char> (0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader ()
{
}
bool
Reader::parse ( std::string const& document,
Value& root)
{
document_ = document;
const char* begin = document_.c_str ();
const char* end = begin + document_.length ();
return parse ( begin, end, root );
}
bool
Reader::parse ( std::istream& sin,
Value& root)
{
//std::istream_iterator<char> begin(sin);
//std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// create an extra copy.
std::string doc;
std::getline (sin, doc, (char)EOF);
return parse ( doc, root );
}
bool
Reader::parse ( const char* beginDoc, const char* endDoc,
Value& root)
{
begin_ = beginDoc;
end_ = endDoc;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
errors_.clear ();
while ( !nodes_.empty () )
nodes_.pop ();
nodes_.push ( &root );
bool successful = readValue ();
Token token;
skipCommentTokens ( token );
if ( !root.isArray () && !root.isObject () )
{
// Set error location to start of doc, ideally should be first token found in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError ( "A valid JSON document must be either an array or an object value.",
token );
return false;
}
return successful;
}
bool
Reader::readValue ()
{
Token token;
skipCommentTokens ( token );
bool successful = true;
switch ( token.type_ )
{
case tokenObjectBegin:
successful = readObject ( token );
break;
case tokenArrayBegin:
successful = readArray ( token );
break;
case tokenInteger:
successful = decodeNumber ( token );
break;
case tokenDouble:
successful = decodeDouble ( token );
break;
case tokenString:
successful = decodeString ( token );
break;
case tokenTrue:
currentValue () = true;
break;
case tokenFalse:
currentValue () = false;
break;
case tokenNull:
currentValue () = Value ();
break;
default:
return addError ( "Syntax error: value, object or array expected.", token );
}
return successful;
}
void
Reader::skipCommentTokens ( Token& token )
{
do
{
readToken ( token );
}
while ( token.type_ == tokenComment );
}
bool
Reader::expectToken ( TokenType type, Token& token, const char* message )
{
readToken ( token );
if ( token.type_ != type )
return addError ( message, token );
return true;
}
bool
Reader::readToken ( Token& token )
{
skipSpaces ();
token.start_ = current_;
Char c = getNextChar ();
bool ok = true;
switch ( c )
{
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString ();
break;
case '/':
token.type_ = tokenComment;
ok = readComment ();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = readNumber ();
break;
case 't':
token.type_ = tokenTrue;
ok = match ( "rue", 3 );
break;
case 'f':
token.type_ = tokenFalse;
ok = match ( "alse", 4 );
break;
case 'n':
token.type_ = tokenNull;
ok = match ( "ull", 3 );
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if ( !ok )
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void
Reader::skipSpaces ()
{
while ( current_ != end_ )
{
Char c = *current_;
if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
++current_;
else
break;
}
}
bool
Reader::match ( Location pattern,
int patternLength )
{
if ( end_ - current_ < patternLength )
return false;
int index = patternLength;
while ( index-- )
if ( current_[index] != pattern[index] )
return false;
current_ += patternLength;
return true;
}
bool
Reader::readComment ()
{
Char c = getNextChar ();
if ( c == '*' )
return readCStyleComment ();
if ( c == '/' )
return readCppStyleComment ();
return false;
}
bool
Reader::readCStyleComment ()
{
while ( current_ != end_ )
{
Char c = getNextChar ();
if ( c == '*' && *current_ == '/' )
break;
}
return getNextChar () == '/';
}
bool
Reader::readCppStyleComment ()
{
while ( current_ != end_ )
{
Char c = getNextChar ();
if ( c == '\r' || c == '\n' )
break;
}
return true;
}
Reader::TokenType
Reader::readNumber ()
{
static char const extended_tokens[] = { '.', 'e', 'E', '+', '-' };
TokenType type = tokenInteger;
if ( current_ != end_ )
{
if (*current_ == '-')
++current_;
while ( current_ != end_ )
{
if (!std::isdigit (*current_))
{
auto ret = std::find (std::begin (extended_tokens),
std::end (extended_tokens), *current_);
if (ret == std::end (extended_tokens))
break;
type = tokenDouble;
}
++current_;
}
}
return type;
}
bool
Reader::readString ()
{
Char c = 0;
while ( current_ != end_ )
{
c = getNextChar ();
if ( c == '\\' )
getNextChar ();
else if ( c == '"' )
break;
}
return c == '"';
}
bool
Reader::readObject ( Token& tokenStart )
{
Token tokenName;
std::string name;
currentValue () = Value ( objectValue );
while ( readToken ( tokenName ) )
{
bool initialTokenOk = true;
while ( tokenName.type_ == tokenComment && initialTokenOk )
initialTokenOk = readToken ( tokenName );
if ( !initialTokenOk )
break;
if ( tokenName.type_ == tokenObjectEnd && name.empty () ) // empty object
return true;
if ( tokenName.type_ != tokenString )
break;
name = "";
if ( !decodeString ( tokenName, name ) )
return recoverFromError ( tokenObjectEnd );
Token colon;
if ( !readToken ( colon ) || colon.type_ != tokenMemberSeparator )
{
return addErrorAndRecover ( "Missing ':' after object member name",
colon,
tokenObjectEnd );
}
// Reject duplicate names
if (currentValue ().isMember (name))
return addError ( "Key '" + name + "' appears twice.", tokenName );
Value& value = currentValue ()[ name ];
nodes_.push ( &value );
bool ok = readValue ();
nodes_.pop ();
if ( !ok ) // error already set
return recoverFromError ( tokenObjectEnd );
Token comma;
if ( !readToken ( comma )
|| ( comma.type_ != tokenObjectEnd &&
comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment ) )
{
return addErrorAndRecover ( "Missing ',' or '}' in object declaration",
comma,
tokenObjectEnd );
}
bool finalizeTokenOk = true;
while ( comma.type_ == tokenComment &&
finalizeTokenOk )
finalizeTokenOk = readToken ( comma );
if ( comma.type_ == tokenObjectEnd )
return true;
}
return addErrorAndRecover ( "Missing '}' or object member name",
tokenName,
tokenObjectEnd );
}
bool
Reader::readArray ( Token& tokenStart )
{
currentValue () = Value ( arrayValue );
skipSpaces ();
if ( *current_ == ']' ) // empty array
{
Token endArray;
readToken ( endArray );
return true;
}
int index = 0;
while ( true )
{
Value& value = currentValue ()[ index++ ];
nodes_.push ( &value );
bool ok = readValue ();
nodes_.pop ();
if ( !ok ) // error already set
return recoverFromError ( tokenArrayEnd );
Token token;
// Accept Comment after last item in the array.
ok = readToken ( token );
while ( token.type_ == tokenComment && ok )
{
ok = readToken ( token );
}
bool badTokenType = ( token.type_ != tokenArraySeparator &&
token.type_ != tokenArrayEnd );
if ( !ok || badTokenType )
{
return addErrorAndRecover ( "Missing ',' or ']' in array declaration",
token,
tokenArrayEnd );
}
if ( token.type_ == tokenArrayEnd )
break;
}
return true;
}
bool
Reader::decodeNumber ( Token& token )
{
Location current = token.start_;
bool isNegative = *current == '-';
if ( isNegative )
++current;
if (current == token.end_)
{
return addError ( "'" + std::string ( token.start_, token.end_ ) +
"' is not a valid number.", token );
}
// The existing Json integers are 32-bit so using a 64-bit value here avoids
// overflows in the conversion code below.
std::int64_t value = 0;
static_assert(sizeof(value) > sizeof(Value::maxUInt),
"The JSON integer overflow logic will need to be reworked.");
while (current < token.end_ && (value <= Value::maxUInt))
{
Char c = *current++;
if ( c < '0' || c > '9' )
{
return addError ( "'" + std::string ( token.start_, token.end_ ) +
"' is not a number.", token );
}
value = (value * 10) + (c - '0');
}
// More tokens left -> input is larger than largest possible return value
if (current != token.end_)
{
return addError ( "'" + std::string ( token.start_, token.end_ ) +
"' exceeds the allowable range.", token );
}
if ( isNegative )
{
value = -value;
if (value < Value::minInt || value > Value::maxInt)
{
return addError ( "'" + std::string ( token.start_, token.end_ ) +
"' exceeds the allowable range.", token );
}
currentValue () = static_cast<Value::Int>( value );
}
else
{
if (value > Value::maxUInt)
{
return addError ( "'" + std::string ( token.start_, token.end_ ) +
"' exceeds the allowable range.", token );
}
// If it's representable as a signed integer, construct it as one.
if ( value <= Value::maxInt )
currentValue () = static_cast<Value::Int>( value );
else
currentValue () = static_cast<Value::UInt>( value );
}
return true;
}
bool
Reader::decodeDouble( Token &token )
{
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
// Sanity check to avoid buffer overflow exploits.
if (length < 0) {
return addError( "Unable to parse token length", token );
}
// Avoid using a string constant for the format control string given to
// sscanf, as this can cause hard to debug crashes on OS X. See here for more
// info:
//
// http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
char format[] = "%lf";
if ( length <= bufferSize )
{
Char buffer[bufferSize+1];
memcpy( buffer, token.start_, length );
buffer[length] = 0;
count = sscanf( buffer, format, &value );
}
else
{
std::string buffer( token.start_, token.end_ );
count = sscanf( buffer.c_str(), format, &value );
}
if ( count != 1 )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
currentValue() = value;
return true;
}
bool
Reader::decodeString ( Token& token )
{
std::string decoded;
if ( !decodeString ( token, decoded ) )
return false;
currentValue () = decoded;
return true;
}
bool
Reader::decodeString ( Token& token, std::string& decoded )
{
decoded.reserve ( token.end_ - token.start_ - 2 );
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while ( current != end )
{
Char c = *current++;
if ( c == '"' )
break;
else if ( c == '\\' )
{
if ( current == end )
return addError ( "Empty escape sequence in string", token, current );
Char escape = *current++;
switch ( escape )
{
case '"':
decoded += '"';
break;
case '/':
decoded += '/';
break;
case '\\':
decoded += '\\';
break;
case 'b':
decoded += '\b';
break;
case 'f':
decoded += '\f';
break;
case 'n':
decoded += '\n';
break;
case 'r':
decoded += '\r';
break;
case 't':
decoded += '\t';
break;
case 'u':
{
unsigned int unicode;
if ( !decodeUnicodeCodePoint ( token, current, end, unicode ) )
return false;
decoded += codePointToUTF8 (unicode);
}
break;
default:
return addError ( "Bad escape sequence in string", token, current );
}
}
else
{
decoded += c;
}
}
return true;
}
bool
Reader::decodeUnicodeCodePoint ( Token& token,
Location& current,
Location end,
unsigned int& unicode )
{
if ( !decodeUnicodeEscapeSequence ( token, current, end, unicode ) )
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF)
{
// surrogate pairs
if (end - current < 6)
return addError ( "additional six characters expected to parse unicode surrogate pair.", token, current );
unsigned int surrogatePair;
if (* (current++) == '\\' && * (current++) == 'u')
{
if (decodeUnicodeEscapeSequence ( token, current, end, surrogatePair ))
{
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
}
else
return false;
}
else
return addError ( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current );
}
return true;
}
bool
Reader::decodeUnicodeEscapeSequence ( Token& token,
Location& current,
Location end,
unsigned int& unicode )
{
if ( end - current < 4 )
return addError ( "Bad unicode escape sequence in string: four digits expected.", token, current );
unicode = 0;
for ( int index = 0; index < 4; ++index )
{
Char c = *current++;
unicode *= 16;
if ( c >= '0' && c <= '9' )
unicode += c - '0';
else if ( c >= 'a' && c <= 'f' )
unicode += c - 'a' + 10;
else if ( c >= 'A' && c <= 'F' )
unicode += c - 'A' + 10;
else
return addError ( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
}
return true;
}
bool
Reader::addError ( std::string const& message,
Token& token,
Location extra )
{
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back ( info );
return false;
}
bool
Reader::recoverFromError ( TokenType skipUntilToken )
{
int errorCount = int (errors_.size ());
Token skip;
while ( true )
{
if ( !readToken (skip) )
errors_.resize ( errorCount ); // discard errors caused by recovery
if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
break;
}
errors_.resize ( errorCount );
return false;
}
bool
Reader::addErrorAndRecover ( std::string const& message,
Token& token,
TokenType skipUntilToken )
{
addError ( message, token );
return recoverFromError ( skipUntilToken );
}
Value&
Reader::currentValue ()
{
return * (nodes_.top ());
}
Reader::Char
Reader::getNextChar ()
{
if ( current_ == end_ )
return 0;
return *current_++;
}
void
Reader::getLocationLineAndColumn ( Location location,
int& line,
int& column ) const
{
Location current = begin_;
Location lastLineStart = current;
line = 0;
while ( current < location && current != end_ )
{
Char c = *current++;
if ( c == '\r' )
{
if ( *current == '\n' )
++current;
lastLineStart = current;
++line;
}
else if ( c == '\n' )
{
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int (location - lastLineStart) + 1;
++line;
}
std::string
Reader::getLocationLineAndColumn ( Location location ) const
{
int line, column;
getLocationLineAndColumn ( location, line, column );
char buffer[18 + 16 + 16 + 1];
sprintf ( buffer, "Line %d, Column %d", line, column );
return buffer;
}
std::string
Reader::getFormatedErrorMessages () const
{
std::string formattedMessage;
for ( Errors::const_iterator itError = errors_.begin ();
itError != errors_.end ();
++itError )
{
const ErrorInfo& error = *itError;
formattedMessage += "* " + getLocationLineAndColumn ( error.token_.start_ ) + "\n";
formattedMessage += " " + error.message_ + "\n";
if ( error.extra_ )
formattedMessage += "See " + getLocationLineAndColumn ( error.extra_ ) + " for detail.\n";
}
return formattedMessage;
}
std::istream& operator>> ( std::istream& sin, Value& root )
{
Json::Reader reader;
bool ok = reader.parse (sin, root);
//JSON_ASSERT( ok );
if (! ok)
jbcoin::Throw<std::runtime_error> (reader.getFormatedErrorMessages ());
return sin;
}
} // namespace Json
| 23.138254 | 131 | 0.508334 | trongnmchainos |
3384423eb091f293f99d66f52a09831939616fde | 32,676 | cpp | C++ | applications/mne_scan/plugins/ssvepbci/ssvepbci.cpp | 13grife37/mne-cpp-swpold | 9b89b3d7fe273d9f4ffd69b504e17f284eaba263 | [
"BSD-3-Clause"
] | 2 | 2017-04-20T20:21:16.000Z | 2017-04-26T16:30:25.000Z | applications/mne_scan/plugins/ssvepbci/ssvepbci.cpp | 13grife37/mne-cpp-swpold | 9b89b3d7fe273d9f4ffd69b504e17f284eaba263 | [
"BSD-3-Clause"
] | null | null | null | applications/mne_scan/plugins/ssvepbci/ssvepbci.cpp | 13grife37/mne-cpp-swpold | 9b89b3d7fe273d9f4ffd69b504e17f284eaba263 | [
"BSD-3-Clause"
] | 1 | 2017-04-23T15:55:31.000Z | 2017-04-23T15:55:31.000Z | //=============================================================================================================
/**
* @file ssvepbci.cpp
* @author Viktor Klüber <viktor.klueber@tu-ilmenau.de>;
* Lorenz Esch <lorenz.esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date May, 2016
*
* @section LICENSE
*
* Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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.
*
*
* @brief Contains the implementation of the BCI class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "ssvepbci.h"
#include <iostream>
#include <Eigen/Dense>
#include <utils/ioutils.h>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QtPlugin>
#include <QtCore/QTextStream>
#include <QDebug>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace SSVEPBCIPLUGIN;
using namespace SCSHAREDLIB;
using namespace SCMEASLIB;
using namespace IOBUFFER;
using namespace FSLIB;
using namespace std;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SsvepBci::SsvepBci()
: m_qStringResourcePath(qApp->applicationDirPath()+"/mne_scan_plugins/resources/ssvepbci/")
, m_bProcessData(false)
, m_dAlpha(0.25)
, m_iNumberOfHarmonics(2)
, m_bUseMEC(true)
, m_bRemovePowerLine(false)
, m_iPowerLine(50)
, m_bChangeSSVEPParameterFlag(false)
, m_bInitializeSource(true)
, m_iNumberOfClassHits(15)
, m_iClassListSize(20)
, m_iNumberOfClassBreaks(30)
{
// Create configuration action bar item/button
m_pActionBCIConfiguration = new QAction(QIcon(":/images/configuration.png"),tr("BCI configuration feature"),this);
m_pActionBCIConfiguration->setStatusTip(tr("BCI configuration feature"));
connect(m_pActionBCIConfiguration, &QAction::triggered, this, &SsvepBci::showBCIConfiguration);
addPluginAction(m_pActionBCIConfiguration);
// Create start Stimuli action bar item/button
m_pActionSetupStimulus = new QAction(QIcon(":/images/stimulus.png"),tr("setup stimulus feature"),this);
m_pActionSetupStimulus->setStatusTip(tr("Setup stimulus feature"));
connect(m_pActionSetupStimulus, &QAction::triggered, this, &SsvepBci::showSetupStimulus);
addPluginAction(m_pActionSetupStimulus);
// Intitalise BCI data
m_slChosenChannelsSensor << "9Z" << "8Z" << "7Z" << "6Z" << "9L" << "8L" << "9R" << "8R"; //<< "TEST";
//m_slChosenChannelsSensor << "24" << "25" << "26" << "28" << "29" << "30" << "31" << "32";
m_lElectrodeNumbers << 33 << 34 << 35 << 36 << 40 << 41 << 42 << 43;
//m_lElectrodeNumbers << 24 << 25 << 26 << 28 << 29 << 30 << 31 << 32;
m_lDesFrequencies << 6.66 << 7.5 <<8.57 << 10 << 12;
m_lThresholdValues << 0.12 << 0.12 << 0.12 << 0.12 << 0.12;
setFrequencyList(m_lDesFrequencies);
}
//*************************************************************************************************************
SsvepBci::~SsvepBci()
{
//If the program is closed while the sampling is in process
if(this->isRunning()){
this->stop();
}
}
//*************************************************************************************************************
QSharedPointer<IPlugin> SsvepBci::clone() const
{
QSharedPointer<SsvepBci> pSSVEPClone(new SsvepBci());
return pSSVEPClone;
}
//*************************************************************************************************************
void SsvepBci::init()
{
m_bIsRunning = false;
// Inputs - Source estimates and sensor level
m_pRTSEInput = PluginInputData<RealTimeSourceEstimate>::create(this, "BCIInSource", "BCI source input data");
connect(m_pRTSEInput.data(), &PluginInputConnector::notify, this, &SsvepBci::updateSource, Qt::DirectConnection);
m_inputConnectors.append(m_pRTSEInput);
m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, "BCIInSensor", "SourceLab sensor input data");
connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &SsvepBci::updateSensor, Qt::DirectConnection);
m_inputConnectors.append(m_pRTMSAInput);
// // Output streams
// m_pBCIOutputOne = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data One");
// m_pBCIOutputOne->data()->setArraySize(1);
// m_pBCIOutputOne->data()->setName("Boundary");
// m_outputConnectors.append(m_pBCIOutputOne);
// m_pBCIOutputTwo = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Two");
// m_pBCIOutputTwo->data()->setArraySize(1);
// m_pBCIOutputTwo->data()->setName("Left electrode var");
// m_outputConnectors.append(m_pBCIOutputTwo);
// m_pBCIOutputThree = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Three");
// m_pBCIOutputThree->data()->setArraySize(1);
// m_pBCIOutputThree->data()->setName("Right electrode var");
// m_outputConnectors.append(m_pBCIOutputThree);
// m_pBCIOutputFour = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Four");
// m_pBCIOutputFour->data()->setArraySize(1);
// m_pBCIOutputFour->data()->setName("Left electrode");
// m_outputConnectors.append(m_pBCIOutputFour);
// m_pBCIOutputFive = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Five");
// m_pBCIOutputFive->data()->setArraySize(1);
// m_pBCIOutputFive->data()->setName("Right electrode");
// m_outputConnectors.append(m_pBCIOutputFive);
// Delete Buffer - will be initailzed with first incoming data
m_pBCIBuffer_Sensor = CircularMatrixBuffer<double>::SPtr();
m_pBCIBuffer_Source = CircularMatrixBuffer<double>::SPtr();
// Delete fiff info because the initialisation of the fiff info is seen as the first data acquisition from the input stream
m_pFiffInfo_Sensor = FiffInfo::SPtr();
// Intitalise GUI stuff
m_bUseSensorData = true;
// // Init BCIFeatureWindow for visualization
// m_BCIFeatureWindow = QSharedPointer<BCIFeatureWindow>(new BCIFeatureWindow(this));
}
//*************************************************************************************************************
void SsvepBci::unload()
{
}
//*************************************************************************************************************
bool SsvepBci::start()
{
// Init debug output stream
QString path("BCIDebugFile.txt");
path.prepend(m_qStringResourcePath);
m_outStreamDebug.open(path.toStdString(), ios::trunc);
m_pFiffInfo_Sensor = FiffInfo::SPtr();
// initialize time window parameters
m_iWriteIndex = 0;
m_iReadIndex = 0;
m_iCounter = 0;
m_iReadToWriteBuffer = 0;
m_iDownSampleIndex = 0;
m_iFormerDownSampleIndex = 0;
m_iWindowSize = 8;
m_bIsRunning = true;
// starting the thread for data processing
QThread::start();
return true;
}
//*************************************************************************************************************
bool SsvepBci::stop()
{
m_bIsRunning = false;
// Get data buffers out of idle state if they froze in the acquire or release function
//In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)
if(m_bProcessData) // Only clear if buffers have been initialised
{
m_pBCIBuffer_Sensor->releaseFromPop();
m_pBCIBuffer_Sensor->releaseFromPush();
// m_pBCIBuffer_Source->releaseFromPop();
// m_pBCIBuffer_Source->releaseFromPush();
}
// Stop filling buffers with data from the inputs
m_bProcessData = false;
// Delete all features and classification results
clearClassifications();
return true;
}
//*************************************************************************************************************
IPlugin::PluginType SsvepBci::getType() const
{
return _IAlgorithm;
}
//*************************************************************************************************************
QString SsvepBci::getName() const
{
return "SSVEP-BCI-EEG";
}
//*************************************************************************************************************
QWidget* SsvepBci::setupWidget()
{
SsvepBciWidget* setupWidget = new SsvepBciWidget(this);//widget is later destroyed by CentralWidget - so it has to be created everytime new
//init properties dialog
setupWidget->initGui();
return setupWidget;
}
//*************************************************************************************************************
void SsvepBci::updateSensor(SCMEASLIB::NewMeasurement::SPtr pMeasurement)
{
// initialize the sample array which will be filled with raw data
QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>();
if(pRTMSA){
//Check if buffer initialized
m_qMutex.lock();
if(!m_pBCIBuffer_Sensor)
m_pBCIBuffer_Sensor = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTMSA->getNumChannels(), pRTMSA->getMultiSampleArray()[0].cols()));
}
//Fiff information
if(!m_pFiffInfo_Sensor)
{
m_pFiffInfo_Sensor = pRTMSA->info();
//emit fiffInfoAvailable();
// QStringList chs = m_pFiffInfo_Sensor->ch_names;
//calculating downsampling parameter for incoming data
m_iDownSampleIncrement = m_pFiffInfo_Sensor->sfreq/100;
m_dSampleFrequency = m_pFiffInfo_Sensor->sfreq/m_iDownSampleIncrement;//m_pFiffInfo_Sensor->sfreq;
// determine sliding time window parameters
m_iReadSampleSize = 0.1*m_dSampleFrequency; // about 0.1 second long time segment as basic read increment
m_iWriteSampleSize = pRTMSA->getMultiSampleArray()[0].cols();
m_iTimeWindowLength = int(5*m_dSampleFrequency) + int(pRTMSA->getMultiSampleArray()[0].cols()/m_iDownSampleIncrement) + 1 ;
//m_iTimeWindowSegmentSize = int(5*m_dSampleFrequency / m_iWriteSampleSize) + 1; // 4 seconds long maximal sized window
m_matSlidingTimeWindow.resize(m_lElectrodeNumbers.size(), m_iTimeWindowLength);//m_matSlidingTimeWindow.resize(rows, m_iTimeWindowSegmentSize*pRTMSA->getMultiSampleArray()[0].cols());
cout << "Down Sample Increment:" << m_iDownSampleIncrement << endl;
cout << "Read Sample Size:" << m_iReadSampleSize << endl;
cout << "Downsampled Frequency:" << m_dSampleFrequency << endl;
cout << "Write Sample SIze :" << m_iWriteSampleSize<< endl;
cout << "Length of the time window:" << m_iTimeWindowLength << endl;
}
m_qMutex.unlock();
// filling the matrix buffer
if(m_bProcessData){
MatrixXd t_mat;
for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i){
t_mat = pRTMSA->getMultiSampleArray()[i];
m_pBCIBuffer_Sensor->push(&t_mat);
}
}
}
//*************************************************************************************************************
void SsvepBci::updateSource(SCMEASLIB::NewMeasurement::SPtr pMeasurement)
{
QSharedPointer<RealTimeSourceEstimate> pRTSE = pMeasurement.dynamicCast<RealTimeSourceEstimate>();
if(pRTSE)
{
//Check if buffer initialized
if(!m_pBCIBuffer_Source){
m_pBCIBuffer_Source = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTSE->getValue()->data.rows(), pRTSE->getValue()->data.cols()));
}
if(m_bProcessData)
{
MatrixXd t_mat(pRTSE->getValue()->data.rows(), pRTSE->getValue()->data.cols());
for(unsigned char i = 0; i < pRTSE->getValue()->data.cols(); ++i)
t_mat.col(i) = pRTSE->getValue()->data.col(i);
m_pBCIBuffer_Source->push(&t_mat);
}
}
// Initalize parameter for processing BCI on source level
if(m_bInitializeSource){
m_bInitializeSource = false;
}
QList<Label> labels;
QList<RowVector4i> labelRGBAs;
QSharedPointer<SurfaceSet> SPtrSurfSet = pRTSE->getSurfSet();
SurfaceSet *pSurf = SPtrSurfSet.data();
SurfaceSet surf = *pSurf;
qDebug() << "label acquisation successful:" << pRTSE->getAnnotSet()->toLabels(surf, labels, labelRGBAs);
foreach(Label label, labels){
qDebug() << "label IDs: " << label.label_id << "\v" << "label name: " << label.name;
}
QList<VectorXi> vertNo = pRTSE->getFwdSolution()->src.get_vertno();
foreach(VectorXi vector, vertNo){
cout << "vertNo:" << vector << endl;
}
}
//*************************************************************************************************************
void SsvepBci::clearClassifications()
{
m_qMutex.lock();
m_lIndexOfClassResultSensor.clear();
m_qMutex.unlock();
}
//*************************************************************************************************************
void SsvepBci::setNumClassHits(int numClassHits){
m_iNumberOfClassHits = numClassHits;
}
//*************************************************************************************************************
void SsvepBci::setNumClassBreaks(int numClassBreaks){
m_iNumberOfClassBreaks = numClassBreaks;
}
//*************************************************************************************************************
void SsvepBci::setChangeSSVEPParameterFlag(){
m_bChangeSSVEPParameterFlag = true;
}
//*************************************************************************************************************
void SsvepBci::setSizeClassList(int classListSize){
m_iClassListSize = classListSize;
}
//*************************************************************************************************************
QString SsvepBci::getSsvepBciResourcePath(){
return m_qStringResourcePath;
}
//*************************************************************************************************************
void SsvepBci::showSetupStimulus()
{
QDesktopWidget Desktop; // Desktop Widget for getting the number of accessible screens
if(Desktop.numScreens()> 1){
// Open setup stimulus widget
if(m_pSsvepBciSetupStimulusWidget == NULL)
m_pSsvepBciSetupStimulusWidget = QSharedPointer<SsvepBciSetupStimulusWidget>(new SsvepBciSetupStimulusWidget(this));
if(!m_pSsvepBciSetupStimulusWidget->isVisible()){
m_pSsvepBciSetupStimulusWidget->setWindowTitle("ssvepBCI - Setup Stimulus");
//m_pSsvepBciSetupStimulusWidget->initGui();
m_pSsvepBciSetupStimulusWidget->show();
m_pSsvepBciSetupStimulusWidget->raise();
}
//sets Window to the foreground and activates it for editing
m_pSsvepBciSetupStimulusWidget->activateWindow();
}
else{
QMessageBox msgBox;
msgBox.setText("Only one screen detected!\nFor stimulus visualization attach one more.");
msgBox.exec();
return;
}
}
//*************************************************************************************************************
void SsvepBci::showBCIConfiguration()
{
// Open setup stimulus widget
if(m_pSsvepBciConfigurationWidget == NULL)
m_pSsvepBciConfigurationWidget = QSharedPointer<SsvepBciConfigurationWidget>(new SsvepBciConfigurationWidget(this));
if(!m_pSsvepBciConfigurationWidget->isVisible()){
m_pSsvepBciConfigurationWidget->setWindowTitle("ssvepBCI - Configuration");
m_pSsvepBciConfigurationWidget->show();
m_pSsvepBciConfigurationWidget->raise();
}
//sets Window to the foreground and activates it for editing
m_pSsvepBciConfigurationWidget->activateWindow();
}
//*************************************************************************************************************
void SsvepBci::removePowerLine(bool removePowerLine)
{
m_qMutex.lock();
m_bRemovePowerLine = removePowerLine;
m_qMutex.unlock();
}
//*************************************************************************************************************
void SsvepBci::setPowerLine(int powerLine)
{
m_qMutex.lock();
m_iPowerLine = powerLine;
m_qMutex.unlock();
}
//*************************************************************************************************************
void SsvepBci::setFeatureExtractionMethod(bool useMEC)
{
m_qMutex.lock();
m_bUseMEC = useMEC;
m_qMutex.unlock();
}
//*************************************************************************************************************
void SsvepBci::changeSSVEPParameter(){
// update frequency list from setup stimulus widget if activated
if(m_pSsvepBciSetupStimulusWidget){
setFrequencyList(m_pSsvepBciSetupStimulusWidget->getFrequencies());
}
if(m_pSsvepBciConfigurationWidget){
// update number of harmonics of reference signal
m_iNumberOfHarmonics = 1 + m_pSsvepBciConfigurationWidget->getNumOfHarmonics();
// update channel select
QStringList channelSelectSensor = m_pSsvepBciConfigurationWidget->getSensorChannelSelection();
if(channelSelectSensor.size() > 0){
// update the list of selected channels
m_slChosenChannelsSensor = channelSelectSensor;
// get new list of electrode numbers
m_lElectrodeNumbers.clear();
foreach(const QString &str, m_slChosenChannelsSensor){
m_lElectrodeNumbers << m_mapElectrodePinningScheme.value(str);
}
// reset sliding time window parameter
m_iWriteIndex = 0;
m_iReadIndex = 0;
m_iCounter = 0;
m_iReadToWriteBuffer = 0;
m_iDownSampleIndex = 0;
m_iFormerDownSampleIndex = 0;
// resize the time window with new electrode numbers
m_matSlidingTimeWindow.resize(m_lElectrodeNumbers.size(), m_iTimeWindowLength);
}
}
// reset flag for changing SSVEP parameter
m_bChangeSSVEPParameterFlag = false;
}
//*************************************************************************************************************
void SsvepBci::setThresholdValues(MyQList thresholds){
m_lThresholdValues = thresholds;
}
//*************************************************************************************************************
void SsvepBci::run(){
while(m_bIsRunning){
if(m_bUseSensorData){
ssvepBciOnSensor();
}
else{
ssvepBciOnSource();
}
}
}
//*************************************************************************************************************
void SsvepBci::setFrequencyList(QList<double> frequencyList)
{
if(!frequencyList.isEmpty()){
// update list of desired frequencies
m_lDesFrequencies.clear();
m_lDesFrequencies = frequencyList;
// update the list of all frequencies
m_lAllFrequencies.clear();
m_lAllFrequencies = m_lDesFrequencies;
for(int i = 0; i < m_lDesFrequencies.size() - 1; i++){
m_lAllFrequencies.append((m_lDesFrequencies.at(i) + m_lDesFrequencies.at(i + 1) ) / 2);
}
// emit novel frequency list
emit getFrequencyLabels(m_lDesFrequencies);
}
}
//*************************************************************************************************************
QList<double> SsvepBci::getCurrentListOfFrequencies(){
return m_lDesFrequencies;
}
//*************************************************************************************************************
double SsvepBci::MEC(MatrixXd &Y, MatrixXd &X)
{
// Remove SSVEP harmonic frequencies
MatrixXd X_help = X.transpose()*X;
MatrixXd Ytilde = Y - X*X_help.inverse()*X.transpose()*Y;
// Find eigenvalues and eigenvectors
SelfAdjointEigenSolver<MatrixXd> eigensolver(Ytilde.transpose()*Ytilde);
// Determine number of channels Ns
int Ns;
VectorXd cumsum = eigensolver.eigenvalues();
for(int j = 1; j < eigensolver.eigenvalues().size(); j++){
cumsum(j) += cumsum(j - 1);
}
for(Ns = 0; Ns < eigensolver.eigenvalues().size() ; Ns++){
if(cumsum(Ns)/eigensolver.eigenvalues().sum() > 0.1){
break;
}
}
Ns += 1;
// Determine spatial filter matrix W
MatrixXd W = eigensolver.eigenvectors().block(0, 0, eigensolver.eigenvectors().rows(), Ns);
for(int k = 0; k < Ns; k++){
W.col(k) = W.col(k)*(1/sqrt(eigensolver.eigenvalues()(k)));
}
// Calcuclate channel signals
MatrixXd S = Y*W;
// Calculate signal energy
MatrixXd P(2, Ns);
double power = 0;
for(int k = 0; k < m_iNumberOfHarmonics; k++){
P = X.block(0, 2*k, X.rows(), 2).transpose()*S;
P = P.array()*P.array();
power += 1 / double(m_iNumberOfHarmonics*Ns) * P.sum();
}
return power;
}
//*************************************************************************************************************
double SsvepBci::CCA(MatrixXd &Y, MatrixXd &X)
{
// CCA parameter
int n = X.rows();
int p1 = X.cols();
int p2 = Y.cols();
// center data sets
MatrixXd X_center(n, p1);
MatrixXd Y_center(n, p2);
for(int i = 0; i < p1; i++){
X_center.col(i) = X.col(i).array() - X.col(i).mean();
}
for(int i = 0; i < p2; i++){
Y_center.col(i) = Y.col(i).array() - Y.col(i).mean();
}
// QR decomposition
MatrixXd Q1, Q2;
ColPivHouseholderQR<MatrixXd> qr1(X_center), qr2(Y_center);
Q1 = qr1.householderQ() * MatrixXd::Identity(n, p1);
Q2 = qr2.householderQ() * MatrixXd::Identity(n, p2);
// SVD decomposition, determine max correlation
JacobiSVD<MatrixXd> svd(Q1.transpose()*Q2); // ComputeThinU | ComputeThinV
return svd.singularValues().maxCoeff();
}
//*************************************************************************************************************
void SsvepBci::readFromSlidingTimeWindow(MatrixXd &data)
{
data.resize(m_matSlidingTimeWindow.rows(), m_iWindowSize*m_iReadSampleSize);
// consider matrix overflow case
if(data.cols() > m_iReadIndex + 1){
int width = data.cols() - (m_iReadIndex + 1);
data.block(0, 0, data.rows(), width) = m_matSlidingTimeWindow.block(0, m_matSlidingTimeWindow.cols() - width , data.rows(), width );
data.block(0, width, data.rows(), m_iReadIndex + 1) = m_matSlidingTimeWindow.block(0, 0, data.rows(), m_iReadIndex + 1);
}
else{
data = m_matSlidingTimeWindow.block(0, m_iReadIndex - (data.cols() - 1), data.rows(), data.cols()); // consider case without matrix overflow
}
// transpose in the same data space and avoiding aliasing
data.transposeInPlace();
}
//*************************************************************************************************************
void SsvepBci::ssvepBciOnSensor()
{
// Wait for fiff Info if not yet received - this is needed because we have to wait until the buffers are firstly initiated in the update functions
while(!m_pFiffInfo_Sensor){
msleep(10);
}
// reset list of classifiaction results
MatrixXd m_matSSVEPProbabilities(m_lDesFrequencies.size(), 0);
// Start filling buffers with data from the inputs
m_bProcessData = true;
MatrixXd t_mat = m_pBCIBuffer_Sensor->pop();
// writing selected feature channels to the time window storage and increase the segment index
int writtenSamples = 0;
while(m_iDownSampleIndex >= m_iFormerDownSampleIndex){
// write from t_mat to the sliding time window while doing channel select and downsampling
m_iFormerDownSampleIndex = m_iDownSampleIndex;
for(int i = 0; i < m_lElectrodeNumbers.size(); i++){
m_matSlidingTimeWindow(i, m_iWriteIndex) = t_mat(m_lElectrodeNumbers.at(i), m_iDownSampleIndex);
}
writtenSamples++;
// update counter variables
m_iWriteIndex = (m_iWriteIndex + 1) % m_iTimeWindowLength;
m_iDownSampleIndex = (m_iDownSampleIndex + m_iDownSampleIncrement ) % m_iWriteSampleSize;
}
m_iFormerDownSampleIndex = m_iDownSampleIndex;
// calculate buffer between read- and write index
m_iReadToWriteBuffer = m_iReadToWriteBuffer + writtenSamples;
// execute processing loop as long as there is new data to be red from the time window
while(m_iReadToWriteBuffer >= m_iReadSampleSize)
{
if(m_iCounter > m_iNumberOfClassBreaks)
{
// determine window size according to former counted miss classifications
m_iWindowSize = 10;
if(m_iCounter <= 50 && m_iCounter > 40){
m_iWindowSize = 20;
}
if(m_iCounter > 50){
m_iWindowSize = 40;
}
// create current data matrix Y
MatrixXd Y;
readFromSlidingTimeWindow(Y);
// create realtive timeline according to Y
int samples = Y.rows();
ArrayXd t = 2*M_PI/m_dSampleFrequency * ArrayXd::LinSpaced(samples, 1, samples);
// Remove 50 Hz Power line signal
if(m_bRemovePowerLine){
MatrixXd Zp(samples,2);
ArrayXd t_PL = t*m_iPowerLine;
Zp.col(0) = t_PL.sin();
Zp.col(1) = t_PL.cos();
MatrixXd Zp_help = Zp.transpose()*Zp;
Y = Y - Zp*Zp_help.inverse()*Zp.transpose()*Y;
}
qDebug() << "size of Matrix:" << Y.rows() << Y.cols();
// apply feature extraction for all frequencies of interest
VectorXd ssvepProbabilities(m_lAllFrequencies.size());
for(int i = 0; i < m_lAllFrequencies.size(); i++)
{
// create reference signal matrix X
MatrixXd X(samples, 2*m_iNumberOfHarmonics);
for(int k = 0; k < m_iNumberOfHarmonics; k++){
ArrayXd t_k = t*(k+1)*m_lAllFrequencies.at(i);
X.col(2*k) = t_k.sin();
X.col(2*k+1) = t_k.cos();
}
// extracting the features from the data Y with the reference signal X
if(m_bUseMEC){
ssvepProbabilities(i) = MEC(Y, X); // using Minimum Energy Combination as feature-extraction tool
}
else{
ssvepProbabilities(i) = CCA(Y, X); // using Canonical Correlation Analysis as feature-extraction tool
}
}
// normalize features to probabilities and transfering it into a softmax function
ssvepProbabilities = m_dAlpha / ssvepProbabilities.sum() * ssvepProbabilities;
ssvepProbabilities = ssvepProbabilities.array().exp(); // softmax function for better distinguishability between the probabilities
ssvepProbabilities = 1 / ssvepProbabilities.sum() * ssvepProbabilities;
// classify probabilites
int index = 0;
double maxProbability = ssvepProbabilities.maxCoeff(&index);
if(index < m_lDesFrequencies.size()){
//qDebug()<< "index:" << index;
if(m_lThresholdValues[index] < maxProbability){
//qDebug() << "comparison: "<< m_lThresholdValues[index] << "and" << maxProbability;
m_lIndexOfClassResultSensor.append(index+1);
}
else{
m_lIndexOfClassResultSensor.append(0);
}
}
else{
m_lIndexOfClassResultSensor.append(0);
}
// clear classifiaction if it hits its threshold
if(m_lIndexOfClassResultSensor.size() > m_iClassListSize){
m_lIndexOfClassResultSensor.pop_front();
}
// transfer values to matrix containing all SSVEPProabibilities of desired frequencies of one calculationstep
m_matSSVEPProbabilities.conservativeResize(m_lDesFrequencies.size(), m_matSSVEPProbabilities.cols() + 1);
m_matSSVEPProbabilities.col( m_matSSVEPProbabilities.cols() - 1) = ssvepProbabilities.head(m_lDesFrequencies.size());
}
// update counter and index variables
m_iCounter++;
m_iReadToWriteBuffer = m_iReadToWriteBuffer - m_iReadSampleSize;
m_iReadIndex = (m_iReadIndex + m_iReadSampleSize) % (m_iTimeWindowLength);
}
// emit classifiaction results if any classifiaction has been done
if(!m_lIndexOfClassResultSensor.isEmpty()){
// finding a classifiaction result that satisfies the number of classifiaction hits
for(int i = 1; (i <= m_lDesFrequencies.size()) && (!m_lIndexOfClassResultSensor.isEmpty() ); i++){
if(m_lIndexOfClassResultSensor.count(i) >= m_iNumberOfClassHits){
emit classificationResult(m_lDesFrequencies[i - 1]);
m_lIndexOfClassResultSensor.clear();
m_iCounter = 0;
break;
}
else{
emit classificationResult(0);
}
}
}
// calculate and emit signal of mean probabilities
if(m_matSSVEPProbabilities.cols() != 0){
QList<double> meanSSVEPProbabilities;
for(int i = 0; i < m_lDesFrequencies.size(); i++){
meanSSVEPProbabilities << m_matSSVEPProbabilities.row(i).mean();
}
emit SSVEPprob(meanSSVEPProbabilities);
//qDebug() << "emit ssvep:" << meanSSVEPProbabilities;
}
// change parameter and reset the time window if the change flag has been set
if(m_bChangeSSVEPParameterFlag){
changeSSVEPParameter();
}
}
//*************************************************************************************************************
void SsvepBci::ssvepBciOnSource()
{
}
| 37.344 | 191 | 0.562095 | 13grife37 |